AlgoViz

Facade pattern

easy 50 min

The Facade pattern gives a group of classes one simple front.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:23

Facade

1:03Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Adapter vs facade

0:34Reel

Theory

Read or listen first. About 2 min.

What it is

The Facade pattern is a structural design pattern. A facade is a class that offers a simple interface to a subsystem, a group of classes that work together.

The facade holds the parts and passes requests to them, usually several calls for one request. The parts do not know it.

It does not forbid direct use. It makes the usual case easy and leaves the unusual case possible.

Why it exists

Many small classes are good for those who build a system, and hard for those who use it. Without a front, each client learns all parts, their order and their numbers.

With a front, the knowledge exists once. Clients depend on one class, parts can be replaced, and tests of clients need one fake.

It is also a place for what concerns the whole operation: undo after a failure, time limits, one log line, protection against repeats.

A short history

  1. 1987

    Ian Holland proposes the law of Demeter in the Demeter project at Northeastern University: talk only to your close friends. Facades are one way to follow it.

  2. 1994

    The book Design Patterns appears on 31 October and lists Facade among its structural patterns.

  3. 2003

    Eric Evans publishes Domain-Driven Design, which among other things describes layers that keep foreign models out. The Azure guide to this pattern speaks of a facade or adapter layer.

  4. 2023

    Go 1.21 adds log/slog to its standard library: package functions such as slog.Info are a short front over a Logger and its Handler.

Words to know

Facade
The class with the simple interface.
Subsystem
The group of classes behind it.
Wish
Something a client wants as a whole, such as watch a movie.
Coarse-grained
Few large operations. The opposite is fine-grained.
Remote facade
A coarse front over a network.
Service layer
The operations of an application with rules and transactions.
Compensation
An action that makes up for an earlier one, such as a refund.
Outbox
Messages written down with the data, sent later.
God object
A class that knows and does too much.
Seam
A place where you can change what is behind without changing what is in front.
Backend for frontend
One remote facade for each kind of client.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Client asks for a wish. One call to one class

Understand it

Start here

One lever for a whole mill

A watermill has a gate, a wheel, a brake, a hopper and a chute. To make flour you must use all of them, in the right order. The Facade pattern gives you one lever. Behind it, everything is still there.

The miller's lever
gatewheelbrakehoppersack

Visitors use the lever. Experts use the side door. The mill is the same mill.

Three parts

  • Facade

    A few methods for common wishes: watch_movie, place_order. Holds the parts, knows the order, passes the work on.

  • Subsystem

    The classes that do the work: Tv, Lights, Inventory. They know nothing of the facade and can be used without it.

  • Client

    Calls the facade for the usual case. May go around it for the unusual one.

Why

What goes wrong without it

Movie night at home: lights down, television on, channel 3, projector on, speakers on, volume 50, DVD player on, play. Eight calls to five devices. Now three buttons in the house do this: the wall panel, the phone, and the voice assistant.

Python
class Speakers:    def __init__(self):        self.on = False    def turn_on(self):        self.on = True    def set_volume(self, percent):        if not self.on:            raise RuntimeError("the speakers are off")        print("volume", percent)class Lights:    def dim(self, percent):        print("lights", percent)def wall_panel(lights, speakers):    lights.dim(10)    speakers.turn_on()    speakers.set_volume(50)def phone(lights, speakers):            # copied, then changed    speakers.set_volume(50)    speakers.turn_on()    lights.dim(10)wall_panel(Lights(), Speakers())try:    phone(Lights(), Speakers())except RuntimeError as error:    print("phone:", error)
Run it. The same steps, copied, in another order. The wall panel works, the phone does not.
Edit and run it in your browser

The design that hurts

WallPanel+ press(): 8 callsTv+ turnOn()+ setChannel(n)Speakers+ turnOn()+ setVolume(p)Lights+ dim(p)

1/2One client

It must know three classes here, five in the real room, their order and their valid numbers.

uses

The smell: the same sequence of calls to the same classes in several places. If one part changes, all clients are edited.

With a facade

  • Clients know one class
  • The order is written once
  • Client tests need one fake
  • A new projector ends at the facade

Without a facade

  • Each client knows every part
  • The order of calls is copied
  • Every test needs five fakes
  • A new projector means editing all clients

The idea

A front door

Write down what clients really want, in their words: watch a movie, end the movie. Make a class with exactly these methods. Give it the parts. Move the sequence of calls into it.

The Facade pattern in general

SubsystemA+ operationA1()+ operationA2()SubsystemB+ operationB1()+ operationB2()SubsystemC+ operationC1()+ operationC2()

1/3The parts

They exist already and work. They may know each other, and none of them knows a facade.

useshas (lives on)

No arrow goes from a part to the facade. If a part must call back, you have a mediator.

One call, eight calls

The lights go down first, so that nobody is dazzled by the projector. Such reasons now have one home.

What a facade knows, so that clients need not

KnowledgeExampleIf a client forgets it
Which partsThe projector is needed tooSound without a picture
OrderTurn on before volumeError
NumbersChannel 3 is the DVD inputThe evening news
StoppingReverse order, all of themThe projector runs all night
FailureNo disc: lights on againPeople sit in the dark
ThreadsOne start at a timeTwo buttons, mixed steps

Two pictures

The universal remote and the concierge

A universal remote has a button Movie night. It replaces none of the devices and none of their own remotes. It only presses their buttons for you, in order. A hotel concierge does the same with people: you ask once, and they call the taxi, the restaurant and the theatre. You could call them yourself, and sometimes you will.

Forms

Kinds of facade

  • Convenience facade

    Short ways for common wishes over a library. subprocess.run over Popen.

  • Module facade

    The only public class of a package. Everything else is private to it.

  • Remote facade

    Coarse methods over a network, so that one wish is one request.

  • Vendor facade

    A small interface in front of a large third-party library. Often an adapter as well.

  • Facade over old code

    New callers use the new front. Behind it the old parts are replaced one by one.

Two facades over one subsystem

GuestApp+ movieNight()HomeTheaterFacade+ watchMovie(m)+ endMovie()Projector+ on()+ off()+ hours()Speakers+ turnOn()+ selfTest()

1/2For guests

Two methods. No word about lamp hours.

useshas (lives on)

One facade for each kind of client, not one for each subsystem.

Choosing

When to use it and when not

Use it when

  • A common wish needs several classes in a certain order
  • Clients should not depend on the parts
  • Layers of a system need an entry point
  • A third-party library is larger than your need
  • Several callers repeat the same calls

Leave it when

  • The subsystem is already simple: one class, two methods
  • Every client needs every option
  • It would only pass calls on, one to one
  • It would collect everything: a god object
  • There is one caller, and a private method is enough

Do I need a facade?

Ten is a rule of thumb, not a law. The question behind it: do all methods serve the same kind of client?

Guests now want to choose the volume and the brightness. The facade has watch_movie(movie). What do you change?

BreaksEleven parameters
How
watch_movie(movie, volume, light, channel, delay, ...)
Limit
The facade has become as complicated as the parts.
Choose when
Never.
WorksGetters for the parts
How
theater.speakers().set_volume(65)
Limit
Clients depend on the parts again, through the facade. Law of Demeter.
Choose when
For an expert tool that says so.
StrongA small settings value with good defaults
How
watch_movie(movie, Scene(volume=65)), and named scenes such as Scene.LATE.
Limit
The value grows slowly. Review it.
Choose when
When a few choices matter to most clients. Experts use the parts directly.

Neighbours

Facade and the patterns beside it

PatternPurposeWrapsDo the parts know it?
FacadeMake many things easyA groupNo
AdapterMake one thing fit an expected interfaceOne, mostlyNo
MediatorLet parts talk without knowing each otherA groupYes, they call it
ProxyControl access, same interfaceOneNo
Abstract factoryHide which classes are createdCreation onlyNo
Service layerThe operations of an application, with transactions and rulesThe domainNo
API gatewayOne network entry for many servicesServicesNo
Facade and service layer often meet in one class. The question is where the rules are: a facade simplifies, a service layer defines what the application can do.

What you gain and what you pay

  • Simple

    One call for one wish, named in the client's words.

  • Loosely coupled

    Parts can be replaced, and clients do not notice.

  • One home

    Order, numbers, undo, metrics and logs of the operation stand in one place.

  • Magnet

    Everybody adds one more method. Without care it becomes the class that knows everything.

  • Hidden cost

    One harmless call may start eight others and a network request. Say so in the name or the documentation.

Summary

The whole topic in one minute.

Collect the wishes of one kind of client. One method per wish, the parts come from outside, the order and the numbers live inside. No arrow goes back.

Starting is all or nothing, stopping is as much as possible. Every step with an effect brings its undo.

In production: keys against repeats, an outbox for mails, one request per wish over a network, a guarded border, and a split by client before it becomes a god object.

  • A facade is a simple front for a group of classes. The group stays usable without it.
  • Methods are wishes of a client, not operations of the parts.
  • It owns order, numbers, stopping and undo of the common operations.
  • Parts do not know the facade. If they call it, it is a mediator.
  • One facade for each kind of client. Split it when it grows.
  • Across a network: one wish, one request, with a time limit and a key.

Sources