programmingconcepts

§ 7.3 · Design

Dependency injection

Give an object the things it depends on from outside, instead of letting it create them itself.

Dependency injection means passing an object the things it depends on, such as a clock, database or HTTP client, instead of having it create them. The calling code decides which implementation to use: the real one in production, a fake in tests. It applies the dependency inversion principle and makes code easier to test, configure and change.

In one line
Pass it in; don't create it
Main benefit
Testable code
Common forms
Constructor, parameter, setter
Applies
Dependency inversion (the D in SOLID)
Requires
SOLID

The problem

Say a Greeter says “Good morning” or “Good evening” depending on the time. If it reads the system clock itself, you can only test the evening greeting in the evening. The same goes for a class that opens its own database connection or creates its own HTTP client: every test needs a real database or a real network.

The class has a hidden dependency, and you can’t swap it.

The fix

Pass the dependency in. The Greeter below doesn’t know or care where the hour comes from. It receives a clock with an hour() method:

from datetime import datetime


class SystemClock:
    def hour(self):
        return datetime.now().hour


class Greeter:
    def __init__(self, clock):
        self.clock = clock  # passed in, not created here

    def greet(self, name):
        hour = self.clock.hour()
        if hour < 12:
            part = "morning"
        elif hour < 18:
            part = "afternoon"
        else:
            part = "evening"
        return f"Good {part}, {name}"


# In the app: Greeter(SystemClock()). In a test: any object with hour().

In the app, you pass the real SystemClock. In a test, you pass a fake that always says 9 o’clock, and check for “Good morning”. The tests for this code do exactly that for five different hours, and they run instantly at any time of day.

Three ways to inject

Form How When
Constructor Greeter(clock) The default. The object is complete as soon as it exists.
Parameter greet(name, clock) Only one method needs it, or it changes per call.
Setter greeter.clock = clock Optional dependencies. Easy to forget, so use it sparingly.

How it relates to SOLID

The D in SOLID, dependency inversion, says high-level code should depend on abstractions, not concrete details. Dependency injection is how you do that in practice: Greeter depends on “anything with hour()”, and the concrete clock is chosen outside it.

It’s also why design patterns books warn against Singleton: a singleton is a dependency the object reaches out and grabs, the opposite of injection.

Common mistakes

  1. Injecting everything. Plain values and pure helpers, like a max function, don’t need injecting. Inject things that touch the outside world or that you’d want to fake: time, randomness, files, network, databases.
  2. Constructors with ten parameters. That’s usually a sign the class has too many responsibilities. Split the class rather than hiding the list in a framework.
  3. Service locators. Passing a global registry and letting the object pick what it needs hides the dependencies again. The point is that they’re visible in the signature.

Check yourself

Check yourself

A function calls random.random() directly, so its tests give different results each run. What's the injection-style fix?

Check yourself

Which is constructor injection?

Sources

  • Martin Fowler, “Inversion of Control Containers and the Dependency Injection pattern” (2004), martinfowler.com.
  • Mark Seemann and Steven van Deursen, Dependency Injection: Principles, Practices, and Patterns (2019).
  • Robert C. Martin, “The Dependency Inversion Principle,” C++ Report (1996).

Newsletter

One new concept each week, by email.

Signup opens soon.