Liskov Substitution Principle (LSP)

img

What is LSP?

The Liskov Substitution Principle is one of the five object-oriented design principles collectively known as SOLID. It was introduced by Barbara Liskov in 1987 during her conference keynote. Essentially, the LSP states:

"Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program."

In simpler terms, if class B is a subtype of class A, then we should be able to replace A with B without disrupting the behavior of our program.

Why is LSP Important?

  • Highlights challenges with inheritance: Inheritance is taught as a core and relatively simple concept. While in reality inheritance is much harder to get right. LSP highlights this fact and points us towards: Favor Composition over Inheritance.
  • Promotes robustness: Adhering to the LSP increases the robustness of the system by ensuring that extending the system via inheritance does not introduce new bugs.
  • Enhances maintainability: Systems that follow LSP are more modular and easier to understand, making maintenance simpler.
  • Improves reusability: By ensuring that subclasses remain substitutable for their base classes, LSP aids in reusing components, which is a hallmark of effective object-oriented design.

Implementing LSP

To comply with the Liskov Substitution Principle, ensure that:

  1. Subtypes enhance, not alter functionalities: Subclasses should implement their superclass methods in a way that does not weaken superclass behavior.
  2. Do not strengthen preconditions: Subclasses should not impose stricter validation or input requirements than their base classes.
  3. Do not weaken postconditions: The outcome and effects of overridden methods in subclasses should meet or exceed what is specified in the base class.
  4. Exceptions are consistent: Subclasses should not introduce new exceptions that can be thrown by methods of the base class, unless those exceptions are equivalents of the base class exceptions.

Example Violation

Consider a class Bird with a method fly(). A subclass Penguin inherits from Bird but cannot fly. If the program attempts to make a Penguin fly, this would violate LSP because Penguin cannot be used as a substitute for Bird in this context.

Remember...

Following the Liskov Substitution Principle helps in creating truly modular systems, where individual components can be replaced and updated without affecting the integrity of the overall system. It's all about keeping your inheritance tree clean and logical.


Backlinks