Liskov’s Substitution Principle (LSP) – S.O.L.I.D. Framework

The third principle of the S.O.L.I.D. Framework is the Liskov’s Substitution Principle (LSP).

The main statement of this principle is “derived types must be completely substitutable for their base types“.

What does that means? Well, basically that every parent class should be replaceable by one of its derived child classes without any problems. Imagine we have a Car base class which provides a Accelerate() method. If we are now using the derived ElectricCar Class we would suggest that the Accelerate() would accelerate the car and not slow it down it.

In this case we would violate against the LSP because the behaviour changes without any reason and the programmer would probably running in a problem because he trusts that the Accelerate() method in the derived classes does the same as in the parent class.

LSP Violation
Liskov’s Substitution Principle Violation

To demonstrate the outcome I have written two little Unit Tests shown above. The first one uses the Car Class and after calling the Accelerate() method the speed property increase by one – and therefore is it greater than zero – so the test passes. In the second Test I used the ElectricCar class and the test fails because the ElectricCar implementation overrides the Accelerate() method and acutally decreases the speed – therefore it is lower than 0.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.