Junior — Middle
Could you explain what the principle of dependency inversion means in the context of software system design?
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.
In simpler terms, instead of concrete classes directly creating or using other concrete classes, they should work through abstract interfaces or base 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 DataManager:
def __init__(self, db: Database):
self.db = db
def save_data(self, data):
self.db.save(data)
# Usage
mysql_db = MySQLDatabase()
data_manager = DataManager(mysql_db)
data_manager.save_data("data")
Here, DataManager depends on the abstraction Database, not on the concrete implementation MySQLDatabase. This allows easy swapping of database implementations without changing DataManager.