Skip to the guide

Open/closed: adding features without editing old code

IntermediateConcept6 pages

The open/closed principle says that a class should be open for extension and closed for modification. In practice, a new feature arrives as new code, and the classes that already work and already have tests stay as they are. Interviewers want to see where your design puts that new code, and whether you know which changes it can't absorb.

A coffee machine that takes pods

Think of a coffee machine that takes pods. The machine heats the water and pushes it through whatever pod sits in its slot. Every pod has the same shape, so a new flavour arrives in the shops as a new pod, and nobody opens the machine. Each cup uses one pod, so you pick the one that suits you best.

In code, the machine is the TicketPricer of a zoo, which sells a $20.00 ticket. The shape of the slot is the Discount interface, whose one method, off, says how much a discount takes off the price. Each pod is a discount class: ChildDiscount, SeniorDiscount and StudentDiscount. One pod a cup is the pricer's rule that only the biggest discount applies, and the pricer does the picking for the visitor. A new flavour on the shelf is a new discount class, and the machine that nobody opens is the pricer's code, which doesn't change.