Cheatsheet

Facade

Intent

Offer one simple door to a set of parts that together do something complicated, so whoever uses it doesn't have to know them or coordinate them.

Structure (UML)

Spring contextMemberRegistryAccessCardsMemberControllerBillingOnboardingFacadeFront deskWaiversKioskControllerVisitor30IntroClassesMailer

Participants

  • Facade (OnboardingFacade), which exposes the join() operation and knows which parts to call and in what order
  • Subsystems (MemberRegistry, AccessCards, Billing, Waivers, IntroClasses, Mailer), which do the work and don't know there's a facade
  • Clients (MemberController, KioskController), which only know the facade

OnboardingFacade.java

public Welcome join(JoinRequest req) {
    billing.priceOf(req.plan());                       // fail fast on an unknown plan
    Member member = registry.register(req.name(), req.email());
    String card;
    try {
        card = cards.issue(member.id());               // reversible steps first…
    } catch (RuntimeException e) {
        undo(e, () -> registry.remove(member.id()));
        throw e;
    }
    Subscription sub;
    try {
        sub = billing.subscribe(member.id(), req.plan(), req.paymentToken());   // …charge last
    } catch (RuntimeException e) {
        undo(e, () -> cards.revoke(card));             // undo what was done
        undo(e, () -> registry.remove(member.id()));
        throw e;
    }
    // Paid: from here on the member is in. Follow-ups that fail are logged, not undone.
    followUp("waiver", () -> waivers.send(member));
    String introClass = followUp("intro class", () -> intro.bookIntro(member.id()), "to be confirmed");
    followUp("welcome email", () -> mailer.welcome(member, card, introClass));
    return new Welcome(member.id(), member.name(), card, sub.plan(), sub.monthlyPrice(), introClass);
}

Pros

  • Clients make one call instead of coordinating six
  • The order of the steps and how to undo them live in one place
  • Subsystems can change inside without touching the clients

Cons

  • If you keep adding to it, the facade ends up as a huge class that knows too much
  • It's one more layer between the client and the real work
  • Anyone who needs something the facade doesn't offer has to go to the subsystem directly

← Facade · Run it