Liskov Substitution Principle
1. Introduction
The Liskov Substitution Principle (LSP) is one of the five SOLID principles of object-oriented design. It focuses on ensuring that a subclass can stand in for its parent class without altering the desirable properties of the program.
2. Definition
The Liskov Substitution Principle states that:
“If S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of the program.”
3. Key Concepts
- **Substitutability**: Subtypes should be substitutable for their base types.
- **Behavior Preservation**: The behavior of the program should remain consistent when a subclass is used in place of a superclass.
- **Contract Compliance**: Subclasses must adhere to the contract defined by the parent class.
4. Code Examples
class Bird {
fly() {
console.log("I can fly!");
}
}
class Sparrow extends Bird {
fly() {
console.log("Sparrow flying!");
}
}
function letBirdFly(bird: Bird) {
bird.fly();
}
let mySparrow = new Sparrow();
letBirdFly(mySparrow); // Output: Sparrow flying!
In this example, the Sparrow
class correctly extends Bird
, maintaining the behavior expected by the letBirdFly
function.
5. Best Practices
- Always ensure that subclasses adhere strictly to the expectations of their base class.
- Use interfaces to define contracts that subclasses must follow.
- Test subclasses to ensure they can replace their superclasses without issues.
- Avoid overriding methods in a way that changes expected behavior.
6. FAQ
What happens if LSP is violated?
Violating LSP can lead to unexpected behaviors, making your code fragile and difficult to maintain.
Can you provide a real-world example of LSP?
Consider a payment processing system where a CreditCardPayment
class and a PayPalPayment
class both extend a Payment
class. Both should be able to substitute the Payment
class without changing the payment flow.