...

/

What is Dependency Injection?

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 properties, on the other hand, are needed by the specific operation encoded into an interface are very unlikely to change as they are tied to the logical definition of the operation itself, and not to the application needs.

If interfaces are designed according to the interface segregation principle, then each interface is responsible for a single pattern of interaction. This means classes will evolve by changing the way they implement their methods, and by implementing several more interfaces, but the interfaces should not change.

We may conclude that each class should ...