Facade

November 25, 20268 minutes

Publishing a podcast episode takes six calls to five classes, and three clients repeat them. Learn how a Facade gives the common task one front door while the back doors stay open.

Publishing one podcast episode takes six calls to five classes. Encode the audio, tag it, upload it, add it to the feed, publish the feed, and announce it. The web uploader makes those six calls. So does the command-line tool. And so does the scheduler, which publishes episodes at six in the morning. Last week the scheduler’s copy announced the episode before uploading it. Every listener who tapped the link got a dead page. So who else knows the six steps, and the order they go in? There’s a better way, and it’s called the Facade 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.

Six calls, five classes

A sequence every client must remember is a sequence some client will get wrong.

Three clients (web uploader, CLI, scheduler) each call five subsystem classes in a six-step order; the scheduler's copy announces before uploading, so listeners get a dead link. Three clients (web uploader, CLI, scheduler) each call five subsystem classes in a six-step order; the scheduler's copy announces before uploading, so listeners get a dead link.
Three clients, five classes, one order to remember.

A wedding planner

Think of a wedding. You need a venue, a caterer, a florist, a band and a photographer. And the order matters. The caterer needs the venue’s address first. You could phone all five yourselves, and keep track of who needs what. Or you hire a planner.

You give her the date and the budget. She calls everyone, in the right order. She doesn’t cook, and she doesn’t play in the band. She knows who to call, and when. And if you care about the flowers, you can still phone the florist yourself.

In code, the vendors are the subsystem, classes that do the real work. The planner is the facade. And the couple is the client.

The couple calls the planner once with the date and budget; the planner calls the venue, caterer, florist, band and photographer in order; a dashed line shows the couple can still call the florist directly. The couple calls the planner once with the date and budget; the planner calls the venue, caterer, florist, band and photographer in order; a dashed line shows the couple can still call the florist directly.
One call to the planner; the vendors are still there.

The obvious version: make the calls yourself

Here’s the web uploader’s code. Encode the recording, write the title and the cover art, and upload the file. Then add the episode to the feed, publish the feed, and announce it, with the link.

Path mp3 = encoder.encode(wav);
tags.write(mp3, episode.title(), episode.cover());
URI url = storage.upload(mp3);
feed.addItem(episode, url);
feed.publish();
notifier.announce(episode, url);

With one client, this is good code. Six lines you can read top to bottom, and each class does one job. And it’s honest. Nothing hides behind another layer, so when something fails, you can see exactly which call it was.

Why it breaks

But there are three clients. The command-line tool and the scheduler paste the same six lines. Now three places know all five classes, and the order. The scheduler’s copy is the one that went wrong. Announce ended up above upload, and nothing stopped it.

Then the team adds a step. Every episode gets a transcript, attached before the upload: transcripts.attach(episode, mp3);. That line has to go into three places, in the right spot each time.

One new step, transcripts.attach, must be inserted between tag and upload in each of the three clients: the web uploader, the CLI and the scheduler. One new step, transcripts.attach, must be inserted between tag and upload in each of the three clients: the web uploader, the CLI and the scheduler.
One new step, three edits.

And testing any client now means setting up all five parts. It’s the couple, both sets of parents and the best friend, all phoning the caterer. Five classes, three clients, fifteen lines of coupling.

The key idea: one door for the common task

The clients don’t need five classes. They need one task: publish this episode. So give that task one method, on one class that knows the parts and the order. The clients call it, and nothing else.

The Gang of Four describe it (Design Patterns, 1994):

“Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.”

The five classes stay exactly as they were, and they stay public. A client that needs more can still reach them.

One front door. The back doors stay open.

Building it

Here’s the facade. EpisodePublisher holds the five parts, and they come in through its constructor. It has one method, publish. It makes the same six calls, in the right order, and hands back the link.

public class EpisodePublisher {
    private final AudioEncoder encoder;
    private final TagWriter tags;
    private final Storage storage;
    private final Feed feed;
    private final Notifier notifier;

    // constructor: takes the five parts and stores them

    public URI publish(Episode episode, Path wav) {
        Path mp3 = encoder.encode(wav);
        tags.write(mp3, episode.title(), episode.cover());
        URI url = storage.upload(mp3);
        feed.addItem(episode, url);
        feed.publish();
        notifier.announce(episode, url);
        return url;
    }
}

Each client shrinks to one line. The uploader, the command-line tool and the scheduler all call publish.

URI url = publisher.publish(episode, wav);

And the transcript step? It goes in once, between the tags and the upload, and all three clients get it. Testing a client gets easier too. A fake publisher has one method to fake, not five classes to set up.

Follow one episode through. The scheduler calls publish once, at six in the morning. The facade encodes, tags, uploads, updates the feed, and only then announces. The link works.

Sequence: the scheduler calls publish on EpisodePublisher; the facade calls encode, write tags, upload, addItem and publish on the feed, and only then announce, and returns the URL. Sequence: the scheduler calls publish on EpisodePublisher; the facade calls encode, write tags, upload, addItem and publish on the feed, and only then announce, and returns the URL.
The order lives in one place.

Anatomy and back doors

The pattern has three roles. The facade knows which part handles what, and passes each request on. The subsystem classes do the work. And the clients call the facade. The parts don’t know the facade exists. They keep no reference to it (GoF), so they can be used, and tested, on their own.

