S.O.L.I.D. : 3. Liskov Substitution Principle

Liskov substitution principle says:-

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

It little bit difficult to understand the rule, so just take help of an example,

Suppose a class Animal and object of this class Animal is a Parker (any animal). Then there is an another class Dog which inherit the class Animal, now there is an object of Dog class named Bruno.

So according to the rule if Parker has a property then Bruno should also have the same property like having 4 legs.

Basically the principle what to say that every class that inherit from a parent class, must not replicate functionality already implemented in the parent class. Then the parent class should be able to be replaced by any of its subclasses in any region of the code.

Example:-

In the above example there is a class Rectangle which getter and setter functions for height and width.

Then there is another class square, according to Geometry square is a special case of rectangle. So a coder just inherited class rectangle in class square.

But in square height and width are same, so every time someone provide height or width, it will set both height and width same as the provided value.

Now if we calculate the area of a rectangle using the above class like

So in this case the output will be as expected which is 6.

Then let another case of square, here we are going to  calculate area of square like

Here the expected result is 6, but the output will be 9.

So to avoid these type of confusions we should follow this principle while defining inheritance.

Here is the better way of defining inheritance for the same problem

Next Principle >>

<< Previous Principle

Please follow and like us:
20