SyntaxPilot
Courses/Low-Level Design/Lesson 13

Low-Level Design · Lesson 13 of 90 · 11 min

SOLID 2: Open-Closed Principle

Open-Closed Principleopen for extensionclosed for modificationextension pointsplug-in architectureswitch statement smellpolymorphic extensionprotected variation

These are the notes for Low-Level Design (LLD) episode 13: the O in SOLID, the Open-Closed Principle (OCP). The promise: add a brand new feature without editing a single line of code that already works. We break a food-delivery checkout by adding one payment method, find the smell behind it (the switch statement smell), and invent the fix: extension points, polymorphic extension, a small plug-in architecture, and protected variation. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.

1. The real-life problem: a house with no sockets

Imagine a house with no sockets. A new air conditioner? The electrician breaks open the wall and wires it straight in. A fridge next month? He breaks the same wall again. A microwave? This time he cuts the wrong wire, and the lights, which worked for years, go out. Adding something new broke something old.

Sockets solve this: the wiring is installed once and never opened again, and every new appliance just plugs in. That is the whole idea of today's principle.

2. The checkout that must be cracked open

Two terms first:

  • An enum (episode 3) is a type with a fixed list of named values: enum PayType { UPI, CARD, COD }. COD is cash on delivery; UPI is India's instant bank-to-bank payment system.
  • A switch chooses one branch of code based on a value. A switch statement uses case X: labels and can have a default: branch for "anything else". A switch expression (Java 14+) uses case X -> arrows and produces a value.
enum PayType { UPI, CARD, COD }

class Checkout {
    int fee(PayType t, int amount) {
        switch (t) {
            case UPI:  return 0;
            case CARD: return amount * 2 / 100;   // 2% card charge
            case COD:  return 40;                 // cash-on-delivery handling
            default:   return 0;
        }
    }
    int total(PayType t, int amount) { return amount + fee(t, amount); }
}
public class Main {
    public static void main(String[] args) {
        Checkout c = new Checkout();
        for (PayType t : PayType.values())
            System.out.println(t + ": Rs " + c.total(t, 1000));
    }
}
UPI: Rs 1000
CARD: Rs 1020
COD: Rs 1040

Correct, tested, shipped. Now the product team adds a wallet with a 1% fee. A developer adds WALLET to the enum (enum PayType { UPI, CARD, COD, WALLET }) and nothing else. It compiles. Run:

UPI: Rs 1000
CARD: Rs 1020
COD: Rs 1040
WALLET: Rs 1000

The fee should be Rs 10, but the new value fell into default and got Rs 0. No error, no warning: the company quietly loses 1% on every wallet order.

Making it loud: a switch expression

A switch expression over an enum with no default must cover every value, or the code does not compile:

enum PayType { UPI, CARD, COD, WALLET }

class Checkout {
    int fee(PayType t, int amount) {
        return switch (t) {
            case UPI  -> 0;
            case CARD -> amount * 2 / 100;
            case COD  -> 40;
        };
    }
    int total(PayType t, int amount) { return amount + fee(t, amount); }
}
Main.java:5: error: the switch expression does not cover all possible input values
        return switch (t) {
               ^
1 error

Better: the compiler found the missing case. But the fix is still the same: open Checkout and edit tested code, in every switch that branches on PayType.

3. Why it hurts: the switch statement smell

A code smell is a pattern in code that hints at a design problem (episode 12). The switch statement smell is code that branches on a type code, a value that says what kind of thing something is (PayType, shapeType, userKind).

  • Every new kind forces an edit to code that was already tested and shipped, so it must all be retested.
  • The switch never stays alone: fees, labels, refunds and receipts each switch on the same type. Every new type edits all of them.
  • Miss one, and default hides it (silent wrong answer) or, at best, the build breaks.

What we want is the opposite: add the new kind without editing the old code at all.

4. The Open-Closed Principle

"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." Bertrand Meyer, Object-Oriented Software Construction, 1988

  • Software entity: any piece of code: a class, a module, a function.
  • Open for extension: you can make it do new things (new payment methods).
  • Closed for modification: you do that without editing its source code, which is already tested and in use.

It sounds like a contradiction. The wall socket shows how both can be true:

At home In Java Role
Wall socket: a fixed shape every plug follows interface PaymentMethod the extension point
Wiring inside the wall: never opened again class Checkout closed for modification
Any new appliance: just plug it in class Wallet open for extension

5. Polymorphic extension: a new feature is a new class

interface PaymentMethod { String name(); int fee(int amount); }   // the extension point
class Upi implements PaymentMethod {
    public String name() { return "UPI"; }
    public int fee(int amount) { return 0; }
}
class Card implements PaymentMethod {
    public String name() { return "CARD"; }
    public int fee(int amount) { return amount * 2 / 100; }
}
class Cod implements PaymentMethod {
    public String name() { return "COD"; }
    public int fee(int amount) { return 40; }
}
class Checkout {                          // closed: no switch, never edited again
    int total(PaymentMethod m, int amount) { return amount + m.fee(amount); }
}
class Wallet implements PaymentMethod {   // open: a NEW class, no edits above
    public String name() { return "WALLET"; }
    public int fee(int amount) { return amount / 100; }
}
public class Main {
    public static void main(String[] args) {
        Checkout c = new Checkout();
        PaymentMethod[] all = { new Upi(), new Card(), new Cod(), new Wallet() };
        for (PaymentMethod m : all)
            System.out.println(m.name() + ": Rs " + c.total(m, 1000));
    }
}
UPI: Rs 1000
CARD: Rs 1020
COD: Rs 1040
WALLET: Rs 1010
  • Each case of the switch became a class.
  • Checkout has no switch and knows no payment method by name.
  • Wallet was added; no line above it was edited. The three old methods give exactly what they gave before, because their code never changed.

Names for what we built:

  • Extension point: a place in the design made on purpose for new code to plug in. Here, PaymentMethod.
  • Polymorphic extension: adding behaviour by writing a new class behind an interface. Checkout calls m.fee(amount) and runtime polymorphism (episode 9: Java picks the method of the object's real class at run time) runs the right version.
  • Meyer's original 1988 version extended classes through implementation inheritance. In the 1990s the idea was redefined around abstract interfaces and polymorphism: the polymorphic open-closed principle, popularised by Robert C. Martin's 1996 article The Open-Closed Principle. That's the version most people mean today.

A classic mistake: weaker access privileges

Forget public on the new class's method:

class Wallet implements PaymentMethod {
    public String name() { return "WALLET"; }
    int fee(int amount) { return amount / 100; }   // no public
}
Main.java:19: error: fee(int) in Wallet cannot implement fee(int) in PaymentMethod
    int fee(int amount) { return amount / 100; }
        ^
  attempting to assign weaker access privileges; was public
1 error

Interface methods are always public, so implementations must be public too.

6. Plug-in architecture

A plug-in is a piece added to a program from outside, without changing its core. A plug-in architecture is a small, stable core plus a defined way to register plug-ins. A registry is a lookup table of available plug-ins, here a Map (episode 4: stores values by key).

import java.util.*;

interface PaymentMethod { String name(); int fee(int amount); }
class Upi implements PaymentMethod {
    public String name() { return "UPI"; }
    public int fee(int amount) { return 0; }
}
class Wallet implements PaymentMethod {
    public String name() { return "WALLET"; }
    public int fee(int amount) { return amount / 100; }
}
class Checkout {                         // the core: knows no payment method by name
    private final Map<String, PaymentMethod> plugins = new HashMap<>();
    void register(PaymentMethod m) { plugins.put(m.name(), m); }
    int total(String name, int amount) {
        PaymentMethod m = plugins.get(name);
        if (m == null) throw new IllegalArgumentException("No plug-in for " + name);
        return amount + m.fee(amount);
    }
}
public class Main {
    public static void main(String[] args) {
        Checkout c = new Checkout();
        c.register(new Upi());           // plug-ins are added at start-up
        c.register(new Wallet());
        System.out.println("WALLET: Rs " + c.total("WALLET", 1000));
        System.out.println("CRYPTO: Rs " + c.total("CRYPTO", 1000));
    }
}
WALLET: Rs 1010
Exception in thread "main" java.lang.IllegalArgumentException: No plug-in for CRYPTO
    at Checkout.total(Main.java:17)
    at Main.main(Main.java:27)

An unknown name is a clear failure with the exact name, instead of a silent zero. Supporting crypto would be one new class and one register line; the core never changes.

You use plug-in architectures every day: browser extensions (the browser isn't rebuilt to add an ad blocker), code-editor extensions (new languages without a new editor), apps on a phone (installing one doesn't change the operating system), and payment gateways (a new method behind one interface).

7. Protected variation and strategic closure

A house doesn't put a socket every ten centimetres; you put them where appliances are expected.

  • Variation point: a place in the design you expect to change (payment methods, discount rules, notification channels).
  • Protected variation: put a stable interface around each predicted variation point, so changes behind it can't ripple outwards. It is a pattern by Alistair Cockburn; in 2001 Craig Larman linked it to the open-closed principle (and to David Parnas's information hiding, episode 6).
  • Strategic closure: no class can be closed against every possible change. You choose which changes to protect against, based on what really changes in your domain. An interface around everything "just in case" is complexity for nothing.

8. When editing is still right

OCP is not "never edit old code".

Change What to do
A bug in total() Fix it. Edit the core.
A rule for all payments changes (e.g. a new tax on the platform fee) The core's own job changed. Edit the core.
One more variant of something that varies (BNPL, crypto, gift card) Add a class. Don't edit.

The skill is telling these two kinds of change apart.

The class diagram

+--------------------------------------+   uses   +-----------------------+
| Checkout                             | -------> | <<interface>>         |
| - plugins: Map<String,PaymentMethod> |          | PaymentMethod         |
| + register(m)                        |          | + name(): String      |
| + total(name, amount): int           |          | + fee(amount): int    |
+--------------------------------------+          +-----------------------+
                                                     ^   ^   ^   ^   (dashed, hollow triangle:
                                          Upi  Card  Cod  Wallet      "realizes the interface")

Adding Wallet added one box and one line; nothing else on the diagram changed.

Common mistakes

Mistake Exact message Why Fix
default: return 0; in a switch on a type no error: WALLET: Rs 1000 A new value falls into default Polymorphism, or no default
Adding an enum value, missing a switch error: the switch expression does not cover all possible input values Every switch must be edited One class per variant
int fee(int amount) in Wallet attempting to assign weaker access privileges; was public Interface methods are public public int fee(...)
Looking up an unregistered plug-in IllegalArgumentException: No plug-in for CRYPTO Nobody registered it Register it at start-up
An interface for everything "just in case" no error: just complexity Closure is strategic Only at real variation points

Mini project

Add a GiftCard payment method with a flat Rs 10 fee to the plug-in checkout, and print totals for UPI, WALLET and GIFTCARD on Rs 1000. Don't edit Checkout.

Solution
import java.util.*;

interface PaymentMethod { String name(); int fee(int amount); }
class Upi implements PaymentMethod {
    public String name() { return "UPI"; }
    public int fee(int amount) { return 0; }
}
class Wallet implements PaymentMethod {
    public String name() { return "WALLET"; }
    public int fee(int amount) { return amount / 100; }
}
class GiftCard implements PaymentMethod {          // the only new code
    public String name() { return "GIFTCARD"; }
    public int fee(int amount) { return 10; }
}
class Checkout {
    private final Map<String, PaymentMethod> plugins = new HashMap<>();
    void register(PaymentMethod m) { plugins.put(m.name(), m); }
    int total(String name, int amount) {
        PaymentMethod m = plugins.get(name);
        if (m == null) throw new IllegalArgumentException("No plug-in for " + name);
        return amount + m.fee(amount);
    }
}
public class Main {
    public static void main(String[] args) {
        Checkout c = new Checkout();
        c.register(new Upi());
        c.register(new Wallet());
        c.register(new GiftCard());                  // plus one line here
        for (String n : List.of("UPI", "WALLET", "GIFTCARD"))
            System.out.println(n + ": Rs " + c.total(n, 1000));
    }
}

Output:

UPI: Rs 1000
WALLET: Rs 1010
GIFTCARD: Rs 1010

Checkout was not edited. One new class, one register line.

Practice

  1. Do the video's quiz: replace the shape switch with a Shape interface. Print the areas of a circle (r = 2), a square (a = 3) and a regular hexagon (side 2; area = 3√3/2 · s²).
Solution
interface Shape { String name(); double area(); }
record Circle(double r) implements Shape {
    public String name() { return "Circle"; }
    public double area() { return Math.PI * r * r; }
}
record Square(double a) implements Shape {
    public String name() { return "Square"; }
    public double area() { return a * a; }
}
record Hexagon(double s) implements Shape {          // added, nothing edited
    public String name() { return "Hexagon"; }
    public double area() { return 3 * Math.sqrt(3) / 2 * s * s; }
}
public class Main {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(2), new Square(3), new Hexagon(2) };
        for (Shape s : shapes)
            System.out.printf("%s: %.2f%n", s.name(), s.area());
    }
}

