Junior — Middle
Can you explain the essence of the Dependency Inversion Principle (DIP)?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) is one of the five SOLID principles, which 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.
This means that instead of a class directly creating or using specific implementations, it should work with abstractions (such as interfaces or abstract classes). This increases flexibility and makes testing easier.
Example in Python:
from abc import ABC, abstractmethod
class Database(ABC):
@abstractmethod
def save(self, data):
pass
class MySQLDatabase(Database):
def save(self, data):
print(f"Saving {data} to MySQL")
class UserService:
def __init__(self, db: Database):
self.db = db
def add_user(self, user):
self.db.save(user)
# Usage
mysql_db = MySQLDatabase()
service = UserService(mysql_db)
service.add_user("John")
Here, UserService depends on the abstraction Database, not on the specific implementation MySQLDatabase.