Junior — Middle
Could you give an example of implementing the dependency inversion principle in code?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle states that high-level modules should not depend on low-level modules; both should depend on abstractions (such as interfaces or abstract classes). In Python, this can be implemented through dependency injection via constructors or methods.
Example:
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):
# business logic
self.db.save(user_data)
# Usage
mysql_db = MySQLDatabase()
service = UserService(mysql_db)
service.create_user({'name': 'Ivan'})
Here, UserService depends not on a specific database implementation but on the abstraction Database. This makes it easier to replace implementations and for testing.