Search code examples
solid-principles

Liskov Substitution Principle example


LSP is the hardest in SOLID for me to understand correctly.

LSP states that objects in a program should be replaceable with instances of their subtypes without altering the correctness of the program.

So if we have this typical rectangle - square example:

rect = new Rectangle();

rect.width  = 10;
rect.height = 20;

and then we try to test it:

assert 10 == rect.width
assert 20 == rect.height

Everything is ok, but when we try to say that square is rectangle as well we use:

rect = new Square();

Square actually has both height and width the same, which will make tests fail.

So how do we resolve this problem? We segragate classes for Square and Rectangle to avoid LSP problem in this case?


Solution

  • In this particular example, the solution is to not let Square derive from Rectangle, because although we usually say inheritance is an 'is a' relationship, you should see it as an 'behaves like' relationship. So although mathematically, a Square is a Rectangle, a Square does certainly not behave like a Rectangle (as you prove in the code above).

    Instead, let them both derive from the same base class:

    public abstract class Shape { }
    
    public class Square : Shape { 
        public int Size;
    }
    
    public class Rectangle : Scape { 
        public int Height;
        public int Weight;
    }