What is Dependency Injection?
In this lesson, we will learn a fundamental pattern for the cooperation between objects called dependency injection.
Classes mutual dependencies
In all object languages, objects need to call methods of other objects to do their job. This is called object cooperation.
Object cooperation must be carefully designed since complex patterns of object cooperation can undermine the whole application’s modularity. In fact, a class that cooperates with too many other classes is likely to be changed each time one of the classes it “knows of” changes.
The problematic acquaintances are not hardwired classes like the fundamental types (string, decimals, etc.) and classes that are part of the programming framework. This is because they are very unlikely to change, but all other application classes are likely to change as the application evolves and is maintained.
Mitigating mutual dependencies with interfaces
A way to mitigate dependency on other classes is to hide acquaintances behind interfaces. One might object that this way, we move from the problem of dependency on other classes to an equivalent problem of dependency on other interfaces. However, this is not the case.
In fact, well-designed interfaces are specific to a single purpose, while classes are specific to roles and responsibilities that are evolving concepts with a wider scope. Roles, and the way they are implemented, changes with the application evolution since they are tied to the application needs. The methods and ...