Bridge

November 26, 20269 minutes

Three kinds of notification and three channels make nine classes, and Slack makes twelve. Learn how Bridge turns that into three plus three, and how it differs from Adapter and Strategy.

Your app sends notifications. There are three kinds: alerts, reminders and digests. And three ways to deliver them: email, text message and push. Easy enough: one class for each pair. That’s nine classes. Then the team wants Slack, which is three more. And a new kind, say receipts, means four more. Every new idea multiplies the classes. There’s a better way, and it’s called the Bridge pattern.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

Nine classes

Three kinds times three channels is nine classes. A fourth channel adds three; a fourth kind adds four. By the time both have grown, you have sixteen classes, and each new idea multiplies the count instead of adding to it.

A grid of nine classes: EmailAlert, SmsAlert, PushAlert, EmailReminder, SmsReminder, PushReminder, EmailDigest, SmsDigest and PushDigest, one for every pair of kind and channel; adding Slack would add three more. A grid of nine classes: EmailAlert, SmsAlert, PushAlert, EmailReminder, SmsReminder, PushReminder, EmailDigest, SmsDigest and PushDigest, one for every pair of kind and channel; adding Slack would add three more.
One class per pair: nine, and growing.

A camera and its lenses

Think of a camera. The body decides how you shoot. A compact is simple, and a pro body has dials. The lens decides what you see: wide, or zoom. Bodies and lenses are designed and sold separately. Any body takes any lens, because they meet at one agreed point: the lens mount.

Nobody sells a separate product for every pair. That would be four cameras to design, and two more every time a lens arrives. Next year you can buy a new lens and the body doesn’t change; buy a new body and every lens you own still fits.

In code, the body is the abstraction. The lens is the implementor. And the mount, the thing that joins them, is the bridge.

The camera analogy mapped onto code: the camera body is the abstraction (Notification), the lens is the implementor (Channel), and the lens mount that joins them is the bridge (the channel field). The camera analogy mapped onto code: the camera body is the abstraction (Notification), the lens is the implementor (Channel), and the lens mount that joins them is the bridge (the channel field).
The camera, mapped onto the code.

The obvious version: one class per pair

Here’s the obvious version. A notification has one method, send. An email alert extends it, shouts the text, and delivers it by email.

abstract class Notification {
    abstract void send(String user, String text);
}

class EmailAlert extends Notification {
    void send(String user, String text) {
        Smtp.send(user, "ALERT: " + text.toUpperCase());
    }
}

A text alert shouts the same way, and delivers by text message instead.

class SmsAlert extends Notification {
    void send(String user, String text) {
        SmsGateway.text(user, "ALERT: " + text.toUpperCase());
    }
}

(Smtp and SmsGateway are made-up helpers.) For one kind and two channels, that’s fair. Each class is short, and does one clear thing.

Why it breaks

But the grid keeps growing. Add Slack, and every kind needs a Slack version. Add a kind, and every channel needs a new class.

Worse, the same code gets pasted around. The alert wording lives in every alert class. The email sending lives in every email class. Change the wording, and you edit every alert class. Change the email provider, and you edit every email class. Miss one, and the channels disagree.

Two things change here, and for different reasons. The product team changes the kinds (what to say). The platform team changes the channels (how to send). One hierarchy is carrying both. And testing is awkward: to check the alert wording, you’d have to send a real email, because the wording and the sending live in one class.

The key idea: two hierarchies, one field

So split the hierarchy in two. One for what the message is: alert, reminder, digest. One for how it travels: email, text, push. Now join them the way the camera does. The notification holds a channel in a field, and sends through it. That field is the bridge.

Notice the shape: it’s composition, not inheritance. A notification has a channel; it isn’t one. Three kinds plus three channels is six classes, not nine, and any kind works with any channel.

