Junior — Middle
What are the main advantages of using dependency injection mechanisms in code?
sobes.tech AI
Answer from AI
Dependency Injection (DI) allows passing necessary objects (dependencies) into a class from outside, rather than creating them inside. The main advantages:
- Improved testability: dependencies can be easily replaced with mocks or stubs during testing.
- Reduced coupling: classes do not depend on specific implementations but work with abstractions.
- Increased flexibility and extensibility: it's easy to change dependency implementations without modifying the class code.
- Simplified lifecycle management of objects: DI containers can create and reuse objects.
Example in Python with simple DI:
class Service:
def do_something(self):
print("Service is working")
class Client:
def __init__(self, service):
self.service = service
def run(self):
self.service.do_something()
service = Service()
client = Client(service)
client.run()
Here, Client does not create Service itself but receives it from outside, making it easier to replace Service with another implementation.