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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)