Bird
Raised Fist0

You are designing a notification system that must support sending alerts via email, SMS, and push notifications. Which design approach best follows the Open/Closed Principle?

easy🔍 Pattern Recognition Q1 of Q15
OOP & Design Patterns - Open/Closed Principle - Open for Extension, Closed for Modification
You are designing a notification system that must support sending alerts via email, SMS, and push notifications. Which design approach best follows the Open/Closed Principle?
ACreate a single Notification class and add new methods for each alert type as needed.
BDefine a Notification interface and implement separate classes for Email, SMS, and Push notifications.
CUse conditional statements inside one class to handle different notification types.
DModify the existing Notification class each time a new alert type is added.
Step-by-Step Solution
Solution:
  1. Step 1: Identify the principle

    The Open/Closed Principle states that software entities should be open for extension but closed for modification.
  2. Step 2: Analyze each option

    Create a single Notification class and add new methods for each alert type as needed violates OCP by requiring modification of the same class. Define a Notification interface and implement separate classes for Email, SMS, and Push notifications uses abstraction and polymorphism, allowing new notification types without changing existing code. Use conditional statements inside one class to handle different notification types requires modifying the class for new types, violating OCP. Modify the existing Notification class each time a new alert type is added explicitly modifies the class, violating OCP.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Separate classes extend functionality without modifying existing code [OK]
Quick Trick: Separate behaviors via interfaces/classes to avoid modifying existing code [OK]
Common Mistakes:
MISTAKES
  • Thinking adding methods in one class is extension
  • Believing conditionals are OCP-compliant
Trap Explanation:
PITFALL
  • Candidates often confuse adding methods or conditionals as extension, but these require modifying existing code, violating OCP.
Interviewer Note:
CONTEXT
  • Tests basic understanding of OCP and use of abstraction/polymorphism.
Master "Open/Closed Principle - Open for Extension, Closed for Modification" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes