Sobes.tech
Junior — Middle

Can you give an example of a situation where the Liskov principle from SOLID is violated?

sobes.tech AI

Answer from AI

The Liskov Substitution Principle states that objects of a subclass should be interchangeable with objects of the superclass without altering the correctness of the program.

Example of violation:

Suppose there is a base class Bird with a method fly(). The subclass Penguin inherits from Bird, but penguins cannot fly. If in the code, where any Bird is expected, fly() is called, it will lead to an error or incorrect behavior for Penguin.

class Bird {
  void fly() {
    print('Flying');
  }
}

class Penguin extends Bird {
  @override
  void fly() {
    throw Exception('Penguins cannot fly');
  }
}

void makeBirdFly(Bird bird) {
  bird.fly();
}

void main() {
  Bird sparrow = Bird();
  Bird penguin = Penguin();

  makeBirdFly(sparrow); // Works
  makeBirdFly(penguin); // Error, violation of Liskov's principle
}

In this case, Penguin violates the Liskov principle because it cannot replace Bird without changing behavior.