Contact Me

Liskov Substitution Principle

Objects of a superclass should be replaceable with objects of its subclasses without breaking the application

 It states that objects of a superclass should be able to be replaced with objects of a subclass without affecting the correctness of the program. In other words, a subclass should be a subtype of its superclass and should be able to replace the superclass without changing the desirable properties of the program.

 The key aspect of the LSP is that subtypes must be substitutable for their base types. This means that if a program is using a base type, it should be able to continue working correctly if a subtype is used instead.


 An easy way to stay within this principle is to check if pre and post conditions were met.

  1. Precondition:
  2.  - Cannot be strengthened in subtype

  3. Postcondition:
  4.  - Cannot be weakened in subtype


 One way to adhere to the Liskov Substitution Principle in JavaScript is to use polymorphism. Polymorphism allows objects of different classes to be used interchangeably.

 For example, let's say we have a basic Bird class that has a fly() method. To create a new type of bird, like a penguin, we can create a new Penguin class that inherits from the Bird class. However, penguins can't fly, so we need to provide an alternative method that penguins can use to move, like swim()

class Bird {

fly() {

  console.log('I can fly');

}

}

class Penguin extends Bird {

fly() {

  throw new Error(''I can't fly'');

}

swim() {

  console.log('I can swim');

}

}

 In this example, the Penguin class is a subtype of the Bird class. The Penguin class overrides the fly() method, but provides an alternative method swim() that can be used instead. This allows objects of the Bird and Penguin classes to be used interchangeably, without affecting the correctness of the program.