Liskov Substitution Principle
Topic | Source |
---|---|
๐งน Clean Code | Clean Code - Udemy |
Objects should be replaceable with instances of their subclasses without altering the behavior.
This means, that you should be able to use a subclass instead of the main class and everything should still work.
class Bird {}
fly() {
console.log('Fyling...');
}
}
class Eagle extends Bird {
dive() {
console.log('Diving...');
}
}
// this is fine
const eagle = new Bird();
eagle.fly();
// and this is fine, you can replace the bird with the eagle
const eagle2 = new Eagle();
eagle2.fly();
);
// this is not right
class Penguin extends Bird {
// Problem: Can't fly!
}
This example shows, that you need a different parent class to fulfill the Liskov Substitution Principle:
class Bird {}
class FlyingBird extends Bird {
fly() {
console.log('Fyling...');
}
}
class Eagle extends FlyingBird {
dive() {
console.log('Diving...');
}
}
const eagle = new Eagle();
eagle.fly();
eagle.dive();
class Penguin extends Bird {
}
This ensures, that you can replace Bird
with Eagle
, without breaking when you replace Bird
with Penguin
.