Junior — Middle
Do you use the principle of dependency inversion in your projects?
sobes.tech AI
Answer from AI
Yes, the Dependency Inversion Principle (DIP) is often used to increase the flexibility and testability of code. In Python, this is achieved through the use of abstractions (such as interfaces or base classes) and dependency injection via function parameters or class constructors.
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 Service:
def __init__(self, db: Database):
self.db = db
def process(self, data):
# business logic
self.db.save(data)
# Usage
mysql_db = MySQLDatabase()
service = Service(mysql_db)
service.process('data')
This approach allows for easy swapping of database implementations without changing the Service class, which aligns with the dependency inversion principle.