Liskov Substitution Principle

Inès Chokri
3 min readAug 6, 2020

Introduction

I have recently started learning about object oriented design and I have been put in a situation where a derived class can’t replace it’s base class and work perfectly as intended and that is against one of SOLID design principles.

So I am writing this article to maybe enlighten other developers on this subject.

Liskov Substitution Principle

Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of the program

Let me explain what Wikipedia stated above with some examples.

Let’s say you have a class named Animal and two other classes that inherits from it called Dog and Cat. In every single line you use Animal, you should be able to replace it by Dog or Cat and keep everything working fine as it did before, that is what Liskov principle says.

The situation I have been put in is the following.

I had a class Shape that has a method called Area that throws an exception.

A class Rectangle that inherits from Shape. It has two private fields width and height, two properties Width and Height, the Area method and ToString.

And Finally a class Square that inherits from Rectangle, has a size field and a Size property.

Now, this code works fine if I execute the following :

the result is :

aRect width: 6
aRect height: 8
aRect area: 48
[Rectangle] 6 / 8
------------------
aSquare width: 12
aSquare height: 12
aSquare area: 144
[Square] 12 / 12

and nothing i wrong with it.

But what if I try to assign a Square’s width and height directly :

using System;

class Program
{
static void Main(string[] args)
{
Square aSquare = new Square();

try
{
aSquare.Width = 12;
aSquare.Height = 8;

Console.WriteLine("aSquare width: {0}", aSquare.Width);
Console.WriteLine("aSquare height: {0}", aSquare.Height);
Console.WriteLine("aSquare size: {0}", aSquare.Size);
Console.WriteLine("aSquare area: {0}", aSquare.Area());
Console.WriteLine(aSquare.ToString());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}

I would get the following :

aSquare width: 12
aSquare height: 8
aSquare size: 0
aSquare area: 96
[Square] 0 / 0

Size haven’t been set and so is zero and broke Liskov principle !

So it would be best to make Square inherits from Shape instead of Rectangle to solve it and follow Liskov principle.

--

--