DEV Community

loading...
Cover image for What Is The Liskov Substitution Principle?

What Is The Liskov Substitution Principle?

ellehallal profile image Elle Hallal πŸ‘©πŸ½β€πŸ’» Originally published at ellehallal.dev on ・2 min read

Originally posted at ellehallal.devπŸ‘©πŸ½β€πŸ’»


The Principle Definition

Let Ο†(x) be a property provable about objects x of type T. Then Ο†(y) should be true for objects y of type S where S is a subtype of T.

That’s great, but what does it mean πŸ€·πŸ½β€β™€οΈ? In simpler terms, a child class should be able to substitute a parent class, without any unexpected behaviour. It ensures inheritance is being used correctly.


An example of adhering to the Liskov Substitution Principle

Below is the class Animal. When the speak method is called, a string is expected to be returned. The method does not have any parameters.

class Animal
    def speak
    ""
    end
end

Below are subclasses Cat and Dog. Both inherit from Animal and have a speak method.

class Cat < Animal
    def speak
    "Meow!"
    end
end

class Dog < Animal
    def speak
    "Woof!"
    end
end


cat = Cat.new
dog = Dog.new

cat.speak  # "Meow!"
dog.speak  # "Woof!"

Although calling the speak method on Cat returns 'Meow!' and 'Woof!' for Dog, a string is returned in both cases. In addition, no arguments are required. As a result, instances of these subclasses can be substituted where an instance of Animal is used.


Violation of the Liskov Substitution Principle

Below is the class Jellyfish, which is a subclass of Animal. Its speak method has a parameter name and returns a string.

Although this method returns a string, it needs a name as an argument when called. As the parent class’ speak method doesn’t require a name argument, an instance of the Animal class cannot be substituted with an instance of the Jellyfish class.

class Jellyfish < Animal
    def speak(name)
    "#{name} cannot speak"
    end
end

jellyfish = Jellyfish.new
jellyfish.speak("Jelly")  # "Jelly cannot speak"

In addition, if the speak method of a subclass returned anything other than a string, this would also violate the principle.


In conclusion

To adhere to the Liskov Substitute Principle, a child class should be able to substitute a parent class, without any unexpected behaviour. This is to ensure inheritance is being used correctly.


Helpful resources

Discussion (0)

pic
Editor guide