Junior — Middle
Can you give an example of how the Liskov Substitution Principle is applied in programming practice?
sobes.tech AI
Answer from AI
The Liskov Substitution Principle (LSP) states that objects of a subclass should be interchangeable with objects of the superclass without affecting the correctness of the program.
Example in JavaScript (Node.js):
class Bird {
fly() {
console.log('Bird is flying');
}
}
class Sparrow extends Bird {
fly() {
console.log('Sparrow is flying');
}
}
class Ostrich extends Bird {
fly() {
throw new Error('Ostrich cannot fly');
}
}
function makeBirdFly(bird) {
bird.fly();
}
const sparrow = new Sparrow();
makeBirdFly(sparrow); // Sparrow is flying
const ostrich = new Ostrich();
makeBirdFly(ostrich); // Error — violates LSP
Here, the Ostrich class violates the Liskov Substitution Principle because the subclass does not support the behavior of the base class (the fly method). To adhere to LSP, it is better to separate classes into flying and non-flying birds, for example, through interfaces or separate base classes.