What is the Dependency Inversion Principle?
The Dependency Inversion Principle (DIP) is one of the five SOLID principles that states:
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend on details. Details should depend on abstractions.
Let’s break this down by examples.
In this example:
- High-level Module(or Class): Class that executes an action with a tool.
- Low-level Module (or Class): The tool that is needed to execute the action.
- Abstraction: Represents an interface that connects the two Classes.
- Details: How the tool works.
Another example Vehicle and Engine:
Without DIP:
The
Vehicleclass directly instantiates a specificEngineclass (e.g.,PetrolEngine).The
Vehicledepends on concrete details ofPetrolEngine.
With DIP:
-
Introduce an abstraction:
- Create an interface Engine with methods like
start()andstop().
- Create an interface Engine with methods like
-
Refactor
Vehicle:-
Vehicledepend on theEngineinterface instead of a concreteEngineclass. - Inject a concrete
Engineimplementation (e.g.,PetrolEngineorElectricEngine) at runtime.
-
Benefits:
Enhanced flexibility: Change engine types without modifying
Vehiclecode.Easier testing: Mock Engine for testing
Vehiclein isolation.
This principle says a Class should not be fused with the tool it uses to execute an action. Rather, it should be fused to the interface that will allow the tool to connect to the Class.
It also says that both the Class and the interface should not know how the tool works. However, the tool needs to meet the specifications of the interface.

Top comments (0)