Liskov's Substitution Principle (LSP) - S.O.L.I.D. Framework

Frameworks Mar 19, 2017

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.

public class Car
{
    public double speed { get; set; }

    public virtual void Accelerate()
    {
        speed++;
    }
}

public class ElectricCar : Car
{
    public override void Accelerate()
    {
        speed--;
    }
}

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.

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.