I am learning spring. I understood dependency injection. In some place I also see it called dependency inversion. I got why it is termed as injection but what is meant by "inversion"? Which dependency is it actually inverting?
The Dependency Inversion Principle (DIP) states that high level modules should not depend on low level modules; both should depend on abstractions. Abstractions should not depend on details. Details should depend upon abstractions.
It turns out that a long time ago higher level modules depending on lower level modules was something that was considered good practice (before Object Oriented Design). The name “Dependency Inversion” is alluding to this.
Inversion of Control (IoC) is a design principle that allows classes to be loosely coupled and, therefore, easier to test and maintain. IoC refers to transferring the control of objects and their dependencies from the main program to a container or framework.
Good question - the word inversion
is somewhat surprising (since, after applying the DIP, the lower level dependency module obviously doesn't now depend
on the higher level caller module, either - both caller and dependency are now just more loosely coupled through an additional abstraction).
Citing Robert C Martin's original source
One might question why I use the word “inversion”. Frankly, it is because more traditional software development methods, such as Structured Analysis and Design, tend to create software structures in which high level modules depend upon low level modules, and in which abstractions depend upon details. Indeed one of the goals of these methods is to define the subprogram hierarchy that describes how the high level modules make calls to the low level modules. ... Thus, the dependency structure of a well designed object oriented program is “inverted” with respect to the dependency structure that normally results from traditional procedural methods.
One point to note when reading Uncle Bob's paper on the DIP is that C++ didn't (and at time of writing, still doesn't) have interfaces, so achieving this abstraction in C++ is typically implemented through an abstract / pure virtual base class, whereas in Java or C# the abstraction to loosen the coupling would usually be through decoupling by abstracting an interface from the dependency, and coupling the higher level module(s) to the interface.
Edit Just to clarify:
"In some place I also see it called dependency inversion"
Note that Dependency Injection (DI) is ONE of the possible implementations to achieve the Dependency Inversion Principle (DIP) - the "D" in SOLID design principles, so DI
and DIP
are not entirely interchangeable.
Other DIP implementations include the Service locator pattern (which is nowadays often regarded as an anti-pattern); and Plugin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With