Part 2 of 7 · 1 min read
The principle
Extend by adding, not by editing.
Think of a power strip. When a new device arrives, a person plugs it into a spare socket. Nobody opens the wall and rewires the house. The strip is open for extension (more sockets), and the wiring is closed for modification (it stays as it is).
Bertrand Meyer named the principle in 1988. CA sums it up in a short phrase: open to extension, shut to modification. New behaviour should arrive as added code, and old code that already works should stay as it is.
HF explains why this matters. The old code has already been tested and its bugs removed. Each edit to it risks new bugs in features that used to work. A design that lets people add instead of edit holds up better when requirements change, and they always do.
It sounds contradictory, since a thing that cannot be changed is hard to extend. HF answers with an example from the observer pattern: adding a new observer extends a subject without any code change inside the subject. The trick is to place a stable abstraction (an interface) between the old code and the new code. The old code talks to the interface. New code arrives as another class that implements it.
Open-closed principle
The open-closed principle says that a class or module should allow new behaviour to be added by writing new code, without editing the code that is already there.
Example: a Pricer that accepts one more PricingRule class, with no change to Pricer.
Check yourself: 1. Why is editing working code risky? 2. What stands between old code and new code to make extension possible? 3. How does the power strip show the idea?