Facade

Escrito por Darjus Kazakevic · revisado el

One call in front of the steps a subsystem needs.

Placing an order takes several calls to three services, in a fixed order, with a refund if shipping fails. If every caller learns that sequence, it gets copied into checkout, admin and retry code, and changing it means finding every copy.

A Facade is one object with methods named for what callers want, like place(order). It does not hide the subsystem: rare callers can still use it directly. In TypeScript a facade is often a module of plain functions, not a class.

En esencia — Give the common path through a subsystem one simple entry point, so callers stop depending on its internal steps and you stay free to change them.

Cuándo recurrir a él

Recurre a él cuando

  • The same multi-step sequence is copied across several call sites
  • Callers must remember an order of calls, a compensation or a cleanup
  • You want one place to change when the subsystem changes

Reconsidéralo cuando

  • Callers really need the subsystem's flexibility, not a common path
  • To rename a single call: that adds a hop, not a simplification
  • When it would need a method for every edge case of every caller

Conceptos clave

Subsystem
The group of classes or services behind the facade. They stay unchanged and can still be used directly.
Facade method
One method per common task, named for the caller's goal. It knows the order of calls and any compensation: undoing earlier steps after a failure.
In modern TypeScript
A module that exports placeOrder() and cancelOrder() is a facade. Use a class, or a function that takes dependencies, when you swap those dependencies in tests.

Reglas de diseño

Name it for what the caller wants
place(order), not a method named after the steps. Use the verb the business already uses, so the steps can change without the name, or any caller, changing too.
Simplify, do not seal
A facade adds no new capability and hides nothing: the subsystem stays reachable for rare callers. Forbid that, and the facade grows a method per edge case until it is the subsystem.
Keep business rules out of the facade
A facade puts calls in order. If it starts deciding prices or eligibility, it becomes a second domain layer. Keep the rules in the domain and let the facade call them.

Errores habituales

  • A god facade: one class with 60 methods that every module imports.
  • Sealing the subsystem, so the facade must grow a method for every special case.
  • Business rules creeping into the facade, so it becomes a second domain layer.