I'll Be Backend
Principles · Java

Dependency Inversion: let the policy own the interface

Keep your business rules untouched when you swap how messages are sent.

14 steps4 chapters~6 min at 1.25×#solid#dependency inversion#interfaces#decoupling
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the Java video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–4

Refactor

Steps 5–10

Payoff

Steps 11–12

Recap

Steps 13–14

The code: before and after

Before

record Customer(String name, String email, String phone) {}
record Order(int id, Customer customer, int total) {}

record SmtpMailer(String host) {
    void sendMail(String to, String subject, String body) {
        System.out.println("mail to " + to + ": " + subject + ": " + body);
    }
}

class ReceiptService {
    private final SmtpMailer mailer;

    ReceiptService() {
        mailer = new SmtpMailer("smtp.shop.test");
    }

    void sendReceipt(Order order) {
        String text =
            "Order " + order.id() + " paid: " + order.total() + " EUR";
        mailer.sendMail(order.customer().email(), "Your receipt", text);
    }
}

class Shop {
    public static void main(String[] args) {
        Customer ana = new Customer("Ana", "ana@shop.test", "0700 111 222");
        Order order = new Order(42, ana, 30);
        new ReceiptService().sendReceipt(order);
    }
}

After

record Customer(String name, String email, String phone) {}
record Order(int id, Customer customer, int total) {}

record SmtpMailer(String host) {
    void sendMail(String to, String subject, String body) {
        System.out.println("mail to " + to + ": " + subject + ": " + body);
    }
}

record SmsGateway(String apiKey) {
    void sendText(String phone, String text) {
        System.out.println("text to " + phone + ": " + text);
    }
}

record EmailReceipts(SmtpMailer mailer) implements ReceiptChannel {
    public void send(Customer customer, String text) {
        mailer.sendMail(customer.email(), "Your receipt", text);
    }
}

record SmsReceipts(SmsGateway gateway) implements ReceiptChannel {
    public void send(Customer customer, String text) {
        gateway.sendText(customer.phone(), text);
    }
}

interface ReceiptChannel {
    void send(Customer customer, String text);
}

class ReceiptService {
    private final ReceiptChannel channel;

    ReceiptService(ReceiptChannel channel) {
        this.channel = channel;
    }

    void sendReceipt(Order order) {
        String text =
            "Order " + order.id() + " paid: " + order.total() + " EUR";
        channel.send(order.customer(), text);
    }
}

class Shop {
    public static void main(String[] args) {
        Customer ana = new Customer("Ana", "ana@shop.test", "0700 111 222");
        Order order = new Order(42, ana, 30);
        SmsGateway gateway = new SmsGateway("demo-key");
        new ReceiptService(new SmsReceipts(gateway)).sendReceipt(order);
    }
}

Transcript, step by step

Problem

Step 1: A shop that mails receipts Before

Customer and Order are records, and Ana's customer record has an email and a phone number. SMTP Mailer is built with a host, and its send mail method takes an address, a subject and a body. Receipt Service creates that mailer itself in its constructor, builds the receipt text, and mails it to the customer. Receipts were always mailed, so calling the mailer straight from the receipt code was the shortest path.

Step 2: Receipts go by text Change request

Customers read texts faster than mail, so receipts now go to the customer's phone as a text message. The quick way adds SMS Gateway, built with an API key, and its send text method takes a phone and a text. Then Receipt Service changes its field type, builds the gateway in its constructor, and calls send text with the phone. It compiles, and the program now prints the receipt as a text to Ana's phone.

Step 3: The rule depends on a detail Code smell

Receipt Service holds the business rule, what a receipt says and when it goes out, and that code is called the policy. SMS Gateway does one technical job the rule doesn't care about, so it's called a detail. Yet the policy depends on that detail, because it names the gateway's type here, creates it here, and calls its method here. The receipt text line didn't change, but the policy was edited in three places for a change in delivery. And the policy can't run at all without building a real gateway with its API key.

Step 4: Dependency Inversion Principle

So the arrow has to turn around: the policy declares what it needs, and the detail implements it. In plain words, the policy declares the interface it needs, in its own words, and each detail implements it. Right now the dependency points the other way, from the policy down to the detail.

Refactor

Step 5: Refactor first Back it out

We take the gateway back out, so receipts go by mail again. Then we refactor in small steps, and text messages come back once the policy owns its interface.

Step 6: Delivery in its own method Extract Method

First, the mailer call moves into a private method called deliver, which takes a customer and a text. Send receipt now builds the text and hands it to deliver, so the output is the same mail line.

Step 7: Email receipts move out Extract Class

Deliver moves into a new record, Email Receipts, which holds the SMTP Mailer, and the method is renamed to send. Receipt Service now creates an Email Receipts and calls send, so it no longer calls the mailer's method.

Step 8: The policy names its need Extract Interface

Right next to Receipt Service we declare an interface, Receipt Channel, with one method, send, that takes a customer and a text. Email Receipts implements it, but nothing calls through the interface yet.

Step 9: Who owns the interface Extract Interface

You might put a Mailer interface over SMTP Mailer, with send mail's address, subject and body. But a text has no subject, so the policy would still speak mail, and texts would edit it again. Its shape matters, because it says what the policy needs, a customer and a text, and nothing about hosts or subjects. An interface declared by the code that calls it, in that code's words, is what Martin calls interface ownership. But Receipt Service still names Email Receipts here, so it still depends on the mail detail.

Step 10: Pass the channel in Change Function Declaration

If Receipt Service still built Email Receipts itself, it would still name a mail type, and texts would edit it again. Receipt Service's constructor now takes a Receipt Channel and stores it, and passing it in like this is called constructor injection. The field type becomes Receipt Channel too, so Receipt Service names no mail type at all. Shop builds the mailer, wraps it in Email Receipts, passes that in, and the same mail line prints. Before, the policy depended on the mailer, and now the detail depends on an interface the policy owns. That change in direction is the inversion the principle is named for.

Payoff

Step 11: Text messages, take two Payoff

So the text message request from the start can come back in. Text messages come back now, so how many lines of Receipt Service do you think change? SMS Gateway returns as it was, and SMS Receipts implements Receipt Channel by sending the text to the customer's phone. Shop builds the gateway with its API key and passes an SMS Receipts in, so the receipt goes to Ana's phone.

Step 12: The policy did not change Payoff

None, because Receipt Service and Receipt Channel didn't change to add text messages. The three places from before name only Receipt Channel now, the field here, the constructor here, and the call here. Changing delivery meant adding the text classes and editing Shop, because the policy owns the interface and the details plug into it. The policy declares the interface and each detail implements it, and that's called the Dependency Inversion Principle. But you pay with one more type to read, and Shop now has to put the pieces together itself.

Recap

Step 13: Where we started, where we ended Before / after

On the left, Receipt Service created the SMTP Mailer itself and called send mail directly. So every change in delivery meant editing the policy. On the right, Receipt Service gets a Receipt Channel through its constructor, an interface it declares in its own words. SMS Receipts plugs into that interface and keeps the gateway call to itself.

Step 14: When to reach for it Takeaways

Reach for it when a policy calls a detail that changes on its own schedule, like mail or payments. Skip it when the class you call is stable with no second version in sight, like the standard list types. Spot it by a business class that creates its own mail or database client, or an interface that copies a vendor's method. And JDBC already works this way, because Java declares the Driver interface and each database vendor implements it.