wasAsked.

what is liskov substitution principal

Mphasis · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

The Liskov Substitution Principle (LSP) is the "L" in SOLID, defined by Barbara Liskov. It states that objects of a subclass should be replaceable for objects of their base class without breaking the program's correctness. In simple words: if your code works with a base class or interface, it must keep working correctly when you pass any derived class. What a subclass must respect - It must accept the same inputs the base accepts (no extra restrictions). - It must provide the results and guarantees the base promises. - It must not throw unexpected exceptions for operations the base supports. - It must keep the base class's rules (invariants) true. Example of a violation public class Account { public decimal Balance { get; protected set; } public virtual void Withdraw(decimal amount) { if (amount > Balance) throw new InvalidOperationException("Insufficient funds"); Balance -= amount; } } public class FixedDepositAccount : Account { public override void Withdraw(decimal amount) => throw new NotSupportedException("Cannot withdraw before maturity"); } void PayBill(Account account, decimal amount) => account.Withdraw(amount); // breaks for fixed deposits PayBill was written for Account, but a FixedDepositAccount cannot actually substitute for it. Fix public abstract class Account { public decimal Balance { get; protected set; } } public interface IWithdrawable { void Withdraw(decimal amount); } public class SavingsAccount : Account, IWithdrawable { public void Withdraw(decimal amount) { ... } } public class FixedDepositAccount : Account { /* no withdraw capability */ } void PayBill(IWithdrawable account, decimal amount) => account.Withdraw(amount); Now only accounts that genuinely support withdrawal can be used, and the compiler enforces it. Why LSP matters - Polymorphism stays reliable, so you can add new subclasses without breaking existing code (supporting the Open/Closed Principle). - Fewer type checks (if account is FixedDepositAccount) scattered in the code. - Dependency injection works safely: any implementation of an interface behaves as expected. Warning signs: NotImplementedException or NotSupportedException in overrides, empty overrides, and is-type checks on base references.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics