#31 SOLID - Liskov substitution principle
Introduction
Previously, we talked about the Open-closed principle. This time we will keep going on introducing the next principle L in SOLID - Liskov substitution principle.
To revise the Open-closed principle, go here.
Liskov substitution principle
If S is a subtype of T, then objects of type T in a program may be replaced with object of type S without altering any of the desirable properties of that program
To simplify the definition, it means we should be able to use the alternative objects with the same superclass without affecting anything.
Remember the circle and square we have created? Now we want to add a rectangle shape which the code may like as below.
class Rectangle implements Shape {
public int width;
public int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int sum() {
return 2*this.width + 2*this.height;
}
}
And now, you may think the Square should inherit Rectangle. Which is correct in mathematics that a square is derived from a Rectangle.
However, imagine the property is private and having width and height get/set method in Rectangle class.
If we can either update the width or the height with different values using Rectangle's set property methods, it can not be claimed as a Square and may cause to the wrong calculation, which violates Liskov substitution principle. It is a great principle to follow which can help us to write a program that easy maintainable.
We have only mentioned part of the Liskov substitution principle. Search the principle if you are interested.
Discussion