Liskov’s substitution principle

Liskov’s Substitution Principle was coined by Barbara Liskov in 1987 during a conference on Hierarchy and Data Abstraction. Its main task is to ensure in the inheritance between classes of Object-Oriented Programming that a derived class is not only but must behave like the base class. Its definition is:

If for each object o1 of type S there exists an object o2 of type T such that for all P programs defined in terms of T and the behavior of P remains unchanged when o1 is replaced by o2, then S is a subtype of T.

Despite how complex the definition may seem in practice, we can see it with a little more clarity with the typical example of the square and the rectangle. The following C # code snippet shows the classes.

Apparently, at first glance, it may seem that inheritance is correct, at least from a technical point of view its implementation is correct, however, the behavior is quite different. While in a Rectangle the Width and Height can contain any value, a Square, by definition, the Width and Height must be the same value, otherwise it would not be a square. Let’s look at the setter of the Width and Height properties of the Square class; both cancel each other out. We can see it more clearly with a Unit Test.

Basically we check that, if a Square object with Width = 5 and Height = 2, its Area, since we assume that it is a Rectangle, is Width * Height, that is, equal 10. The Test fails because the Height setter imposes in addition to this the Width to 2, so the Area is 4.

Here we find the error since the method takes only one number to make the calculation and forces us to carry out the code with checks or return exceptions. This means that our abstraction is incorrect a square is not a rectangle.

There are some heuristics that can help you find violations of the Liskov principle. They all have to do with derived classes that somehow remove or corrupt the functionality of the base classes.

The author of Derived has considered that method tom is not necessary. Unfortunately, users using Base don’t know that they shouldn’t call the tom method, this is a clear LSP violation.

Another common cause of LSP violation is throwing exceptions in derived classes whose base classes are not thrown. If the users of the base classes do not expect exceptions, adding them will make them non-replaceable.

Systems Engineer with a huge experience working on IT infrastructure projects and passionate about software development, AR/VR, Big Data, and Machine Learning.

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