Bird
Raised Fist0

How does this affect adherence to the Open/Closed Principle?

medium🧠🧾 Concept Trace Q4 of Q15
OOP & Design Patterns - Open/Closed Principle - Open for Extension, Closed for Modification
A legacy system uses a large switch statement to handle different file parsers. A developer replaces the switch with polymorphic parser classes but still modifies the base parser class for new file types. How does this affect adherence to the Open/Closed Principle?
AThe system fully adheres to OCP because polymorphism replaced the switch.
BThe system partially adheres to OCP but still violates it by modifying the base class.
CThe system violates OCP because switch statements are required for extension.
DThe system fully violates OCP because polymorphism is not allowed.
Step-by-Step Solution
Solution:
  1. Step 1: Understand OCP requirements

    OCP requires that existing code, including base classes, should not be modified when extending behavior.
  2. Step 2: Analyze scenario

    Replacing switch with polymorphism is a step towards OCP, but modifying the base class for new types violates OCP.
  3. Step 3: Evaluate options

    The system fully adheres to OCP because polymorphism replaced the switch is incorrect because modification still occurs. The system partially adheres to OCP but still violates it by modifying the base class correctly identifies partial adherence with violation. The system violates OCP because switch statements are required for extension is false; switch statements violate OCP. The system fully violates OCP because polymorphism is not allowed is false; polymorphism supports OCP.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Base class modification breaks OCP despite polymorphism [OK]
Quick Trick: Modifying base classes breaks OCP even if polymorphism is used [OK]
Common Mistakes:
MISTAKES
  • Assuming polymorphism alone guarantees OCP
  • Believing switch statements are necessary
Trap Explanation:
PITFALL
  • Candidates often think polymorphism automatically means OCP compliance, ignoring base class modifications.
Interviewer Note:
CONTEXT
  • Tests nuanced understanding of OCP and polymorphism limits.
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