Notes
The problem
Here is the first version. A shipping quote class has a fee method with a switch over the option name: standard, express and same day, each with its own formula. A second method, days, has another switch with the same three cases. There may be a third switch for the label printer. The code is short and clear, so where is the problem?
long fee(String option, Parcel p) {
switch (option) {
case "STANDARD": return 40 + 10 * kg;
case "EXPRESS": return 90 + 15 * kg;
case "SAME_DAY": return 150 + 3 * km;
default: throw new Illegal...
}
}
int days(String option) {
switch (option) { ... same cases }
} Why it hurts
The product team now wants drone delivery. You must edit the fee switch, the days switch and every other switch on the option name. Miss one, and the code fails at runtime with an unknown option. You also have to retest standard, express and same day, even though nothing about them changed, because their file was edited. Two teams adding options at once will fight over the same lines.
- edit fee(): add a case
- edit days(): add a case
- edit the label code: add a case
- miss one: runtime error
- retest standard, express and
- same day, though they did
- not change
- two teams adding options at
- once: merge conflicts
The idea
The principle says code should be open for extension but closed for modification. Open means you can add new behaviour. Closed means you can do it without editing the code that already works. The usual tool is an abstraction, like an interface, that new code can plug into. The stable code talks only to the interface, so new options arrive as new classes.
- software should be open for
- extension, but closed for
- modification
- open: you can add new
- behaviour
- closed: you do it without
- editing code that already
- works and is tested
- tool: an abstraction to plug into
The structure
Here is the new structure. A delivery option interface describes what every option can do. Standard, express and same day each become a small class that implements it. The shipping quote class holds a list of options and talks only to the interface. It no longer knows the names or formulas of any option, so there is nothing in it to edit when options change.
The interface
The interface has a label, a fee and the number of days for a parcel. It also has an accepts method with a default that says yes, so an option can refuse parcels it cannot carry. Notice that the fee and days logic, which used to live in two separate switches, now sit together in the same class for each option. That alone removes the risk of updating one switch and forgetting the other.
interface DeliveryOption {
String label();
long fee(Parcel parcel);
int days(Parcel parcel);
default boolean accepts(Parcel p) {
return true;
}
}
record Parcel(int kg, int km) { } One option
Each option is now a small class. Express delivery returns its label, charges ninety rupees plus fifteen per kilo, and takes one day, or two days for distances over five hundred kilometres. Everything that is true about express lives in this one place. If express pricing changes, only this file changes, and only express needs retesting.
class ExpressDelivery
implements DeliveryOption {
public String label() {
return "Express"; }
public long fee(Parcel p) {
return 90 + 15L * p.kg(); }
public int days(Parcel p) {
return p.km() > 500 ? 2 : 1; }
} The closed part
The shipping quote class receives a list of options in its constructor. To quote a parcel, it loops over them, skips the ones that do not accept the parcel, and asks each for its label, fee and days. There is no switch and no option name anywhere in this class. That is what closed for modification looks like: it can be finished, tested, and left alone.
private final List<DeliveryOption> opts;
List<String> quotes(Parcel parcel) {
List<String> out = new ArrayList<>();
for (DeliveryOption o : opts)
if (o.accepts(parcel))
out.add(o.label() + ": " +
o.fee(parcel) + " rupees, " +
o.days(parcel) + " days");
return out;
} Adding drone delivery
Now drone delivery arrives. You write one new class. Drones only accept parcels up to two kilos within fifteen kilometres, charge a flat one hundred and twenty rupees, and arrive the same day. Then the wiring code at startup adds it to the list. The shipping quote class and the three old options are not touched, so their tests still pass without being rerun.
class DroneDelivery
implements DeliveryOption {
public boolean accepts(Parcel p) {
return p.kg() <= 2
&& p.km() <= 15; }
public long fee(Parcel p) {
return 120; }
... label(), days()
} Run-through
Quote a one kilo parcel going eight kilometres. The quote class asks standard, then express, then same day for a fee and delivery days. Then it asks the drone whether it accepts the parcel. It does, so the drone gives its flat fee too. For a five kilo parcel, the drone says no and is quietly skipped. The loop never changed.
Something still changes
Be honest about one thing: some code still changes. Somebody has to create the drone option and put it in the list. That happens in the wiring code at startup, not in the business logic. It is a single line, it contains no rules, and it can even come from configuration or a dependency injection container. The principle is about protecting tested logic, not about never editing any file.
ShippingQuote quote = new ShippingQuote(
List.of(new StandardDelivery(),
new ExpressDelivery(),
new SameDayDelivery(),
new DroneDelivery()));
the only edited line: the list
can come from config, a plugin
loader or a DI container Pick the axis
No design is closed against every possible change. Here we protected against new delivery options, because that is what the business keeps asking for. If the change were a new field on every option, the interface would need editing anyway. So pick the axis of change you actually expect. A good habit: the first time, a plain if statement is fine. When a second or third case arrives, extract the interface.
- ask: what will change most?
- here: new delivery options
- first time: a plain if is fine
- second or third new case:
- extract the interface
- do not add plug-in points for
- changes nobody has asked for
The other direction
There is a real trade-off here. With one class per option, adding an option is easy, but adding a new operation, like a carbon footprint estimate, means editing every class. With switches, it is the reverse. Java seventeen adds sealed interfaces, which list all allowed subtypes, a good fit when the set of types is fixed and new operations are more likely. Choose the shape that matches how your code really grows.
- one class per option:
- new option: easy, one file
- new operation: edit every
- class
- one switch per operation:
- new operation: easy
- new option: edit every switch
- Java 17: sealed interfaces
- list every allowed subtype
Where you see it
You use this every day in Java. The sort method on a list is never edited, yet it can sort by anything, because you pass it a new comparator. The service loader finds implementations of an interface at runtime, so libraries can be extended by adding a jar. In Spring, you can inject a list of every bean that implements an interface. Add one more bean, and the list grows with no other change.
- List.sort(Comparator): sort is
- never edited, you pass a new
- Comparator
- ServiceLoader: finds new
- implementations at runtime
- Spring: inject a List of every
- bean of an interface; add
- a bean, the list grows
Related ideas
Many design patterns are ready made ways to follow this principle. Strategy swaps an algorithm behind an interface, which is exactly what we built. Decorator adds behaviour by wrapping an object instead of editing it. Template method fixes the steps and lets subclasses fill in gaps. And it all relies on the next principle, Liskov substitution: a new class only plugs in safely if it behaves the way the interface promises.
- Strategy: swap an algorithm
- behind an interface
- Decorator: add behaviour by
- wrapping, not editing
- Template Method: fixed steps,
- subclasses fill the gaps
- Factory + registry: map a key
- to a new class
- depends on Liskov: new classes
- must behave
In LLD interviews
In LLD interviews, this is what makes a design feel extensible. Parking lot fees, payment methods, notification channels and rate limiting algorithms are all natural plug-in points. Say it out loud: to add a new payment method, I add one class, and checkout does not change. The classic mistakes are switching on a type name in many places, and the opposite, adding interfaces for things that will never vary.
- parking lot: fee strategy per
- vehicle or per lot
- payments: card, UPI, wallet
- notifications: email, SMS, push
- rate limiter: token bucket,
- sliding window
- mistake: switch on a type
- string in many places
- mistake: interfaces for things
- that never vary