The Dependency Inversion Principle is the last principle in SOLID. As a recap, SOLID is an acronym that stands for the five software design principles which Robert Martin discusses in his book “Clean Architecture — A Craftsman’s Guide to Software Structure and Design”.
- S: Single Responsibility Principle
- O: Open Closed Principle
- L: Liskov Substitution Principle
- I: Interface Segregation Principle
- D: Dependency Inversion Principle
What is Dependency Inversion Principle (DIP) about?
- High level policies.
- Classes should depend on interfaces and abstractions instead of concrete implementations.
- Abstract away the low level details that matter less to your business domain.
What is DIP not about?
- DIP is different than Dependency Injection (DI) or Inversion of Control (iOC). Those are three different concepts, but they play well together.
- DIP is not about reversing the dependency between two types. For instance, if A depends on B, then DIP is not about switching the dependency such that B depends on A. That would not make much sense. Instead, it’s about breaking the dependency such that A does not have a direct dependency on B. Rather, A depends on something more abstract.
- DIP is not about making every type or class abstract, as that would not be possible. For example, string in java or C# is a concrete type. However, it’s very stable and does not change often. As such, there is not a strong reason to make string abstract.
DI is about wiring, IoC is about direction, and DIP is about shape.
DIP related concepts
- Programming to interfaces, not implementations
- Other principles in SOLID: Open Closed Principle, Liskov Substitution Principle.
- Clean Architecture
Why should you adhere to DIP?
A class which depends directly on another concrete class is not desirable because of the increase in coupling. Any change to the depended on class may affect the dependent class.