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.
A sequence every client must remember is a sequence some client will get wrong.
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.
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.
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.
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 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.
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.
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.
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.
Files.readStringJava 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 and adapter both wrap other classes, so they get mixed up all the time. The difference is what they wrap, and why.
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.”
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 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.
A planner, not a chef.
Files.readString works the same way.Checklist:
One front door. The back doors stay open.
Related lessons: Adapter, Large Class, Decorator, Encapsulation.
Files.readString javadoc.