Class diagram: three clients (WebUploader, Cli, Scheduler) use EpisodePublisher (facade), which holds AudioEncoder, TagWriter, Storage, Feed and Notifier. An Editor uses TagWriter and Storage directly, past the facade. Class diagram: three clients (WebUploader, Cli, Scheduler) use EpisodePublisher (facade), which holds AudioEncoder, TagWriter, Storage, Feed and Notifier. An Editor uses TagWriter and Storage directly, past the facade.
Three roles, and a back door.

A common belief is that a facade must hide the parts. It doesn’t have to. The Gang of Four say:

“It doesn’t prevent applications from using subsystem classes if they need to.”

An editor fixing one cover image goes straight to the tag writer and the storage. That’s a back door, and it’s fine.

// fixing one cover image: straight to the parts
tags.write(mp3, episode.title(), newCover);
storage.upload(mp3);

The facade offers less than the parts, on purpose (refactoring.guru: a facade “might provide limited functionality in comparison to working with the subsystem directly”). When a second common task shows up, like archiving old episodes, it can get its own facade, such as an EpisodeArchiver.

In the JDK: Files.readString

Java has one you’ve probably used. Before Java 11, reading a text file into a string looked like this. A buffered reader, over an input stream reader, over a file input stream. A loop over the lines, and a try block to close it all.

StringBuilder text = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(
        new FileInputStream(file), StandardCharsets.UTF_8))) {
    String line;
    while ((line = in.readLine()) != null) {
        text.append(line).append('\n');
    }
}

Since Java 11, Files.readString does the common case in one call. It decodes the text as UTF-8, and it closes the file for you (the javadoc: “The method ensures that the file is closed when all content have been read or an I/O error, or other runtime exception, is thrown”).

String text = Files.readString(path);

It works like a facade: one simple call in front of streams, decoders and buffers. (The two versions aren’t byte-for-byte equal: the loop rewrites every line ending as \n.) And the back doors stay open. For a file of several gigabytes, readString can run out of memory (the javadoc warns of an OutOfMemoryError “if the file is extremely large, for example larger than 2GB”). A buffered reader, from Files.newBufferedReader(path), still lets you go line by line.

Facade or adapter?

Facade and adapter both wrap other classes, so they get mixed up all the time. The difference is what they wrap, and why.

  • An adapter makes one existing class fit an interface you already have. It’s a translator: it makes one conversation work.
  • A facade invents a new, simpler interface, over many classes. It’s the planner who turns five calls into one.
  • A mediator looks similar, but there the parts talk to each other through it, and they know it’s there. A facade’s parts never call it.

refactoring.guru sums it up: “Facade defines a new interface for existing objects, whereas Adapter tries to make the existing interface usable. Adapter usually wraps just one object, while Facade works with an entire subsystem of objects.”

Side by side: an adapter fits one class (ThermoJet) to an interface you already have (ReceiptPrinter); a facade puts one new, simpler interface (EpisodePublisher) in front of five classes, and may use an adapter behind it for one awkward part. Side by side: an adapter fits one class (ThermoJet) to an interface you already have (ReceiptPrinter); a facade puts one new, simpler interface (EpisodePublisher) in front of five classes, and may use an adapter behind it for one awkward part.
An adapter fits; a facade simplifies.

So if you’re making one class fit, it’s an adapter. If you’re making many classes easy to use, it’s a facade. A facade can even use an adapter behind it, for one awkward part. (A real-world pair: SLF4J calls itself “a simple facade or abstraction for various logging frameworks”, and plugs into each backend through a provider.)

When not to use it

When should you skip it? If the subsystem is one class with a clear interface, there’s nothing to simplify. If every client needs a different mix of steps, one facade grows a method per client. Split it, or let those clients use the parts.

And keep it a coordinator. Pricing, permissions, the rules for premium episodes: once the facade holds those, it’s a god class (refactoring.guru: “A facade can become a god object coupled to all classes of an app”; see Large Class). A planner who starts cooking and playing in the band isn’t planning any more.

Decision: is the subsystem one simple class? No facade needed. Do clients repeat the same multi-step sequence? Add a facade for that task. Does every client need a different mix? Split into several facades or let them use the parts. Is business logic moving into the facade? Move it back out. Decision: is the subsystem one simple class? No facade needed. Do clients repeat the same multi-step sequence? Add a facade for that task. Does every client need a different mix? Split into several facades or let them use the parts. Is business logic moving into the facade? Move it back out.
A planner, not a chef.

A planner, not a chef.

Recap

  • A sequence that every client repeats is a sequence some client will get wrong.
  • Give the common task one method, on a class that knows the parts and the order.
  • The parts stay public, and Files.readString works the same way.
  • It isn’t an adapter, which fits one class to an interface you have.
  • Keep it a coordinator.
Recap chain: find the repeated sequence, give it one method, keep the parts public, keep the facade a coordinator. Recap chain: find the repeated sequence, give it one method, keep the parts public, keep the facade a coordinator.
One front door. The back doors stay open.

Checklist:

  • Do several clients repeat the same multi-step sequence over several classes?
  • Does the order matter, and has someone got it wrong?
  • Does the facade only delegate, with no business rules of its own?
  • Can a client that needs more still use the parts directly?
  • Is the facade growing a method per client? (Then split it.)

One front door. The back doors stay open.

Related lessons: Adapter, Large Class, Decorator, Encapsulation.

Further reading