DEV Community

Ahmed Osama Bedawy
Ahmed Osama Bedawy

Posted on

Dependency Inversion Principle (DIP)

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:

Image description

  • 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 specific Engine class (e.g., PetrolEngine).

  • The Vehicle depends on concrete details of PetrolEngine.

With DIP:

  1. Introduce an abstraction:

    • Create an interface Engine with methods like start() and stop().
  2. Refactor Vehicle:

    • Vehicle depend on the Engine interface instead of a concrete Engine class.
    • Inject a concrete Engine implementation (e.g., PetrolEngine or ElectricEngine) 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)