What does the Dependency Inversion Principle mean?
The Dependency Inversion Principle (DIP) means that high-level modules should not depend on low-level modules - both should depend on abstractions. And abstractions should not depend on details, details should depend on abstractions.
In detail:
1. High-level modules should not depend on details
Application logic (high level) should not directly depend on concrete implementations, for example:
- a specific database,
- a specific HTTP client,
- a specific logging method. Otherwise, changing the infrastructure breaks the business logic.
2. Details should depend on abstractions
Instead of business code depending on the class MySqlRepository,
it should depend on the interface IRepository.
The concrete implementations (MySQL, Postgres, FileStorage) then depend on this abstraction.
3. Abstractions are stable, implementations are volatile
DIP states: The business should rely on stable contracts, and the volatile details should plug into those contracts.
4. The purpose of the principle
- reduce coupling,
- increase architecture flexibility,
- simplify replacing an implementation,
- allow modules to be tested in isolation.
5. One-phrase formulation
It is not the business logic that should know about technical details, but the technical details that should adapt to the business logic through abstractions.
Summary: DIP requires code to depend on abstractions, not on concrete implementations. This makes the system flexible, replaceable, and resistant to infrastructure changes.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.