Publishing a video on a video site is one action for the person who uploads it. Inside the site it is five jobs, done by five different parts of the system. The original file is stored. It is transcoded into smaller versions that play on slow connections. A thumbnail is made. The video is added to the catalogue, so it shows up on the channel page. Then the channel's subscribers are told.
Each of those parts has its own interface, its own errors and its own team. If every piece of code that publishes a video talks to all five, the copies drift apart. Each one runs the steps in a slightly different order, with a slightly different plan for when step three fails.
The Facade pattern puts one simple class in front of a group of subsystems, with one method for the whole job. In this article we build the publishing code twice. The first version has every caller run the steps itself. The second puts a facade in front of the five subsystems. Then we look at what the pattern costs, how it differs from Adapter, and how it comes up in interviews. Every snippet without a Sketch label comes from a project that compiles, and the finished one runs. The Open file button on a snippet shows the whole file.
The publishing we are building
The site has five subsystems. Each is an interface, so a test can swap in a fake:
MediaStorekeeps files by name.Transcoderturns the original into one smaller version, called a rendition, such as 720p.ThumbnailMakermakes the still image shown before the video plays.Cataloguelists the published videos.SubscriberNotifiertells a channel's subscribers about a new video.
Three pieces of code publish videos: the web upload handler, a bulk importer for old videos, and an admin tool that publishes again after a failed upload. They need the same behaviour:
- One call publishes an upload. The original is stored and transcoded into every rendition its height allows. Then it gets a thumbnail and goes into the catalogue, and the channel's subscribers are told.
- A video appears in the catalogue only when every file it points at exists.
- If any step before the catalogue fails, nothing is left behind: no files and no catalogue entry. The caller learns which step failed. The one exception is a catalogue add that went in, or cannot be confirmed, before it failed.
- Once the video is in the catalogue, it stays published even if telling subscribers fails. The caller learns about that failure too.
- A video is published at most once, even when two uploads of it arrive at the same moment, or one upload is sent twice.
- Other tools can still use one subsystem on its own, such as an admin tool that remakes a thumbnail.
The rendition rule is simple: never make a rendition taller than the source, but give every video a 360p version so it plays on any connection.
This figure is worth drawing first in an interview. It shows the order, and it shows the line between steps that must be undone on failure and the one step that must not.
The first version: every caller runs the steps
The obvious way to write this is for each caller to call the subsystems itself. Here is the web upload handler:
public String handle(Upload upload) { String original = "videos/" + upload.videoId() + "/original"; store.put(original, upload.sizeBytes()); try { Map<Resolution, String> renditions = new EnumMap<>(Resolution.class); for (Resolution resolution : Resolution.forSource(upload.sourceHeight())) { String key = "videos/" + upload.videoId() + "/" + resolution.label(); transcoder.transcode(original, resolution, key); renditions.put(resolution, key); } String thumbnail = "videos/" + upload.videoId() + "/thumb.jpg"; thumbnails.makeThumbnail(original, thumbnail); catalogue.add(new CatalogueEntry(upload.videoId(), upload.channelId(), upload.title(), original, renditions, thumbnail)); notifier.notifySubscribers(upload.channelId(), upload.videoId(), upload.title()); return "Published"; } catch (RuntimeException e) { store.delete(original); return "Upload failed, please try again"; } }And here is the bulk importer, written separately, a few months later:
for (Upload upload : uploads) { String folder = "videos/" + upload.videoId() + "/"; store.put(folder + "original", upload.sizeBytes()); Map<Resolution, String> renditions = new EnumMap<>(Resolution.class); for (Resolution resolution : Resolution.forSource(upload.sourceHeight())) { transcoder.transcode(folder + "original", resolution, folder + resolution.label()); renditions.put(resolution, folder + resolution.label()); } catalogue.add(new CatalogueEntry(upload.videoId(), upload.channelId(), upload.title(), folder + "original", renditions, folder + "thumbnail.jpg")); thumbnails.makeThumbnail(folder + "original", folder + "thumbnail.jpg"); notifier.notifySubscribers(upload.channelId(), upload.videoId(), upload.title()); }Each version works on a good day. The trouble is in how they differ:
The order drifted. The importer adds the video to the catalogue before it makes the thumbnail (lines 30 to 32). For a moment the video is listed with a thumbnail that does not exist yet. If the thumbnail fails, it stays that way.
The cleanup drifted. The handler deletes only the original when something fails (line 36), so the renditions stay behind as files nothing points at. The importer cleans up nothing, and one bad row stops the whole import.
A late failure undoes an early success. In the handler, if telling subscribers throws, the catch deletes the original of a video that is already in the catalogue. The uploader is told the upload failed, while the video is live with its original gone.
Two uploads can overwrite each other. Both callers name files videos/VIDEO_ID/…, with nothing that tells one upload from another. Two uploads of one video write to the same names.
Every caller knows all five subsystems. A new step, such as a copyright scan before the catalogue, means editing every caller. A caller that is missed keeps publishing without the scan.
The idea
The pattern works like this:
- One class, the facade, offers one method for the whole job:
publish(upload). - The facade holds the subsystems and calls them in the right order, with one plan for failures.
- Callers depend on the facade alone. The subsystems do not know the facade exists.
- The subsystems stay available. A caller that needs one of them directly can still use it.
The parts have plain names: the facade (VideoPublisher), the subsystems behind it (the five interfaces), and the clients in front of it (the three callers).
Building it, step by step
Step 1: one method, one request, one result
Everything a publish needs arrives as one Upload record, checked when it is created:
public record Upload(String videoId, String channelId, String title, int sourceHeight, long sizeBytes) { private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9-]{1,64}"); private static final int MAX_HEIGHT = 4320; public Upload { requireSafeId(videoId, "videoId"); requireSafeId(channelId, "channelId"); Objects.requireNonNull(title, "title"); if (title.isBlank()) { throw new IllegalArgumentException("title must not be blank"); } if (sourceHeight < 1 || sourceHeight > MAX_HEIGHT) { throw new IllegalArgumentException("sourceHeight must be 1 to " + MAX_HEIGHT + ", got " + sourceHeight); } if (sizeBytes <= 0) { throw new IllegalArgumentException("sizeBytes must be positive, got " + sizeBytes); } } // Ids become parts of file names, so only letters, digits and dashes are allowed. public static boolean isSafeId(String id) { return id != null && SAFE_ID.matcher(id).matches(); } private static void requireSafeId(String id, String name) { Objects.requireNonNull(id, name); if (!isSafeId(id)) { throw new IllegalArgumentException(name + " must be 1 to 64 letters, digits or dashes, got \"" + id + "\""); } }}The ids become parts of file names, so only letters, digits and dashes are allowed. An id like ../other is refused here, before it can reach the file store. A height outside 1 to 4320 and a size of zero or less are refused too. These are programmer errors: the code that builds an Upload has a bug. They throw IllegalArgumentException or NullPointerException, and nothing has been touched yet.
What does publish take?
Five parameters
publish(videoId, channelId, title, height, size) needs no extra class. But three of the five are strings, so swapping two of them compiles. Every caller also checks the values itself, or none of them do.
One Upload recordOur pick
The record checks its values once, in its constructor, so every caller gets the same checks. A new field changes the record and the code that builds one, and the publish signature stays the same.
Step 2: the steps, in order
This is the facade's main method:
public PublishResult publish(Upload upload) { Objects.requireNonNull(upload, "upload"); List<String> written = new ArrayList<>(); PublishException.Step step = PublishException.Step.CHECK; CatalogueEntry entry = null; try { if (catalogue.contains(upload.videoId())) { throw new IllegalStateException("already published"); } // A fresh folder for every attempt, so two attempts never write to the same files. String folder = "videos/" + upload.videoId() + "/" + UUID.randomUUID() + "/"; step = PublishException.Step.STORE; String original = folder + "original"; written.add(original); store.put(original, upload.sizeBytes()); step = PublishException.Step.TRANSCODE; Map<Resolution, String> renditions = new EnumMap<>(Resolution.class); for (Resolution resolution : Resolution.forSource(upload.sourceHeight())) { String key = folder + resolution.label(); written.add(key); transcoder.transcode(original, resolution, key); renditions.put(resolution, key); } step = PublishException.Step.THUMBNAIL; String thumbnail = folder + "thumbnail.jpg"; written.add(thumbnail); thumbnails.makeThumbnail(original, thumbnail); step = PublishException.Step.CATALOGUE; entry = new CatalogueEntry(upload.videoId(), upload.channelId(), upload.title(), original, renditions, thumbnail); catalogue.add(entry); return notifySubscribers(entry); }The marked lines are the five steps, in the order the figure shows. The last one, notifySubscribers, runs only after the try block has finished. Before each group of calls, the method sets step to the step it is about to run. If anything throws, step says where.
The catalogue call, on line 70, is the last of the steps that are undone on failure. By then the original, every rendition and the thumbnail exist, so requirement 2 holds: a listed video never points at a missing file.
The method does not decide which renditions to make. It asks Resolution.forSource, which holds that rule:
// Never taller than the source, but every video gets 360p so it plays on any connection. public static List<Resolution> forSource(int sourceHeight) { List<Resolution> targets = new ArrayList<>(); for (Resolution resolution : values()) { if (resolution.height <= sourceHeight) { targets.add(resolution); } } if (targets.isEmpty()) { targets.add(P360); } return List.copyOf(targets); }A facade that starts making business decisions grows into the one class every change has to touch. Keeping the rule in Resolution keeps publish about order and failures only.
When does a video become visible?
Add it to the catalogue first, marked as processing
The channel page can show "processing" while the renditions are made, which suits long uploads. But every reader of the catalogue then has to handle a video with missing files, and a failed upload leaves an entry to remove.
Add it to the catalogue lastOur pick
A listed video is always complete, and no reader of the catalogue needs to know about half-made videos. The cost is that an upload is invisible until it is fully done. With uploads that take an hour to transcode, the first option is worth its extra states.
Step 3: when a middle step fails
Steps 1 to 4 must leave nothing behind if any of them fails, unless the catalogue entry went in or cannot be confirmed. The catch block and its helpers do that:
} catch (Throwable e) { List<Throwable> problems = new ArrayList<>(); Listing listing = step == PublishException.Step.CATALOGUE ? listingOf(entry, problems) : Listing.ABSENT; if (listing == Listing.LISTED && !(e instanceof Error)) { return notifySubscribers(entry); } if (listing == Listing.ABSENT) { deleteAll(written, problems); } PublishException.Step reported = listing == Listing.UNKNOWN ? PublishException.Step.CATALOGUE_UNCONFIRMED : step; throw failureFor(upload, reported, e, problems); } return notifySubscribers(entry); } // An Error is not ours to wrap, so it goes on unchanged. Anything else becomes a PublishException. private RuntimeException failureFor(Upload upload, PublishException.Step step, Throwable cause, List<Throwable> problems) { Throwable failure = cause instanceof Error ? cause : new PublishException(upload.videoId(), step, cause); for (Throwable problem : problems) { if (problem != failure) { failure.addSuppressed(problem); } } if (failure instanceof Error error) { throw error; } return (PublishException) failure; } try { boolean ours = catalogue.find(entry.videoId()) .map(found -> found.originalKey().equals(entry.originalKey())) .orElse(false); return ours ? Listing.LISTED : Listing.ABSENT; } catch (Throwable lookupFailed) { problems.add(lookupFailed); return Listing.UNKNOWN; // Newest first, and a failed delete is kept for the failure instead of hiding it. private void deleteAll(List<String> keys, List<Throwable> problems) { for (int i = keys.size() - 1; i >= 0; i--) { try { store.delete(keys.get(i)); } catch (Throwable deleteFailed) { problems.add(deleteFailed); } } }Five details make the cleanup reliable:
- Each file name is recorded before the file is written (lines 51, 58 and 65). A store or transcoder can write half a file and then fail, and that half file is deleted too.
MediaStore.deletedoes nothing for a name that was never written, so recording a name early is safe. - Files are deleted newest first, the reverse of the order they were made. The Command pattern page's macro undoes its steps in the same order when a later step fails.
- A failed delete does not hide the real failure.
deleteAllkeeps it in a list of problems (line 123) and carries on with the next file.failureForthen attaches each problem to the failure withaddSuppressed, so the caller still sees why publishing failed. - An add can store the entry and still fail. A catalogue on another machine can save the entry and lose its reply. So after a CATALOGUE failure,
listingOffirst asks whether this attempt's entry is there, by comparing the original's file name, which no other attempt shares. If it is there, the video is live, andpublishgoes on to tell subscribers. If the catalogue cannot answer, the files are kept, because unused files are cheaper than a listed video with no files. The failure then names the stepCATALOGUE_UNCONFIRMED: the video may be live with nobody told, so the caller must look it up, and notify subscribers itself if it is there. - Every kind of failure is cleaned up after. The
catchtakes anyThrowable: anErrorsuch asAssertionError, and a checked exception that a library threw without declaring it. The files are deleted either way. AnErrorthen goes on unchanged (line 87), because it is not a publishing failure to wrap.
For any other failure the caller gets one PublishException. It names the video and the step that failed, and its cause is the exception the subsystem threw. This is a message for a person: the web handler can show "Publishing failed while making the thumbnail, please try again".
Clean up, or keep the files for a retry?
Keep what was made, so a retry can reuse it
A retry after a thumbnail failure would skip the transcoding, which is the slow part. But the retry has to find the files, trust that each one is complete, and know which attempt they came from. An attempt that is never retried leaves files nothing points at.
Delete everything written so farOur pick
A failed publish leaves the system as it was before, so a retry is just another publish. The cost is that a retry transcodes again. The one risk is deleting the files of a video that did go live, which is why a failed catalogue add first asks whether the entry went in.
Five fixed steps read well written out in one method. When steps differ per caller, or there are many more, each step can become an object with run and undo. The facade runs the list and, on a failure, undoes the finished steps in reverse, like the Command page's macro. Across services this shape is called a saga.
Step 4: two uploads of one video
A publish first asks the catalogue whether the video is already there (line 43). That check catches the usual case, an admin publishing a finished video again, before any file is written.
The check alone is not enough. Two uploads of one video can arrive at the same moment, both see "not published", and both start writing. Two things keep that safe. First, the catalogue's add must check and insert in one step. The Catalogue interface says so, because the guarantee rests on it:
public interface Catalogue { boolean contains(String videoId); Optional<CatalogueEntry> find(String videoId); // Must check and add as one step: if the id is already there, it throws IllegalStateException // and adds nothing. This is what lets only one of two uploads of a video in. void add(CatalogueEntry entry);}The in-memory catalogue keeps that promise with putIfAbsent, which adds the entry only if no entry has that id, as one step:
@Override public void add(CatalogueEntry entry) { // putIfAbsent checks and adds in one step, so two uploads of one video cannot both get in. if (entries.putIfAbsent(entry.videoId(), entry) != null) { throw new IllegalStateException("video " + entry.videoId() + " is already in the catalogue"); } }So only one upload gets in. The other upload's add throws, and its catch block cleans up. Second, every publish writes into a folder of its own, named with a fresh random UUID (line 47), so the losing attempt deletes only its own files, never the winner's.
What are the files called?
videos/video id/original
The names are short and easy to find. But two uploads of one video write to the same names, and the loser's cleanup deletes the files of the video that just went live.
videos/video id/upload id from the caller/original
Two different uploads get two folders. But the same upload sent twice, by a double click or a retried request, carries the same id, writes to one folder, and the loser's cleanup again deletes the winner's files.
videos/video id/attempt id/originalOur pick
The facade names each attempt's folder with a random UUID it makes itself, so no two attempts share a folder, whatever the caller sends. The cleanup can only touch its own attempt's files. The cost is a long, unreadable name, and a folder from a lost race that the cleanup removes.
Step 5: after the video is live
Once catalogue.add returns, the video is published. Telling subscribers is the only step left, and its failure must not undo anything:
// The video is live by now, so a notification problem is reported in the result, not thrown. private PublishResult notifySubscribers(CatalogueEntry entry) { try { int told = notifier.notifySubscribers(entry.channelId(), entry.videoId(), entry.title()); if (told < 0) { throw new IllegalStateException("notifier reported " + told + " subscribers"); } return new PublishResult(entry, told, null); } catch (RuntimeException e) { return new PublishResult(entry, 0, e); } }A failure here comes back inside the PublishResult, as the same exception the notifier threw. The caller can show "Published" and retry the notification later. A notifier that reports a negative count is treated as a failure too. An Error still passes through, as it should.
The facade does not log the failure itself, so a logger that throws cannot break a publish that already went live. The caller decides how to record it.
Throw or report a notification failure?
Throw it, like every other failure
One way to fail is simple. But the caller cannot tell "nothing was published" from "published, but nobody was told". The first version's web handler made exactly this mistake and deleted the original of a live video.
Report it in the resultOur pick
PublishResult carries the entry, the number of subscribers told, and the failure if there was one. A PublishException then means the video did not go live, except for the step CATALOGUE_UNCONFIRMED, which tells the caller to look the video up. The cost is a result the caller must look at, or it misses the failed notification.
Step 6: what stays outside the facade
The subsystems are still public interfaces. An admin tool that remakes one blurry thumbnail calls ThumbnailMaker directly, and the facade is not involved. A facade is a convenience for the common job, not a wall. Hiding the subsystems would force every rare job through the facade, and the facade would grow a method for each of them.
The same reasoning keeps the facade small. publish holds the order and the failure plan, and nothing else. The rendition rule lives in Resolution, the input checks in Upload, and the duplicate check in the catalogue. A second job, such as unpublishing a video, can get its own method or its own small facade. Recommendations, comments and analytics do not belong here at all.
May callers still use the subsystems directly?
No: make them package-private behind the facade
Nobody can call the steps in the wrong order. But every job that needs one subsystem now needs a facade method, and the facade grows a method per rare job.
Yes: the facade is the easy path, not the only pathOur pick
The common job goes through the facade, with the right order and cleanup. A tool that needs one subsystem uses it directly. The cost is that a caller can still do the full job by hand and get it wrong, so code review has to send such callers to the facade.
The finished design
Here is one publish that fails at the thumbnail, traced through the objects:
The whole project is below. Click any class name in the code to open that class.
package publish; import java.util.ArrayList;import java.util.EnumMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.UUID; import catalogue.Catalogue;import media.CatalogueEntry;import media.Resolution;import media.Upload;import notification.SubscriberNotifier;import store.MediaStore;import thumbnail.ThumbnailMaker;import transcode.Transcoder; public class VideoPublisher { private enum Listing { LISTED, ABSENT, UNKNOWN } private final MediaStore store; private final Transcoder transcoder; private final ThumbnailMaker thumbnails; private final Catalogue catalogue; private final SubscriberNotifier notifier; public VideoPublisher(MediaStore store, Transcoder transcoder, ThumbnailMaker thumbnails, Catalogue catalogue, SubscriberNotifier notifier) { this.store = Objects.requireNonNull(store, "store"); this.transcoder = Objects.requireNonNull(transcoder, "transcoder"); this.thumbnails = Objects.requireNonNull(thumbnails, "thumbnails"); this.catalogue = Objects.requireNonNull(catalogue, "catalogue"); this.notifier = Objects.requireNonNull(notifier, "notifier"); } public PublishResult publish(Upload upload) { Objects.requireNonNull(upload, "upload"); List<String> written = new ArrayList<>(); PublishException.Step step = PublishException.Step.CHECK; CatalogueEntry entry = null; try { if (catalogue.contains(upload.videoId())) { throw new IllegalStateException("already published"); } // A fresh folder for every attempt, so two attempts never write to the same files. String folder = "videos/" + upload.videoId() + "/" + UUID.randomUUID() + "/"; step = PublishException.Step.STORE; String original = folder + "original"; written.add(original); store.put(original, upload.sizeBytes()); step = PublishException.Step.TRANSCODE; Map<Resolution, String> renditions = new EnumMap<>(Resolution.class); for (Resolution resolution : Resolution.forSource(upload.sourceHeight())) { String key = folder + resolution.label(); written.add(key); transcoder.transcode(original, resolution, key); renditions.put(resolution, key); } step = PublishException.Step.THUMBNAIL; String thumbnail = folder + "thumbnail.jpg"; written.add(thumbnail); thumbnails.makeThumbnail(original, thumbnail); step = PublishException.Step.CATALOGUE; entry = new CatalogueEntry(upload.videoId(), upload.channelId(), upload.title(), original, renditions, thumbnail); catalogue.add(entry); } catch (Throwable e) { List<Throwable> problems = new ArrayList<>(); Listing listing = step == PublishException.Step.CATALOGUE ? listingOf(entry, problems) : Listing.ABSENT; if (listing == Listing.LISTED && !(e instanceof Error)) { return notifySubscribers(entry); } if (listing == Listing.ABSENT) { deleteAll(written, problems); } PublishException.Step reported = listing == Listing.UNKNOWN ? PublishException.Step.CATALOGUE_UNCONFIRMED : step; throw failureFor(upload, reported, e, problems); } return notifySubscribers(entry); } // An Error is not ours to wrap, so it goes on unchanged. Anything else becomes a PublishException. private RuntimeException failureFor(Upload upload, PublishException.Step step, Throwable cause, List<Throwable> problems) { Throwable failure = cause instanceof Error ? cause : new PublishException(upload.videoId(), step, cause); for (Throwable problem : problems) { if (problem != failure) { failure.addSuppressed(problem); } } if (failure instanceof Error error) { throw error; } return (PublishException) failure; } // An add can store the entry and still fail. Deleting a live video's files would be worse // than leaving unused ones, so files are deleted only when the entry is known to be absent. private Listing listingOf(CatalogueEntry entry, List<Throwable> problems) { if (entry == null) { return Listing.ABSENT; } try { boolean ours = catalogue.find(entry.videoId()) .map(found -> found.originalKey().equals(entry.originalKey())) .orElse(false); return ours ? Listing.LISTED : Listing.ABSENT; } catch (Throwable lookupFailed) { problems.add(lookupFailed); return Listing.UNKNOWN; } } // Newest first, and a failed delete is kept for the failure instead of hiding it. private void deleteAll(List<String> keys, List<Throwable> problems) { for (int i = keys.size() - 1; i >= 0; i--) { try { store.delete(keys.get(i)); } catch (Throwable deleteFailed) { problems.add(deleteFailed); } } } // The video is live by now, so a notification problem is reported in the result, not thrown. private PublishResult notifySubscribers(CatalogueEntry entry) { try { int told = notifier.notifySubscribers(entry.channelId(), entry.videoId(), entry.title()); if (told < 0) { throw new IllegalStateException("notifier reported " + told + " subscribers"); } return new PublishResult(entry, told, null); } catch (RuntimeException e) { return new PublishResult(entry, 0, e); } }}The demo in demo/Main.java uses an in-memory store and catalogue, and small fakes for the other three subsystems. It runs seven steps:
1. A 1080p upload live: v-1 at [360p, 720p, 1080p], told 3 subscribers files in its attempt folder: [1080p, 360p, 720p, original, thumbnail.jpg] 2. A 480p upload live: v-2 at [360p], told 3 subscribers 3. The thumbnail service is down refused: Publishing v-3 failed at THUMBNAIL: thumbnail service timed out files left: [], in catalogue: false 4. The push service is down live: v-4 at [360p, 720p], notification failed: push service unavailable 5. The same video again refused: Publishing v-1 failed at CHECK: already published 6. An admin tool remakes one thumbnail, without the facade done, and v-1 is still published: true 7. The same upload sent twice at the same moment published 1, refused 1, files left 4 from 1 attempt
Follow the numbers. The 1080p upload gets three renditions, and its five files share one attempt folder. The 480p upload gets 360p only. With the thumbnail service down, upload 3 is refused at THUMBNAIL and leaves no files and no catalogue entry. With the push service down, upload 4 is still live, and the result reports the failed notification. Publishing v-1 again is refused at CHECK, before any file is written. The admin tool remakes a thumbnail without the facade. The same upload sent twice at the same moment ends with one published and one refused, and only the winning attempt's four files remain.
What it costs
The facade adds one class and one more call between a caller and the work. That is cheap. The real costs are elsewhere:
- One policy for every caller. Every caller gets catalogue-last and full cleanup. A caller that needs a different order has to go around the facade, and then it is back to doing the steps by hand.
- Growth. The facade is the obvious place to put each new feature that touches videos. Without care, it collects unpublish, re-transcode, replace thumbnail and edit title, and becomes the class every change touches.
When a facade is too much
A facade earns its place when several callers do the same multi-step job. A caller that needs one call can make it directly:
// A nightly job that only refreshes thumbnails needs no facade.for (CatalogueEntry entry : entriesWithOldThumbnails) { thumbnails.makeThumbnail(entry.originalKey(), entry.thumbnailKey());}We would not add one in two more cases:
- One subsystem. A class that only forwards to one other class adds a name and nothing else.
- No shared order or failure plan. If the steps are independent and any caller may run any subset, there is nothing for the facade to own.
Facade or Adapter?
Both put a class in front of other code, and both make that code easier to call. They solve different problems.
| Facade | Adapter | |
|---|---|---|
| What it does | Simplifies: one call for a job that needs several subsystems | Translates: makes one class fit an interface that already exists |
| How many classes behind it | Several | Usually one |
| Whose interface it offers | A new one, designed for the job | One the code already expects |
| Example in these pages | VideoPublisher over five subsystems | An SMS vendor client behind our SmsSender |
The Adapter pattern page puts it in one line: a facade simplifies, and an adapter translates.
Mediator is the other name that comes up here. A mediator sits between objects that would otherwise talk to each other, hears what each one reports, and decides what the others should do. A facade is one-way. Callers talk to the facade, the facade talks to the subsystems, and the subsystems never talk back to it.
In an interview
A facade sits inside most full design questions, even when nobody names it. In the Parking Lot design, ParkingLot plays the facade role for park and leave, over floors, an allocation rule, a pricing rule and payments, though it also owns the ticket state. A booking service in a movie ticket design or a checkout service in a shop does the same. The question rarely says "use a facade". It says "design the service that does X", and X needs several parts in order.
We suggest presenting it in this order:
- List the subsystems and draw the order of calls. Mark which steps must be undone on failure and which come after the point of no return.
- Write the facade's one method, with the order and the cleanup.
- Say what stays out of it: the business rules, the rare jobs, and direct access to the subsystems.
Mistakes to avoid:
- A facade with no cleanup. It calls five subsystems and lets the first exception escape, leaving files from steps 1 and 2 behind.
- Undoing a step that cannot be undone. Telling subscribers, sending an email and charging a card cannot be taken back. Put them after the point of no return, and report their failures.
- Business rules inside the facade.
Resolutiondecides which renditions to make, notpublish. - A god facade. One class with every operation on videos is no longer a facade. Split it by job.
- Hiding the subsystems. Tools that need one subsystem should not have to go through a method written for another job.
Summary
- Use a facade when several callers do the same job that needs several subsystems in a fixed order.
- The facade owns the order and the failure plan. Business rules stay in their own classes.
- Record each name before writing it, delete newest first on failure, and attach a failed delete instead of throwing it.
- Steps after the point of no return report their failures in the result. They are never undone.
- The subsystems stay available. The facade is the easy path, not the only path.
- A facade simplifies several classes. An adapter translates one.