Bird
Raised Fist0

If a subclass needs to violate a superclass method's postcondition to implement a new feature, what is the best interview-ready approach to maintain LSP compliance?

hard🎤 Interviewer Follow-up Q10 of Q15
OOP & Design Patterns - Liskov Substitution Principle - Subtype Behavioural Contract
If a subclass needs to violate a superclass method's postcondition to implement a new feature, what is the best interview-ready approach to maintain LSP compliance?
ARefactor the class hierarchy to extract a new superclass with a relaxed contract that both classes can adhere to.
BIgnore LSP and document the violation clearly for future maintainers.
CUse runtime type checks to apply different behaviors depending on the actual subclass type.
DOverride the method and throw an exception to prevent misuse.
Step-by-Step Solution
Solution:
  1. Step 1: Understand LSP violation by postcondition change

    Violating postconditions breaks substitutability and LSP.
  2. Step 2: Analyze solutions

    A proposes refactoring the hierarchy to create a new superclass with a relaxed contract, allowing both subclasses to comply, preserving LSP.
  3. Step 3: Evaluate other options

    B accepts violation, not interview-ready. C breaks polymorphism and LSP. D prevents substitution by throwing exceptions, violating LSP.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Refactoring hierarchy to relax contracts preserves LSP [OK]
Quick Trick: Refactor hierarchy to relax contracts instead of violating LSP [OK]
Common Mistakes:
MISTAKES
  • Ignoring LSP violations hoping documentation suffices
  • Using runtime type checks instead of proper design
Trap Explanation:
PITFALL
  • Candidates often propose quick fixes that break LSP rather than redesigning properly.
Interviewer Note:
CONTEXT
  • Tests deep understanding of LSP and ability to propose robust design solutions.
Master "Liskov Substitution Principle - Subtype Behavioural Contract" 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