Facade Pattern
Learn how to hide a complicated set of classes behind one simple entry point, using an order placement example, and how to avoid turning a facade into a giant class.
When you stay in a hotel and want a taxi, a table at a restaurant and tickets for a show, you do not phone the taxi company, the restaurant and the theatre yourself. You go to the reception desk or ask the concierge, and say "please arrange my evening". The concierge knows whom to call, in which order and what to say. You get one simple interface, and all the complicated work happens behind the desk.
The Facade pattern gives your code a reception desk. A facade is a class that offers one simple interface to a complex group of classes, and takes care of the details of calling them in the right way. A "facade" is also the front wall of a building, which is a good picture: visitors see a neat front, and the complicated plumbing and wiring stay behind it.
01The problem: too many parts to know
Think about what placing an order in an online shop really involves. Behind one button, several parts of the system must work together, in the right order:
- check that the item is in stock, and reserve it,
- charge the customer,
- if the payment fails, release the reserved stock,
- schedule the shipping,
- send a confirmation message.
Each step is a separate class with its own methods and rules. If every screen or API endpoint that places an order has to do all of this itself, you get:
- Duplicated code: the same five steps copied in the website, the mobile API and the admin tool.
- Mistakes: one copy forgets to release the stock when payment fails.
- Tight coupling: every caller knows four subsystems and the order of calls. When one subsystem changes, many callers break.
Loading the rest of the lesson…