LOW-LEVEL DESIGN · SOLID PRINCIPLES · O · 9 OF 48

Open/Closed Principle in Java: Extend Without Editing Old Code

The O in SOLID, shown with a courier app whose delivery fees live in a growing switch statement. Learn what open for extension and closed for modification really mean, how an interface plus one class per option lets you add drone delivery without touching tested code, which axis of change to protect, the sealed-type trade-off, and how it appears in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 17

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 123 lines, with a small main() demo. Save it as OpenClosedDemo.java, then run javac OpenClosedDemo.java && java OpenClosedDemo.

import java.util.ArrayList;
import java.util.List;

/** Open/closed: a switch that must be edited for every option, then options as pluggable classes. */
public class OpenClosedDemo {

    public static void main(String[] args) {
        Parcel small = new Parcel(1, 8);
        Parcel heavy = new Parcel(5, 600);

        System.out.println("--- Before: switch on the option name ---");
        ShippingQuoteV1 v1 = new ShippingQuoteV1();
        for (String option : List.of("STANDARD", "EXPRESS", "SAME_DAY")) {
            System.out.println(option + ": " + v1.fee(option, small) + " rupees, "
                    + v1.days(option) + " days");
        }
        try {
            v1.fee("DRONE", small);
        } catch (IllegalArgumentException e) {
            System.out.println("DRONE: " + e.getMessage() + " (must edit every switch)");
        }

        System.out.println();
        System.out.println("--- After: one class per option ---");
        // The wiring is the only place that changed when drone delivery was added.
        ShippingQuote quote = new ShippingQuote(List.of(
                new StandardDelivery(), new ExpressDelivery(), new SameDayDelivery(), new DroneDelivery()));
        System.out.println("1 kg, 8 km:");
        quote.quotes(small).forEach(line -> System.out.println("  " + line));
        System.out.println("5 kg, 600 km (same day and drone refuse it):");
        quote.quotes(heavy).forEach(line -> System.out.println("  " + line));
    }
}

record Parcel(int kg, int km) { }

// ---------------------------------------------------------------
// BEFORE: every option is a case, repeated in every method.
// Adding an option means editing this tested class in several places.
// ---------------------------------------------------------------
class ShippingQuoteV1 {

    long fee(String option, Parcel p) {
        switch (option) {
            case "STANDARD": return 40 + 10L * p.kg();
            case "EXPRESS": return 90 + 15L * p.kg();
            case "SAME_DAY": return 150 + 3L * p.km();
            default: throw new IllegalArgumentException("unknown option " + option);
        }
    }

    int days(String option) {
        switch (option) {
            case "STANDARD": return 5;
            case "EXPRESS": return 1;
            case "SAME_DAY": return 0;
            default: throw new IllegalArgumentException("unknown option " + option);
        }
    }
}

// ---------------------------------------------------------------
// AFTER: ShippingQuote is closed; new options are new classes.
// ---------------------------------------------------------------
interface DeliveryOption {
    String label();

    long fee(Parcel parcel);

    int days(Parcel parcel);

    /** Options that cannot carry every parcel override this. */
    default boolean accepts(Parcel parcel) {
        return true;
    }
}

class StandardDelivery implements DeliveryOption {
    @Override public String label() { return "Standard"; }
    @Override public long fee(Parcel p) { return 40 + 10L * p.kg(); }
    @Override public int days(Parcel p) { return p.km() > 500 ? 7 : 5; }
}

class ExpressDelivery implements DeliveryOption {
    @Override public String label() { return "Express"; }
    @Override public long fee(Parcel p) { return 90 + 15L * p.kg(); }
    @Override public int days(Parcel p) { return p.km() > 500 ? 2 : 1; }
}

class SameDayDelivery implements DeliveryOption {
    @Override public String label() { return "Same day"; }
    @Override public long fee(Parcel p) { return 150 + 3L * p.km(); }
    @Override public int days(Parcel p) { return 0; }
    @Override public boolean accepts(Parcel p) { return p.km() <= 50; }
}

/** Added later as a brand new file. Nothing above was edited. */
class DroneDelivery implements DeliveryOption {
    @Override public String label() { return "Drone"; }
    @Override public long fee(Parcel p) { return 120; }
    @Override public int days(Parcel p) { return 0; }
    @Override public boolean accepts(Parcel p) { return p.kg() <= 2 && p.km() <= 15; }
}

/** Closed for modification: it never names a specific option. */
class ShippingQuote {
    private final List<DeliveryOption> options;

    ShippingQuote(List<DeliveryOption> options) {
        this.options = List.copyOf(options);
    }

    List<String> quotes(Parcel parcel) {
        List<String> out = new ArrayList<>();
        for (DeliveryOption option : options) {
            if (option.accepts(parcel)) {
                out.add(option.label() + ": " + option.fee(parcel) + " rupees, "
                        + option.days(parcel) + " days");
            }
        }
        return out;
    }
}

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?

ShippingQuoteV1
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.

Adding drone delivery
  • 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.

The principle
  • 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.

DeliveryOption
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.

ExpressDelivery
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.

ShippingQuote
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.

DroneDelivery
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.

Main, the wiring
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.

Which change to protect
  • 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.

A real trade-off
  • 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.

In Java and frameworks
  • 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.

How it relates
  • 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.

Where it comes up
  • 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

Interview questions

What is the open/closed principle?

Software entities should be open for extension but closed for modification. You add new behaviour by writing new code, usually a new class behind an existing abstraction, instead of editing code that already works and is tested.

How do you refactor a switch on a type into something that follows OCP?

Create an interface with the operations the switch performs, move each case into its own implementing class, and let the caller hold a list or map of implementations. Adding a type then means adding a class and registering it, with no change to the caller.

Does OCP mean you never modify existing code?

No. Bug fixes still change code, and the wiring that creates objects usually changes when you add a new class. The goal is that business logic which is already tested does not need editing for the kind of change you expect most often.

Can you be closed against every possible change?

No. Every abstraction protects against one kind of change and makes some other kind harder. Pick the axis of change the business actually brings, and avoid adding extension points for changes nobody has asked for.

Which design patterns help you follow OCP?

Strategy, Decorator, Template Method, Observer and Factory with a registry are common ones. Each provides a fixed structure where new behaviour plugs in as a new class rather than as an edit to existing code.

Where does Java itself follow the open/closed principle?

List.sort and Collections.sort accept any Comparator, so sorting is extended without changing the sort code. ServiceLoader discovers new implementations of an interface at runtime, and frameworks like Spring can inject every bean that implements an interface.

When is a switch statement better than polymorphism?

When the set of types is small and fixed but new operations are added often. Then one switch per operation, ideally over a sealed type, keeps each operation in one place. Polymorphism wins when new types are added more often than new operations.

How would you apply OCP in a parking lot design?

Put fee calculation behind a FeeStrategy interface, with classes such as HourlyFee or FlatWeekendFee, and let the parking lot hold a strategy per vehicle type. New pricing models are new classes, and the lot itself stays unchanged.