Junior — Middle
Is it possible to implement the dependency inversion principle without using dependency injection?
sobes.tech AI
Answer from AI
Yes, the Dependency Inversion Principle can be implemented without using specialized dependency injection tools.
The main idea is to depend on abstractions rather than concrete implementations. In Python, this can be done manually by passing dependencies through function parameters or class constructors.
Example:
class Database:
def get_data(self):
return "data from DB"
class Service:
def __init__(self, db): # db is an abstraction or a concrete object
self.db = db
def process(self):
data = self.db.get_data()
print(f"Processing {data}")
# Usage
my_db = Database()
service = Service(my_db) # manually passing the dependency
service.process()
Thus, dependency injection occurs explicitly and without special frameworks. This makes testing and maintaining the code easier.