Liskov Substitution Principle – SOLID Principles

Liskov Substitution Principle – SOLID Principles

Design Principles, Featured, Javascript, OOPS

In the Previous posts we have already discussed 2 important Principles of SOLID principles – Single Responsibility Principle and Open Closed Principle. In this post we are going to discuss the third principle Liskov Substitution Principle – SOLID Principles

Accoding to Uncle Bob :

Derived classes must be substitute for their base classes.

This means that child classes which are inherited from their base class must be a substitute of base class.

In the other context we can say that :

  1. Methods of a subclass that override methods of a base class must have exactly the same number of arguments.
  2. Each argument of the overridden method must be the same type as the method of the base class.
  3. The return type of the overridden method must be the same as the method of the base class.
  4. The types of exceptions thrown from the overridden method must be the same as the method of the base class.

Lets Understand using an Liskov Substitution Principle example :

class Bird {
  fly(speed) {
    return `Flying at ${speed} km/h`;
  }
}

class Eagle extends Bird {
  dive() {
    // ...
  }

  fly(speed) {
    return `Soaring through the sky at ${speed}`;
  }
}

// LSP Violation:
class Penguin extends Bird {
  fly() {
    return new Error("Sorry, I cant fly");
  }
}

In the above example Class Eagle is inheriting the parent class Bird and also overrides the method fly with same number of arguments The LSP does not insists that the return value of an overridden method also has to be the same.

The Penguin Class violates the LSP rules

  1. The overridden fly method does not have the same number of arguments.
  2. The return type of the fly method is not the same.
  3. The types of exceptions thrown are not the same.

Summary

The Liskov Substitution Principle is the third of Robert C. Martin’s SOLID design principles. It extends the Open/Closed principle and enables you to replace objects of a parent class with objects of a subclass without breaking the application. 

In the upcoming post we will discuss the remaining two solid principles Interface Segregation Principle and Dependency Inversion Principle.

Please provide your comments if you have any suggestion and follow us for next coming tutorials. Happy Coding…!!!

Leave a Reply