Created
December 8, 2023 15:43
-
-
Save suhailgupta03/ece9281621851e2a28beff8f4a0994f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Liskov Substitution Principle (LSP): Objects of a superclass should be | |
* replaceable with objects of a subclass without affecting the | |
* correctness of the program. | |
*/ | |
class Bird { | |
fly() { | |
console.log('I can fly'); | |
} | |
} | |
class Penguin extends Bird { // penguin is-a bird | |
fly() { | |
throw new Error('I cannot fly'); | |
} | |
} | |
function makeBirdFly(bird) { | |
bird.fly(); | |
} | |
const bird = new Bird(); | |
const penguin = new Penguin(); | |
makeBirdFly(bird); // I can fly | |
makeBirdFly(penguin); // I cannot fly | |
// ---- | |
// Good Practice | |
class Bird { | |
move() {} | |
} | |
class FlyingBird extends Bird { // flying bird is-a bird | |
move() { | |
console.log('I can fly'); | |
} | |
} | |
class NonFlyingBird extends Bird { // non-flying bird is-a bird | |
move() { | |
console.log('The bird walks'); | |
} | |
} | |
function makeBirdMove(bird) { | |
bird.move(); | |
} | |
const sparrow = new FlyingBird(); | |
const penguin = new NonFlyingBird(); | |
makeBirdMove(sparrow); // The bird flies | |
makeBirdMove(penguin); // The bird walks | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment