Request: A better Liskov Substitution explaination/examples?

I’m confused by the explanation of the Liskov Substitution Principle from the SOLID lesson in the Software Design Principles course.

The Codecademy lesson says that subclasses should be able to be substituted with their parent class without breaking the code. It gives an example of a parent class, Pet, and says that any subclass of Pet(Dog, Cat, Turtle) should be able to be swapped with Pet:

To me this makes no sense. If the parent class can already do everything the subclasses can do, why write the subclasses at all? And if the subclasses do have new properties the parent class lacks, how could it be possible to replace any subclasses with their parent without breaking the code? Presumably there’s code that references unique methods and properties in the subclass(eg. ‘shell’ from Turtle, ‘claws’ from Cat, etc.) - how could you substitute them with a parent class that lacks those things without creating reference errors?

Looking into this elsewhere, any other example I’ve found seems to say the opposite of the Codecademy lesson - ie. that you should be able to replace a parent class with any of its subclasses without breaking the code.

To me this inversion makes perfect sense, because obviously the subclasses have all the properties of the parent, so nothing connected to those properties in the parent will break after the substitution.

So, why does Codecademy give a seemingly wrong(and impossible!) description of the LSP compared to anywhere else?

I agree with you. That is an inadequate and mislieading explanation. Reading through the Wikipedia page on it may help. The criticism section seems to explain how some misinterpretations (like CC’s) have come to be.

If you can make sense of it, the following from the aforementioned Wikipedia page explains the principle pretty well.

1 Like

Right; the ‘flow’ of consistency in properties/truth makes sense to me in one direction(from type to subtype), just not the reverse.

1 Like