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 that manages user accounts and sends notification emails. According to the Single Responsibility Principle, how should you organize these responsibilities?
easy
A. Separate user account management and email notification into different classes because each has a different reason to change.
B. Combine user account management and email notification in one class because they are related to users.
C. Put all user-related functionalities, including notifications, into a single class to reduce the number of classes.
D. Create one class for user management and embed email notification logic inside its methods to simplify interactions.

Solution

  1. Step 1: Identify reasons to change

    User account management changes when user data or authentication changes; email notifications change when messaging or delivery requirements change.
  2. Step 2: Apply SRP

    Since these reasons to change differ, they should be separated into different classes to avoid coupling unrelated changes.
  3. Step 3: Evaluate other options

    Options A, C, and D combine responsibilities, increasing coupling and reducing cohesion, violating SRP.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Separate classes for distinct reasons to change -> SRP compliant.
Hint: One class, one reason to change.
Common Mistakes:
  • Assuming related domain means same responsibility.
  • Combining functionalities to reduce class count.
  • Embedding multiple responsibilities for convenience.
2. Which of the following statements about interfaces and abstract classes is INCORRECT?
medium
A. Interfaces can declare fields that hold state.
B. Abstract classes can have constructors and maintain state.
C. Interfaces can contain default method implementations in some languages.
D. Abstract classes can provide partial method implementations.

Solution

  1. Step 1: Interfaces and state

    Interfaces cannot hold instance fields; they only declare constants (static final fields).
  2. Step 2: Abstract classes and state

    Abstract classes can have constructors and instance variables to maintain state.
  3. Step 3: Default methods in interfaces

    Modern languages allow default method implementations in interfaces.
  4. Step 4: Partial implementation in abstract classes

    Abstract classes can provide some method implementations while leaving others abstract.
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Interfaces cannot hold mutable state; abstract classes can.
Hint: Interfaces declare behavior, abstract classes can hold state and code.
Common Mistakes:
  • Assuming interfaces can have instance variables.
  • Confusing default methods with full implementations.
  • Believing abstract classes cannot have constructors.
3. Which of the following statements about handling concurrency in the Library Management System's LoanManager is INCORRECT?
medium
A. Optimistic locking is unsuitable because it always leads to deadlocks in high contention scenarios.
B. Using pessimistic locking on book records ensures no two users can borrow the same book simultaneously.
C. Implementing atomic check-and-update operations prevents race conditions during loan processing.
D. Using version numbers or timestamps can help detect conflicting updates in optimistic concurrency control.

Solution

  1. Step 1: Understand pessimistic locking

    Pessimistic locking prevents concurrent conflicting access, so Using pessimistic locking on book records ensures no two users can borrow the same book simultaneously. is correct.
  2. Step 2: Why optimistic locking is not always deadlock?

    Optimistic locking is unsuitable because it always leads to deadlocks in high contention scenarios. is incorrect; optimistic locking reduces deadlocks by retrying on conflicts.
  3. Step 3: Atomic operations prevent race conditions

    Implementing atomic check-and-update operations prevents race conditions during loan processing. is correct and essential for concurrency safety.
  4. Step 4: Versioning aids optimistic concurrency

    Using version numbers or timestamps can help detect conflicting updates in optimistic concurrency control. correctly describes conflict detection mechanisms.
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Optimistic locking reduces deadlocks; it does not always cause them.
Hint: Optimistic locking avoids deadlocks by retrying, pessimistic locking blocks access [OK]
Common Mistakes:
  • Believing optimistic locking always causes deadlocks
  • Confusing locking types and their effects
  • Ignoring atomicity in concurrency control
4. What is a key trade-off or limitation when using multiple inheritance to solve the Diamond Problem in object-oriented design?
medium
A. Multiple inheritance always leads to ambiguous method calls that cannot be resolved.
B. Multiple inheritance eliminates the need for Method Resolution Order (MRO).
C. Multiple inheritance reduces code reuse compared to single inheritance.
D. Using multiple inheritance can increase complexity and make the class hierarchy harder to understand and maintain.

Solution

  1. Step 1: Understand the Diamond Problem

    Diamond Problem arises when a class inherits from two classes that share a common ancestor, causing ambiguity.
  2. Step 2: Evaluate Multiple inheritance always leads to ambiguous method calls that cannot be resolved.

    Multiple inheritance can cause ambiguity, but languages use MRO to resolve it, so it is not always unresolved.
  3. Step 3: Evaluate Multiple inheritance eliminates the need for Method Resolution Order (MRO).

    MRO is essential in multiple inheritance to resolve method calls, so multiple inheritance does not eliminate MRO.
  4. Step 4: Evaluate Multiple inheritance reduces code reuse compared to single inheritance.

    Multiple inheritance generally increases code reuse by combining features from multiple classes.
  5. Step 5: Correct trade-off

    Using multiple inheritance can increase complexity and make the class hierarchy harder to understand and maintain. correctly identifies that multiple inheritance increases complexity and can make hierarchies harder to maintain.
  6. Final Answer:

    Option D -> Option D
  7. Quick Check:

    Complexity and maintainability are key trade-offs in multiple inheritance.
Hint: Multiple inheritance = power with complexity cost
Common Mistakes:
  • Believing multiple inheritance always causes irresolvable ambiguity
  • Thinking MRO is unnecessary with multiple inheritance
  • Assuming multiple inheritance reduces code reuse
5. Suppose you want to extend the payment system to allow switching payment strategies at runtime based on user input, including invalid or unsupported methods. Which modification best supports this requirement while maintaining clean design?
hard
A. Use a factory method to get the strategy instance and inject it into PaymentProcessor; handle invalid methods by raising exceptions.
B. Keep the strategy selection logic inside the PaymentProcessor's pay method with if-else chains.
C. Hardcode all payment methods inside PaymentProcessor and add a default fallback strategy for invalid inputs.
D. Remove the strategy interface and implement all payment methods inside PaymentProcessor with switch-case.

Solution

  1. Step 1: Understand runtime strategy switching

    Switching strategies at runtime requires decoupling strategy selection from the context and handling invalid inputs gracefully.
  2. Step 2: Identify design that supports clean extensibility and error handling

    Using a factory method to create strategy instances and injecting them into PaymentProcessor allows runtime flexibility and clean error handling via exceptions.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Factory + DI + exceptions enable runtime switching and robustness [OK]
Hint: Factory and DI enable runtime strategy switching with error handling [OK]
Common Mistakes:
  • Hardcoding strategies or using conditionals inside context
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