Before and after. Before: nine pair classes, one per kind-and-channel combination. After: a Notification hierarchy (Alert, Reminder, Digest) holds a Channel (Email, Sms, Push); 3 + 3 = 6 classes. Before and after. Before: nine pair classes, one per kind-and-channel combination. After: a Notification hierarchy (Alert, Reminder, Digest) holds a Channel (Email, Sms, Push); 3 + 3 = 6 classes.
Nine classes become three plus three.

The Gang of Four put it this way (Design Patterns, 1994):

“Decouple an abstraction from its implementation so that the two can vary independently.”

Two reasons to change, two hierarchies.

Building it

Start with the implementor. Channel is an interface with one method, deliver. It knows nothing about alerts or reminders.

public interface Channel {
    void deliver(String user, String message);
}

Each channel implements it. The email channel delivers by email. Text and push do the same job, their own way (SmsChannel and PushChannel have the same shape).

public class EmailChannel implements Channel {
    @Override
    public void deliver(String user, String message) {
        Smtp.send(user, message);
    }
}

Now the abstraction. Notification holds a channel, and takes it in the constructor. Its subclasses decide what to say.

public abstract class Notification {
    protected final Channel channel;

    protected Notification(Channel channel) {
        this.channel = channel;
    }

    public abstract void send(String user, String text);
}

An alert shouts its text, then hands it to the channel. It never knows which channel it has.

public class Alert extends Notification {
    public Alert(Channel channel) {
        super(channel);
    }

    @Override
    public void send(String user, String text) {
        channel.deliver(user, "ALERT: " + text.toUpperCase());
    }
}

Follow one message through. The caller sends an alert to Maya. The alert shouts the text, passes it to the text message channel, and the channel delivers it. The alert never learns how.

Sequence: the caller sends 'Server is down' to an Alert; the Alert turns it into 'ALERT: SERVER IS DOWN' and calls deliver on the SmsChannel, which sends the text message. The Alert never learns how the message travels. Sequence: the caller sends 'Server is down' to an Alert; the Alert turns it into 'ALERT: SERVER IS DOWN' and calls deliver on the SmsChannel, which sends the text message. The Alert never learns how the message travels.
The alert never learns how.

The caller picks one of each. An alert over text message, and a reminder over email. Any pair, and no new class.

Notification a = new Alert(new SmsChannel());
Notification r = new Reminder(new EmailChannel());

And Slack? One new class, the Slack channel. Every kind can use it straight away. (Naive: three new classes. Bridge: one.)

public class SlackChannel implements Channel {
    @Override
    public void deliver(String user, String message) {
        Slack.post(user, message);
    }
}

Tests get easier too. A fake channel that records its messages can stand in for the real one, and no email goes out.

Anatomy

The pattern has four roles. Notification is the abstraction, and Alert and Reminder are its refined abstractions. Channel is the implementor, and email, text and push are the concrete implementors.

Class diagram of Bridge: Notification (abstraction) holds a Channel (implementor interface with deliver). Alert and Reminder extend Notification. EmailChannel, SmsChannel and PushChannel implement Channel. Class diagram of Bridge: Notification (abstraction) holds a Channel (implementor interface with deliver). Alert and Reminder extend Notification. EmailChannel, SmsChannel and PushChannel implement Channel.
Two hierarchies, joined by one field.

Four choices matter:

  1. Keep the implementor small and basic, like deliver. Don’t copy the abstraction’s methods (sendAlert) into it. refactoring.guru’s description of the pattern says the abstraction “isn’t supposed to do any real work on its own” and relies on the implementation for the low-level work.
  2. The abstraction decides what to say; the implementor decides how to send. If a channel starts choosing the wording, the line has moved.
  3. Usually you pick the channel once, when you build the notification. It’s a field, so you could swap it later, but most designs never do.
  4. Someone has to build the pair. Often a factory (see Abstract Factory) or your dependency injection setup, so the rest of the code never names a channel.

In the JDK: JDBC

The JDK has a well known example, in its database API. Your code uses Connection and Statement. Each database vendor supplies the classes behind them.

try (Connection con = DriverManager.getConnection(url);
     Statement st = con.createStatement()) {
    st.execute("select 1");
}

Connection is an interface in java.sql, and DriverManager attempts to select an appropriate driver from the registered JDBC drivers for the database address you give it (both from the javadoc). Change the address, and the driver changes. Your code stays as it is.

Your code uses the JDK's Connection and Statement interfaces. DriverManager picks a registered driver by database address: the Postgres driver or the MySQL driver, which each supply the classes behind the interfaces. Your code uses the JDK's Connection and Statement interfaces. DriverManager picks a registered driver by database address: the Postgres driver or the MySQL driver, which each supply the classes behind the interfaces.
Your code names the interfaces; the vendor supplies the rest.

That API is often described as a bridge, with the driver interfaces in the implementor role. Write-ups don’t agree on which piece is which, so that’s our reading.

The mix-up: “just an interface”, Adapter and Strategy

Now a common mix-up: Bridge is just an interface. But one interface alone is plain polymorphism. The point is two hierarchies, each free to grow. And “abstraction” here doesn’t mean the Java keyword. It means the high-level layer, which asks for work and never does the low-level work itself.

Bridge looks like Adapter, because both put an object between two sides. But an adapter fixes a mismatch after the fact. A bridge is designed up front, so both sides can vary.

It also looks like Strategy. Both hold an interface in a field. But a strategy swaps one algorithm. A bridge splits a whole hierarchy in two, and is usually fixed when you construct the object. (Because you can replace the object in the field, people mix the two up; the intent and the problem are what tell them apart.)

PatternHolds an interface in a field?PurposeUsually decided
Adapterwraps one classrepair a mismatch that already existsafter the fact
Strategyyesswap one algorithmat run time, as needed
Bridgeyessplit a hierarchy that varies two waysup front, at construction

Same shape, different purpose. Adapter repairs. Strategy swaps. Bridge splits.

When not to use it

When should you skip it? If only one thing varies, you don’t need two hierarchies. Plain subclasses are fine. If the second side will only ever have one implementation, the channel interface is indirection for nothing. Add it when the second one arrives.

A bridge costs an extra interface, and an extra hop on every call. Pay that when you can see two sides growing for their own reasons. Not before. refactoring.guru lists the same cost: it can add unnecessary complexity to a class that is already highly cohesive. And keep it light: the abstraction should do little itself, and the implementor interface should stay small. Otherwise the bridge becomes a new place for tangles.

Decision: do two things vary? If no, use plain subclasses. Does each grow for its own reasons? If no, wait. Does the second side have more than one implementation? If no, wait until the second arrives. If yes, use a bridge. Decision: do two things vary? If no, use plain subclasses. Does each grow for its own reasons? If no, wait. Does the second side have more than one implementation? If no, wait until the second arrives. If yes, use a bridge.
Bridge two dimensions, not one.

Recap

  • When two things both vary, inheritance multiplies the classes.
  • Split them into two hierarchies. The abstraction holds the implementor in a field. That field is the bridge.
  • Three plus three, not three times three. Slack is one new class.
  • It isn’t an adapter or a strategy, and one dimension needs no bridge.
Recap chain: spot two dimensions that vary for different reasons, split them into two hierarchies, join them with a field. Recap chain: spot two dimensions that vary for different reasons, split them into two hierarchies, join them with a field.
Two reasons to change, two hierarchies.

Checklist:

  • Does one hierarchy grow in two independent directions (kind and channel, shape and colour)?
  • Do the two directions change for different reasons, or for different teams?
  • Does the abstraction hold the implementor in a field, and only call its small, basic methods?
  • Is the second side going to have more than one implementation?
  • Could a plain subclass, a strategy or an adapter do the job with less?

Two reasons to change, two hierarchies.

Related lessons: Adapter, Strategy, Abstract Factory, Polymorphism.

Further reading