You are designing a payment processing system with a base class PaymentMethod and subclasses like CreditCard and CryptoCurrency. Which design choice best ensures LSP compliance while allowing subclass-specific behaviors?
AUse type checks in client code to handle each subclass differently, bypassing polymorphism.
BDefine abstract methods with strict contracts in PaymentMethod and implement subclass-specific logic without changing method contracts.
CAllow subclasses to override methods freely, including changing input validation and side effects.
DImplement all payment logic in the base class and use flags to differentiate behavior.
Step-by-Step Solution
Solution:
Step 1: Understand LSP in design
LSP requires subclasses to honor base class contracts to ensure substitutability.
Step 2: Analyze options
C correctly enforces strict contracts in the base class and allows subclass-specific logic without breaking contracts, ensuring LSP compliance. A breaks polymorphism and LSP. B breaks LSP by allowing contract changes. D centralizes logic, reducing extensibility and violating open-closed principle.
Final Answer:
Option B -> Option B
Quick Check:
Strict base contracts with subclass-specific logic preserve LSP [OK]
Quick Trick:Base class contracts must be honored by subclasses [OK]
Common Mistakes:
MISTAKES
Allowing subclasses to change contracts arbitrarily
Using type checks instead of polymorphism
Trap Explanation:
PITFALL
Candidates often prioritize flexibility over contract preservation, breaking LSP.
Interviewer Note:
CONTEXT
Evaluates ability to design LSP-compliant class hierarchies in real-world scenarios.