So say I have class A, B, and C. Class A has a single responsibility but needs functionality from class B and C so at first I wanted to get A to inherit from B and C then realized by following the “composition over inheritance” principle and making B and C members of A I could reduce the rigidity of the design and make those two classes more reusable.
At first B and C only needed to be instantiated in the constructor of A but eventually they had methods that needed to be called in two or three other places- as I was reusing the classes elsewhere I was forgetting to call some of the methods in the right places creating a lot of unnecessary defects and time wasted… my question is does dependency injection help with this problem, does it help reduce the complexity of using composition, and if so how?
public class A
{
private mB;
private mC;
public A(IB b, IC c)
{
mB = b;
mC = c;
}
public MethodX()
{
mB.DoWhatever();
}
public MethodY()
{
mC.DoSomething();
}
}
From what I understand DI would let me configure what concrete classes for IB and IC get put through the constructor like this and handle its creation- but how else would it help (complexity wise)?
I decided to ask this question based on not understanding this article: http://lostechies.com/chadmyers/2010/02/13/composition-versus-inheritance/
For a real life example, say I have a State class that contains an EventListener class which has to register its events when the State calls its Begin method, unregister when it calls its End method.
Your reasoning is sound, and you are on the right track.
The use of DI and composition via interfaces/abstractions makes it bot easier to tst and construct the code. You can use temporary “fake” implementations of B and C while building A, if that helps your process.
The typical solution is to factor the construction and configuration of A, B and C out into a factory class or a subclass of A.