Liskov Substitution Principle

Overview

You will learn the Liskov substation principle which is part of the SOLID principle. So what does SOLID stand for? SOLID principles are the design principles that enable us to manage most of the software design problems we encounter. 

The term SOLID refers to five design principles that make software designs more understandable, flexible, and maintainable.

“SOLID” each letter has its own meaning,

  • S: Single Responsibility Principle
  • O: Open-Closed Principle
  • L: Liskov Substitution Principle
  • I: Interface Segregation principle
  • D: Dependency Inversion principle 

Liskov Substitution Principle

Barbara Liskov introduced this concept in her work pertaining to data abstraction and type theory. A derived class should be a substitute for its base class so that using the base class should continue to function properly if a derivative of that class is used.

“The idea is that derived classes replace the base classes they are derived from”,

Liskov Substitution Principle

Technical Discussion

Problem statement

You might have seen multiple blogs on LSP sharing examples of fruit, birds, or squares and rectangles. Now I have taken some real-world examples. 

As an example, let's examine the 3Ds authentication services that they offer their debit card and credit card merchants to verify their transaction credentials. It has multiple authentication versions: version 1 and version 2. Anyone can utilize any of the authentication versions. As well, new versions could be added in the future. Therefore, let try to use substitution concept to resolve this versions problem.

Solution Discussion

In the below diagram, you can see three classes: authresopseBase is the base class that is inherited by two derived classes: authresposeV1 and AuthorsposeV2. 

Liskov Substitution Principle

Below is a code snippet showing a base class. 

The following code snippet shows that the base class inherits from the derived class for version 1.

Liskov Substitution Principle

You can see in the below code snippet that the base class inherits from the derived class for version 2.

Liskov Substitution Principle

Below is a screenshot showing how the AuthResponseBase class object can be easily replaced with the object of the V1 AuthResponse class, which is a derived class of AuthResponseBase.

Liskov Substitution Principle

Furthermore, you will notice that the authorization service returns a V2 AuthResponse object, which completely replaces the AuthresponseBase object without altering desirable properties. 

Liskov Substitution Principle

Conclusion

LSP states that the child class object completely replaces the parent object without affecting any of the desirable aspects of the program.


Similar Articles