# FacadePublishing 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.

{{< lesson-video youtube="vbZA8ozqd4I" title="Facade" >}}

## Six calls, five classes

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

```mermaid {alt="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." caption="Three clients, five classes, one order to remember."}
flowchart LR
  W["web uploader"] -->|6 calls| S["AudioEncoder, TagWriter,<br/>Storage, Feed, Notifier"]
  C["CLI"] -->|6 calls| S
  K["scheduler"] -->|"6 calls, wrong order"| S
  S --> X["announced before upload:<br/>dead link"]
  class S muted
  class K,X bad
```

## 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**.

```mermaid {alt="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." caption="One call to the planner; the vendors are still there."}
flowchart LR
  C["couple (client)"] -->|date, budget| P["planner (facade)"]
  P -->|1| V["venue"]
  P -->|2| CA["caterer"]
  P -->|3| F["florist"]
  P -->|4| B["band"]
  P -->|5| PH["photographer"]
  C -. "still free to call" .-> F
  class P c6
```

## 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.

```java
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.

```mermaid {alt="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." caption="One new step, three edits."}
flowchart LR
  T["new step:<br/>transcripts.attach"] --> W["web uploader"]
  T --> C["CLI"]
  T --> K["scheduler"]
  class T hl
  class W,C,K warn
```

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.

```java
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`.

```java
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.

```mermaid {alt="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." caption="The order lives in one place."}
sequenceDiagram
  participant K as Scheduler
  participant P as EpisodePublisher
  participant S as Subsystem
  K->>P: publish(episode, wav)
  P->>S: encode, write tags
  P->>S: upload
  P->>S: addItem, publish feed
  P->>S: announce (last)
  P-->>K: url
```

## 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.

```mermaid {alt="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." caption="Three roles, and a back door."}
classDiagram
  class EpisodePublisher {
    +publish(episode, wav) URI
  }
  WebUploader --> EpisodePublisher
  Cli --> EpisodePublisher
  Scheduler --> EpisodePublisher
  EpisodePublisher --> AudioEncoder
  EpisodePublisher --> TagWriter
  EpisodePublisher --> Storage
  EpisodePublisher --> Feed
  EpisodePublisher --> Notifier
  Editor ..> TagWriter : back door
  Editor ..> Storage : 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.

```java
// 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.

```java
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").

```java
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](/patterns/adapter-pattern/) 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."

```mermaid {alt="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." caption="An adapter fits; a facade simplifies."}
flowchart LR
  subgraph AD["Adapter"]
    direction TB
    J["ThermoJet"] --> R["ReceiptPrinter<br/>(an interface you have)"]
  end
  subgraph FA["Facade"]
    direction TB
    P["EpisodePublisher<br/>(a new, simpler one)"] --> S["five subsystem classes"]
    P --> A["an adapter<br/>for one awkward part"]
  end
  AD ~~~ FA
  class J c1
  class R c6
  class P c6
  class A c5
  class S muted
```

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](/code-smells/large-class/)). A planner who starts cooking
and playing in the band isn't planning any more.

```mermaid {alt="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." caption="A planner, not a chef."}
flowchart TD
  Q1{"One simple class?"} -->|yes| A1["no facade"]
  Q1 -->|no| Q2{"Clients repeat the<br/>same sequence?"}
  Q2 -->|no| A2["let them use the parts"]
  Q2 -->|yes| A3["one facade method<br/>for that task"]
  A3 --> Q3{"Rules creeping in?"}
  Q3 -->|yes| A4["move them back to the parts"]
  class A3 good
  class A4 warn
```

> **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.

```mermaid {alt="Recap chain: find the repeated sequence, give it one method, keep the parts public, keep the facade a coordinator." caption="One front door. The back doors stay open."}
flowchart LR
  A["find the repeated sequence"] --> B["one method for the task"] --> C["parts stay public"] --> D["a coordinator only"]
  class B c6
  class D good
```

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](/patterns/adapter-pattern/), [Large Class](/code-smells/large-class/),
[Decorator](/patterns/decorator-pattern/), [Encapsulation](/fundamentals/encapsulation/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Facade.
- refactoring.guru: [Facade](https://refactoring.guru/design-patterns/facade).
- [`Files.readString`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)) javadoc.
- [SLF4J user manual](https://www.slf4j.org/manual.html).
