DEV Community

Eduardo Julião
Eduardo Julião

Posted on

3 1

Liskov substitution principle

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay