Close
Liskov substitution principle

Software Design S.O.L.I.D principles guide book – Liskov Substitution Principle

Introduction

Continuing our discussion on S.O.L.I.D principles, in the previous blog we discussed OCP(Open Closed Principle), check it out in case missed. Now let’s discuss the Liskov Substitution Principle short hand (LSP). Let’s dive in.

Liskov Substitution Principle

LSP states that:

“If the base class object is being used by the client function, then the derived class object should be exchangeable with the base class object, even then client function should still work fine”

Now lets understand this with an example

Lets take the Vehicle interface, with the below virtual function implemented by the derived class.

  • gear
  • accelerate

Now lets consider Bike, Bicycle both are derived class implements. So far no issue for bicycle class if it implements the Vehicle interface. As Bicycle class simply returns ‘0’ in ‘accelerate‘ API’s and return number of gears as current day Bicycle does support gears, so yes it looks like Bicycle does quality as vehicle. So let’s add it as a derived class for now.

class diagram to illustrate the Liskov substitution principle violation.

Client messed up everything – LSP Violation

Now lets see the client code which is using the interface class

public void validate(Vehicle obj) {
     assert(obj.gear() > 0, true);
     assert(obj.accelerate > 0, true);
}

If you see the client code looks like Bycycle is going to break client code. So what went wrong here exactly? We basically broke LSP, Let’s see how. The interface has an API ‘accelerate‘ which the Bicycle implementation adds default 0 as return. Which client never expects. So the Bicycle class should have never qualified as the derived class of the Vehicle interface as it cannot deliver the contract made by the interface.

So always double think extending/implementating class/interface. As if breaking LSP gets out of hand then redesign can be very different, in such cases we have to add hacks. Which in turn breaks other SOLID principles. Like in this case we will break OCP if we add a check only Bike class object make client function work.

Final thoughts ordered to qualify as derived class, so always remember this quote from Robort C. Martin 2000 paper

“derived methods should expect no more and provide no less.”

Conclusion

We discussed LSP in this blog, now this is well understood. Hope you will carefully decide when adding any class as a derived class. we will discuss yet another SOLID principle in the next blog, So stay tuned.