I am reading about SOLID principles and have just read that Dependency Inversion (DI, to be distinguished here from Dependency injection, which is one way of achieving the inversion) is an extension to the Open-Closed Principle (OCP). How is that exactly meant, if OCP is about making class extensible without touching the original code, basically.
Dependency Injection is more of a pattern than a principle. So it's not an extension of OCP. Using the DI pattern can allow one to adhere to the Dependency Inversion Principle but it's not the only way. OCP relates to this only because following OCP prohibits relying on making direct modifications to satisfy changing requirements. Therefor, some method of allowing extensible behavior is needed. DI can be that method, but there are others.– candied_orangeFeb 1, 2018 at 8:27
2@CandiedOrange Not Injection, that is one way to implement dependency inversion). Please note that R.Martin himself stated that DI is an extension to his OCP. I think it has to do with replacability and abstraction. See here: books.google.de/…– Ezoela VaccaFeb 1, 2018 at 8:36
1Martin came up with DIP (dependency inversion) mainly through a rigorous application of both Liskov substitution and OCP. His original paper on the subject came up with the principle as a natural result of rigorously applying both OCP and LS. I'm not sure if we should really call that an 'extension" exactly but the principle came about from a realization he made when applying both principles. Of course DIP goes a whole lot further than OCP and LS, but both laid the foundation for DIP.– user204677Feb 1, 2018 at 9:28
1Dug up the old paper: labri.fr/perso/clement/enseignements/ao/DIP.pdf. Oh, he actually calls it a "generalization" of both principles there. Also just a small thing but to avoid confusion, maybe use DIP for the acronym (as Martin does) to distinguish it from dependency injection (DI).– user204677Feb 1, 2018 at 9:30
@TeamUpvote THanks, you are right, should have used DIP.– John VFeb 1, 2018 at 9:42
The DIP requires your classes to depend on abstractions. Because you can always provide different implementations of these abstract dependencies, they create natural extension points that allow you to modify the behavior of the class without changing the class itself.
This, of course, is exactly what the OCP requires.
For example, imagine you have a
TaxReporter that requires an instance of an interface
ITaxCalculator during construction. By providing a different implementation of
ITaxCalculator, you have modified the way reports are generated without touching the
Inheritance is not the only way to realize the OCP.