Liskov Substitution Principle
The Liskov Substitution Principle (LSP) states that objects of a superclass should be replaceable with objects of its subclasses without breaking the application. In other words, derived classes must be substitutable for their base classes.
This principle was introduced by Barbara Liskov in 1987 and is a fundamental concept in object-oriented design.
Understanding the Principle
Section titled “Understanding the Principle”The Liskov Substitution Principle ensures that:
- Subclasses must honor the contract of their base class
- Subclasses should not weaken preconditions (requirements before a method runs)
- Subclasses should not strengthen postconditions (guarantees after a method runs)
- Subclasses should not throw new exceptions that the base class doesn’t throw
In simple terms: If it looks like a duck and quacks like a duck, it should behave like a duck!
Example 1: Rectangle and Square Problem
Section titled “Example 1: Rectangle and Square Problem”This is a classic example that demonstrates LSP violation. Let’s see why a Square should NOT inherit from Rectangle.
Violating LSP (Bad Approach)
Section titled “Violating LSP (Bad Approach)”Following LSP (Good Approach)
Section titled “Following LSP (Good Approach)”Why this follows LSP:
- Both
RectangleandSquarehonor theShapecontract - They can be used interchangeably where
Shapeis expected - No unexpected behavior changes
Example 2: Payment Processing System
Section titled “Example 2: Payment Processing System”Consider a payment processing system where different payment methods need to be processed. Let’s see how LSP violations can cause real-world problems.
Violating LSP (Bad Approach)
Section titled “Violating LSP (Bad Approach)”Why this violates LSP:
- Code expecting
PaymentProcessorbreaks withCryptocurrencyProcessor refund()should always work, but crypto version throws exception- The contract is broken: refunds should be possible for all payment types
Following LSP (Good Approach)
Section titled “Following LSP (Good Approach)”Why this follows LSP:
- Each class honors its specific contract
CryptocurrencyProcessordoesn’t promise refunds it can’t deliver- Type system prevents using non-refundable processors where refunds are needed
- No unexpected behavior or exceptions
Common LSP Violations to Avoid
Section titled “Common LSP Violations to Avoid”1. Throwing New Exceptions
Section titled “1. Throwing New Exceptions”2. Returning Incompatible Types
Section titled “2. Returning Incompatible Types”3. Weakening Preconditions
Section titled “3. Weakening Preconditions”4. Strengthening Postconditions
Section titled “4. Strengthening Postconditions”Benefits of Following LSP
Section titled “Benefits of Following LSP”Key Takeaways
Section titled “Key Takeaways”Remember: The Liskov Substitution Principle ensures that inheritance is used correctly and polymorphism works as expected! 🎯