DEV Community

loading...

Liskov substitution principle

Eduardo Julião
Software Developer | Geek since 1993 | @monsieurxuxu on twitter
・1 min read

Created by created by Barbara Liskov and Jeannette Wing, the Liskov Substitution Principle or (LSP for short) states that:

You should be able to use any derived class instead of a parent class and have it behave in the same manner without modification

In other words, each derived class must maintain the behaviour from the parent class along new behaviour unique to the child class. Making new classes that inherit from the parent class, works without any change to the existing code.

static void Main()
{
    Apple orange = new Orange();
    Console.WriteLine(orange.GetColor());
    // outputs: "Orange";
}

public class Apple
{
    public string GetColor() => "Red";
}

public class Orange
{
    public string GetColor() => "Orange";
}

Enter fullscreen mode Exit fullscreen mode

Let's implement the Liskov Substitution Principle:

static void Main()
{
    Fruit orange = new Orange();
    Console.WriteLine(orange.GetColor());
    // outputs: "Orange"
    Fruit apple = new Apple();
    Console.WriteLine(apple.GetColor());
    // outputs: "Red"
    Orange fruit = new Apple();
    Console.WriteLine(fruit.GetColor());
    // outputs: "Red"
}

public abstract class Fruit
{
    public abstract string GetColor();
}

public class Apple: Fruit
{
    public override string GetColor() => "Red";
}

public class Orange: Fruit
{
    public override string GetColor() => "Orange";
}
Enter fullscreen mode Exit fullscreen mode

Here, the Liskov Substitution is satisfied by our code. The application don't need to change to support a new Fruit, since the subtype (Apple and Orange) that inherit from the type Fruit, can be replaced with each other without raising errors.

Discussion (0)