I've been looking at strategy pattern implementation examples and it seems to me like they are very similar to c# delegates. The only difference I see is that strategy pattern implementations don't need to explicitly declare a delegate.
But other than that, they both seem to point to functions that need a specific signature and they can both be used to determine what to execute at run time.
Is there a more obvious difference that I am missing?
I guess a related question would be, IF they are similar, what's the advantage of using one over the other?
Put simply, you can use delegates to implement strategy pattern.
Strategy pattern is a pattern. Delegates are a language feature. You use the language feature to implement the pattern. They reside in two separate categories of concepts altogether, but are related in their interaction with each other.
In other words, strategy pattern is the blueprint, the C# delegates are the bricks. You can't build the (strategy pattern) house without either. (You could build it with other kinds of bricks also, but nothing in the language feature of delegates inherently describes strategy pattern).
Design Patterns are language agnostic, high-level solutions to commonly-encountered problems.
Delegates can be used in a platform-specific implementation of the strategy pattern for .NET, but aren't the only way of implementing such a solution.
An alternative solution is to define an interface like:
public interface IStrategy
{
void DoStuff(...)
}
Strategies would then be represented by classes implementing this interface, rather than by a delegate.
Delegates may be an okay implementation if you expect your strategies to be very simple. For anything reasonably complex, implementing strategies as interfaces gives you a lot more options when it comes to keeping track of state, organizing things into multiple methods, sharing code between implementations, etc.
How else would you implement the strategy pattern in C#?
Patterns are a matter of architecture. Delegates are a matter of implementation.
In C#, a strategy pattern will nearly always be implemented using a delegate.
The strategy pattern is a design pattern that allows you to choose distinct functions at execution time while a delegate is a language construct that allows you to create a reference to a function and use it as a variable.
The strategy pattern is better implemented with polymorphism rather than delegates as polymorphic dispatch tends to be more elegant.
Delegates can be seen similar to a functional interface used in Java - Essentially an interface with just one method.
Starting Java8, you can actually provide implementations to functional interfaces, in a much more anonymous/in-line way.
For a behaviour that can be covered by a single method, doing a strategy implementation is kind of an overkill, and too verbose.
They essentially solve the same purpose of "inserting swappable behaviours in a class"
Related
Many times when designing interfaces I keep running into the same situation. The situation is where certain implementations using an interface require particular parameters in the interface while others do not.
What is the best practice when designing an interface?
Is it OK to have certain implementations that implement the interface but not use all the parameters?
Or in these situations should I just be taking in a list (some structure) of parameters and deal with that list accordingly in each implementation?
No it's not OK. It breaks Liskovs Substituion Principle.
Sounds to me that your interfaces are trying to do too much. Either use interface inheritance or split the interface into multiple ones. Do note that it's better having many small interfaces than one large. Classes can still implement all of those.
Interfaces, like classes, should follow SRP (Single Responsibility Principle). imho it's much much more important that interfaces do so since they force a design upon the rest of your application.
I also tend to try to avoid adding properties as much as possible from interfaces.
It's ok in some cases. It doesn't really matter what you actually do with the parameters in the implementation as long as it satisfies the contract that the interface promises to uphold.
But you should reconsider whether you don't actually want a more specific interface for some things that need those parameters. In your abstraction stack, having a "lower" interface need "higher" parameters is a break of encapsulation.
Do extension methods follow the object-oriented paradigm in C#?
Is it a good practice to use extension methods?
In the software development lifecycle how should we consider this question in the design phase?
Eric Lippert has blogged about this and I suspect I can't do much better than to quote him:
So, yes, the oft-heard criticism that
"extension methods are not
object-oriented" is entirely correct,
but also rather irrelevant. Extension
methods certainly are not
object-oriented. They put the code
that manipulates the data far away
from the code that declares the data,
they cannot break encapsulation and
talk to the private state of the
objects they appear to be methods on,
they do not play well with
inheritance, and so on. They're
procedural programming in a convenient
object-oriented dress.
They're also incredibly convenient and
make LINQ possible, which is why we
added them. The fact that they do not
conform to some philosophical ideal of
what makes an object-oriented language
was not really much of a factor in
that decision.
I would add, however, that they're useful beyond just LINQ - for the same reason that they're useful in LINQ. It's really nice to be able to express algorithms which work on arbitrary implementations of a particular interface (such as IEnumerable<T> in LINQ to Obhects). Such algorithms typically don't have any context beyond the interfaces you're working on, so they're often naturally static.
If you accept that you've got some static utility method, which syntax would you rather use?
// Traditional
CollectionUtils.Sort(collection);
// Extension methods
collection.Sort();
The latter is simply more readable in my opinion. It concisely expresses what you want to do. It doesn't make it clear how you want to do it, but that's less important for most of the time - and more important when you're debugging that particular line, of course.
Extension methods are not an object oriented language feature. (compared to: classes, inheritance, polymorphism etc).
Like every language feature, it should be used where it is appropriate and for what it is designed for. There are already dozens of questions about when and how to use Extension methods.
What are the best practices for using Extension Methods in .Net?
Possible overuses of Extension Methods
Do Extension Methods Hide Dependencies?
There are two parts to it.
Is it OO when we use it
No; it makes you feel that you are calling method on the particular type
Is it OO based on how it is compiled/built
Yes; Compiled code has a static method using the object on which extension method was invoked
Extension methods are just a language feature. They work on object instances and are very nice tool.
Consider them as a different way to extend class functionality. You can add new functionality to a class:
By adding a partial class declaration. The class then instantly gets a bunch of new methods and properties.
By including a namespace with your extension methods holder class. The class then gets a bunch of new methods again.
Rather an organizational / language feature. Does not break object-oriented concept in any way. Just as header/source file division in C/C++ has nothing to do with object-orientation, just a language/framework feature.
It depends. Extension methods are just a tool. They can be very useful when used appropriately. But if you use them too much, it can obscure your code.
Extension Methods are just static methods that work with a specific Class or Class Hierarchy. Python is OO but has modules, Ruby has mixins. I see it more as a language feature. I am pretty sure its still OO friendly
I would like to know if C# extension method is based on any existing design pattern.
A design pattern is simply a well known paradigm, i.e. "when you want to achieve X, do Y". A well known paradigm in object-oriented languages such as C# is "when you want to act on the state of an object, call a method on an instance of it".
However, before extension methods were created, you could not call your own method on an instance of an object that you could not add an implementation to (e.g. interfaces because they cannot have implementations, or library classes because they are already compiled). Extension methods fill this gap by allowing you to make methods that appear to be callable on instances of objects, while being defined externally to the implementation of the object.
So yes, arguably extension methods are based on this very simple design pattern, of making methods that act on the state of an object appear to be callable from an instance of it.
The extension methods can be thought as a replacement of the Visitor Pattern. It is also proposed that they can be used as Adapters.
In general languages evolve to make the need of design patterns less necessary. There is a quote for example that Lisp doesn't need design patterns, because everything is built in the language. So the right question will be, what design patterns do extension methods replace?
No. It's just a language feature.
They are not based on an existing design pattern. When this 'feature' was first introduced in Delphi, under the name 'class helpers', Borland even warned users away from them. They were considered a bit of a hack, but now the dust has settled they have found a place of their own.
Like everything else, use when appropriate.
The closest canonical design patterns is probably the Decorator pattern.
No, they are not, because they are only syntactic sugar.
No, but extension methods are excellent for implementing certain GoF design patterns (e.g., Prototype).
Of course you can use C# extension methods if you want to implement certain design patterns. For example simulate mixins in C#.
I wouldn't label Extension Methods as any of the common design patterns, but it can be used to implement patterns like, Decorator and Adapter etc..
The best matching design pattern to extension method is Facade pattern.
My Reason: We usually use extension methods not to introduce a new functionality beyond the target class responsibility, but simplifying using existing target class usage.
Because simplifying the target class usage is the Facade pattern concern, extension methods can alternatively be implemented using the Facade pattern.
There are some problems in extending and unit testing extension methods. So I think implementing Facade pattern is a better approach against using extension methods.
However it is possible to implement some extension methods that wrap the facade interface in order to provide a coding facility for client codes.
I would like to have your opinion as to the pros and cons of using delegates instead of virtual functions aud subclassing?
I think the delegate issue is a red herring: this is really about the strategy pattern versus the template pattern.
"Favor composition over inheritance" is excellent advice, so the strategy pattern is the better default technique (whether you use objects or delegates to do your dirty work), mainly because it provides superior decoupling.
I only use subclassing (the template pattern) when there's a suitable inheritance relationship (per the Liskov Substitution Principle), the algorithm I'm varying needs access to the protected methods of the base class and I want a high degree of cohesion.
It very muych depends whether you're aiming for the object oriented or functional style really.
Object oriented => inheritance and overriding of methods
Functional => passing delegates to method
Usually it's best to pick one or the other, but sometimes it doesn't hurt to mix. I generally try to stick to the OO approach, since that is the main heritage of C#.
However, in certain circumstances, passing lambda epxressions to functions removes a lot of the boilerplate code. Indeed, in the extreme case, the alternative to creating a method that takes a delegate/lambda expression could be overriding the base class a dozen or so times with minor changes. Saying this, if the behaviour you want to customise is fairly fixed, than subclassing is usually the better choice.
Vague question, so you get a vague answer:
Use virtual methods and subclassing to represent a model. Use delegates to implement a mechanism.
See my answer to
When to use callbacks instead of events in c#?
for additional thoughts in this vein.
Here is my take.
Its not object oriented programming anymore. It's the old way of doing things.
Hm. That's all I have.
I wonder what's the pros/cons of using delegate vs OOP when implementing strategy design pattern?
Which one do you recommend to use? or what kind of problem does delegate solve? and why should we use OOP if OOP is better?
Thanks!
-tep
Both techniques can be powerful and valuable - here are some of my opinions about when to use which.
Use an Interface/Implementation approach when the strategy:
maintains state
needs configuration
uses dependency injection
needs to be configured by an IoC container (think ConnectionProvider)
combines multiple responsibilities (think DataAdapter from ADO.NET)
is too complex or long as a single method
is likely to be subclassed to create new strategies
needs to return state information to the caller
needs to access internals of the object is applies to
Would require too many direct parameters
Otherwise, tend to use delegates based on Func<> or Action<>, especially if
There are likely to be a very large variety of strategies (think sort expressions)
The strategy is best expressed as as lambda
There's an existing method you want to leverage
In favour of delegates:
Delegates are easier to implement in a light-weight way using lambda expressions and dynamic methods
Delegates can be created from "normal" methods with the right signature
Delegates being multi-cast can be useful at times (though relatively rarely outside eventing)
In favour of interfaces:
An object can implement an interface and still do other things: a delegate is just a delegate
An interface can have multiple methods; a delegate just has the one
Could go either way:
With interfaces you end up with two names: the interface and the method. With delegates you just have the one. Often I find that single-method interfaces either repeat the same name twice (with variations) or the method name is very bland
Personally I'm a big fan of delegates for their flexibility, but it really depends on the situation.
In my opinion, if you use delegates then you're not actually implementing the Strategy pattern. You're actually implementing something more akin to the Observer pattern. The whole point of design patterns is that when you say "I've used the Strategy pattern here," everyone has a lot of context on what you've done. When you start saying things like "I've used the Strategy pattern except with my own personal modifications," then things get dicey.
But, if I understand what you're trying to say, one of the nice things about the Strategy pattern that isn't so clear with delegates is you can have a hierarchy of objects that implement a strategy.
Let's say that I'm testing some piece of software. I want to test it using the mouse and using the keyboard. So I'll implement a Strategy pattern to plug in the interface method to use for each test case ... so I can write the test case once and run it completely using the MouseStrategy and KeyboardStrategy. From there I can implement specializations such as MouseExceptForDialogsStrategy, a specialization of MouseStrategy. This sort of hierarchy, how to extend it and override it is easily understood by anyone familiar with OOP concepts ... whereas how to achieve and extend the same with delegates is much more complicated and very much more obscure.
As with many things ... it is not a question of "can you do it?", but "should you do it?".
I like to use an interface to abstract my strategy. My concrete implementations then have a visible file for each strategy. When working with a Class instead of a method it gives you more flexibility. I can use Rhino mocks to mock out the strategy to test around it. I can also easy use DI frameworks such as Ninject to bind the strategy application wide very easily. I use Delegates to extract the implementation mostly in WinForm Dialogs.
According to this Pluralsight blog post:
The primary difference between Delegates and Interfaces is that while delegates reduce the code base and increase readability of code, you have to be careful on how you use them otherwise you might end up sacrificing testability. Coding to interfaces is usually more reliable, even if it requires more code