Search code examples
oopsolid-principlesglossaryprinciplesdependency-inversion

What is the dependency inversion principle and why is it important?


What is the dependency inversion principle and why is it important?


Solution

  • Check this document out: The Dependency Inversion Principle.

    It basically says:

    • High level modules should not depend upon low-level modules. Both should depend upon abstractions.
    • Abstractions should never depend upon details. Details should depend upon abstractions.

    As to why it is important, in short: changes are risky, and by depending on a concept instead of on an implementation, you reduce the need for change at call sites.

    Effectively, the DIP reduces coupling between different pieces of code. The idea is that although there are many ways of implementing, say, a logging facility, the way you would use it should be relatively stable in time. If you can extract an interface that represents the concept of logging, this interface should be much more stable in time than its implementation, and call sites should be much less affected by changes you could make while maintaining or extending that logging mechanism.

    By also making the implementation depend on an interface, you get the possibility to choose at run-time which implementation is better suited for your particular environment. Depending on the cases, this may be interesting too.