Output:

Circle: 12.57
Square: 9.00
Hexagon: 10.39
  1. Because PaymentMethod has two methods, it can't be a lambda. Design a one-method FeeRule interface and register fee rules as lambdas in a Map<String, FeeRule>.
Solution
import java.util.*;

@FunctionalInterface
interface FeeRule { int fee(int amount); }

public class Main {
    public static void main(String[] args) {
        Map<String, FeeRule> rules = new LinkedHashMap<>();
        rules.put("UPI", amount -> 0);
        rules.put("CARD", amount -> amount * 2 / 100);
        rules.put("WALLET", amount -> amount / 100);   // a new rule = one new line
        rules.forEach((name, rule) -> System.out.println(name + ": Rs " + (1000 + rule.fee(1000))));
    }
}

Output:

UPI: Rs 1000
CARD: Rs 1020
WALLET: Rs 1010

A functional interface has exactly one abstract method, so a lambda (episode 5) can implement it. This is the same extension point, just lighter.

  1. Which of these changes should edit Checkout, and which should add a class? (a) Card fee goes from 2% to 1.5%. (b) A 5% platform fee on every order. (c) Pay-later (BNPL) with a Rs 25 fee.
Solution

(a) Edit Card, not Checkout: the card's own rule changed. (b) Edit Checkout: a rule for all payments is the core's own job. (c) Add a PayLater class and register it: one more variant.

  1. List three variation points in a ride-booking app and the interface you'd put at each.
Solution

Pricing (FareRule: normal, surge, night), vehicle types (VehicleType: bike, auto, cab), and notifications (Notifier: SMS, push, email). Each changes often, so each deserves an extension point. The trip-booking flow itself changes rarely: no interface needed there.

Quick quiz

double area(Shape s) {
    switch (s.type) {
        case CIRCLE: return 3.14 * s.r * s.r;
        case SQUARE: return s.a * s.a;
        default:     return 0;
    }
}

Tomorrow you need a Hexagon. Which change follows OCP?

  • A. Add case HEXAGON to the switch
  • B. Add a Shape interface with area(); one class per shape
  • C. Remove the default branch
  • D. Put a comment: "add new shapes here"
Answer

B. Then a hexagon is a new class and area(Shape) is never edited again. A works today but repeats the problem for every new shape; C only turns a silent bug into a loud one (still an edit); D changes nothing.

Interview questions

  1. State the Open-Closed Principle. Software entities should be open for extension but closed for modification (Bertrand Meyer, 1988): you add behaviour by adding code, not by editing tested code.
  2. How do you achieve OCP in Java? Put an interface (or abstract class) at the point that varies; each variant is a new implementing class; the core depends only on the interface and uses polymorphism.
  3. What is the switch statement smell? Branching on a type code. Every new type edits every such switch; a default can hide a missing case.
  4. Is a switch expression without default enough? It makes a missing case a compile error ("does not cover all possible input values"), which is better, but adding a type still means editing every switch. Polymorphism (or sealed types where the set of variants is fixed) is the structural fix.
  5. What's the difference between Meyer's OCP and the polymorphic OCP? Meyer extended classes by implementation inheritance; the 1990s version (popularised by Robert C. Martin, 1996) uses abstract interfaces and swappable implementations.
  6. What is a plug-in architecture? A small stable core plus a registry of plug-ins that implement a known interface; new features are new plug-ins.
  7. What is protected variation? Wrapping a predicted variation point in a stable interface (Cockburn; linked to OCP by Larman, 2001).
  8. Can a class be closed against all changes? No. Closure is strategic: choose likely variation points; don't add interfaces everywhere.
  9. Does OCP forbid fixing bugs in old code? No. Bugs and changes to the core's own job are edits; new variants are extensions.
  10. How does OCP relate to SRP? SRP gives each actor its own class; OCP lets each class grow through extension points instead of edits. Together they keep changes small and local.

