Liskov Substitution Principle in C#

This is the third of the 5 principles in the acronym S.O.L.I.D, the Liskov's Substitution Principle, that has the acronym LSP.

This principle was introduced by Barbara Liskov. A definition from the Wikipedia about this principle says:

If S is a subtype of T, then objects of type T may be replaced with objects of type S (in other words, objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, and so on).

In simple technical language, it means, when we have a base class and child class relationship, then, if we can successfully replace the object/instance of a parent class with an object/instance of the child class, without affecting the results that we get with the base class instance, then the two classes conform to this principle. That might be a bit confusing, let's discuss it with an example.

To understand this principle, we will use the same example of the Rectangle-Square hierarchy that you might have often seen, where Rectangle is the base class and Square is the derived class. Our discussion focus will be on how the code violates the LSP, rather then the actual code is or should have been written for it. The code for this example is below.



And, the client code is:



As per the definition of this principle, if this example does not violate the LSP, then the getArea method in the base class will give the same area of a rectangle, in other words whether we execute this method with the instance of the Rectangle class or the Square class, we should get the area as 120. But it is not and this is how it violates the LSP.

Where is the issue?

At first, it might seem that the code is fine (until we run it). In fact, the code will work fine if we attempt to get the area using the instance of the rectangle class. But if we use an instance of the square class then the result is different. The reason is, when we write:

Rectangle _iShape = new Square();

_iShape holds reference of the the type Square. Next, when we execute the setWidth and setHeight methods, it executes the methods of the Square class, that sets height = width (as per the logic of the square has length = breadth) and when the getArea is executed, it calculates an incorrect area.

This is the reason that this code violates the Liskov Substitution Principle, when we replace the object/instance of the Rectangle with that of Square and this is what this principle is all about. In other words, if S is a subtype of T, then objects of type T may be replaced with objects of type S (in other words, objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, and so on).

So this is about the concept of the Liskov Substitution Principle. I hope you enjoyed reading it...!!!


Similar Articles