Site Tools


swe:liskov-substitution-principle

Table of Contents

Liskov substitution principle

Liskov substitution principle states that if S is a subtype of T, you can substitute S for T without breaking the program. It is the L in SOLID. This is about behavioural contract, not just syntax: a subclass must honour the base class contract, not weaken postconditions or strengthen preconditions.

A classic violation: Square extends Rectangle but breaks the contract that set_width leaves height unchanged. Code that works with Rectangle fails with Square because the behaviour is different. Substituting Square for Rectangle violates LSP.

LSP guides inheritance versus composition: if you cannot substitute freely, inheritance is wrong. A square is geometrically a rectangle but not a behavioural subtype of a mutable one. Fix it by making Rectangle immutable or using composition instead of inheritance.

This code violates LSP: Square breaks the Rectangle contract that height stays unchanged after setting width.

// Violation: code expecting Rectangle behavior fails with Square
class Rectangle {
public:
    void set_width(int w) { width = w; }  // height unchanged
    int get_area() { return width * height; }
protected:
    int width, height;
};
 
class Square : public Rectangle {
public:
    void set_width(int w) { width = w; height = w; }  // WRONG!
};
 
// Problem: this code assumes Rectangle behavior
Rectangle* r = new Square(5);  // Area should stay 25
r->set_width(10);              // Square makes it 100 instead
swe/liskov-substitution-principle.md · Last modified: by 127.0.0.1