Rule
Objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program.
Description
The Liskov Substitution Principle (LSP) asserts that derived classes should be replaceable by their base classes without altering the functionality of the program. This means that subclasses should maintain the contract of the base class. They should not override or remove functionality in a way that causes unexpected behavior in the program.
Benefits
-
Behavioral Consistency: Subclasses behave consistently with the base class.
-
Improves Flexibility: Subtypes can be used interchangeably with their base class, improving system flexibility.
-
Prevents Unintended Side Effects: Ensures derived classes do not inadvertently break functionality.
Example (Correct):
class Bird {
public function fly() {
// Flying logic
}
}
class Sparrow extends Bird {
public function fly() {
// Specific flying logic for sparrow
}
}
Example (Incorrect):
class Bird {
public function fly() {
// Flying logic
}
}
class Penguin extends Bird {
public function fly() {
throw new Exception("Penguins can't fly!");
}
}