Junior — Middle
Can you explain the main idea of the dependency inversion principle and how it is applied in software development?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle states that:
- High-level modules should not depend on low-level modules directly.
- Both types of modules should depend on abstractions (e.g., interfaces).
- Abstractions should not depend on details, and details should depend on abstractions.
This reduces component coupling and increases flexibility and testability of the code.
Example of application 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 create_user(self, user_data):
self.db.save(user_data)
# Usage
mysql_db = MySQLDatabase()
service = UserService(mysql_db)
service.create_user({'name': 'Alice'})
Here, UserService depends on the abstraction Database, not on the specific implementation MySQLDatabase, which makes it easier to replace the database and test.