Patterns for structure · Chapter 12

Facade pattern

Give a tangle of classes one simple front door that knows the steps and their order. Java and Python checkout code, failure handling, and how Facade differs from Adapter, Mediator and an API gateway.

BeginnerInterview priority: Medium35 min
On this page
  1. The problem: every caller repeats the same dance
  2. The idea: one simple front door
  3. Build it step by step
  4. Facades you already use
  5. Facade, Adapter, Mediator: how they differ
  6. When not to use it
  7. In the interview
  8. Quiz

The problem: every caller repeats the same dance

To watch a film on a home theatre, someone has to switch on the amplifier, choose its input, dim the lights, lower the screen, start the projector and press play, in that order. Get the order wrong (play before the projector warms up) and it misbehaves.

Five objects, six calls, in the right order

  1. To watch a movie on a home theatre, someone has to: turn on the amplifier, pick the input, dim the lights, lower the screen, start the projector and press play. Five objects, six calls, in the right order.

Software has the same shape. Placing an order in a shop means: reserve stock, charge the card, book a courier, send a confirmation email. If the web app, the mobile API and the kiosk each do those four calls themselves:

  • The sequence is copied three times, and the copies drift: the kiosk forgets to release stock when the card is declined.
  • Every caller depends on four classes. Change the payment API and you edit three callers.
  • New developers must learn the whole subsystem just to place one order.

The idea: one simple front door

A facade is a class with a small, task-shaped interface (placeOrder(), watchMovie()) that calls the classes behind it, the subsystem, in the right order. Callers talk to one object. The facade adds no new capability; it packages existing ones into the operations people actually need.

The facade knows the steps and the order

  1. A facade is one simple front door: HomeTheater.watchMovie(). It knows the steps and the order, and calls the parts behind it, called the subsystem. The caller talks to one object.
RoleIn the checkout exampleResponsibility
FacadeOrderServiceOffers simple, task-level methods and orchestrates the subsystem
Subsystem classesInventory, Payments, Shipping, MailerDo the real work; they don't know the facade exists
ClientsWeb controller, mobile API, kioskCall the facade instead of the subsystem

Build it step by step

1. Leave the subsystem alone. Each class keeps its own detailed API.

2. Give the facade the parts through its constructor, so tests can pass in fakes.

3. Write one method per task that calls the parts in order.

4. Handle failure in one place. This is where a facade earns its keep: if payment is declined, release the stock; if shipping fails after payment, refund and release. A failed confirmation email should not cancel a paid order.

import java.util.*;

// ---- The subsystem: four classes, each with its own API ----
class Inventory {
    private final Map<String, Integer> stock;
    Inventory(Map<String, Integer> initial) { stock = new HashMap<>(initial); }
    boolean reserve(String sku, int qty) {
        int have = stock.getOrDefault(sku, 0);
        if (have < qty) return false;
        stock.put(sku, have - qty);
        return true;
    }
    void release(String sku, int qty) { stock.merge(sku, qty, Integer::sum); }
}

class PaymentDeclinedException extends Exception {
    PaymentDeclinedException(String msg) { super(msg); }
}

class Payments {
    String charge(String card, int cents) throws PaymentDeclinedException {
        if (card.startsWith("0")) throw new PaymentDeclinedException("card declined");
        return "pay-" + UUID.randomUUID().toString().substring(0, 8);
    }
    void refund(String paymentId) { System.out.println("  refunded " + paymentId); }
}

class Shipping {
    String book(String sku, int qty, String email) {
        if (email.endsWith(".invalid")) throw new IllegalStateException("no courier");
        return "ship-" + sku + "-" + qty;
    }
}

class Mailer {
    void send(String to, String text) { System.out.println("  email to " + to + ": " + text); }
}

// ---- The facade: one method that knows the steps and their order ----
record OrderResult(boolean ok, String message) {}

class OrderService {
    private static final int PRICE_CENTS = 1200;
    private final Inventory inventory;
    private final Payments payments;
    private final Shipping shipping;
    private final Mailer mailer;

    OrderService(Inventory inventory, Payments payments, Shipping shipping, Mailer mailer) {
        this.inventory = inventory;
        this.payments = payments;
        this.shipping = shipping;
        this.mailer = mailer;
    }

    public OrderResult placeOrder(String email, String sku, int qty, String card) {
        if (!inventory.reserve(sku, qty))                         // 1. reserve stock
            return new OrderResult(false, "out of stock");
        String paymentId;
        try {
            paymentId = payments.charge(card, PRICE_CENTS * qty); // 2. take payment
        } catch (PaymentDeclinedException e) {
            inventory.release(sku, qty);                          // undo step 1
            return new OrderResult(false, e.getMessage());
        }
        String shipmentId;
        try {
            shipmentId = shipping.book(sku, qty, email);          // 3. book shipping
        } catch (RuntimeException e) {
            payments.refund(paymentId);                           // undo step 2
            inventory.release(sku, qty);                          // undo step 1
            return new OrderResult(false, "shipping unavailable");
        }
        try {
            mailer.send(email, "Order confirmed, shipment " + shipmentId);  // 4. confirm
        } catch (RuntimeException e) {
            System.out.println("  email failed, will retry later");  // the order still stands
        }
        return new OrderResult(true, paymentId + " / " + shipmentId);
    }
}

public class Main {
    public static void main(String[] args) {
        OrderService orders = new OrderService(
            new Inventory(Map.of("mug", 3)), new Payments(), new Shipping(), new Mailer());

        System.out.println(orders.placeOrder("ana@example.com", "mug", 2, "4242"));
        System.out.println(orders.placeOrder("bo@example.com", "mug", 1, "0000"));  // declined
        System.out.println(orders.placeOrder("cy@example.com", "mug", 5, "4242"));  // no stock
        System.out.println(orders.placeOrder("dee@x.invalid", "mug", 1, "4242"));  // no courier
    }
}

The client code is now one line per order. All three front ends share the same sequence and the same clean-up rules, and a change to Payments touches one class: the facade.

The parts stay available

A facade is a convenience, not a wall. The admin tool that needs to refund a single payment can still call Payments.refund() directly. This is the main difference from strict layering: the facade lowers coupling (how many classes a caller depends on) for the common path, without forbidding the detailed path.

Most callers use the front door; power users can still go round it

  1. The facade doesn’t lock the parts away. A power user can still call lights.dim() directly. It just gives most callers an easy path, and lowers coupling: callers depend on one class instead of five.

It also helps with the Law of Demeter ("talk only to your immediate friends"): a controller calling orders.placeOrder(...) is better than one calling orders.payments().gateway().charge(...).

Facades you already use

FacadeWhat it hides
SLF4J (Simple Logging Facade for Java)Logback, Log4j 2 or java.util.logging behind one Logger API
Spring's JdbcTemplateGetting a connection, preparing statements, iterating result sets, closing everything, translating SQLException
Python's requests.get(url)Connection pools, redirects, encoding and retries in urllib3
Python's subprocess.run() and shutil.copytree()Popen pipes and waits; walking directories and copying files and metadata
A service layer (OrderService, BookingService)The domain objects and repositories behind each use case

A service class is a facade over the order subsystem

  1. In real apps, a facade often looks like OrderService.placeOrder(): it checks stock, takes payment, books shipping and sends the email. The web app, the phone app and the kiosk each call one method instead of repeating the whole dance.

At the system level the same idea appears as an API gateway or a backend for frontend (BFF): one endpoint that calls several microservices so the mobile app makes one request instead of five. See monolith vs microservices.

Facade, Adapter, Mediator: how they differ

FacadeAdapterMediator
WrapsMany classes (a subsystem)One classSits between peer objects
InterfaceNew, simpler, task-shapedThe specific interface a client already expectsPeers talk to the mediator instead of each other
DirectionOne way: client → facade → parts; parts don't know the facadeOne wayTwo way: parts call the mediator and it calls them
IntentMake common tasks easyMake an incompatible class fitUntangle many-to-many communication
ExampleOrderService.placeOrder()InputStreamReaderAn air-traffic controller; a chat room relaying messages

A decorator or proxy keeps the same interface as one wrapped object, so neither is easily confused with a facade once you look at the interface. A facade can, however, use an adapter for one of its parts (wrapping a vendor shipping API) and still be a facade to its callers.

When not to use it

In the interview

Your turn: a video upload facade

Uploading a video involves: Storage.put(bytes) returns a key; Transcoder.submit(key, profiles) returns a job id; Thumbnailer.create(key) returns an image key; Catalog.save(meta) makes the video visible; Notifier.notifyFollowers(userId, videoId). Design VideoService.upload(userId, title, bytes). Which steps must succeed for the upload to count, and what do you do when each one fails?

Compare with our answer
class VideoService {
    // storage, transcoder, thumbnailer, catalog, notifier injected in the constructor
    public String upload(String userId, String title, byte[] bytes) {
        String key = storage.put(bytes);                       // must succeed
        try {
            String job = transcoder.submit(key, List.of("480p", "1080p"));
            String thumb = thumbnailer.tryCreate(key).orElse(DEFAULT_THUMB);  // optional
            String videoId = catalog.save(new VideoMeta(userId, title, key, thumb, job, Status.PROCESSING));
            try { notifier.notifyFollowers(userId, videoId); } catch (RuntimeException e) { log.warn("notify failed", e); }
            return videoId;
        } catch (RuntimeException e) {
            storage.delete(key);                               // don't leave orphan files
            throw new UploadFailedException(e);
        }
    }
}
class VideoService:
    # storage, transcoder, thumbnailer, catalog, notifier injected in __init__
    def upload(self, user_id: str, title: str, data: bytes) -> str:
        key = self._storage.put(data)                         # must succeed
        try:
            job = self._transcoder.submit(key, ["480p", "1080p"])
            thumb = self._thumbnailer.try_create(key) or DEFAULT_THUMB   # optional
            video_id = self._catalog.save(VideoMeta(user_id, title, key, thumb, job, "processing"))
            try:
                self._notifier.notify_followers(user_id, video_id)
            except Exception:
                log.warning("notify failed", exc_info=True)
            return video_id
        except Exception as e:
            self._storage.delete(key)                         # don't leave orphan files
            raise UploadFailed() from e

A strong answer mentions: storage, transcoding job and catalog entry are required; thumbnail and notification are best-effort · compensation for required failures (delete the stored file) · the catalog entry saved with a "processing" status, since transcoding finishes later · notifications sent asynchronously or retried, never failing the upload · the facade's constructor taking the parts so tests can fake them.

Your turn: the requirement changes

Six months later OrderService has 2,400 lines: checkout, returns, order history, admin refunds, gift cards and loyalty points, with 14 constructor parameters. Tests take minutes to set up. What do you do, and how do you avoid breaking the three front ends that call it?

Compare with our answer

A strong answer mentions: split by use case into several small facades (CheckoutService, ReturnsService, OrderHistoryService, LoyaltyService) · each with only the dependencies it needs · moving one use case at a time, with the old OrderService methods delegating to the new classes until callers move · shared steps (like refunds) going into a subsystem class, not copied · the constructor size as a signal of too many responsibilities.

Facade on one page
  • Intent: one simple, task-shaped entry point to a subsystem of many classes.
  • Roles: facade (orchestrates) · subsystem classes (unaware of it) · clients.
  • Wins: no copied call sequences; callers depend on one class; failure handling in one place.
  • Not a wall: the parts remain usable directly for unusual needs.
  • Real ones: SLF4J, JdbcTemplate, requests, subprocess.run, service-layer classes, API gateways and BFFs.
  • Not Adapter (one class, expected interface) and not Mediator (two-way, between peers).
  • Watch for: god facades (split by use case), fake atomicity across services (compensate, record status, sagas), hidden latency.
Interactive labPractise it: wire up the home theatre behind one buttonOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. A web app, a mobile API and an admin tool each run the same five calls to create a user account, and they have started to differ in how they handle failures. What is the best fix?

2. A team says, "Now that we have OrderService, nobody may call Payments directly." What is wrong with treating the facade that way?

3. placeOrder() charges the card, then the process crashes before booking shipping. The catch block that refunds never ran. What is the most robust fix?

4. Which statement best separates Facade from Mediator?

5. An OrderService facade has grown to 40 methods and 14 constructor dependencies. What does that most likely indicate?

6. A mobile app makes five API calls to render its home screen and is slow on poor networks. Which system-level facade helps most?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.