Liskov Substitution Principle

Check out the SOLID series:

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.

Tagged with: , , , , , ,
Posted in CPP, software design
One comment on “Liskov Substitution Principle

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 353 other followers

%d bloggers like this: