Bird
Raised Fist0
Interview Prepoop-design-patternsmediumAmazonGoogleMicrosoftFlipkartSwiggyRazorpay

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

Choose your preparation mode3 modes available
🎯
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 are designing a system where a class needs to inherit features from two unrelated classes. Which type of inheritance best fits this scenario?
easy
A. Single inheritance
B. Multiple inheritance
C. Multilevel inheritance
D. Hierarchical inheritance

Solution

  1. Step 1: Understand inheritance types

    Single inheritance involves one parent and one child class, so it cannot inherit from two unrelated classes.
  2. Step 2: Multiple inheritance definition

    Multiple inheritance allows a class to inherit from more than one parent class, fitting the scenario.
  3. Step 3: Multilevel and hierarchical inheritance

    Multilevel is a chain of inheritance, hierarchical is one parent with multiple children, neither fits inheriting from two unrelated classes.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Multiple inheritance is the only type that supports inheriting from multiple unrelated classes.
Hint: Multiple inheritance = multiple parents
Common Mistakes:
  • Confusing multilevel with multiple inheritance
  • Assuming hierarchical inheritance allows multiple parents
  • Thinking single inheritance can have multiple parents
2. Which of the following statements about the Adapter pattern is INCORRECT?
medium
A. Adapter changes the interface of an existing object to match what the client expects
B. Adapter can be implemented using inheritance or composition
C. Adapter adds new functionality to the adapted object without modifying it
D. Adapter is used to simplify a complex subsystem by providing a unified interface

Solution

  1. Step 1: Review Adapter intent

    Adapter converts incompatible interfaces to make them compatible.
  2. Step 2: Check each statement

    A is correct: Adapter changes interface. B is correct: Adapter can use inheritance or composition. C is correct: Adapter can add behavior without modifying original object. D is incorrect: Simplifying a complex subsystem is Facade's role, not Adapter's.
  3. Final Answer:

    Option D -> Option D
Hint: Adapter = interface converter; Facade = interface simplifier
Common Mistakes:
  • Confusing Adapter with Facade's simplification role
  • Thinking Adapter only uses inheritance
  • Assuming Adapter cannot add new behavior
3. What is the worst-case space complexity of the Composite pattern iterator when traversing a tree with n nodes and height h?
medium
A. O(n) because all nodes are stored in the stack at once.
B. O(1) since the iterator uses constant extra space.
C. O(log n) assuming a balanced tree reduces height.
D. O(h) because the stack stores nodes along the current path only.

Solution

  1. Step 1: Understand iterator stack usage

    The iterator stack holds nodes along the current traversal path, not all nodes simultaneously.
  2. Step 2: Relate stack size to tree height

    Maximum stack size corresponds to the height h of the tree, as children are pushed and popped during traversal.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Stack size bounded by tree height h, not total nodes n [OK]
Hint: Iterator stack size bounded by tree height, not total nodes [OK]
Common Mistakes:
  • Assuming stack holds all nodes at once
  • Confusing height with log n for unbalanced trees
4. Which of the following statements about the Single Responsibility Principle is INCORRECT?
medium
A. SRP means a class should only have one method to ensure simplicity.
B. Applying SRP improves cohesion and reduces coupling.
C. A class should have only one reason to change, which means it should have only one responsibility.
D. Violating SRP can lead to fragile code that breaks when unrelated changes occur.

Solution

  1. Step 1: Analyze each statement

    A class should have only one reason to change, which means it should have only one responsibility. correctly states the core SRP definition.
  2. Step 2: Evaluate SRP means a class should only have one method to ensure simplicity.

    SRP is about reasons to change, not the number of methods; a class can have many methods if they serve one responsibility.
  3. Step 3: Confirm options A, B, and D

    Options A, B, and D are true: SRP improves cohesion, reduces coupling, and prevents fragile code.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    SRP ≠ one method per class; it's about one reason to change.
Hint: SRP is about reasons to change, not method count.
Common Mistakes:
  • Confusing responsibility with method count.
  • Assuming fewer methods always means better design.
  • Ignoring cohesion and coupling effects.
5. In a language that supports multiple inheritance with MRO, what happens if two parent classes define a method with the same name, but one parent class inherits from the other (forming a diamond), and the child class overrides that method? How does the MRO affect which method is called when the child class method calls super()?
hard
A. super() follows the MRO linearization, calling the next method in the MRO sequence, which may skip some classes.
B. super() calls the method from the immediate parent class only, ignoring the diamond structure.
C. super() calls all parent methods with the same name in parallel, combining their effects.
D. super() always calls the method from the base class at the top of the diamond first.

Solution

  1. Step 1: Understand super() in multiple inheritance

    super() does not simply call the immediate parent but follows the MRO linearization.
  2. Step 2: MRO linearization

    MRO creates a linear order of classes to avoid ambiguity and duplication, so super() calls the next method in this order.
  3. Step 3: Eliminate incorrect options

    super() calls the method from the immediate parent class only, ignoring the diamond structure is incorrect because super() is not limited to immediate parent. super() calls all parent methods with the same name in parallel, combining their effects is wrong because super() does not call methods in parallel. super() always calls the method from the base class at the top of the diamond first is incorrect because super() does not always start at the base class.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    super() respects MRO linearization, ensuring consistent method calls in diamond inheritance.
Hint: super() = next in MRO chain
Common Mistakes:
  • Thinking super() calls only immediate parent
  • Believing super() calls all parents simultaneously
  • Assuming super() always calls base class first
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard