What is the main benefit of dependency injection?
Options
- It produces fewer lines of code in every class of the system
- Components get collaborators from outside, so they are easy to test (Correct option)
- It makes the program run faster at runtime in all cases
- It removes the need to write interfaces for the components
Answer
Components receive their collaborators from outside, so they are loosely coupled and easy to test with fakes
Why
Without DI, a class creates what it needs inside itself (self.db = PostgresDB()), so it is glued to that choice.
With DI, the class receives it from outside (def __init__(self, db)). The caller decides which implementation to pass: the real one in production, a fake in tests.
FastAPI's Depends is a DI system.
Remember
Don't create your dependencies inside; receive them.