Repaso
EspaƱol
Design & PracticesIntermediateDP-09

What is the main benefit of dependency injection?

Options

  1. It produces fewer lines of code in every class of the system
  2. Components get collaborators from outside, so they are easy to test (Correct option)
  3. It makes the program run faster at runtime in all cases
  4. 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.

Key terms

Practice this question in Repaso