No, you do not need interfaces. In addition to injecting classes or interfaces, you can also introduce delegates. This is comparable to introducing an interface with a single method.
Example:
public delegate int DoMathFunction(int value1, int value2); public class DependsOnMathFunction { private readonly DoMathFunction _doMath; public DependsOnAFunction(DoMathFunction doMath) { _doMath = doMath; } public int DoSomethingWithNumbers(int number1, int number2) { return _doMath(number1, number2); } }
You can do this without declaring a delegate, simply by entering Func<Something, Whatever> , and it will work as well. I tend to be delegate because it is easier to configure DI. Perhaps you have two delegates with the same signature that serve unrelated purposes.
One of the advantages of this is that it manages the code to segregate the interface. Someone may be tempted to add a method to the interface (and its implementation), because it is already injected somewhere so that it is convenient.
It means
- The interface and implementation takes on responsibility that they probably should not have just because it is convenient for someone at the moment.
- A class that depends on the interface can also grow in its responsibility, but it is more difficult to identify, since the number of its dependencies has not grown.
- Other classes end up depending on a bloated, less divided interface.
I have seen cases where one dependency eventually turns into something that should really be two or three completely separate classes, because it was convenient to add to the existing interface and class instead of introducing something new. This, in turn, helped some classes get in the way of 2500 lines.
You cannot stop someone from doing what they do not need. You cannot prevent someone from simply making the class depend on 10 different delegates. But he can set a pattern that will help future growth in the right direction and provide some resistance to growing interfaces and classes.
(This does not mean that you are not using interfaces. It means that you have options.)
source share