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.
On this page
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
- 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
- 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.
| Role | In the checkout example | Responsibility |
|---|---|---|
| Facade | OrderService | Offers simple, task-level methods and orchestrates the subsystem |
| Subsystem classes | Inventory, Payments, Shipping, Mailer | Do the real work; they don't know the facade exists |
| Clients | Web controller, mobile API, kiosk | Call 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
}
}import uuid
from dataclasses import dataclass
# ---- The subsystem ----
class Inventory:
def __init__(self, stock: dict[str, int]):
self._stock = dict(stock)
def reserve(self, sku: str, qty: int) -> bool:
if self._stock.get(sku, 0) < qty:
return False
self._stock[sku] -= qty
return True
def release(self, sku: str, qty: int) -> None:
self._stock[sku] = self._stock.get(sku, 0) + qty
class PaymentDeclined(Exception):
pass
class Payments:
def charge(self, card: str, cents: int) -> str:
if card.startswith("0"):
raise PaymentDeclined("card declined")
return "pay-" + uuid.uuid4().hex[:8]
def refund(self, payment_id: str) -> None:
print(" refunded", payment_id)
class Shipping:
def book(self, sku: str, qty: int, email: str) -> str:
if email.endswith(".invalid"):
raise RuntimeError("no courier")
return f"ship-{sku}-{qty}"
class Mailer:
def send(self, to: str, text: str) -> None:
print(f" email to {to}: {text}")
# ---- The facade ----
@dataclass(frozen=True)
class OrderResult:
ok: bool
message: str
class OrderService:
PRICE_CENTS = 1200
def __init__(self, inventory: Inventory, payments: Payments,
shipping: Shipping, mailer: Mailer):
self._inventory = inventory
self._payments = payments
self._shipping = shipping
self._mailer = mailer
def place_order(self, email: str, sku: str, qty: int, card: str) -> OrderResult:
if not self._inventory.reserve(sku, qty): # 1. reserve stock
return OrderResult(False, "out of stock")
try:
payment_id = self._payments.charge(card, self.PRICE_CENTS * qty) # 2. pay
except PaymentDeclined as e:
self._inventory.release(sku, qty) # undo step 1
return OrderResult(False, str(e))
try:
shipment_id = self._shipping.book(sku, qty, email) # 3. book shipping
except RuntimeError:
self._payments.refund(payment_id) # undo step 2
self._inventory.release(sku, qty) # undo step 1
return OrderResult(False, "shipping unavailable")
try:
self._mailer.send(email, f"Order confirmed, shipment {shipment_id}") # 4. confirm
except OSError:
print(" email failed, will retry later") # the order still stands
return OrderResult(True, f"{payment_id} / {shipment_id}")
orders = OrderService(Inventory({"mug": 3}), Payments(), Shipping(), Mailer())
print(orders.place_order("ana@example.com", "mug", 2, "4242"))
print(orders.place_order("bo@example.com", "mug", 1, "0000")) # declined
print(orders.place_order("cy@example.com", "mug", 5, "4242")) # no stock
print(orders.place_order("dee@x.invalid", "mug", 1, "4242")) # no courierThe 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
- 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
| Facade | What it hides |
|---|---|
| SLF4J (Simple Logging Facade for Java) | Logback, Log4j 2 or java.util.logging behind one Logger API |
Spring's JdbcTemplate | Getting 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
- 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
| Facade | Adapter | Mediator | |
|---|---|---|---|
| Wraps | Many classes (a subsystem) | One class | Sits between peer objects |
| Interface | New, simpler, task-shaped | The specific interface a client already expects | Peers talk to the mediator instead of each other |
| Direction | One way: client → facade → parts; parts don't know the facade | One way | Two way: parts call the mediator and it calls them |
| Intent | Make common tasks easy | Make an incompatible class fit | Untangle many-to-many communication |
| Example | OrderService.placeOrder() | InputStreamReader | An 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
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.
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.
- 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.
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?
The problem is a repeated sequence with drifting error handling: exactly what a facade packages. Adapters change interfaces of single classes; singletons share instances, not behaviour.
2. A team says, "Now that we have OrderService, nobody may call Payments directly." What is wrong with treating the facade that way?
Facades simplify the common path without forbidding the detailed one. An admin refund tool may legitimately call Payments.refund(). Strict hiding is a layering rule you can choose separately.
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?
External calls can't join a local transaction, and charging last only moves the problem. Recording state (or running a saga) lets a background process complete or undo work after a crash.
4. Which statement best separates Facade from Mediator?
Facade communication is one way: client to facade to parts. A mediator sits between peers who each call it, so communication is two way. Both can coordinate many classes.
5. An OrderService facade has grown to 40 methods and 14 constructor dependencies. What does that most likely indicate?
A huge constructor is a sign of too many responsibilities. Several small facades over the same subsystem, one per use case, keep each easy to test. A builder hides the symptom.
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?
A BFF or API gateway is a facade at system level: one round trip from the phone, with the fan-out happening on the fast data-centre network. Caching helps repeated reads but still leaves five round trips.
Score 60% or more and the lesson is marked complete.