Dependency inversion is one of the popular SOLID principles, which is an acronym for the first five object-oriented design principles by Robert C. Martin Dependency Injection is a well-known pattern and de-facto standard for implementing a Dependency Inversion Principle. Most modern frameworks have some level of support for Dependency Injection.
- A high-level modules should not depend on low-level modules. Both should depend on abstractions (SOLID)
- Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions
- Avoid circular dependencies and keep code testable. The Acylic Dependency Rule describes this phenomenon in more detail.
When high-level modules depend on abstractions, it promotes loose coupling, making it easier to change the implementation of the low-level modules without affecting the high-level modules. Loose coupling, where you have minimal interdependence between components or modules of a system, is a sign of a well-structured application.
final readoly class HighLevelComponent {
private final LowLevelComponentInterface; // dependency
}
interface LowLevelComponentInterface
{
}
final readoly class LowLevelComponent implements LowLevelComponentInterface
{
}