Junior — Middle
Can you explain the concept of dependency injection and how it is used in software development?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a design pattern where objects receive their dependencies from outside rather than creating them themselves. This increases modularity, testability, and flexibility of the code.
Example: instead of a class creating a database object itself, it receives it through a constructor or setter.
class Database:
def query(self):
return "data"
class Service:
def __init__(self, db: Database):
self.db = db
def get_data(self):
return self.db.query()
# Dependency injection
database = Database()
service = Service(database)
print(service.get_data())
This approach makes it easier to replace dependencies (for example, with mocks during testing) and improves code maintenance.