The Liskov Substitution Principle says objects of a derived type must be usable wherever the base type is expected, without breaking the program's correctness. A subclass must honour the base class's contract: it should not strengthen preconditions, weaken postconditions or break invariants. Practical example: a payment system Violation: public class PaymentMethod { public virtual void Refund(decimal amount) { /* refund to the original method */ } } public class GiftCard : PaymentMethod { public override void Refund(decimal amount) => throw new NotSupportedException("Gift cards cannot be refunded"); } void ProcessReturn(PaymentMethod method, decimal amount) => method.Refund(amount); // explodes for gift cards Code written against PaymentMethod assumes every payment method supports refunds. GiftCard breaks that assumption, so callers start adding checks like "if (method is GiftCard)" — a sign LSP is violated. Fix: model capabilities explicitly public abstract class PaymentMethod { public abstract Task ChargeAsync(decimal amount); } public interface IRefundable { Task RefundAsync(decimal amount); } public class CardPayment : PaymentMethod, IRefundable { ... } public class UpiPayment : PaymentMethod, IRefundable { ... } public class GiftCard : PaymentMethod { ... } // no refund promise async Task ProcessReturnAsync(IRefundable method, decimal amount) => await method.RefundAsync(amount); Now every type fulfils exactly the contract it claims, and the compiler prevents refunding a gift card. Another classic example: Rectangle and Square If Square inherits from Rectangle and setting Width also changes Height, code that sets width 5 and height 4 and expects area 20 breaks. Mathematically a square is a rectangle, but behaviourally the mutable Square cannot substitute for a mutable Rectangle. Fix: separate types implementing an IShape interface, or immutable shapes. Signs of LSP violations - Overrides throwing NotImplementedException or NotSupportedException. - Type checks (is or as) on base-class references to handle special subclasses. - Overrides that ignore parameters or silently do nothing. Why it matters: polymorphic code stays reliable, new subtypes do not require changes to existing callers (supporting Open/Closed), and tests written for the base contract can run against every implementation.
Ravindra Wadile · · 0 likes