Sobes.tech
Middle

Tell me more about the Liskov Substitution principle.

sobes.tech AI

Answer from AI

The Liskov Substitution Principle (LSP) is one of the five SOLID principles, which states that objects of a subclass should be interchangeable with objects of the base class without affecting the correctness of the program.

This means that if class B inherits from class A, then anywhere an object of class A is expected, an object of class B can be used without changing the program's behavior.

Violating LSP leads to unexpected errors and complicates code maintenance.

An example of violating LSP in Python:

class Bird:
    def fly(self):
        print("I can fly")

class Ostrich(Bird):
    def fly(self):
        raise Exception("I can't fly")

# Usage
birds = [Bird(), Ostrich()]
for bird in birds:
    bird.fly()  # Error for ostrich

Here, Ostrich inherits from Bird but does not support the fly method, which violates LSP. It would be better to design the hierarchy differently, for example, by separating flying birds into a different class.