Bird
Raised Fist0

How should this be addressed to maintain LSP compliance?

hard🎤 Interviewer Follow-up Q15 of Q15
OOP & Design Patterns - Liskov Substitution Principle - Subtype Behavioural Contract
Consider a subclass that overrides a method with a covariant return type but also changes the method's side effects in a way that violates the superclass's behavioral contract. How should this be addressed to maintain LSP compliance?
AAllow the side effect changes since the return type is covariant and thus safe.
BIgnore side effects as they are not part of the method signature and thus irrelevant to LSP.
CRefactor the subclass to preserve the original side effects or weaken them, ensuring behavioral compatibility.
DChange the superclass method to accommodate the subclass's side effects.
Step-by-Step Solution
  1. Step 1: Understand LSP behavioral contract

    LSP requires that subclasses preserve the observable behavior of the superclass, including side effects.
  2. Step 2: Analyze covariant return type

    Covariant return types are allowed and safe, but side effects must still comply with the superclass contract.
  3. Step 3: Evaluate options

    Refactor the subclass to preserve the original side effects or weaken them, ensuring behavioral compatibility. correctly suggests refactoring to preserve or weaken side effects. Allow the side effect changes since the return type is covariant and thus safe. is incorrect; side effect changes can break clients. Ignore side effects as they are not part of the method signature and thus irrelevant to LSP. is false; side effects are part of behavior and relevant. Change the superclass method to accommodate the subclass's side effects. is risky and breaks superclass abstraction.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Behavioral compatibility includes side effects, not just signatures.
Quick Trick: Covariant returns are safe, but side effects must not violate superclass behavior.
Common Mistakes:
MISTAKES
  • Ignoring side effects in LSP
  • Assuming covariant return types cover all behavioral changes
  • Modifying superclass to fit subclass
Trap Explanation:
PITFALL
  • Option A confuses safe signature changes with unsafe behavioral changes; option B ignores side effects; option D breaks abstraction.
Interviewer Note:
CONTEXT
  • Tests deep understanding of behavioral contracts beyond method signatures.
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