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().class SystemClock {
hour() {
return new Date().getHours();
}
}
class Greeter {
constructor(clock) {
this.clock = clock; // passed in, not created here
}
greet(name) {
const hour = this.clock.hour();
const part = hour < 12 ? 'morning' : hour < 18 ? 'afternoon' : 'evening';
return `Good ${part}, ${name}`;
}
}
// In the app: new Greeter(new SystemClock()). In a test: any object with hour().import "time"
type Clock interface {
Hour() int
}
type SystemClock struct{}
func (SystemClock) Hour() int { return time.Now().Hour() }
type Greeter struct {
clock Clock // passed in, not created here
}
func NewGreeter(clock Clock) *Greeter {
return &Greeter{clock: clock}
}
func (g *Greeter) Greet(name string) string {
hour := g.clock.Hour()
part := "evening"
if hour < 12 {
part = "morning"
} else if hour < 18 {
part = "afternoon"
}
return "Good " + part + ", " + name
}
// In the app: NewGreeter(SystemClock{}). In a test: any Clock.use std::time::{SystemTime, UNIX_EPOCH};
trait Clock {
fn hour(&self) -> u64;
}
struct SystemClock;
impl Clock for SystemClock {
fn hour(&self) -> u64 {
// Hour of the day in UTC; the standard library has no time zones.
let secs = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
secs / 3600 % 24
}
}
struct Greeter<C: Clock> {
clock: C, // passed in, not created here
}
impl<C: Clock> Greeter<C> {
fn new(clock: C) -> Self {
Greeter { clock }
}
fn greet(&self, name: &str) -> String {
let part = match self.clock.hour() {
0..=11 => "morning",
12..=17 => "afternoon",
_ => "evening",
};
format!("Good {}, {}", part, name)
}
}
// In the app: Greeter::new(SystemClock). In a test: any Clock.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
- Injecting everything. Plain values and pure helpers, like a
maxfunction, don’t need injecting. Inject things that touch the outside world or that you’d want to fake: time, randomness, files, network, databases. - 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.
- 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?
With the random source passed in, tests can pass a fake that returns fixed numbers. Seeding the global generator works too, but it’s shared state that other code can disturb.
Check yourself
Which is constructor injection?
The caller creates the database and hands it over. The first option hides the dependency, and the third is a singleton lookup.
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).
Finished this page?
Your list