Revisiting the L in SOLID

Photo by Pavel Nekoranec on Unsplash

This is a continuation of the SOLID. In the last post, I covered the O and now we will be continuing with the L. So if you didn’t check the last post, feel free to click on the link: https://sightlless.medium.com/revisiting-the-o-in-solid-7d58de7f7c56

Let z be a property provable about objects x of type T. Then z should be true for objects y of type S where S is a subtype of T.

In a nutshell: A has a property A, if B is a subtype of A then B has also the property A and B should behave the way A is expected to behave. And that means any derived class (B) should be able to substitute its parent class (A) without the consumer knowing it.

Example:

Let’s suppose we have a car Class and two other classes Ferrari and Bugatti. Both of the cars are just..cars…sooo..they should behave like a normal car would do, right?

public class Car {
public int speed;

public Car(int speed) {
this.speed = speed;
}
}

public class Bugatti extends Car {
public Bugatti (int speed) {
super(speed);
}
}

public class Ferrari extends Car {
public Ferrari (int speed) {
super(speed);
}
}

And now let’s suppose we want to customize a car by increasing its speed, usually, we would write a method inside the Car like this:

public static void increaseSpeed(Car car) {
String message = "You increased the speed of " + car.getClass().getSimpleName() + " from " + car.speed;

System.out.println(message);
}

Please notice that increaseSpeed takes any car as a parameter.
We didn’t have to implement this method in each class (Ferrari and Bugatti) because they should behave the superclass (car) would. No Complications. And that’s the Liskov Substitute Pattern. We replaced the car argument with one of the subtypes each time, and nothing has changed.
Now let’s check our results:

You increased the speed of Bugatti from 200 
You increased the speed of Ferrari from 210

Conclusion:

The Liskov Substitution Principle extends the open/closed principle by preventing breaking client code.

Sources :

Meyer, B. (1997): Object-Oriented Software Construction, 2nd edition
http://www.cvc.uab.es/shared/teach/a21291/temes/object_oriented_design/materials_adicionals/principles_and_patterns.pdf
Robert C. Martin “Principles of OOD”
https://en.wikipedia.org/wiki/Liskov_substitution_principle
https://www.youtube.com/watch?v=rtmFCcjEgEw
https://www.baeldung.com/solid-principles

Originally published at https://dev.to on January 24, 2021.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Elyess Eleuch

Elyess Eleuch

I am a JS developer, mainly React and NodeJS. Currently working with Java, SQL and Hibernate.