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.
Top comments (0)