DEV Community

Walter Nascimento
Walter Nascimento

Posted on

Liskov Substitution Principle (LSP)

The Liskov Substitution Principle (LSP) is the third SOLID principle and states that objects of a base class should be replaced by objects of its derived classes without affecting the correctness of the program. In other words, if a class is a subtype of another, it must be able to be used in place of that class without the program behaving in an unexpected way. By following LSP, you guarantee that derived classes will not exhibit behavior that is not compatible with the contract predicted by the base class.

Example After Applying LSP in PHP:

<?php

class Animal
{
    protected $name;

    public function setName($name)
    {
        $this->name = $name;
    }

    public function makeNoise()
    {
        // Generic logic for making noise, each animal can have its own sound
    }
}

class Cat extends Animal
{
    public function makeNoise()
    {
        return "Meow!"; // Specific implementation for the sound of a cat
    }
}

class Dog extends Animal
{
    public function makeNoise()
    {
        return "Oof Oof!"; // Specific implementation for the sound of a dog
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, Animal is the base class that contains a makeNoise() method. The Cat and Dog classes are subclasses of Animal and implement the makeNoise() method according to the sound that each animal makes.

According to the LSP, you can use objects of the Cat or Dog class in place of objects of the Animal class without this causing problems in the program logic.

Example of use:

<?php

function makeAnimalNoise(Animal $animal)
{
    echo $animal->makeNoise();
}

$cat = new Cat();
$cat->setName("Frajola");
makeAnimalNoise($cat); // Output: Meow!

$dog = new Dog();
$dog->setName("Rex");
makeAnimalNoise($dog); // Output: Au Au!
Enter fullscreen mode Exit fullscreen mode

In this code, the MakeAnimalNoise() function accepts an object from the Animal class, but we can pass objects from the Cat or Dog subclasses without any problems, thanks to the LSP. Each animal makes its own noise, as expected.


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (0)