DIP (Dependency Inversion Principle) — Explained with Examples
The Dependency Inversion Principle states that high-level modules should not depend on low-level modules — both should depend on abstractions, not concretions.
DIP stands for Dependency Inversion Principle, the fifth of the five SOLID principles. Robert C. Martin summarized it: “Depend on abstractions, not on concretions.”
Why DIP Matters
When high-level business logic depends directly on low-level implementations (a database driver, a file system, an API client), swapping those implementations requires rewriting the high-level code. DIP inverts this: both layers depend on interfaces, making the system flexible and decoupled.
Real-World Analogy
A TV remote doesn’t know the internal circuitry of the TV — it depends on the abstract “IR signal” contract. The TV manufacturer can redesign the internal components without breaking the remote, as long as the IR signal contract stays the same.
Example: Violating vs Following DIP
# Violating DIP — high-level depends on low-level concretions
class MySQLDatabase:
def save_user(self, user):
print(f"Saving {user} to MySQL")
class UserService:
def __init__(self):
self.db = MySQLDatabase() # tightly coupled to MySQL
def register(self, user):
self.db.save_user(user)# Following DIP — both depend on abstraction
from abc import ABC, abstractmethod
class Database(ABC):
@abstractmethod
def save_user(self, user): pass
class MySQLDatabase(Database):
def save_user(self, user):
print(f"Saving {user} to MySQL")
class PostgreSQLDatabase(Database):
def save_user(self, user):
print(f"Saving {user} to PostgreSQL")
class UserService:
def __init__(self, db: Database): # depends on abstraction
self.db = db
def register(self, user):
self.db.save_user(user)
# Swap implementations without changing UserService
service = UserService(MySQLDatabase())
service.register("Alice")
service = UserService(PostgreSQLDatabase())
service.register("Bob")Related Terms
SOLID, Dependency Injection, Open/Closed Principle, Clean Architecture
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro