On this page

Facade

A facade is a class (or module) that offers a few simple, task-shaped methods in front of a subsystem made of many classes. Instead of every caller learning that checkout means "reserve stock, authorise the card, book a courier, capture the payment, send an email, and undo the right steps if any of that fails", callers call checkout(...) and the facade does the choreography.

The structural patterns overview introduces Facade with a short example. This page goes further: the problem it solves in real code, a full implementation with failure handling in three languages, the facades hiding in the standard libraries you use every day, how Facade differs from Adapter, Mediator and an API gateway, and the most common way it goes wrong, which is growing into a god object.

Intent

Provide a single, simplified interface to a set of interfaces in a subsystem, so that clients can do the common tasks without knowing how the subsystem is put together.

The words that matter:

  • Simplified. The facade's interface is smaller and higher-level than the subsystem's. It speaks in tasks ("check out this cart"), not mechanisms ("authorise, then capture").
  • A set of interfaces. A facade sits in front of several collaborating objects. If it wraps exactly one object and keeps its interface, you're looking at a proxy or decorator. If it wraps one object and changes its interface to fit what you need, that's an adapter.
  • Common tasks. A facade covers the 80% case. It doesn't have to expose everything the subsystem can do, and it shouldn't try.

Just as important is what a facade does not do. It doesn't hide the subsystem by force. The classes behind it stay usable. An admin tool that needs to adjust stock directly can still talk to Inventory. The facade is a convenient default path, not a wall. If you need a wall, that's a module boundary enforced by visibility rules, and a facade can be its public face, but the two ideas are separate.

The problem

Here's an online shop. Checkout touches four subsystems, each with its own API: inventory reservations, a payment service with authorise, capture and void, a shipping service that books couriers, and a notifier. The web controller does all of it inline. Then the mobile API team copies the code, and a third copy ends up in the "reorder" button.

import java.util.*;

class Inventory {
    final Map<String, Integer> stock = new HashMap<>(Map.of("BOOK", 5));
    void reserve(String sku, int qty) {
        int have = stock.getOrDefault(sku, 0);
        if (have < qty) throw new IllegalStateException("out of stock: " + sku);
        stock.put(sku, have - qty);
    }
    void release(String sku, int qty) { stock.merge(sku, qty, Integer::sum); }
}

class Payments {
    final Map<String, String> auths = new HashMap<>();
    String authorize(String card, long cents) {
        if (card.startsWith("0000")) throw new IllegalStateException("declined");
        String id = "auth-" + (auths.size() + 1);
        auths.put(id, "AUTHORIZED");
        return id;
    }
    void capture(String authId) { auths.put(authId, "CAPTURED"); }
}

class WebCheckoutController {
    String checkout(Inventory inv, Payments pay, String sku, int qty, String card) {
        inv.reserve(sku, qty);
        String auth;
        try {
            auth = pay.authorize(card, qty * 1_500L);
        } catch (RuntimeException e) {
            inv.release(sku, qty);                  // the web team remembered to undo
            throw e;
        }
        pay.capture(auth);
        return auth;
    }
}

class MobileCheckoutHandler {
    String checkout(Inventory inv, Payments pay, String sku, int qty, String card) {
        inv.reserve(sku, qty);
        String auth = pay.authorize(card, qty * 1_500L);  // copy-paste lost the release
        pay.capture(auth);
        return auth;
    }
}

class Demo {
    public static void main(String[] args) {
        Inventory inv = new Inventory();
        Payments pay = new Payments();
        try { new WebCheckoutController().checkout(inv, pay, "BOOK", 2, "0000-1111"); }
        catch (IllegalStateException expected) { }
        assert inv.stock.get("BOOK") == 5;          // web path released the stock

        try { new MobileCheckoutHandler().checkout(inv, pay, "BOOK", 2, "0000-1111"); }
        catch (IllegalStateException expected) { }
        assert inv.stock.get("BOOK") == 3;          // mobile path leaked two books
        System.out.println("before: two callers, two versions of checkout, one stock leak");
    }
}

The problems:

  1. The workflow is duplicated in every caller. Web, mobile and reorder each know the order of the steps and the compensation rules. They drift apart. Here, the mobile copy lost the release call, and stock leaks whenever a card is declined.
  2. Callers are coupled to every subsystem. A controller that should only care about "the user clicked buy" imports four services and knows that payments are two-phase. When the payment provider adds a fraud check step, all three callers change.
  3. The rules are hard to test. To test "a declined card releases stock" you have to drive an HTTP controller, and you have to do it three times, once per copy.
  4. New team members face the whole subsystem at once. There's no obvious "here's how you check out an order" entry point. They read the controller, copy it, and the cycle repeats.

What we want is one place that owns the checkout choreography, a small method that every channel calls, and subsystems that stay independent of each other and of the callers.

Structure

classDiagram
    direction LR
    class WebController
    class MobileHandler
    class CheckoutFacade {
        +checkout(orderId, lines, card, address) Receipt
    }
    class Inventory {
        +reserve(lines) String
        +release(reservationId)
    }
    class Payments {
        +authorize(card, cents) String
        +capture(authId)
        +voidAuth(authId)
    }
    class Shipping {
        +book(address, lines) String
    }
    class Notifier {
        +send(to, message)
    }
    class AdminStockTool
    WebController --> CheckoutFacade
    MobileHandler --> CheckoutFacade
    CheckoutFacade --> Inventory
    CheckoutFacade --> Payments
    CheckoutFacade --> Shipping
    CheckoutFacade --> Notifier
    AdminStockTool --> Inventory : still allowed

The arrows only point one way. The facade knows the subsystems. The subsystems don't know the facade, and they don't know each other. AdminStockTool uses Inventory directly, which is fine: the facade is a shortcut, not a gate.

The happy path and the compensation path look like this:

sequenceDiagram
    participant C as Client
    participant F as CheckoutFacade
    participant I as Inventory
    participant P as Payments
    participant S as Shipping
    participant N as Notifier
    C->>F: checkout(order, lines, card, address)
    F->>I: reserve(lines)
    I-->>F: reservationId
    F->>P: authorize(card, total)
    P-->>F: authId
    F->>S: book(address, lines)
    alt courier booked
        S-->>F: tracking number
        F->>P: capture(authId)
        F->>N: send confirmation
        F-->>C: Receipt
    else booking fails
        S-->>F: error
        F->>P: voidAuth(authId)
        F->>I: release(reservationId)
        F-->>C: CheckoutFailed
    end

Participants

ParticipantIn the exampleResponsibility
FacadeCheckoutFacadeKnows which subsystem classes handle a task and in what order. Turns one client call into the right sequence of subsystem calls, including undoing steps when a later one fails.
Subsystem classesInventory, Payments, Shipping, NotifierDo the real work. Each is cohesive and independent. They don't know the facade exists.
ClientsWeb controller, mobile handler, reorder jobCall the facade for common tasks. May still call subsystem classes directly for unusual ones.

A facade often comes with a result type of its own (Receipt, CheckoutFailed) so that clients don't see subsystem-specific types like an authorisation id or a courier booking object. That's part of the simplification: one vocabulary for the outside world.

Implementation

The facade below owns the checkout workflow, including compensation: if payment is declined, stock is released, and if the courier booking fails, the authorisation is voided and stock is released. The subsystem classes are deliberately ordinary, and the demo shows an admin tool still using Inventory directly.

import java.util.*;

record Line(String sku, int qty, long unitCents) {}
record Receipt(String orderId, long totalCents, String tracking) {}

final class CheckoutFailed extends RuntimeException {
    CheckoutFailed(String message, Throwable cause) { super(message, cause); }
}

// ---- Subsystem: each class is independent and knows nothing about the facade ----

final class Inventory {
    private final Map<String, Integer> stock = new HashMap<>();
    private final Map<String, List<Line>> reservations = new HashMap<>();

    Inventory(Map<String, Integer> initial) { stock.putAll(initial); }

    String reserve(List<Line> lines) {
        for (Line l : lines) {
            if (stock.getOrDefault(l.sku(), 0) < l.qty()) throw new IllegalStateException("out of stock: " + l.sku());
        }
        lines.forEach(l -> stock.merge(l.sku(), -l.qty(), Integer::sum));
        String id = "res-" + (reservations.size() + 1);
        reservations.put(id, List.copyOf(lines));
        return id;
    }

    void release(String reservationId) {
        List<Line> lines = reservations.remove(reservationId);
        if (lines != null) lines.forEach(l -> stock.merge(l.sku(), l.qty(), Integer::sum));
    }

    void adjust(String sku, int delta) { stock.merge(sku, delta, Integer::sum); }   // used by admin tools
    int available(String sku) { return stock.getOrDefault(sku, 0); }
}

final class Payments {
    final Map<String, String> status = new LinkedHashMap<>();

    String authorize(String card, long cents) {
        if (card.startsWith("0000")) throw new IllegalStateException("card declined");
        String id = "auth-" + (status.size() + 1);
        status.put(id, "AUTHORIZED");
        return id;
    }
    void capture(String authId) { status.put(authId, "CAPTURED"); }
    void voidAuth(String authId) { status.put(authId, "VOIDED"); }
}

final class Shipping {
    String book(String address, List<Line> lines) {
        if (!address.endsWith(", IN")) throw new IllegalStateException("no courier for " + address);
        return "TRK-" + Math.abs(address.hashCode() % 10_000);
    }
}

final class Notifier {
    final List<String> sent = new ArrayList<>();
    void send(String to, String message) { sent.add(to + ": " + message); }
}

// ---- Facade: one task-shaped method, owns order and compensation ----

final class CheckoutFacade {
    private final Inventory inventory;
    private final Payments payments;
    private final Shipping shipping;
    private final Notifier notifier;

    CheckoutFacade(Inventory inventory, Payments payments, Shipping shipping, Notifier notifier) {
        this.inventory = inventory;
        this.payments = payments;
        this.shipping = shipping;
        this.notifier = notifier;
    }

    Receipt checkout(String orderId, List<Line> lines, String card, String address, String email) {
        long total = lines.stream().mapToLong(l -> l.qty() * l.unitCents()).sum();

        String reservation;
        try {
            reservation = inventory.reserve(lines);
        } catch (IllegalStateException e) {
            throw new CheckoutFailed("items unavailable", e);
        }

        String auth;
        try {
            auth = payments.authorize(card, total);
        } catch (IllegalStateException e) {
            inventory.release(reservation);
            throw new CheckoutFailed("payment declined", e);
        }

        String tracking;
        try {
            tracking = shipping.book(address, lines);
        } catch (IllegalStateException e) {
            payments.voidAuth(auth);
            inventory.release(reservation);
            throw new CheckoutFailed("cannot ship to this address", e);
        }

        payments.capture(auth);
        notifier.send(email, "Order " + orderId + " confirmed, tracking " + tracking);
        return new Receipt(orderId, total, tracking);
    }
}

class Demo {
    public static void main(String[] args) {
        Inventory inventory = new Inventory(Map.of("BOOK", 5, "PEN", 10));
        Payments payments = new Payments();
        Notifier notifier = new Notifier();
        CheckoutFacade checkout = new CheckoutFacade(inventory, payments, new Shipping(), notifier);
        List<Line> cart = List.of(new Line("BOOK", 2, 1_500), new Line("PEN", 3, 200));

        // Happy path: one call does the whole workflow.
        Receipt r = checkout.checkout("o-1", cart, "4242-4242", "12 MG Road, Pune, IN", "asha@example.com");
        assert r.totalCents() == 3_600;
        assert inventory.available("BOOK") == 3 && inventory.available("PEN") == 7;
        assert payments.status.get("auth-1").equals("CAPTURED");
        assert notifier.sent.size() == 1;

        // Declined card: stock is released, nothing captured.
        try {
            checkout.checkout("o-2", cart, "0000-1111", "12 MG Road, Pune, IN", "ben@example.com");
            throw new AssertionError("expected CheckoutFailed");
        } catch (CheckoutFailed e) {
            assert e.getMessage().equals("payment declined");
        }
        assert inventory.available("BOOK") == 3;

        // Shipping fails after authorisation: payment voided AND stock released.
        try {
            checkout.checkout("o-3", cart, "4242-4242", "1 Main St, Springfield, US", "cy@example.com");
            throw new AssertionError("expected CheckoutFailed");
        } catch (CheckoutFailed e) {
            assert e.getMessage().equals("cannot ship to this address");
        }
        assert payments.status.get("auth-2").equals("VOIDED");
        assert inventory.available("BOOK") == 3 && inventory.available("PEN") == 7;

        // The facade doesn't lock anyone out: an admin tool uses the subsystem directly.
        inventory.adjust("BOOK", 10);
        assert inventory.available("BOOK") == 13;
        System.out.println("checkout facade ok: " + r);
    }
}
from dataclasses import dataclass


@dataclass(frozen=True)
class Line:
    sku: str
    qty: int
    unit_cents: int


@dataclass(frozen=True)
class Receipt:
    order_id: str
    total_cents: int
    tracking: str


class CheckoutFailed(Exception):
    pass


# ---- Subsystem: each class is independent and knows nothing about the facade ----

class Inventory:
    def __init__(self, initial: dict[str, int]) -> None:
        self._stock = dict(initial)
        self._reservations: dict[str, list[Line]] = {}

    def reserve(self, lines: list[Line]) -> str:
        for line in lines:
            if self._stock.get(line.sku, 0) < line.qty:
                raise LookupError(f"out of stock: {line.sku}")
        for line in lines:
            self._stock[line.sku] -= line.qty
        rid = f"res-{len(self._reservations) + 1}"
        self._reservations[rid] = list(lines)
        return rid

    def release(self, reservation_id: str) -> None:
        for line in self._reservations.pop(reservation_id, []):
            self._stock[line.sku] += line.qty

    def adjust(self, sku: str, delta: int) -> None:     # used by admin tools
        self._stock[sku] = self._stock.get(sku, 0) + delta

    def available(self, sku: str) -> int:
        return self._stock.get(sku, 0)


class Payments:
    def __init__(self) -> None:
        self.status: dict[str, str] = {}

    def authorize(self, card: str, cents: int) -> str:
        if card.startswith("0000"):
            raise PermissionError("card declined")
        auth_id = f"auth-{len(self.status) + 1}"
        self.status[auth_id] = "AUTHORIZED"
        return auth_id

    def capture(self, auth_id: str) -> None:
        self.status[auth_id] = "CAPTURED"

    def void(self, auth_id: str) -> None:
        self.status[auth_id] = "VOIDED"


class Shipping:
    def book(self, address: str, lines: list[Line]) -> str:
        if not address.endswith(", IN"):
            raise ValueError(f"no courier for {address}")
        return f"TRK-{sum(map(ord, address)) % 10_000}"


class Notifier:
    def __init__(self) -> None:
        self.sent: list[str] = []

    def send(self, to: str, message: str) -> None:
        self.sent.append(f"{to}: {message}")


# ---- Facade: one task-shaped method, owns order and compensation ----

class CheckoutFacade:
    def __init__(self, inventory: Inventory, payments: Payments,
                 shipping: Shipping, notifier: Notifier) -> None:
        self._inventory = inventory
        self._payments = payments
        self._shipping = shipping
        self._notifier = notifier

    def checkout(self, order_id: str, lines: list[Line], card: str,
                 address: str, email: str) -> Receipt:
        total = sum(line.qty * line.unit_cents for line in lines)
        try:
            reservation = self._inventory.reserve(lines)
        except LookupError as e:
            raise CheckoutFailed("items unavailable") from e

        try:
            auth = self._payments.authorize(card, total)
        except PermissionError as e:
            self._inventory.release(reservation)
            raise CheckoutFailed("payment declined") from e

        try:
            tracking = self._shipping.book(address, lines)
        except ValueError as e:
            self._payments.void(auth)
            self._inventory.release(reservation)
            raise CheckoutFailed("cannot ship to this address") from e

        self._payments.capture(auth)
        self._notifier.send(email, f"Order {order_id} confirmed, tracking {tracking}")
        return Receipt(order_id, total, tracking)


if __name__ == "__main__":
    inventory = Inventory({"BOOK": 5, "PEN": 10})
    payments = Payments()
    notifier = Notifier()
    checkout = CheckoutFacade(inventory, payments, Shipping(), notifier)
    cart = [Line("BOOK", 2, 1_500), Line("PEN", 3, 200)]

    r = checkout.checkout("o-1", cart, "4242-4242", "12 MG Road, Pune, IN", "asha@example.com")
    assert r.total_cents == 3_600
    assert inventory.available("BOOK") == 3 and inventory.available("PEN") == 7
    assert payments.status["auth-1"] == "CAPTURED"
    assert len(notifier.sent) == 1

    try:
        checkout.checkout("o-2", cart, "0000-1111", "12 MG Road, Pune, IN", "ben@example.com")
        raise AssertionError("expected CheckoutFailed")
    except CheckoutFailed as e:
        assert str(e) == "payment declined"
    assert inventory.available("BOOK") == 3

    try:
        checkout.checkout("o-3", cart, "4242-4242", "1 Main St, Springfield, US", "cy@example.com")
        raise AssertionError("expected CheckoutFailed")
    except CheckoutFailed as e:
        assert str(e) == "cannot ship to this address"
    assert payments.status["auth-2"] == "VOIDED"
    assert inventory.available("BOOK") == 3 and inventory.available("PEN") == 7

    inventory.adjust("BOOK", 10)          # direct subsystem access is still allowed
    assert inventory.available("BOOK") == 13
    print("checkout facade ok:", r)
import assert from "node:assert/strict";

interface Line { readonly sku: string; readonly qty: number; readonly unitCents: number }
interface Receipt { readonly orderId: string; readonly totalCents: number; readonly tracking: string }

class CheckoutFailed extends Error {}
class OutOfStock extends Error {}
class Declined extends Error {}
class Undeliverable extends Error {}

// ---- Subsystem: each class is independent and knows nothing about the facade ----

class Inventory {
  private readonly stock: Map<string, number>;
  private readonly reservations = new Map<string, readonly Line[]>();
  constructor(initial: Record<string, number>) {
    this.stock = new Map(Object.entries(initial));
  }
  reserve(lines: readonly Line[]): string {
    for (const l of lines) {
      if ((this.stock.get(l.sku) ?? 0) < l.qty) throw new OutOfStock(l.sku);
    }
    for (const l of lines) this.stock.set(l.sku, this.stock.get(l.sku)! - l.qty);
    const id = `res-${this.reservations.size + 1}`;
    this.reservations.set(id, [...lines]);
    return id;
  }
  release(reservationId: string): void {
    for (const l of this.reservations.get(reservationId) ?? []) {
      this.stock.set(l.sku, (this.stock.get(l.sku) ?? 0) + l.qty);
    }
    this.reservations.delete(reservationId);
  }
  adjust(sku: string, delta: number): void {
    this.stock.set(sku, (this.stock.get(sku) ?? 0) + delta); // used by admin tools
  }
  available(sku: string): number {
    return this.stock.get(sku) ?? 0;
  }
}

class Payments {
  readonly status = new Map<string, "AUTHORIZED" | "CAPTURED" | "VOIDED">();
  authorize(card: string, cents: number): string {
    if (card.startsWith("0000")) throw new Declined(`card declined for ${cents}`);
    const id = `auth-${this.status.size + 1}`;
    this.status.set(id, "AUTHORIZED");
    return id;
  }
  capture(authId: string): void {
    this.status.set(authId, "CAPTURED");
  }
  void(authId: string): void {
    this.status.set(authId, "VOIDED");
  }
}

class Shipping {
  book(address: string, lines: readonly Line[]): string {
    if (!address.endsWith(", IN")) throw new Undeliverable(address);
    return `TRK-${lines.length}${address.length}`;
  }
}

class Notifier {
  readonly sent: string[] = [];
  send(to: string, message: string): void {
    this.sent.push(`${to}: ${message}`);
  }
}

// ---- Facade: one task-shaped method, owns order and compensation ----

class CheckoutFacade {
  constructor(
    private readonly inventory: Inventory,
    private readonly payments: Payments,
    private readonly shipping: Shipping,
    private readonly notifier: Notifier,
  ) {}

  checkout(orderId: string, lines: readonly Line[], card: string, address: string, email: string): Receipt {
    const totalCents = lines.reduce((sum, l) => sum + l.qty * l.unitCents, 0);

    let reservation: string;
    try {
      reservation = this.inventory.reserve(lines);
    } catch (e) {
      if (e instanceof OutOfStock) throw new CheckoutFailed("items unavailable", { cause: e });
      throw e;
    }

    let auth: string;
    try {
      auth = this.payments.authorize(card, totalCents);
    } catch (e) {
      this.inventory.release(reservation);
      if (e instanceof Declined) throw new CheckoutFailed("payment declined", { cause: e });
      throw e;
    }

    let tracking: string;
    try {
      tracking = this.shipping.book(address, lines);
    } catch (e) {
      this.payments.void(auth);
      this.inventory.release(reservation);
      if (e instanceof Undeliverable) throw new CheckoutFailed("cannot ship to this address", { cause: e });
      throw e;
    }

    this.payments.capture(auth);
    this.notifier.send(email, `Order ${orderId} confirmed, tracking ${tracking}`);
    return { orderId, totalCents, tracking };
  }
}

const inventory = new Inventory({ BOOK: 5, PEN: 10 });
const payments = new Payments();
const notifier = new Notifier();
const checkout = new CheckoutFacade(inventory, payments, new Shipping(), notifier);
const cart: Line[] = [
  { sku: "BOOK", qty: 2, unitCents: 1_500 },
  { sku: "PEN", qty: 3, unitCents: 200 },
];

const r = checkout.checkout("o-1", cart, "4242-4242", "12 MG Road, Pune, IN", "asha@example.com");
assert.equal(r.totalCents, 3_600);
assert.equal(inventory.available("BOOK"), 3);
assert.equal(payments.status.get("auth-1"), "CAPTURED");
assert.equal(notifier.sent.length, 1);

assert.throws(
  () => checkout.checkout("o-2", cart, "0000-1111", "12 MG Road, Pune, IN", "ben@example.com"),
  { message: "payment declined" },
);
assert.equal(inventory.available("BOOK"), 3);

assert.throws(
  () => checkout.checkout("o-3", cart, "4242-4242", "1 Main St, Springfield, US", "cy@example.com"),
  { message: "cannot ship to this address" },
);
assert.equal(payments.status.get("auth-2"), "VOIDED");
assert.equal(inventory.available("PEN"), 7);

inventory.adjust("BOOK", 10); // direct subsystem access is still allowed
assert.equal(inventory.available("BOOK"), 13);
console.log("checkout facade ok:", r);

Walking through it

One method, one workflow, one place to test it. "A declined card releases stock" and "a failed courier booking voids the payment" are now tested once, against the facade, with in-memory subsystems. The web, mobile and reorder paths all inherit the fix the day it's made. The leak from the "before" code can't recur in a fourth copy, because there is no fourth copy.

The facade translates failures into its own vocabulary. Each subsystem fails in its own way: a lookup error, a permission error, a validation error. Clients see one type, CheckoutFailed, with a message that makes sense to a person who clicked "buy". The original exception is kept as the cause for logs. This is a quiet but important part of simplification. A facade that leaks every subsystem's exception types hasn't really hidden the subsystem.

Compensation order is the reverse of the forward order. Reserve, authorise, book on the way in. Void, release on the way out. Writing that in one place, next to the forward steps, is much easier to get right than spreading it across callers. In a distributed system the same idea becomes a saga, and the distributed transactions page covers what changes when the steps are separate services that can fail independently.

The facade holds no business rules of its own. Pricing lives in Line, stock rules live in Inventory, and decline rules live in Payments. The facade decides only order and what to undo. That's the line to hold if you want the facade to stay small, and the section on god objects below explains why.

Subsystems are injected. The facade receives its collaborators through the constructor rather than building them. That keeps it testable with fakes and lets the composition root decide which payment provider is used, which is where dependency injection and facades meet.

