Facade Pattern
Most real features touch several parts of a system. Placing an order checks stock, reserves items, charges a card, books a courier and sends a receipt. Each of those parts is a separate class with its own rules, and each is reasonable on its own. The trouble is the code that has to call all of them, in the right order, every time.
The Facade pattern puts one class in front of those parts with a small number of methods that match what callers
actually want to do: place_order, cancel_order. Callers talk to the facade; the facade talks to everything
else.
🏛️ In one sentence: give a group of classes one simple front door, a class whose methods match what callers want to do, so callers don't need to know which parts exist or in what order to call them.
The Problem It Solves
Here is an order being placed from a web handler, with every subsystem called directly.
def handle_checkout(request: CheckoutRequest, inventory: Inventory, pricing: Pricing,
payments: PaymentGateway, shipping: Shipping, email: EmailSender) -> dict:
for item in request.items:
if inventory.available(item.sku) < item.qty:
return {"error": f"{item.sku} out of stock"}
hold_id = inventory.reserve(request.items)
total = pricing.total(request.items, request.coupon)
result = payments.charge(total, "USD", request.card_token)
if not result.ok:
inventory.release(hold_id)
return {"error": "payment declined"}
inventory.commit(hold_id)
label = shipping.book(request.address, request.items)
email.send(request.email, f"Order confirmed, tracking {label.tracking}")
return {"ok": True, "tracking": label.tracking}
On its own this looks fine. Now the mobile app needs checkout too, and so does the "reorder" button and the admin tool for phone orders.
The steps get copied. Each caller repeats this sequence. When one of them forgets inventory.release on a
declined payment, stock leaks: items stay held for an order that never happened. That bug lives in one copy and
not the others.
Every caller knows every subsystem. The handler takes six dependencies. A change to how shipping is booked means finding every place that books shipping, in code whose job is handling HTTP requests.
The rules about order are nowhere. "Reserve before charging, commit only after payment succeeds" is the most important rule here, and it exists only as the line order of a function, repeated in four places.
It is hard to test. To test checkout you need six fakes in every caller's tests, and you test the same sequence four times.
⚠️ The smell to look for: the same sequence of calls to several classes appearing in more than one caller, or a caller whose constructor takes five or six collaborators just to do one thing. That is the cue for a facade.