Skip to main content

Definition of Liskov Substitution Principle

Liskov Substitution Principle (LSP)

Definition

Formal Definition The Liskov Substitution Principle states: "Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program."

This means that if you have a function that works with a base class, it should also work with any subclass derived from that base class without the need to alter the function's logic. The derived class should maintain the behavior and expectations of the base class.

Simplified Definition In simpler terms, LSP means that subclasses should be able to stand in for their parent classes without causing any unexpected behavior. When you use a subclass in place of a parent class, everything should work just as it did with the parent class, ensuring that the program's functionality remains correct and unchanged.

Analogy Think of subclasses as actors who can take over a role in a play without changing the script. If an understudy steps in for the lead actor, they must deliver the lines and perform the actions in the same way that the original actor would. The audience should not notice any difference in the performance, ensuring that the story and experience remain consistent.

Similarly, in programming, a subclass should "step into" the role of its superclass seamlessly. The program should not need to know whether it is dealing with the superclass or the subclass; it should just work.

By adhering to LSP, developers ensure that their code is more modular, flexible, and maintainable, allowing for easier updates and extensions without risking the integrity of the existing functionality.