The SOLID Principles - Liskov Substitution

The SOLID Principles - Liskov Substitution

Exploring the SOLID Principles: Part3 - Liskov Substitution

The Liskov Substitution Principle (LSP) states that if a function or method takes an object of a certain class as a parameter, it should be able to use any subclass of that class without knowing it. In other words, a subclass should be able to substitute for its parent class without affecting the correctness of the program.

Here are some examples of how the LSP can be applied in JavaScript:

Example 1: A Shape Class

Suppose we have a Shape class that represents different shapes in our application. The Shape class has a calculateArea method that calculates the area of the shape. We have several subclasses of the Shape class, such as Circle and Rectangle, that implement their version of the calculateArea method.

Here's an example of how we can ensure that the LSP is being followed:

class Shape {
  calculateArea() {
    // Calculate area
  }
}

class Circle extends Shape {
  calculateArea() {
    // Calculate area of circle
  }
}

class Rectangle extends Shape {
  calculateArea() {
    // Calculate area of rectangle
  }
}

By ensuring that the Circle and Rectangle subclasses can be used interchangeably with the Shape class without affecting the correctness of the program, we can ensure that the LSP is being followed.

Example 2: A Bird Class

Suppose we have a Bird class that represents different types of birds in our application. The Bird class has a fly method that allows the bird to fly. We have several subclasses of the Bird class, such as Penguin and Ostrich, that cannot fly.

Here's an example of how we can ensure that the LSP is being followed:

class Bird {
  fly() {
    // Fly
  }
}

class Penguin extends Bird {
  fly() {
    throw new Error("Penguins cannot fly");
  }
}

class Ostrich extends Bird {
  fly() {
    throw new Error("Ostriches cannot fly");
  }
}

By ensuring that the Penguin and Ostrich subclasses can be used interchangeably with the Bird class without affecting the correctness of the program, we can ensure that the LSP is being followed.

In both examples, we can see how following the LSP helps to create code that is easier to maintain, test, and reuse, since subclasses can be used interchangeably with their parent class without affecting the correctness of the program.