Open Closed Principle
The Open/Closed Principle (OCP) says software entities should be open for extension but closed for modification.
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
- Identify likely variation (vehicle type, discount rule).
- Extract interface or abstract hook at variation point.
- Client depends on abstraction only.
- Register new implementations in factory or DI container.
- Verify adding variant requires zero client edits.
- Document how to register extensions.
Informative example
Fee calculator open for new vehicle types:
public interface ParkingFeePolicy {Money fee(Duration stay, Vehicle vehicle);}public final class StandardFeePolicy implements ParkingFeePolicy {@Overridepublic 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?
Q2BeginnerHow do you achieve OCP in Java?
Q3IntermediateOCP vs YAGNI tension?
Q4IntermediateExample of OCP violation?
Q5AdvancedMake elevator scheduling open for new algorithms.
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.