Bird
Raised Fist0
Interview Prepoop-design-patternsmediumAmazonGoogleMicrosoftFlipkartSwiggyRazorpay

Open/Closed Principle - Open for Extension, Closed for Modification

Choose your preparation mode3 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
🎯
Open/Closed Principle - Open for Extension, Closed for Modification
mediumOOPAmazonGoogleMicrosoft

Imagine a payment system that needs to support new payment methods frequently without breaking existing code. How can you design it so that adding new methods doesn't require changing the core logic?

💡 Beginners often confuse 'open for extension' with 'open for modification', thinking that adding new features always means changing existing code, which defeats the principle.
📋
Interview Question

Explain the Open/Closed Principle in object-oriented design. What does it mean to be 'open for extension but closed for modification'? How does this principle improve software maintainability?

Definition of Open/Closed Principle (OCP)Difference between extension and modificationRole of abstraction and polymorphism in OCP
💡
Scenario & Trace
ScenarioA notification system initially supports email notifications but later needs to support SMS and push notifications.
Initially, the system has a class handling email notifications. To add SMS, instead of modifying the existing class, a new class implementing a common notification interface is created. The system uses polymorphism to send notifications, allowing new types to be added without changing existing code.
ScenarioAn e-commerce platform calculates discounts differently for various customer types.
Instead of modifying the discount calculation logic every time a new customer type is introduced, the platform defines a discount strategy interface. Each customer type has its own discount strategy class. The platform can add new discount strategies without altering existing ones.
  • What if a new feature requires changing existing class behavior fundamentally?
  • How to handle legacy code that violates OCP?
  • What if extension leads to excessive class proliferation and complexity?
⚠️
Common Mistakes
Thinking OCP means never changing existing code under any circumstance

Interviewer thinks candidate is rigid and unaware of practical refactoring needs

Explain that OCP encourages minimizing changes to existing code but sometimes refactoring is necessary

Confusing 'open for extension' with 'open for modification'

Candidate fails to distinguish adding new code from changing old code

Clarify that extension means adding new modules/classes, not altering existing ones

Ignoring the role of abstraction and polymorphism in enabling OCP

Candidate gives vague answers without explaining how OCP is achieved

Emphasize interfaces, abstract classes, and design patterns as mechanisms to implement OCP

Believing OCP eliminates all bugs and maintenance effort

Interviewer doubts candidate's realistic understanding of software design

Acknowledge OCP reduces risk but does not guarantee bug-free code or zero maintenance

🧠
Basic Definition - What It Is
💡 This level gives you the essential understanding to answer basic interview questions confidently.

Intuition

Software entities should allow new functionality without altering existing source code.

Explanation

The Open/Closed Principle states that software modules (classes, functions, etc.) should be open for extension but closed for modification. This means you can add new behavior by adding new code, not by changing existing code. This helps prevent bugs and reduces regression risks because existing tested code remains untouched. It encourages designing systems with abstractions so new features can be added by implementing new classes or modules.

Memory Hook

💡 Think of a plug socket: you can plug in new devices (extensions) without changing the socket itself (modification).

Interview Questions

What does 'open for extension, closed for modification' mean?
  • You can add new functionality without changing existing code.
  • Helps maintain stability and reduces bugs.
  • Achieved by using abstractions and polymorphism.
Depth Level
Interview Time30 seconds
Depthbasic

Covers the fundamental definition and why it matters.

Interview Target: Minimum floor - never go below this

Knowing only this lets you pass initial screening but won't impress in detailed discussions.

🧠
Mechanism Depth - How It Works
💡 This level is expected in product company interviews and shows deeper understanding.

Intuition

OCP is implemented by designing stable abstractions and extending behavior through new derived classes or modules, avoiding changes to existing tested code.

Explanation

To adhere to the Open/Closed Principle, developers design software using interfaces or abstract classes that define contracts. Concrete implementations extend these abstractions to add new behavior. For example, a payment processor interface can have multiple implementations for credit card, PayPal, or cryptocurrency payments. When a new payment method is needed, a new class implementing the interface is added without modifying existing classes. This reduces risk of introducing bugs in stable code and makes the system easier to maintain and test. Design patterns like Strategy and Decorator help achieve OCP by encapsulating varying behavior and allowing dynamic extension. However, blindly applying OCP can lead to many small classes and complexity, so balance is needed.

