A state electricity board sends a bill to every connection each month. Homes, shops and farms pay different rates, so the billing code asks the same two questions of every category: what do these units cost, and what is the fixed charge? Then the state starts a new category for electric vehicle (EV) charging stations, and someone has to teach the code about it.
The Open/Closed Principle says that adding a new kind of thing, like this new category, should mean adding new code, not editing code that already works.
The principle
A class is open for extension when new behaviour can be added to it from outside. It is closed for modification when that new behaviour needs no edit inside it. Code that follows the principle has a place where new kinds plug in, usually an interface. A new kind is a new class that implements it.
The reason is risk. Code that already works has been tested and is running. Each edit to it can break something that was fine. The more places one change has to touch, the more likely it is that one of them is missed.
What it does not say
- It does not say a file is never edited again. A bug in the domestic rates is fixed in the domestic class. Adding a new category still needs one new line where the categories are listed. If the questions themselves change, the interface changes. All three are edits, and all three are fine.
- It does not ask you to close code against every change. You close it against the changes you expect, the kind that has happened before and will happen again. A guess about a change that never comes leaves an interface with one class behind it, and every reader has to step through it.
Example: an electricity bill
Our board has three consumer categories. Each pays an energy charge for the units it used, and a fixed charge for its sanctioned load, the kilowatts the connection is allowed to draw. The rates are examples, not any board's real tariff:
| Category | Energy charge | Fixed charge |
|---|---|---|
| Domestic | $0.12 a unit for the first 100 units, $0.15 for the next 200, $0.20 after that | $4 per kW |
| Commercial | $0.18 a unit | $10 per kW |
| Agricultural | $0.06 a unit | None |
All money in the code is in cents, so $0.12 is 12 and no amount needs a decimal. The first version keeps the category as an enum and uses a switch wherever a rate is needed:
enum Category { DOMESTIC, COMMERCIAL, AGRICULTURAL } final class BillCalculator { long energyCharge(Category category, int units) { switch (category) { case DOMESTIC: return domesticSlabs(units); case COMMERCIAL: return units * 18L; case AGRICULTURAL: return units * 6L; default: throw new IllegalArgumentException("No energy rate for " + category); } } long fixedCharge(Category category, int sanctionedLoadKw) { switch (category) { case DOMESTIC: return sanctionedLoadKw * 400L; case COMMERCIAL: return sanctionedLoadKw * 1_000L; default: return 0; // farm connections pay no fixed charge } } // billInCents() adds the two charges; domesticSlabs() works out the three slabs.}A third switch, in a BillPrinter class, picks the tariff code printed on the bill. This code is fine as long as the categories never change.
The change request
The state announces a tariff for public EV charging stations: $0.25 a unit and $5 per kW of sanctioned load. The developer adds EV_CHARGING to the enum. Then they search for every switch over Category and add a case. They find energyCharge, because the first EV bill throws there, and tariffCode in the printer. They miss fixedCharge.
Its default: return 0 was written for farms, which pay no fixed charge. EV stations now fall into it too. Nothing throws and the compiler says nothing. Every EV station gets a bill without its fixed charge: one that used 3,000 units on a 40 kW load pays $750 instead of $950. The mistake shows up only when someone audits the bills.
Writing each switch as a switch expression with no default would make the compiler report a missing case. That helps, but each new category is still an edit to three working methods in two classes. Each of those edits can break a category that was already right.
Following the principle
Each category becomes a class behind one interface. The interface holds the questions every category must answer:
/** One consumer category's rates. All money is in cents. */interface Tariff { String code(); long energyCharge(int units); long fixedCharge(int sanctionedLoadKw);}DomesticTariff, CommercialTariff and AgriculturalTariff each hold their own rates. The calculator holds the tariffs, keyed by code, and never names one:
final class BillCalculator { private final Map<String, Tariff> tariffsByCode = new HashMap<>(); BillCalculator(List<Tariff> tariffs) { for (Tariff tariff : tariffs) { if (tariffsByCode.putIfAbsent(tariff.code(), tariff) != null) { throw new IllegalArgumentException("Two tariffs use the code " + tariff.code()); } } } long billInCents(String tariffCode, int units, int sanctionedLoadKw) { Tariff tariff = tariffsByCode.get(tariffCode); if (tariff == null) { throw new IllegalArgumentException("Unknown tariff " + tariffCode); } return tariff.energyCharge(units) + tariff.fixedCharge(sanctionedLoadKw); }}billInCents refuses a code it does not know, instead of billing zero. The constructor refuses two tariffs with the same code, because the second one could never be reached.
Now the same change request arrives. EV charging is one new class:
final class EvChargingTariff implements Tariff { private static final long CENTS_PER_UNIT = 25; // $0.25 private static final long FIXED_CENTS_PER_KW = 500; // $5 @Override public String code() { return "LT-EV"; } @Override public long energyCharge(int units) { return units * CENTS_PER_UNIT; } @Override public long fixedCharge(int sanctionedLoadKw) { return sanctionedLoadKw * FIXED_CENTS_PER_KW; }}It also needs one new line where the app builds the calculator:
BillCalculator calculator = new BillCalculator(List.of( new DomesticTariff(), new CommercialTariff(), new AgriculturalTariff(), new EvChargingTariff())); // the one new lineBillCalculator, Tariff and the three old categories do not change. EV stations have no default to fall into. EvChargingTariff does not compile until it implements fixedCharge, so the developer has to decide the fixed charge. BillPrinter prints tariff.code(), so its switch is gone too. The same EV station is now billed $950.
The change this design makes harder
The new design makes adding a category cheap. It makes adding a question expensive. Suppose the state announces a subsidy with a different rule for each category. Homes get their first 100 units free, farms get all their units free, and shops and EV stations get nothing. That is a new method, subsidy(units), on Tariff. Every tariff class must implement it, and BillCalculator must subtract it. In the switch version, it would be one new method in BillCalculator, with one more switch, and one changed line in billInCents.
A Java default method on Tariff that returns 0 would spare the two classes that get nothing. It is also the same silent fallback that billed EV stations wrongly. A category added later would get no subsidy without anyone deciding that.
So the principle asks one question of a design: which way will it grow? For a billing system, new categories are the change we expect, so we close the code against that one.
When not to
An interface and a class per kind are a cost, worth paying only for a change you expect. Suppose we also put the bill's due date behind a DueDatePolicy interface, in case it ever differs by category. If every category keeps the same 15 days, we have an interface, a class and a lookup for a change that never came. A constant would have been clearer. The interface can be added on the day a second rule appears.
Rates are the other trap. Boards revise their rates from time to time. A new rate is a new number, not a new rule. In a real billing system, the rates in our classes would come from a rate table, so a revision changes data and no class. A new class is worth writing when the rule is different, the way the domestic slabs are a different rule from a flat rate.
In an interview
The principle is the reason behind many interfaces you draw in a low-level design (LLD) round. When the interviewer asks "what if the business adds a new kind?", a good answer is "one new class and one line where the objects are listed". Name the change you designed for, and say which change your design makes harder. The Parking Lot uses this for the parking fee and for choosing a spot, and the Strategy pattern page shows the same move on a checkout.
Common mistakes:
- An interface for every class, "in case". It closes the code against changes nobody expects, and every reader pays for it.
- Claiming the code never changes. The registration line and bug fixes are edits. The claim to make is that working categories are not edited.
- A
defaultthat quietly returns 0. A new kind falls into it without anyone deciding that. A compile error or an exception is safer.
Summary
- Adding a new kind of thing should mean adding a class, not editing code that already works.
- A
switchover a type, repeated in several methods, is the usual sign of trouble. Every new kind edits every switch, and a missed one is a silent bug when adefaultcatches it. - The usual fix is one interface for the questions every kind answers, which is the Strategy pattern.
- Close the code against the changes you expect. A new question still touches every class.
- Bug fixes and the one registration line are edits too, and that is fine.