The Liskov Substitution Principle (LSP), the "L" in SOLID, states that if S is a subtype of T, objects of type T can be replaced with objects of type S without altering the correctness of the program. In practice: a derived class must behave in a way that does not surprise code written for the base class. How LSP differs from inheritance - Inheritance is a language mechanism: class Square : Rectangle compiles, and Square gains Rectangle's members. It is about code reuse and type relationships. - LSP is a design rule about behaviour: just because inheritance compiles does not mean the subtype can safely replace the base type. - In other words, inheritance says "is-a" syntactically; LSP checks whether "behaves-as-a" is true. Classic example public class Rectangle { public virtual int Width { get; set; } public virtual int Height { get; set; } public int Area => Width * Height; } public class Square : Rectangle { public override int Width { set { base.Width = value; base.Height = value; } } public override int Height { set { base.Width = value; base.Height = value; } } } void Resize(Rectangle r) { r.Width = 5; r.Height = 4; Debug.Assert(r.Area == 20); } // fails for Square: area is 16 Square inherits correctly from the compiler's point of view, but breaks the base class's behaviour, so LSP is violated. Rules a subtype must follow - Accept at least the inputs the base accepts (no stronger preconditions). - Provide at least the guarantees the base provides (no weaker postconditions). - Preserve the base class's invariants. - Do not throw new exception types for operations the base supports. Why it is useful - Reliable polymorphism: code that works with a base type or interface keeps working with every implementation, including future ones. - Supports Open/Closed: you can add new subclasses without modifying callers. - Safer dependency injection: any IRepository implementation can be swapped in. - Reusable tests: a contract test suite for the base type can run against all implementations. How to fix violations: prefer composition, split interfaces into accurate capabilities (Interface Segregation), make types immutable (an immutable Square and Rectangle can share an IShape interface safely), or avoid inheritance when behaviours differ.
Ravindra Wadile · · 0 likes