Commissioned for this museum · after Gamma, Helm, Johnson & Vlissides, 1994
Facade
TypeScript·1994·36 lines·770 bytes
/**
* Facade — one small surface in front of several larger ones.
*/
class Oven {
heatTo(celsius: number): void {
console.log("oven at " + celsius + "C");
}
}
class Mixer {
mix(what: string): void {
console.log("mixing " + what);
}
}
class Timer {
ring(minutes: number): void {
console.log("ring in " + minutes + " min");
}
}
class Kitchen {
private readonly oven = new Oven();
private readonly mixer = new Mixer();
private readonly timer = new Timer();
// One method, because one method is what almost every caller wants. The
// oven, mixer and timer are still there for the caller who does not.
bakeBread(): void {
this.mixer.mix("flour, water, salt, yeast");
this.oven.heatTo(220);
this.timer.ring(35);
}
}
new Kitchen().bakeBread();Curator’s note
A facade is not a wrapper. A wrapper covers everything underneath and forwards it; a facade covers the one path almost everybody wants and leaves the rest visible. The difference is a judgement about your callers, and it is the only judgement this pattern asks you to make: what is the common case, and is it common enough to deserve a name?
That judgement is also where facades go wrong. bakeBread is a good one because bread is genuinely what most people came for. The failure mode is a facade that keeps growing — a parameter for the temperature, then one for the rise time, then an options object with eleven fields — until it is the subsystem again with an extra layer of indirection in front of it. At that point it has stopped simplifying anything and started costing a hop. A facade that has to expose everything underneath was the wrong shape to begin with.
The name is architectural and the metaphor is exact. A facade on a building is the face it shows the street: it is not the building, it does not pretend to be the building, and nobody is confused about whether there are rooms behind it. The moment a facade tries to *be* the subsystem rather than present it, it becomes a wall — and walls get doors cut into them later, by people who are annoyed about it.
The version worth having is the one you could delete in an afternoon, because everything it calls is still reachable without it.
Elsewhere in the museum
- LectureWhat abstraction costs
- LectureWhy programs are hard to change