Check out the SOLID series:
- Single responsibility,
- Liskov substitution,
- Interface segregation and
- Dependency inversion
We shall elaborate the Liskov Substitution Principle in this post. The principle states that:
“If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program.”
In simple words, the intent of the LSP principle is:
Derived class objects/functions must be completely substitutable for their base types.
We shall now see the implementation of the principle. We shall implement the Bank class having different types of accounts like Saving, Credit. The account has special business rule for depositing the amount. Here we have considered that the rate of interest for the account are different and when the user deposits the money the interests is also deposited along with the principal amount.
Below is the simple implementation adhering to the Liskov Substitution Principle:
Check out the main(..) function implementation. The ‘Bank::DepositAmount(..)’ calls the function from the Account class and the derived class logic gets executed. The abstraction is implemented to call the customized functionality from the derived class without even knowing it.
Bank class is not aware of the different types of Accounts available. The Saving and Credit class extends the functionality of the Account class but maintains the same behavior of the class. The Liskov Substitution Principle is an extension to the Open Closed Principle to ensure that the behaviour of the base type is not modified.