SOLID one by one — L

Date — 16/Sep/2018

rahul reddy
2 min readSep 17, 2018

This is the fourth post in the series of posts on Solid. In this I will explain the third principle in SOLID, L. It stands for Liskov Substitution Principle. The most popular definition of Liskov Substitution Principle is as below:

Liskov Substitution Principle states that 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. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of the program (correctness, task performed, etc.).

The exact definition given by Liskov is as bellow:

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

Liskov Substitution Principle requires a semantic Is-A relation to be maintained between the super class and sub class. In simple terms this proposes that objects of a superclass can be replaceable with objects of its subclasses without breaking the application. One can achieve this by following a few rules, which are pretty similar to the design by contract concept defined by Bertrand Meyer.

An overridden method of a subclass needs to accept the same input parameter values as the method of the superclass. That means we can implement less restrictive validation rules, but we should not enforce stricter ones in our subclass. Otherwise, any code that calls this method on an object of the superclass might cause an exception, if it gets called with an object of the subclass.

Similar rules apply to the return value of the method. The return value of a method of the subclass needs to comply with the same rules as the return value of the method of the superclass.

To make sure that Liskov Substitution Principle is followed we should implement our own checks. This can be done by using tests. We can add extra tests to existing one to make sure that, that part of code works with objects of subclasses.

--

--