Memory Hook

💡 Like a TV remote with programmable buttons: you can add new functions by programming new buttons without redesigning the remote.

Interview Questions

How do you implement OCP in a real system?
  • Use interfaces or abstract classes to define behavior.
  • Add new functionality by creating new derived classes.
  • Use design patterns like Strategy to encapsulate varying behavior.
What are the trade-offs of strictly following OCP?
  • Can increase number of classes and complexity.
  • May require upfront design effort.
  • Helps reduce bugs and improve maintainability.
Depth Level
Interview Time2-3 minutes
Depthintermediate

Demonstrates how OCP is applied and its benefits/trade-offs.

Interview Target: Target level for FAANG on-sites

Mastering this level distinguishes you from most candidates.

📊
Explanation Depth Levels
💡 Choose your depth based on interview stage and role expectations.
LevelInterview TimeSuitable ForRisk
Basic Definition30sScreening call or initial roundsToo shallow for detailed design discussions
Mechanism Depth2-3 minutesOn-site interviews at product companiesRequires good understanding of abstraction and design patterns
💼
Interview Strategy
💡 Use this guide to structure your explanation and anticipate follow-up questions during interviews.

How to Present

Start with a clear definition of the Open/Closed Principle.Give a simple real-world analogy or example.Explain how it is implemented using abstraction and polymorphism.Discuss edge cases and trade-offs to show depth.

Time Allocation

Definition: 30s → Example: 1min → Mechanism: 2min → Edge cases: 30s. Total ~4min

What the Interviewer Tests

Understanding of OCP's definition, implementation, benefits, and limitations.

Common Follow-ups

  • How does OCP relate to other SOLID principles? → It complements Single Responsibility and Dependency Inversion principles.
  • Can you give an example where OCP is violated and its consequences? → Modifying existing classes for new features can introduce bugs and regressions.
💡 These follow-ups test your ability to connect concepts and reason about design trade-offs.
🔍
Pattern Recognition

When to Use

When asked about SOLID principles, software design best practices, or how to add features without breaking existing code.

Signature Phrases

'Explain the Open/Closed Principle''How do you design for extensibility?''What happens when you add a new feature?'

NOT This Pattern When

Similar Problems

Practice

(1/5)
1. You have a legacy payment processing system with an incompatible interface, and you want to integrate it into a new e-commerce platform without changing the legacy code. Which pattern best suits this scenario?
easy
A. Facade, to provide a simplified interface to the legacy system
B. Adapter, to convert the legacy interface to the new platform's expected interface
C. Proxy, to control access and add security to the legacy system
D. Decorator, to add new behavior to the legacy system dynamically

Solution

  1. Step 1: Identify the problem

    The legacy system's interface is incompatible with the new platform.
  2. Step 2: Understand pattern intents

    Adapter converts one interface to another, enabling integration without changing legacy code. Facade simplifies a complex subsystem but doesn't change interfaces. Proxy controls access, not interface compatibility. Decorator adds behavior dynamically, unrelated to interface mismatch.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Adapter is the go-to pattern for interface incompatibility issues.
Hint: Adapter = interface translator; Facade = interface simplifier; Proxy = access controller
Common Mistakes:
  • Confusing Facade with Adapter because both provide a new interface
  • Thinking Proxy changes interfaces rather than controlling access
  • Assuming Decorator handles interface incompatibility
2. You have a payment processing system that currently uses multiple if-else statements to handle different payment methods like credit card, UPI, and net banking. The system needs to be extended frequently with new payment methods without modifying existing code. Which design approach best addresses this requirement?
easy
A. Use a brute force approach with nested if-else statements for each payment method.
B. Implement a strategy pattern where each payment method is encapsulated in its own class implementing a common interface.
C. Use a recursive function that selects payment methods based on input parameters.
D. Apply a greedy algorithm to select the payment method with the lowest processing fee.

Solution

  1. Step 1: Understand the problem of frequent extension

    The system requires adding new payment methods without modifying existing code, which violates the open-closed principle if using if-else chains.
  2. Step 2: Identify the design pattern that encapsulates behaviors

    The strategy pattern encapsulates each payment method in its own class implementing a common interface, allowing easy extension by adding new classes without changing existing code.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Strategy pattern replaces conditionals with polymorphism [OK]
Hint: Replacing conditionals with polymorphism enables easy extension [OK]
Common Mistakes:
  • Thinking recursion or greedy algorithms solve extensibility here
3. What is a common trade-off or limitation when strictly enforcing the Liskov Substitution Principle in a large inheritance hierarchy?
medium
A. It can lead to overly rigid designs that prevent useful specialization.
B. It always improves code flexibility and reduces bugs without downsides.
C. It allows subclasses to freely change method signatures for optimization.
D. It eliminates the need for interface segregation.

Solution

  1. Step 1: Understand strict LSP enforcement

    Strict LSP means subclasses cannot alter behavior or method contracts in incompatible ways.
  2. Step 2: Analyze trade-offs

    This can restrict subclass implementations, making designs rigid and limiting specialization.
  3. Step 3: Evaluate options

    It can lead to overly rigid designs that prevent useful specialization. correctly identifies rigidity as a trade-off. It always improves code flexibility and reduces bugs without downsides. is false; strict LSP can reduce flexibility. It allows subclasses to freely change method signatures for optimization. is incorrect; method signatures must respect variance rules. It eliminates the need for interface segregation. is false; interface segregation addresses different concerns.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Strict LSP can constrain subclass design choices.
Hint: Strict LSP enforces substitutability but can limit subclass flexibility.
Common Mistakes:
  • Believing strict LSP has no downsides
  • Confusing LSP with interface segregation
  • Assuming method signatures can be freely changed
4. If a class exposes a public getter but no setter for a private field, what is a likely reason an interviewer would probe this design choice?
hard
A. To test if the candidate thinks public fields are better than getters
B. To confirm that the candidate knows getters always require setters
C. To verify that the candidate believes private fields should never be exposed
D. To check if the candidate understands immutability and controlled read-only access

Solution

  1. Step 1: Understand getter-only design

    Getter without setter implies read-only access, often for immutability or controlled exposure.
  2. Step 2: Analyze interviewer intent

    Interviewer probes if candidate recognizes design for immutability or encapsulation control.
  3. Step 3: Evaluate incorrect options

    To confirm that the candidate knows getters always require setters is false; setters are not always required. To verify that the candidate believes private fields should never be exposed is extreme; exposing read-only data is common. To test if the candidate thinks public fields are better than getters is a misconception favoring public fields.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Getter-only design supports immutability and controlled access.
Hint: Getter-only means read-only, not incomplete encapsulation [OK]
Common Mistakes:
  • Assuming getters must have setters
  • Thinking private fields must never be exposed
  • Believing public fields are simpler and better
5. Suppose you want to extend the Template Method Pattern to allow clients to optionally skip multiple steps dynamically at runtime (not just condiments). Which modification best preserves the pattern's structure and flexibility?
hard
A. Override the entire template method in each subclass to conditionally skip steps as needed.
B. Add multiple hook methods in the base class for each optional step, with default implementations returning True or False.
C. Remove the base class and implement each beverage's recipe independently with duplicated code.
D. Use a flag parameter in prepare_recipe to decide which steps to execute, breaking encapsulation.

Solution

  1. Step 1: Understand requirement

    Need to optionally skip multiple steps dynamically while preserving fixed sequence and reuse.
  2. Step 2: Evaluate options

    Adding multiple hook methods in base class allows subclasses to override selectively without breaking skeleton.
  3. Step 3: Reject other options

    Overriding entire template method duplicates code and breaks pattern; flags break encapsulation; removing base class loses reuse.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Multiple hooks preserve flexibility and structure [OK]
Hint: Use hooks for optional steps, not override template method [OK]
Common Mistakes:
  • Overriding template method to skip steps
  • Using flags breaking encapsulation