Dependency Inversion: Depend on the Promise
When the report-card sender builds the school's email server inside itself, it can never send a text and can never be tested without sending real email; the dependency inversion principle says the report card should depend on a promise it owns ("a way to send"), and be handed whatever keeps it, which is the start of dependency injection.
Journeyman · OOP · Updated
After this lesson you can
- Hand a class the promise it needs through its constructor, instead of letting it build its own
- Explain dependency inversion: high-level code and low-level details both depend on a promise
Key takeaways
- A class that builds its own helpers with new is stuck with them: it can't use another one, and its tests use the real thing.
- Dependency inversion: the important code (sending report cards) and the detail (the email server) should both depend on a promise, and the promise belongs to the important code.
- Hand the class what it needs through its constructor. A text sender, an email sender or a test's fake can then be handed in.
- Handing a class what it needs is called dependency injection; Pass 4 builds a whole app that way.
Before this: Program to an Interface, Not a Class, and Interface Segregation: Small Promises.
Sam's family asked the school for report cards by text message: nobody in the house reads email. The report-card sender can't do it. It builds the school's email server itself, inside its own constructor, so email is the only way it knows. And there's a second problem nobody mentions out loud: every time the sender's tests run, they send real emails through the school's server. This lesson fixes both with one idea.
The symptom: a class that builds its own helper
The email server isn't connected in this sample, so sending shows as a printed line:
ReportCardSender sender = new ReportCardSender();
sender.Send("Maya", "Maya: Math A, Science B, English C");
sender.Send("Sam", "Sam: Math C, Science D, English B");
class SchoolEmailServer
{
public void Send(string to, string message) => Console.WriteLine("Email to " + to + ": " + message);
}
class ReportCardSender
{
// It builds its own: always this one email server.
private SchoolEmailServer server = new SchoolEmailServer();
public void Send(string name, string reportCard) => server.Send(name + "'s family", reportCard);
}
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
class SchoolEmailServer {
void send(String to, String message) {
IO.println("Email to " + to + ": " + message);
}
}
class ReportCardSender {
// It builds its own: always this one email server.
private SchoolEmailServer server = new SchoolEmailServer();
void send(String name, String reportCard) {
server.send(name + "'s family", reportCard);
}
}
void main() {
ReportCardSender sender = new ReportCardSender();
sender.send("Maya", "Maya: Math A, Science B, English C");
sender.send("Sam", "Sam: Math C, Science D, English B");
}
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
class SchoolEmailServer:
def send(self, to, message):
print("Email to " + to + ": " + message)
class ReportCardSender:
def __init__(self):
self.server = SchoolEmailServer() # It builds its own: always this one email server.
def send(self, name, report_card):
self.server.send(name + "'s family", report_card)
sender = ReportCardSender()
sender.send("Maya", "Maya: Math A, Science B, English C")
sender.send("Sam", "Sam: Math C, Science D, English B")
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
class SchoolEmailServer {
send(to, message) {
console.log("Email to " + to + ": " + message);
}
}
class ReportCardSender {
// It builds its own: always this one email server.
server = new SchoolEmailServer();
send(name, reportCard) {
this.server.send(name + "'s family", reportCard);
}
}
const sender = new ReportCardSender();
sender.send("Maya", "Maya: Math A, Science B, English C");
sender.send("Sam", "Sam: Math C, Science D, English B");
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
class SchoolEmailServer {
send(to: string, message: string): void {
console.log("Email to " + to + ": " + message);
}
}
class ReportCardSender {
// It builds its own: always this one email server.
server = new SchoolEmailServer();
send(name: string, reportCard: string): void {
this.server.send(name + "'s family", reportCard);
}
}
const sender = new ReportCardSender();
sender.send("Maya", "Maya: Math A, Science B, English C");
sender.send("Sam", "Sam: Math C, Science D, English B");
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
Sam's family got another email they won't read.
- The symptom: the sender says
new SchoolEmailServer()inside itself. It can't send any other way, and anything that uses it (its tests included) uses the real server. - The cause: the code that matters (getting report cards to families) depends directly on a detail (which server, which channel). Something a class needs in order to work is called a dependency; this class picks its own, and picks it forever.
What would you try?
Add a flag: new ReportCardSender(useText: true), with an if inside that builds a text sender or the email server. Now the sender builds two helpers and chooses between them, and the next channel (a letter home, the parents' app) is another flag and another branch.
Copy the class as TextReportCardSender. Two copies of the same steps, and a change to the report card's wording has to be made in both.
Keep the email server, and turn it off in tests with a setting. The tests stop sending email, but the code under test is no longer the code that runs for families, and the text-message request is still waiting.
Each try keeps the sender in charge of picking its helper. What if it weren't?
The idea: depend on the promise, and be handed it
A lamp that's wired straight into the wall works with that one wire and nothing else; moving it means calling an electrician. A lamp with a plug works with any outlet, in any room, in any house. It depends on the shape of the plug, a promise, not on one particular wire.

The dependency inversion principle says two things:
- High-level code shouldn't depend on low-level details. Both should depend on a promise. The high-level code is what the program is for (sending report cards to families); the low-level details are how it happens (the school's email server, a text-message service).
- The promise belongs to the high-level side. The report-card sender says what it needs, "a way to send a message to someone", and the email server and the text sender keep that promise.
The "inversion" is about which way the arrows point. Before, the sender pointed down at the email server. After, the email server points up, at the promise the sender owns. Then the sender stops building its helper and is handed one, through its constructor:
new ReportCardSender(new EmailSender()).Send("Maya", "Maya: Math A, Science B, English C");
new ReportCardSender(new TextSender()).Send("Sam", "Sam: Math C, Science D, English B");
// The promise, owned by the report-card side: a way to send a message to someone.
interface ISender
{
void Send(string to, string message);
}
class EmailSender : ISender
{
public void Send(string to, string message) => Console.WriteLine("Email to " + to + ": " + message);
}
class TextSender : ISender
{
public void Send(string to, string message) => Console.WriteLine("Text to " + to + ": " + message);
}
class ReportCardSender
{
private ISender sender;
// Handed in, not built here: any sender that keeps the promise.
public ReportCardSender(ISender sender)
{
this.sender = sender;
}
public void Send(string name, string reportCard) => sender.Send(name + "'s family", reportCard);
}
Email to Maya's family: Maya: Math A, Science B, English C
Text to Sam's family: Sam: Math C, Science D, English B
// The promise, owned by the report-card side: a way to send a message to someone.
interface Sender {
void send(String to, String message);
}
class EmailSender implements Sender {
public void send(String to, String message) { IO.println("Email to " + to + ": " + message); }
}
class TextSender implements Sender {
public void send(String to, String message) { IO.println("Text to " + to + ": " + message); }
}
class ReportCardSender {
private Sender sender;
// Handed in, not built here: any sender that keeps the promise.
ReportCardSender(Sender sender) {
this.sender = sender;
}
void send(String name, String reportCard) {
sender.send(name + "'s family", reportCard);
}
}
void main() {
new ReportCardSender(new EmailSender()).send("Maya", "Maya: Math A, Science B, English C");
new ReportCardSender(new TextSender()).send("Sam", "Sam: Math C, Science D, English B");
}
Email to Maya's family: Maya: Math A, Science B, English C
Text to Sam's family: Sam: Math C, Science D, English B
from abc import ABC, abstractmethod
class Sender(ABC):
"""The promise, owned by the report-card side: a way to send a message to someone."""
@abstractmethod
def send(self, to, message):
...
class EmailSender(Sender):
def send(self, to, message):
print("Email to " + to + ": " + message)
class TextSender(Sender):
def send(self, to, message):
print("Text to " + to + ": " + message)
class ReportCardSender:
def __init__(self, sender):
self.sender = sender # Handed in, not built here: any sender that keeps the promise.
def send(self, name, report_card):
self.sender.send(name + "'s family", report_card)
ReportCardSender(EmailSender()).send("Maya", "Maya: Math A, Science B, English C")
ReportCardSender(TextSender()).send("Sam", "Sam: Math C, Science D, English B")
Email to Maya's family: Maya: Math A, Science B, English C
Text to Sam's family: Sam: Math C, Science D, English B
// The promise, in words: a sender has send(to, message).
class EmailSender {
send(to, message) { console.log("Email to " + to + ": " + message); }
}
class TextSender {
send(to, message) { console.log("Text to " + to + ": " + message); }
}
class ReportCardSender {
// Handed in, not built here: any sender that keeps the promise.
constructor(sender) {
this.sender = sender;
}
send(name, reportCard) {
this.sender.send(name + "'s family", reportCard);
}
}
new ReportCardSender(new EmailSender()).send("Maya", "Maya: Math A, Science B, English C");
new ReportCardSender(new TextSender()).send("Sam", "Sam: Math C, Science D, English B");
Email to Maya's family: Maya: Math A, Science B, English C
Text to Sam's family: Sam: Math C, Science D, English B
// The promise, owned by the report-card side: a way to send a message to someone.
interface Sender {
send(to: string, message: string): void;
}
class EmailSender implements Sender {
send(to: string, message: string): void { console.log("Email to " + to + ": " + message); }
}
class TextSender implements Sender {
send(to: string, message: string): void { console.log("Text to " + to + ": " + message); }
}
class ReportCardSender {
sender: Sender;
// Handed in, not built here: any sender that keeps the promise.
constructor(sender: Sender) {
this.sender = sender;
}
send(name: string, reportCard: string): void {
this.sender.send(name + "'s family", reportCard);
}
}
new ReportCardSender(new EmailSender()).send("Maya", "Maya: Math A, Science B, English C");
new ReportCardSender(new TextSender()).send("Sam", "Sam: Math C, Science D, English B");
Email to Maya's family: Maya: Math A, Science B, English C
Text to Sam's family: Sam: Math C, Science D, English B
Maya's family still gets an email, and Sam's family gets a text. ReportCardSender didn't learn about texts; it never says new for any sender at all. And the tests' problem is solved too: a test hands in a fake sender that writes each message into a list instead of sending it, then checks the list.
Try it. Write a FakeSender that keeps every message in a list instead of printing it. Hand it to a ReportCardSender, send Maya's report card, and print the list: it should hold one line, Maya's family: Maya: Math A, Science B, English C.
Where this goes next: dependency injection
Handing a class the things it needs, instead of letting it build them, has a name of its own: dependency injection. Here it's done by hand, in the constructor, and that's all it takes. Pass 1 meets it again when the bakery's shared settings become something handed in, and Pass 4 (Wiring the App Together) builds a whole web API this way, with the tools frameworks such as ASP.NET Core, Spring and Angular give you to do the handing out.
Dependency inversion is the design idea (depend on a promise the high-level code owns); dependency injection is the everyday technique that puts it to work (hand the class whatever keeps the promise).
When to bend it
- Stable details don't need a promise. Nobody wraps the language's math functions or its list type in an interface; they aren't going to change, and tests can use them as they are.
- A small script can build what it needs. When a second channel or a test needs a stand-in, that's the time to hand it in.
- Don't invent promises nobody keeps twice. An interface with exactly one class that will only ever have one is the extra file Program to an Interface warned about, unless a test needs a fake.
Check yourself
2 questions to try on the lesson page.
So what
The code that matters shouldn't build its own helpers. Let it say what it needs, as a promise, and hand it whatever keeps that promise: an email sender, a text sender, or a test's fake. That's the end of SOLID, and the start of dependency injection.