Liskov Substitution Principle: Definition and Examples
Liskov Substitution Principle is a design rule that says objects of a subclass should be replaceable with objects of their superclass without changing the correctness of the program. It ensures that derived classes extend base classes without altering expected behavior, promoting reliable and maintainable code.How It Works
Imagine you have a remote control that works with any TV brand. The Liskov Substitution Principle (LSP) means you can swap one TV brand for another, and the remote still works perfectly without surprises. In programming, this means a subclass should behave like its parent class so that the rest of the program can use it without knowing the difference.
This principle helps keep code flexible and safe. If a subclass changes how the parent class works in unexpected ways, it can cause bugs. LSP encourages designing subclasses that follow the rules and promises of their parent classes, just like different TV brands following the same remote control signals.
Example
This example shows a base class Bird with a method fly(). A subclass Penguin violates LSP because penguins cannot fly, so replacing Bird with Penguin breaks expected behavior.
class Bird { fly() { return "I can fly!"; } } class Sparrow extends Bird { fly() { return "Sparrow flying."; } } class Penguin extends Bird { fly() { throw new Error("Penguins can't fly!"); } } function makeBirdFly(bird) { try { console.log(bird.fly()); } catch (e) { console.log(e.message); } } const sparrow = new Sparrow(); const penguin = new Penguin(); makeBirdFly(sparrow); // Works fine makeBirdFly(penguin); // Breaks LSP
When to Use
Use the Liskov Substitution Principle when designing class hierarchies to ensure subclasses can stand in for their parent classes without causing errors. It is especially important in large systems where many parts of the code rely on shared interfaces or base classes.
For example, in a payment system, if you have a base class PaymentMethod, all subclasses like CreditCard or PayPal should behave consistently so the system can process payments without special cases. This principle helps avoid bugs and makes the system easier to extend and maintain.
Key Points
- Subclasses must be replaceable for their base classes without changing program behavior.
- Violating LSP leads to unexpected errors and fragile code.
- LSP promotes reliable, maintainable, and extensible software design.
- Think of it as a promise that subclasses keep the rules of their parents.