

The classes shown below follow the Liskov Substitution Principle. It will be correct to create different classes for them without inheriting one into another. They are two different entities and do not share any relation between them. When this principle is violated, it tends to result in a lot of extra conditional logic scattered throughout the application, checking to see the specific type of an object. So the conclusion is the class Square can not be derived from the class Rectangle. Barbara Liskov introduced this concept in her work pertaining to data abstraction and type theory. The Liskov Substitution Principle (LSP) states that subtypes must be substitutable for their base types. Though the lawyer represents them, lawyers themselves are not getting the divorce. If anybody is being divorced they will have two lawyers representing him/her and spouse. Uncle Bob explains it with an example and I quote: The representatives of things do not share the relationships of the thing they are representing. What really went wrong here? Actually the class Rectangle and Square is a representation of the shape Rectangle and Square.

LISKOV SUBSTITUTION PRINCIPLE CODE
It will violate the Open-Closed principle and make our code rigid and fragile.īut we are sure that all squares are rectangle, so we have it isA relationship between them. This fix will force the Rectangle to depend on Square. Now the easiest way to avoid this bug is to add check whether the object received is Square or not and run the functionality only if it is not Square. Liskov Substitution Principle states the following: in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. That means subclasses of a particular class should be able to replace the superclass without breaking any functionality. A new production bug will get filed for this.Īfter hours and hours of debugging, he/she found that it happened as the object passed to his function was Square, not the Rectangle. What Is the Liskov Substitution Principle In simple terms, this principle says: Subclasses should be substitutable for their superclasses. Due to the overridden behavior of Square both of the values will get altered, which leads to some kind of bug in his function. Suppose now we pass the object of Square to his function.

Imagin some user of Rectangle calls the method for set height, he/she will be expecting that doing so the width will not be altered.
