DEV Community

Ahmed Osama Bedawy
Ahmed Osama Bedawy

Posted on

2

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more