The DIP states:
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend upon details. Details should depend upon abstractions.
And the OCP states:
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
I think if we satisfy the DIP, it will cover the OCP too, So, why we separate these two principles?
I think adhering to the DIP makes it easier to comply with the OCP. However, one does not guarantee the other.
For example, I can create a class that has a method that takes a parameter of
base. Ifbaseis an abstract class then I'm adhering to the DIP as I have inverted the dependency to the caller. However, if the code in that method does something like:Then it's not OCP compliant as I have to modify it every time I add a new derivative.
It's very contrived example, but you get my point.