Not everything is a facade concern. Concurrency, for instance: two simultaneous checkouts for the last book are handled (or not) by Inventory.reserve, which must make its check-and-decrement atomic. The facade can't fix a race inside a subsystem, and it shouldn't try to by adding a lock around the whole workflow, which would serialise every checkout in the shop.

Facades you already use

Standard libraries are full of facades: one convenience call that builds and drives several lower-level objects for the common case, while the lower-level API stays available for unusual cases. Comparing the two versions side by side is the quickest way to see the pattern.

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;

class Demo {
    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("facade-demo", ".txt");
        try {
            // Facade: one call opens, encodes, writes and closes.
            Files.write(file, List.of("alpha", "beta"), StandardCharsets.UTF_8);

            // The subsystem it hides: a stream, a decoder, a buffer, a loop and a close.
            List<String> manual = new ArrayList<>();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file.toFile()), StandardCharsets.UTF_8))) {
                for (String line; (line = reader.readLine()) != null; ) manual.add(line);
            }

            // Facade again: same result in one line.
            List<String> easy = Files.readAllLines(file, StandardCharsets.UTF_8);
            assert easy.equals(manual) && easy.equals(List.of("alpha", "beta"));
            System.out.println("Files facade ok: " + easy);
        } finally {
            Files.delete(file);
        }
    }
}
import subprocess
import sys

cmd = [sys.executable, "-c", "import sys; print('hi'); sys.exit(3)"]

# Facade: subprocess.run starts the process, wires the pipes, waits, and collects the result.
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
assert result.stdout == "hi\n" and result.returncode == 3

# The lower-level API it builds on, still available for streaming or interactive cases.
with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) as proc:
    out, err = proc.communicate(timeout=30)
assert out == result.stdout and proc.returncode == result.returncode
print("subprocess facade ok:", repr(result.stdout))
import assert from "node:assert/strict";
import { closeSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, writeFileSync, fstatSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

const dir = mkdtempSync(join(tmpdir(), "facade-demo-"));
const file = join(dir, "notes.txt");
try {
  // Facade: one call opens, writes and closes.
  writeFileSync(file, "alpha\nbeta\n", "utf8");

  // The subsystem it hides: a file descriptor, a size lookup, a buffer, a read and a close.
  const fd = openSync(file, "r");
  let manual: string;
  try {
    const buf = Buffer.alloc(fstatSync(fd).size);
    readSync(fd, buf, 0, buf.length, 0);
    manual = buf.toString("utf8");
  } finally {
    closeSync(fd);
  }

  const easy = readFileSync(file, "utf8");
  assert.equal(easy, manual);
  console.log("fs facade ok:", JSON.stringify(easy));
} finally {
  rmSync(dir, { recursive: true });
}

The pattern is the same each time. The convenience call handles resource cleanup, defaults (encoding, buffering) and error handling for the common case. The lower-level API is still there for streaming huge files, talking to an interactive process, or reading at an offset. Nobody is forced through the facade, and nobody is forced to learn the subsystem for a one-liner.

Facades that become god objects

The danger with a facade is success. It's the obvious place to add things, so things get added: a refund method, then applyCoupon, then recalculateTax, then exportOrdersCsv, then a few if (order.isB2B()) branches. After a year, OrderFacade has 60 methods, imports 25 services and contains half the business rules in the system. That's the god class mistake with a respectable name.

Signs it's happening:

  • Business rules inside the facade. Price calculations, eligibility checks, status transitions. A facade should orchestrate calls to objects that own those rules, not implement them.
  • Methods that serve unrelated clients. Checkout, admin reporting and data export all in one class. Different clients, different reasons to change, which violates single responsibility.
  • Every subsystem call goes through it, including ones that are a single call with no orchestration. facade.getProduct(id) that just returns catalog.get(id) adds nothing.
  • Subsystems call back into the facade. Now the facade is a hub that everything depends on, closer to a mediator, and it's very hard to change.

How to keep it healthy:

  1. One facade per use case or client group. CheckoutFacade, RefundFacade, OrderReportingFacade. Small facades with clear jobs beat one "service" for the whole domain.
  2. Push rules down. If a facade method contains an if about the domain (rather than about which step failed), ask which subsystem object owns that decision and move it there.
  3. Let simple calls go direct. If a client needs one subsystem method, it can depend on that subsystem. A facade is for workflows.
  4. Layer facades if needed. A high-level OrderFacade can call lower-level facades (PaymentFacade over authorise, capture and void). Each layer stays small.

Facades as boundaries and test seams

A facade is also a good place to draw a line around a module. If the payments package exposes one PaymentFacade and keeps its gateway clients, retry policies and webhook parsers package-private, the rest of the codebase has one small surface to depend on. That has three practical effects.

Replacing the internals gets cheaper. Switching payment providers, or splitting the payments code into its own service later, touches the facade's implementation and nothing outside it. Callers wrote against charge(order), not against a vendor's client library.

Faking it in tests gets cheaper. Code that depends on a three-method facade can be tested with a three-method fake. Code that depends on the whole subsystem needs the whole subsystem, or a pile of mocks that mirror its internals and break whenever they change.

The module's contract becomes visible. A reviewer can read the facade and see what the module promises. Anything not on the facade is an internal detail that may change. This is the same idea as an explicit public API in a library, and in Java it pairs naturally with the module system's exports, which can make the facade's package the only exported one.

The trade-off is the one from the previous section: a boundary facade must stay small and task-shaped, or it turns into a mirror of everything inside, which defeats the purpose.

Real-world uses

Java ecosystem

  • SLF4J is a logging facade by name and design: application code calls LoggerFactory.getLogger(...) and log.info(...), and a binding routes those calls to Logback, Log4j 2 or java.util.logging. It simplifies and decouples: your code never touches the backend's API. (It's also an example of a facade combined with bridge-like decoupling of interface and backend.)
  • java.nio.file.Files convenience methods (readAllLines, readString, write, newBufferedReader, copy) build and drive the underlying channels, streams, decoders and buffers for the common case.
  • Spring's JdbcTemplate hides connection acquisition, statement preparation, result-set iteration, exception translation and resource cleanup behind calls such as query(sql, rowMapper, args). RestTemplate and the newer RestClient do the same for HTTP. Spring describes these as templates (they also use template method-style callbacks), but the role they play for application code is a facade.

Python standard library

  • subprocess.run wraps Popen, pipe setup, communicate, timeouts and return-code checks (check=True).
  • shutil offers high-level file operations (copytree, rmtree, make_archive, move) built from many os, os.path and stat calls.
  • urllib.request.urlopen builds an opener, handlers and a request object for you. The handler classes are still available for custom needs.
  • json.dumps and json.loads are convenience functions over JSONEncoder and JSONDecoder instances.

JavaScript

  • jQuery was, for most of its history, a facade over inconsistent browser DOM, event and XHR APIs: $(selector).on("click", fn) instead of per-browser code paths.
  • Node's fs.readFileSync / fs.promises.readFile over open, fstat, read and close, as in the demo above.
  • fetch is a much simpler entry point than the older XMLHttpRequest state machine, though it's a replacement API rather than a wrapper over it.

Architecture level

  • API gateways and backends-for-frontends play a facade's role across services: one endpoint per client need, fanning out to several services. The difference is that they add network concerns (auth, rate limiting, routing) and real failure modes. API composition is the same idea for queries.
  • Module public APIs. A package that exports one index.ts or __init__.py with a few functions, while dozens of internal modules stay private, is a facade for the module.

When NOT to use it

When there's nothing to simplify. If a task is one call to one class, wrapping it adds a layer and teaches nothing. Facades earn their keep when there's a real sequence, real coordination or real error handling to hide.

When clients genuinely need the full power. A facade for a graphics library that only exposes drawRectangle is useless to the client who needs blend modes. Offer the facade and keep the subsystem available. Don't make the facade the only door, and don't keep growing it to match the subsystem one method at a time.

When it would just move a god class. If the subsystem is a tangle, putting a facade in front makes the tangle invisible, not better. Sometimes the right fix is to restructure the subsystem first.

When the "subsystem" is one class you control. If the class is hard to use, fix its API. A facade over your own single class is usually a sign that the class's interface needs work.

When the abstraction leaks anyway. If every client ends up passing subsystem objects through the facade (facade.checkout(cart, paymentAuthOptions, courierConfig)), the facade isn't hiding anything. Either give it real defaults or admit clients need the subsystem.

When it becomes a bottleneck for change. A shared facade owned by one team, which every other team must change to get anything done, slows everyone down. Smaller, per-use-case facades, owned by the teams that use them, avoid this.

The costs, in short: one more layer to read, the risk of growing into a god object, the temptation to put business rules in the wrong place, and an interface that can lag behind the subsystem's capabilities.

PatternWrapsInterfaceDirection of knowledgePurpose
FacadeSeveral subsystem objectsNew, simpler, task-shapedFacade knows subsystems, they don't know itSimplify common tasks
AdapterUsually one objectConverts to an interface the client already expectsAdapter knows the adapteeMake an incompatible thing fit
MediatorSeveral peer objectsColleagues talk to the mediatorTwo-way: colleagues know the mediator and it knows themCoordinate peers so they don't reference each other
ProxyOne objectSame as the wrapped objectProxy knows the subjectControl access
DecoratorOne objectSame as the wrapped objectDecorator knows the componentAdd behaviour
API gatewaySeveral services over a networkNew, client-shapedGateway knows servicesFacade plus routing, auth and rate limiting at the edge

Facade vs Adapter. Both put a new interface in front of existing code, which is why they get confused. An adapter's interface is decided by the client: there's an existing interface (PaymentGateway) and the adapter makes something else fit it. A facade's interface is decided by simplification: there was no interface before, and the facade invents a smaller one. An adapter usually wraps one object, a facade several. In practice they combine: a facade over a third-party SDK is often also an adapter to your domain's types, and the anti-corruption layer is roughly "facade plus adapters plus translation" at the boundary of a bounded context.