Glossary

Term Meaning, with an example
Open-Closed Principle (OCP) Software entities should be open for extension, closed for modification (Meyer, 1988)
Software entity Any piece of code: a class, module or function
Open for extension You can make it do new things. Adding a wallet payment
Closed for modification Its tested source code isn't edited to do so. Checkout stays as it is
Enum A type with a fixed list of named values. enum PayType { UPI, CARD, COD }
UPI India's instant bank-to-bank payment system
COD Cash on delivery
Switch statement Chooses a branch with case X: labels; may have default:
Switch expression case X -> branches that produce a value; over an enum without default it must cover every value
Default branch The "anything else" branch of a switch; can silently swallow new values
Type code A value saying what kind of thing something is. PayType, shapeType
Code smell A pattern in code that hints at a design problem
Switch statement smell Branching on a type code, usually repeated in many places
Extension point A place designed on purpose for new code to plug in. PaymentMethod
Interface A list of methods a class promises to provide (episode 3)
Polymorphic extension Adding behaviour with a new class behind an interface. class Wallet implements PaymentMethod
Runtime polymorphism Java picks the method of the object's real class at run time (episode 9)
Polymorphic open-closed principle The 1990s version of OCP built on interfaces and polymorphism (Martin, 1996)
Weaker access privileges Compile error when an implementation is less visible than the interface method
Plug-in A piece added to a program from outside without changing its core
Plug-in architecture A small stable core plus a defined way to register plug-ins
Core The stable part of a program that plug-ins attach to
Registry A lookup table of available plug-ins. Map<String, PaymentMethod>
IllegalArgumentException Unchecked exception for a bad argument. No plug-in for CRYPTO
Variation point A place you expect to change. Payment methods, discount rules
Protected variation A stable interface around a predicted variation point (Cockburn; Larman, 2001)
Strategic closure Choosing which changes to close against; no class is closed to all
Functional interface An interface with exactly one abstract method; a lambda can implement it
Lambda A short unnamed function. amount -> amount / 100

Summary

  • OCP: open for extension, closed for modification (Bertrand Meyer, 1988).
  • A switch on a type code forces edits to tested code for every new type; default can hide the missing case (WALLET: Rs 1000).
  • Put an extension point (an interface) at the place that varies; each variant is a new class (polymorphic extension).
  • A plug-in architecture adds a registry: a new feature is one class plus one register line.
  • Protected variation: interfaces only at predicted variation points. Closure is strategic.
  • Fixing bugs and changing the core's own job are still edits.

Next episode: SOLID 3: The Liskov Substitution Principle: when a subclass quietly breaks its parent's promise.