The Liskov Substitution Principle.

Mario MontellaMario Montella
2 min read

The Liskov Substitution Principle is one of the five principles of SOLID, a set of guidelines for the design of object-oriented software. This principle was formulated by Barbara Liskov in 1987 and states that objects of a derived class must be able to replace objects of the base class without affecting the correctness of the program.

In other words, if a class B is a subclass of a class A, then the objects of A can be replaced with the objects of B without the program significantly changing its behavior. This implies that the derived class must inherit all the behaviors of the base class and, if necessary, extend or modify these behaviors without introducing errors or unexpected side effects.

An example would be a hierarchy of classes representing geometric shapes:

class Forma:
    def calcola_area(self):
        pass

class Rettangolo(Forma):
    def __init__(self, lunghezza, larghezza):
        self.lunghezza = lunghezza
        self.larghezza = larghezza

    def calcola_area(self):
        return self.lunghezza * self.larghezza

class Quadrato(Forma):
    def __init__(self, lato):
        self.lato = lato

    def calcola_area(self):
        return self.lato * self.lato

In this example, Rectangle and Square are subclasses of Shape. Both implement the calculate_area method, inherited from the base class. We can replace an object of type Shape with an object of type Rectangle or Square without altering the behavior of the program incorrectly.

def stampa_area(forma):
    area = forma.calcola_area()
    print(f"L'area della forma è {area}")

# Use of the Liskov substitution principle
rettangolo = Rettangolo(5, 10)
quadrato = Quadrato(7)

stampa_area(rettangolo)  # Print: The area of the shape is 50
stampa_area(quadrato)    # Print: The area of the shape is 49

In this example, the print_area function accepts an object of type Shape, but we can pass both an object of type Rectangle and one of type Square, thus demonstrating the Liskov substitution principle.

0
Subscribe to my newsletter

Read articles from Mario Montella directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mario Montella
Mario Montella

I love exploring the world of programming and closely following the latest technology trends. With the combination of creativity and technical skill, I am always looking for new challenges and exciting projects.