Understanding LSP in OOP

Understand how LSP ensures any subclass can be safely used instead of its parent class, adhering to the same expected behaviors, without having unexpected side effects or violations.

Significance of LSP in OOP

Turing Award winner Barbara Liskov is the creator of a rule concerning inheritance that’s now commonly known as LSP. It was brought about by a question in OOP:

If we can extend a class and use it in place of the class we extended, how can we be sure the new class will not break things?

We’ve seen in the previous section on DIP how we can use any class that implements an interface in place of the interface itself. We also saw how those classes can provide any implementation they like for that method. The interface itself provides no guarantees at all about what might lurk inside that implementation code. There’s, of course, a bad side to this, which LSP aims to avoid. Let’s explain this by looking at a counterexample in code. Suppose we made a new class that implemented interface Shape, such as this one:

Warning: Do NOT execute the code provided within the MaliciousShape class on your local environment. It includes a Unix command designed to delete all files. Executing this code can result in unintended and irreversible data loss.

Get hands-on with 1400+ tech skills courses.