Facade vs Mediator. Both centralise coordination. The difference is direction. Subsystem classes behind a facade don't know the facade exists, and they can be used without it. A mediator's colleagues are written to talk to the mediator, and the mediator calls back to them. The mediator exists so that peers don't reference each other, and the facade exists so that clients don't have to learn the subsystem. If your subsystem classes start calling the facade, it has become a mediator.

Facade vs Singleton. Facades are often the single entry point to a subsystem, so people make them singletons. There's rarely a reason to. A facade usually has no state of its own beyond its collaborators, so creating it once in the composition root and injecting it gives the same effect without global access.

Facade vs Abstract Factory. An abstract factory can be used with a facade to create subsystem objects in a platform-independent way, with the facade then orchestrating them. They solve different problems (creation versus use) and fit together.

The smell that suggests it

  • The same multi-step sequence copied across callers: reserve, authorise, ship, capture. Especially when the copies have started to differ.
  • Callers importing many classes from one package to do one thing. A controller with eight imports from the payments package to take one payment.
  • Compensation and cleanup logic duplicated or missing in some callers, like the stock leak in the mobile handler.
  • "How do I do X?" questions from new team members whose answer is a 30-line snippet from someone's controller. That snippet wants to be a method.
  • Tests that set up an entire subsystem to check one workflow rule, because the rule lives in an HTTP handler.
  • A third-party library with a huge API of which your team uses five calls. A thin facade with those five calls, in your vocabulary, makes the library replaceable and easier to fake in tests.

And the counter-smells: a facade method that only forwards one call, a facade with business ifs, or subsystems that call back into the facade.

Interview questions

  1. "What's the difference between Facade and Adapter?" An adapter converts one object's interface into an interface the client already expects, so the target interface exists before the adapter. A facade invents a new, simpler interface over several objects to make common tasks easy. Adapters are about compatibility, facades are about simplicity. They often appear together, for example a facade over a third-party SDK that also translates its types into your domain's.

  2. "Facade vs Mediator?" Direction of knowledge. Subsystem classes don't know a facade exists, and you can use them without it. A mediator's colleagues know the mediator and send their events to it, and the mediator coordinates them, so the communication is two-way. A facade simplifies access for outside clients. A mediator decouples peers from each other.

  3. "Does a facade prevent clients from using the subsystem directly?" No, not by itself. It provides a convenient path. Clients with unusual needs can still use the subsystem classes. If you want to enforce the boundary, combine the facade with visibility rules (package-private classes, unexported modules, Java module exports) and let the facade be the module's public API.

  4. "How do you stop a facade becoming a god class?" Keep it to orchestration, with no domain rules, and split it per use case or client group (CheckoutFacade, RefundFacade) rather than one per domain. Let single-call operations go to the subsystem directly. Watch for ifs about business conditions inside it and push those decisions down to the objects that own the data.

  5. "Design a VideoPublishingFacade for a platform where uploads must be transcoded, thumbnailed, scanned for copyright and indexed for search." One method like publish(upload, metadata) that runs the steps in order, returns a PublishedVideo or a clear failure, and compensates (deletes transcoded files, removes the index entry) when a later step fails. Subsystems are injected. Discuss which steps could run in parallel (thumbnails and transcoding), and that slow steps probably belong in an async job with the facade only starting it and returning a status.

  6. "Is an API gateway a facade?" At the architecture level, yes: it gives clients one simplified entry point over many services. But it adds concerns a class-level facade doesn't have, such as routing, authentication, rate limiting, protocol translation and partial failures across the network. It can also turn into a distributed god object if business logic leaks into it.

  7. "How would you test a facade?" Inject fake subsystems (in-memory inventory, a payments fake that can be told to decline) and test each workflow path: success, each failure point, and that the right compensation happens for each. Assert on the facade's result and on the fakes' final state. The subsystems themselves get their own unit tests.

  8. "Should a facade be a singleton?" Usually not. It typically holds no mutable state beyond its injected collaborators. Create it once in the composition root and inject it. Making it a global singleton adds hidden coupling and makes tests harder for no gain.

  9. "Give examples of facades in libraries you use." SLF4J over logging backends, Files.readAllLines over streams and decoders, Spring's JdbcTemplate over raw JDBC, Python's subprocess.run over Popen and shutil over os, jQuery over browser DOM APIs, Node's fs.readFileSync over file descriptors.

  10. "Where should transaction boundaries go: in the facade or the subsystems?" For a workflow that must succeed or fail as a whole against one database, the facade method is a natural transaction boundary, because it's the unit of work the client asked for. When the steps span different systems (a payment provider, a courier API), a database transaction can't cover them, so the facade uses explicit compensation like the void-and-release logic above, or hands off to a saga.