SOLID Principles Demystified — (D)
Dependency Inversion Principle
Classes must depend on abstraction but not on concretion, meaning high-level modules must not depend on low-level modules. Both must depend on the abstraction.
Sample Scenario
Let’s use the same scenario with the AreaCalculator class and add new functionality to it. This time the user would like to introduce inversion to the class AreaCalculatorDisplay.
To not violate Dependency Inversion Principle, we have created an interface called ICalculator which is implemented by the class AreaCalculator and that abstraction is consumed by the class AreaCalculatorDisplay.
Therefore, even if the functionality or methods inside AreaCalculator change, AreaCalculatorDisplay can function without disrupting the functional flow of the application due to the abstraction level of the high-level interface.
Major Benefits
- High-level modules does not need to depend on low-level modules. Both can easily depend on the abstraction.
- The low-level module can carry out the implementation of the interface.
- Enhanced code flexibility and scalability.