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
Vehicle
class directly instantiates a specificEngine
class (e.g.,PetrolEngine
).The
Vehicle
depends 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
:-
Vehicle
depend on theEngine
interface instead of a concreteEngine
class. - Inject a concrete
Engine
implementation (e.g.,PetrolEngine
orElectricEngine
) at runtime.
-
Benefits:
Enhanced flexibility: Change engine types without modifying
Vehicle
code.Easier testing: Mock Engine for testing
Vehicle
in 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)