Junior — Middle
How easy or difficult is it to implement and follow the Liskov principle when designing systems?
sobes.tech AI
Answer from AI
The Liskov Substitution Principle (LSP) states that objects of a subclass should be interchangeable with objects of the base class without altering the correctness of the program. Implementing and adhering to this principle can be challenging, especially in large and complex systems, as it requires careful design and understanding of class hierarchies.
Main difficulties:
- Maintaining the contracts of the base class in subclasses.
- Avoiding violation of invariants and preconditions.
- Properly overriding methods without changing their behavior.
Example of LSP violation:
class Bird {
void fly() { /* fly */ }
}
class Ostrich extends Bird {
@Override
void fly() {
throw new UnsupportedOperationException("Ostrich cannot fly");
}
}
Here, the Ostrich subclass violates LSP because it does not support the behavior of the base class Bird.
To adhere to LSP, design hierarchies so that subclasses extend rather than restrict the behavior of the base class, and use interfaces and composition where inheritance is not suitable.