DEV Community

Cover image for The Power of Liskov Substitution Principle in Improving Software Design
Md. Asif Rahman
Md. Asif Rahman

Posted on

The Power of Liskov Substitution Principle in Improving Software Design

The Liskov Substitution Principle (LSP) is a principle of object-oriented programming and a part of the SOLID design principles. It states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.

A real-life business scenario where the Liskov Substitution Principle can be applied is in a banking system.

Consider a superclass "Account" with subclasses "Savings Account" and "Checking Account".

The Account class could have methods such as "deposit()" and "withdraw()".

Image description

All subclasses of Account, including Savings Account and Checking Account, can provide their own implementation of the deposit() and withdraw() methods, as the rules for depositing and withdrawing money may be different for each type of account.

Image description

Image description

Now, let's say that we have a function that accepts an Account object and performs some operations, such as depositing or withdrawing money.

If we pass a Savings Account object to this function, it should work just as well as if we had passed a Checking Account object.

This is because all of these objects are substitutable for each other, and the function should not care about the specific type of Account it is working with as long as it implements the deposit() and withdraw() methods.

Image description

Now, we can conclude that objects of subclasses can be used interchangeably with objects of the superclass without causing any problems or affecting the correctness of the program, even in a real business scenario.

Top comments (0)