Sobes.tech
Junior — Middle

How does Dependency Injection help manage dependencies in an application?

sobes.tech AI

Answer from AI

Dependency Injection (DI) helps manage dependencies in an application by allowing necessary objects (dependencies) to be passed into a class from outside, rather than creating them inside the class. This increases modularity, simplifies testing, and makes component replacement easier.

For example, instead of the 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
db_instance = Database()
service = Service(db_instance)

This approach makes it easy to replace Database with a mock object during testing or to use a different implementation without changing the Service class.

How does Dependency Injection help manage… - sobes.tech