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
Related
In my project I have defined an interface to describe the methods that each of my different database connection classes must have. This is called IDatabaseConnectivityObject. Each of my classes implements this interface to make sure that they all contain the same methods for running queries, making connections etc etc.
Consider the following code:
IDatabaseConnectivityObject adoDataBaseConnection = new DbProviderFactoryConnection();
DbProviderFactoryConnection adoDataBaseConnection = new DbProviderFactoryConnection();
Will the above lines both behave the same? If so why? If not then why not? What are the benefits of both?
It may be a really stupid question but I havent used interfaces all that long and I am not sure what line 1 does. It was my understanding that you couldnt make an instance of an interface as it merely defines behaviour so how is that line possible?
Will the above lines both behave the same? If so why?
At runtime yes. The difference is that if you declare the variable of type IDatabaseConnectivityObject then at compile time you will be able to see only the members of this interface on the variable. If on the other hand you declare it as DbProviderFactoryConnection then you will see all the members of this class.
As a good practice it is recommended to always work with the highest possible type in the hierarchy when declaring the variable (IDatabaseConnectivityObject in this case) which allows you to access all members that the consumer will need.
The first would allow you to swap in a different implementation of you IDatabaseConnectivityObject moving forward.
This is a good practice as it allows your system to be more resistant to change moving forward. Keeping the cost of change low is key.
Interfaces define the contract that consumers can rely on, the API if you will. The two lines are functionally the same if you intend to use members that are present on the interface.
Using the interface just expresses that you don't care how something is implemented, just that it is implemented to contract. Interfaces also promote Loose Coupling.
The benefit of programming against an interface is that you are programming against the "agreement" and not the "execution", or the contract and not the implementation. This has a large positive impact on testing as you can mock or stub interfaces during tests to reduce the number of extraneous dependencies in a test scenario.
A similar benefit to above is that using interfaces along with something like the factory pattern, IoC, or DI you can provide different implementations of the interface on the fly - for example, a different business logic handler for a different customer.
Another benefit is that it helps get around the lack of multiple inheritance. Most things can be expressed nicely via interfaces, and classes can implement multiple interfaces.
You've asked for benefits.
When you are programming against interfaces (and are using factories to create the concrete types) this makes unit-testing easier as you can mock the instance that is put into the logic (unit).
This is actually a 'Design Pattern Principle':
"Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)
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.
Ok the great thing about programming to an interface is that it allows you to interchange specific classes as long as the new classes implement everything in that interface.
e.g. i program my dataSource object to an interface so i can change it between an xml reader and a sql database reader.
does this mean ideally every class should be programmed to an interface?
when is it not a good idea to use an interface?
When the YAGNI principle applies.
Interfaces are great but it's up to you to decide when the extra time it takes developing one is going to pay off. I've used interfaces plenty of times but there are far more situations where they are completely unnecessary.
Not every class needs to be flexibly interchanged with some other class. Your system design should identify the points where modules might be interchangeable, and use interfaces accordingly. It would be silly to pair every class with an additional interface file if there's no chance of that class ever being part of some functional group.
Every interface you add to your project adds complexity to the codebase. When you deal with interfaces, discoverability of how the program works is harder, because it's not always clear which IComponent is filling in for the job when consumer code is dealing with the interface explicitly.
IMHO, you should try to use interfaces a lot. It's easier to be wrong by not using an interface than by using it.
My main argument on this is because interfaces help you make a more testable code. If a class constructor or a method has a concrete class as a parameter, it is harder (specially in c#, where no free mocking frameworks allow mocking non-virtual methods of concrete classes) for you to make your tests that are REAL unit tests.
I believe that if you have a DTO-like object, than it's overkill to use an interface, once mocking it may be maybe even harder than creating one.
If you're not testing, using dependency injection, inversion of control; and expect never to do any of these (please, avoid being there hehe), then I'd suggest interfaces to be used whenever you will really need to have different implementations, or you want to limit the visibility one class has over another.
Use an interface when you expect to need different behaviours used in the same context. I.e. if your system needs one customer class which is well defined, you probably don't need to use an ICustomer interface. But if you expect a class to comply to a certain behaviour s.a. "object can be saved" which applies to different knids of objects then you shoudl have the class implement an ISavable interface.
Another good reason to use an interface is if you expect different implementations of one kind of object. For example if ypu plan an SMS-Gateway which will route SMS's through several different third-party services, your classes should probably implent a common interface s.a. ISmsGatewayAdapter so your core system is independent from the specific implementation you use.
This also leads to 'dependecy injection' which is a technique to further decouple your classes and which is best implemented by using interfaces
The real question is: what does your class DO? If you're writing a class that actually implements an interface somewhere in the .NET framework, declare it as such! Almost all simple library classes will fit that description.
If, instead, you're writing an esoteric class used only in your application and that cannot possibly take any other form, then it makes no sense to talk about what interfaces it implements.
Starting from the premise of, "should I be implementing an interface?" is flawed. You neither should be nor shouldn't be. You should simply be writing the classes you need, and declaring what they do as you go, including what interfaces they implement.
I prefer to code as much as possible against an interface. I like it because I can use a tool like StructureMap to say "hey...get me an instance of IWidget" and it does the work for me. But by using a tool like this I can programatically or by configuration specify which instance is retrieved. This means that when I am testing I can load up a mock object that conforms to an interface, in my development environment I can load up a special local cache, when I am in production I can load up a caching farm layer, etc. Programming against an interface provides me a lot more power than not programming against an interface. Better to have and not need than need and not have applies here very well. And if you are into SOLID programming the easiest way to achieve many of those principles sort of begins by programming against an interface.
As a general rule of thumb, I think you're better off overusing interfaces a bit than underusing them a bit. Err on the side of interface use.
Otherwise, YAGNI applies.
If you are using Visual Studio, it takes about two seconds to take your class and extract an interface (via the context menu). You can then code to that interface, and hardly any time was spent.
If you are just doing a simple project, then it may be overkill. But on medium+ size projects, I try to code to interfaces throughout the project, as it will make future development easier.
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"