Your web-browser is very outdated, and as such, this website may not display properly. Please consider upgrading to a modern, faster and more secure browser. Click here to do so.
Part of my SOLID programming principles series.
What is the Liskov Substitution Principle?
This Liskov Substitution Principle states that you should be able to replace any object with a sub class of that object and have all of the code still function properly. Any code that uses these objects does not need to know or care what it is getting passed.
Benefits
The benefits of this principle really shine when applied along with the Open/Closed principle. If a class is extended into multiple sub-classes, you can still use the same code you used with the main class with these new classes. This way you prevent dependencies and increase the ability to re-use code.
Applying the Liskov Substitution Principle
For this example, suppose you have 2 classes: A rectangle class and a square class that extends it, since a square is a rectangle.
Rectangle Class
class Rectangle {
private int width;
private int height;
function setWidth(width) { this->width = width; }
function getWidth() { return this->width; }
function setHeight(height) { this->height = height; }
function getHeight() { return this->height; }
}
For the square class, we’ll override the setters so that the square class can make sure that it always remains a square.
Square Class
class Square extends Rectangle {
function setWidth(width) {
this->width = width;
this->height = width;
}
function setHeight(height) {
this->width = height;
this->height = height;
}
}
Now, let’s say that we want to write a function that can take a rectangle and change it’s proporitions so that it is a golden rectangle. that function would probably look something like this:
function makeGoldenRectangle(Rectangle r) {
int newWidth = (int) r->getHeight() * 1.618;
r->setWidth(newWidth);
}
Now you see that even though this is a perfectly fine construction:
Rectangle r = new Square();
when you pass r into the makeGoldenRectangle() function, you are not going to get the results you expected.
If this is hard to understand with shapes, maybe duckies will be easier:

4 notes