Notes
The problem
Here is the naive version. The mobile app calls the stock ledger, the wallet, rider dispatch, the kitchen queue and the SMS sender, one by one. Now copy that into the website, the kiosk and the support tool. One copy forgets to refund when no rider is free, and a customer pays for food that never comes. Every caller is tied to five classes, and a change in any of them ripples everywhere.
stock.reserve(dish, qty);
txn = wallet.charge(user, total);
rider = riders.assign(area);
if (rider.isEmpty()) {
// forgot: wallet.refund(txn)
// forgot: stock.putBack(dish, qty)
return "no rider";
}
kitchen.enqueue(dish, qty);
sms.send(phone, "confirmed"); The idea
The idea in one sentence: give a complicated group of classes one simple front door. The Facade pattern adds a class with a small number of easy methods, and each method runs the right steps on the classes behind it. The caller learns one method, place order. The facade knows the order of calls, the business rules and how to undo a half finished job.
- one class with a few simple
- methods that hide a group of
- classes behind it
- callers learn one method:
- placeOrder(request)
- the facade knows the order,
- the rules and the undo steps
The structure
Three roles. The client is the mobile app. The facade is a class we call OrderDesk. Behind it sit the subsystem classes: StockLedger, WalletGateway, KitchenQueue, RiderDispatch and SmsSender. They do all the real work, and none of them knows the facade exists. The arrows point one way only, from the facade into the subsystem. That is what keeps each subsystem class reusable on its own.
- client: MobileApp
- facade: OrderDesk
- subsystem classes:
- StockLedger, WalletGateway,
- KitchenQueue, RiderDispatch,
- SmsSender
- the subsystem classes do
- NOT know the facade exists
Code: the facade
In code, OrderDesk is an ordinary class. It holds a reference to each subsystem object and receives them through its constructor. It does not create them itself, so in a test you can pass in fakes, like a wallet that always declines. A facade is not magic. It is plain composition with a friendly method on top.
final class OrderDesk {
private final StockLedger stock;
private final WalletGateway wallet;
private final KitchenQueue kitchen;
private final RiderDispatch riders;
private final SmsSender sms;
OrderDesk(StockLedger s, WalletGateway w,
KitchenQueue k, RiderDispatch r,
SmsSender m) { ... }
} Code: placeOrder
The place order method runs the steps in one fixed order. First, reserve the dish in the stock ledger. If it is sold out, stop and tell the customer. Then charge the wallet. If the charge fails, put the stock back. Each step only runs if the one before it worked, and that rule now lives in exactly one place instead of in four different screens.
OrderResult placeOrder(OrderRequest r) {
if (!stock.reserve(r.dish(), r.qty()))
return reject(r, "sold out");
Optional<String> txn =
wallet.charge(r.customer(), r.total());
if (txn.isEmpty()) {
stock.putBack(r.dish(), r.qty());
return reject(r, "payment failed");
}
... Code: undo steps
Next, find a rider before cooking, so food is never made with nobody to carry it. If no rider is free, refund the charge and put the stock back, in reverse order. Only then send the ticket to the kitchen and text the customer their token. The bug from the naive version cannot happen any more, because there is only one copy of these steps.
Optional<String> rider =
riders.assign(r.area());
if (rider.isEmpty()) {
wallet.refund(txn.get());
stock.putBack(r.dish(), r.qty());
return reject(r, "no rider nearby");
}
int token = kitchen.enqueue(r.dish(),
r.qty());
sms.send(r.phone(), "token " + token);
return new OrderResult(true, ...); Run-through
Follow one order. The app calls place order for two paneer wraps. OrderDesk reserves two portions, charges the customer three hundred and sixty rupees, asks rider dispatch for someone in sector twenty one, puts a ticket in the kitchen queue and sends the text. The app gets back one simple result: accepted, with token one. The app made one method call. The facade made five.
Not a wall
A facade is a convenience, not a locked gate. The operations console, used by staff, still talks to the kitchen queue and rider dispatch directly, because it needs features the simple door does not offer, like moving a ticket up the queue or swapping a rider. That is fine. The facade covers the common path for most callers, and the subsystem stays fully usable for the few who need more.
When to use it
Use a facade when many callers repeat the same multi step sequence, when a subsystem is hard to learn, or when you wrap a legacy system or a third party library so the rest of your code never touches it directly. It also gives tests a single seam to fake. Skip it when there is one caller and two simple calls. Then the facade is just one more file to read.
- use it when:
- • many callers repeat the same
- multi-step sequence
- • a subsystem is hard to learn
- • you wrap a legacy system or
- a third-party library
- • you want one seam for tests
- skip it when:
- • one caller, two simple calls
The god object trap
The big risk is the god object. Because the facade is the easy place to add code, people keep adding: discount rules, tax maths, rider scoring. A year later it has three thousand lines and every change is scary. Keep the facade thin. It should coordinate, not compute. Rules belong in the subsystem class that owns the data. If it grows, split it by use case, for example an OrderDesk and a separate RefundDesk.
- warning signs:
- • rules that belong in a
- subsystem class creep in
- • one facade for every feature
- • dozens of methods
- fixes:
- • coordinate, do not compute
- • one facade per use case:
- OrderDesk, RefundDesk
Facade vs Adapter
Facade and Adapter both wrap other code, so people mix them up. An adapter takes one existing class whose interface does not fit, and makes it match an interface your client already expects, like plugging a new payment provider into your own PaymentGateway interface. A facade usually wraps many classes and invents a new, smaller interface that did not exist before. Adapter is about fitting. Facade is about simplifying.
- Adapter:
- ONE existing class with the
- wrong interface; make it fit
- the interface a client
- already expects
- Facade:
- MANY classes; invent a new,
- simpler interface for them
- both wrap; the goal differs
Other neighbours
Two more neighbours. A mediator also sits in the middle of many classes, but those classes know the mediator and send messages through it, so traffic flows both ways. With a facade, the subsystem has no idea the facade exists, and calls only flow downward. Decorator and Proxy keep the same interface as the object they wrap. A facade offers a different, simpler interface.
- Mediator:
- peers talk THROUGH it and
- know it; two-way traffic
- Facade:
- subsystem does not know it;
- calls only flow downward
- Decorator, Proxy:
- keep the SAME interface
- Facade:
- offers a NEW, simpler one
Already in Java
You already use facades. SLF4J, the popular Java logging library, is literally named Simple Logging Facade for Java: your code calls one small logger API, and it forwards to whichever logging library sits underneath. Spring's JdbcTemplate hides opening connections, preparing statements, reading result sets and closing everything. And in most Spring Boot apps, a service class that calls several repositories and clients is a facade in all but name.
- SLF4J: the name means
- Simple Logging Facade for Java
- one logger API, any backend
- Spring JdbcTemplate: hides
- connections, statements,
- result sets and cleanup
- your service classes: often
- facades over repositories
- and clients
In LLD interviews
In machine coding rounds, the facade is usually the top level service that the demo code calls. In a movie booking design, a booking service coordinates seat locks, payment and notifications. A vending machine exposes one front panel over the coin box, the stock and the dispenser. A library system offers check out and return. Name the pattern, keep the class thin, and show that each subsystem still has its own focused class.
- • movie booking: a booking
- service over seat locks,
- payment and notifications
- • vending machine: one front
- panel over coins, stock and
- the dispenser
- • library: checkOut, giveBack
- • food delivery: placeOrder
- mistake: logic in the facade
Say it like this
How to say it in an interview. OrderDesk is a thin facade over five subsystem classes. It runs reserve, charge, assign rider, enqueue and notify in that order, and undoes the earlier steps if a later one fails. Business rules stay in the classes that own the data, and staff tools can still call the subsystem directly. That answer shows you know both the benefit and the trap.
- "OrderDesk is a thin facade.
- It runs reserve, charge,
- assign rider, enqueue and
- notify in order, and undoes
- earlier steps on failure.
- Business rules stay in the
- subsystem classes, and staff
- tools still call them
- directly."