Low-Level Design Tutorial 0/42 lessons ~6 min read Lesson 12

    Open Closed Principle

    The Open/Closed Principle (OCP) says software entities should be open for extension but closed for modification.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    The Open/Closed Principle (OCP) says software entities should be open for extension but closed for modification. Add a new payment type by introducing a class — not by editing a switch in Checkout for the fifth time.

    Interviewers test OCP with extension questions: motorcycles in parking lot, new chess pieces, international tax rules. Your design passes if existing classes stay untouched.

    OCP pairs with polymorphism, strategy pattern, and registry-based factories.

    Understanding the topic

    Key concepts

    • Extend behavior via new types, not editing stable code.
    • Abstractions define extension points.
    • Registry/factory maps keys to implementations.
    • Closed for modification reduces regression risk.
    • Over-abstraction violates YAGNI — extend when needed.
    • Template Method opens extension through overridden hooks.

    Step-by-step explanation

    1. Identify likely variation (vehicle type, discount rule).
    2. Extract interface or abstract hook at variation point.
    3. Client depends on abstraction only.
    4. Register new implementations in factory or DI container.
    5. Verify adding variant requires zero client edits.
    6. Document how to register extensions.

    Informative example

    Fee calculator open for new vehicle types:

    java
    public interface ParkingFeePolicy {
    Money fee(Duration stay, Vehicle vehicle);
    }
    public final class StandardFeePolicy implements ParkingFeePolicy {
    @Override
    public Money fee(Duration stay, Vehicle vehicle) {
    return Money.ofHours(stay.toHours()).multiply(vehicle.rateMultiplier());
    }
    }
    public final class FeeCalculator {
    private final Map<Class<? extends Vehicle>, ParkingFeePolicy> policies = new HashMap<>();
    public void register(Class<? extends Vehicle> type, ParkingFeePolicy policy) {
    policies.put(type, policy);
    }
    public Money calculate(Vehicle vehicle, Duration stay) {
    ParkingFeePolicy policy = policies.getOrDefault(vehicle.getClass(), new StandardFeePolicy());
    return policy.fee(stay, vehicle);
    }
    }

    Register EVTruck policy without editing FeeCalculator.calculate logic — registry extension.

    Real-world use

    Real-world applications

    • Pricing engines, tax rules, export formats.
    • Plugin-style LLD problems with unknown future variants.
    • Framework design with lifecycle hooks.

    Best practices

    • Combine OCP with polymorphism, not reflection hacks.
    • Keep extension points narrow and well-named.
    • Provide sensible default implementation.
    • Test new extensions in isolation.
    • Avoid premature plugin architecture for fixed domains.

    Common mistakes

    • Giant switch statement growing every sprint.
    • Abstracting every line before second variant exists.
    • Modifying sealed core classes instead of adding subtype.
    • Extension via copy-paste duplication.

    Advanced interview questions

    Q1BeginnerWhat is OCP?
    Open for extension (new behavior via new code), closed for modification (stable code unchanged).
    Q2BeginnerHow do you achieve OCP in Java?
    Interfaces, abstract classes, strategy objects, and registries.
    Q3IntermediateOCP vs YAGNI tension?
    Design extension points at known variation axes; do not abstract everything upfront.
    Q4IntermediateExample of OCP violation?
    Checkout class with switch on payment type edited for each new provider.
    Q5AdvancedMake elevator scheduling open for new algorithms.
    ElevatorScheduler interface; FCFS and SCAN implementations; controller holds scheduler injected at config time.

    Summary

    Extend via new types, not editing core logic. Abstractions define stable extension points. Polymorphism and strategy enable OCP. Interview extensions should not rewrite existing classes. Balance OCP with YAGNI.

    Ready to mark this lesson complete?Track your journey across the entire course.