Liskov’s Substitution Principle: SOLID Design Principles

Share the Article

What is Liskov’s Substitution Principle

Liskov’s substitution principle is one of the very basic principle for object oriented application designing. It is also contributing third letter “L” in SOLID acronym where O stand for Liskov’s. This principle tries to address issues due to class extension.

Main idea of Liskov’s substitution principle is that subclass should qualify to be the actual substitution for the base class. This means, during class extension in real world, we need to ensure that derived object should substitute base class object without impacting base class functionality. Therefore, the derived class must support all feature of base class. In any case, the derived class should not block or restrict any of the base class features.

Liskov’s substitution principle acts like, one more check for inheritance. It will support correct derivation of the base class. Due to correct inheritance, the maintainability of the classes for future extension becomes very easy and economical.

Why

Lets us try to understand the need for Liskov’s substitution principle by taking an example of an application having Cricket class with below features :

  • Number of players.
  • Equipment’s required for Cricket.

Below is the class details:

class Cricket { int m_player; public: void setPlayer(int countPlayer) { m_player = countPlayer; } void setEquipment() { cout<<"Added Bat and Ball"<<endl; } };

Later on client adds logic for checking rain condition. Hence, additionally provide rain protection to players if rains are happening.

Sample Example without using Liskov’s Substitution Principle

Below is the sample application. This application provides rain protection as an additional feature.

#include<iostream> //main header for io using namespace std; //for namespace class Cricket { int m_player; public: void setPlayer(int countPlayer) { m_player = countPlayer; } void setEquipment() { cout<<"Added Bat and Ball"<<endl; } }; void RainProtecion(Cricket &c) { cout<<"Giving rain protection for all players"<<endl; } int main() //Client Code { Cricket c1; c1.setPlayer(11); c1.setEquipment(); cout<<"If it is raining "<<endl; RainProtection(c1); return 0; }

Suppose, in future, the application needs to support Badminton also. Similarly, we need provision for setting player and setting their equiptments. Since the Cricket class is already having similar interface, therefore, the new class Badminton can be easily derived from it.

Below is the sample code by extending the functionality for Badminton:

#include<iostream> //main header for io using namespace std; //for namespace class Cricket { int m_player; public: void setPlayer(int countPlayer) { m_player = countPlayer; } void setEquipment() { cout<<"Added Bat and Ball"<<endl; } }; class Badminton: public Cricket { public: void setEquipment() { cout<<"Added Bat and Shuttle"<<endl; } }; void RainProtection(Cricket &c) { cout<<"Giving rain protection"<<endl; } int main() //Client Code { Cricket c1; c1.setPlayer(11); c1.setEquipment(); Badminton b1; b1.setPlayer(2); b1.setEquipment(); cout<<"If it is raining "<<endl; RainProtection(c1); RainProtection(b1); //This is logically wrong return 0; }

Since, the Badminton is inherited from Cricket class, so we will be able to pass badminton object for RainProtection( ) functionality.

In reality, the badminton is an indoor game and cricket is an outdoor game. Rain protection is not a valid feature for Badminton. Hence, the Badminton is not fully compatible with Cricket (base) class.

Therefore, we are violating the Liskov principle here. Since derived class object is not fully compatible with base class, the substitution shall fail. Above hierarchy is dangerous and it will lead to run time surprises in given application . According to Liskov substitution principle- if base class A is having a1 as object and derived class B is having b1 as object, a1 should always be completely replaced by b1. If complete substitution is not possible then current derivation is risky.

How

Lets us try to update the above application with Liskov substitution principle. We need to follow below rules in order to create correct hierarchy with ensured future maintainability.

Create abstract class with generic interface

Create an abstract base class Game which will have all abstract interfaces generic to different games.

Class Game { int m_player; bool m_outdoor; public: void setPlayer(int countPlayer) { m_player = countPlayer; } virtual void setEquipment() = 0; void setOutDoor(bool outdoor) { m_outdoor = outdoor; } bool getOutdoor() { return m_outdoor; } };

AS seen above, now we have base class which support both indoor and outdoor, so it is easy to extend this class.

Derive concrete classes

Derive cricket and badminton from base class Game

class Game { }; class Cricket : public Game { }; class Badminton : public Game { };

Same application now using Liskov’s Substitution Principle

Below is the updated application which will deal with future extensibility also:

#include<iostream> //main header for io using namespace std; //for namespace class Game { int m_player; bool m_outdoor; public: void setPlayer(int countPlayer) { m_player = countPlayer; } virtual void setEquipment() = 0; void setOutDoor(bool outdoor) { m_outdoor = outdoor; } bool getOutdoor() { return m_outdoor; } }; class Cricket: public Game { public: virtual void setEquipment() { cout<<"Added Bat and Ball"<<endl; } }; class Badminton: public Game { public: virtual void setEquipment() { cout<<"Added Bat and Shuttle"<<endl; } }; void RainProtection(Game &c) { if(c.getOutdoor() == true) cout<<"Giving rain protection"<<endl; else cout<<"Rain protection not required"<<endl; } int main() { Cricket c1; c1.setPlayer(11); c1.setEquipment(); c1.setOutDoor(true); Badminton b1; b1.setPlayer(2); b1.setEquipment(); b1.setOutDoor(false); cout<<"If it is raining"<<endl; RainProtection(c1); RainProtection(b1); return 0; }

As seen above, suppose now, if we have to support more games, such as, Golf, Hockey, etc. then we can very easily derive them from Game and use in.

Pros & Cons of Liskov’s Substitution Principle

Pros

  • Firstly, it ensures correct sub-hierarchy with relevant checks.
  • Secondly, it becomes easy to extend new classes.
  • Thirdly, the maintainability of code becomes very easy.
  • Finally, there shall be no runtime surprises in the application.

Cons

  • Sometimes we need to update base class also in order to support new extension.

Main Funda: Liskov’s Substitution Principle ensures that the derived classes are not restricting any base function.

Advanced C++ Topics

Single Responsibility Principle
Open Closed Principle
Singleton Design Pattern
Factory Method Design Pattern
Builder Design Pattern
How std::forward( ) works?
How std::move() function works?
What is reference collapsing?

Share the Article

10,564 thoughts on “Liskov’s Substitution Principle: SOLID Design Principles

  1. Have you ever considered about adding a little bit more than just your articles?
    I mean, what you say is valuable and everything. Nevertheless imagine if you added some great
    images or videos to give your posts more, “pop”! Your content is excellent but with
    images and clips, this site could undeniably be one of
    the best in its field. Very good blog!

  2. We identified resident microglia with EYFP using FACS and recorded a high depletion rate 97 after 4 days P13, which covered the time period of the HI insult and recovery things to do or avoid while taking clomid There have been no studies of the side effects of Tamoxifen use in men but I now have an explanation for the cognitive loss my husband suffered while receiving this treatment for Male Breast Cancer

  3. Pingback: 1macedon
  4. This is very interesting, You’re an excessively skilled blogger.
    I have joined your feed and look ahead to looking for more of your great post.
    Also, I’ve shared your website in my social networks

  5. I do not even know the way I ended up right here, but
    I assumed this publish used to be good. I do not recognize who you’re but definitely you are going to a
    famous blogger in the event you are not already. Cheers!

  6. Wayne LtRQQIpkfnIThJT 5 20 2022 how long does lasix last 16 Quinine was the first drug recognised as being involved in this group of DITP; however quinine type antibodies typically recognise a restricted set of epitopes on glycoprotein Ib IX 17 and glycoprotein IIb IIIa complexes of the platelet membrane

  7. Wonderful blog! I found it while searching on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!
    Thanks

  8. Have you ever considered about adding a little bit more than just your articles?
    I mean, what you say is fundamental and all. However just imagine if you added some great photos or videos to give your posts more, “pop”!

    Your content is excellent but with pics and clips, this website could undeniably be one of the greatest in its
    field. Terrific blog!

  9. My brother suggested I may like this blog. He was once totally right.
    This publish truly made my day. You cann’t consider just how much time I had
    spent for this info! Thank you!

  10. Heya this is somewhat of off topic but I was wanting to know if blogs
    use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding experience so I wanted to get guidance from someone with
    experience. Any help would be greatly appreciated!

  11. Common descriptions of this included an aching of leg muscles 4027, a general feeling of aching in the joints which impedes exercise 4001 and joints and muscles hurt most of the time 325 ivermectin for lice What treatment does my dog need if they have severe kennel cough or CIRD

  12. Thanks , I’vе recentⅼy been looking for information approximatеly tһis subject fоr ɑ ѡhile and yⲟurs iѕ the best I’ѵe came up᧐n tiⅼl now.
    Howeveг, whаt in regɑrds to tһe bottom ⅼine? Are you positive ⅽoncerning tһe
    source?

    Here is mу blog post … circle island tours

  13. Hi there just wanted to give you a brief heads up and let you
    know a few of the pictures aren’t loading properly.
    I’m not sure why but I think its a linking issue.
    I’ve tried it in two different browsers and both show the same outcome.

  14. I constantly really feel a little bit stymied when it concerns locating the ideal thanks gift for my kid’s instructors.
    This write-up is such a useful source!

  15. Online gambling is growing together with digital technologies to become one of the fastest-growing industries worldwide. Because of the security they offer when completing online financial transactions, cryptocurrencies like Bitcoin are being accepted by more industries. As a result, they will continue to significantly impact the future of internet gambling. CloudBet is a great platform for Bitcoin gambling. Since it was first launched in 2013, it refined its website and services, making sure users get the best experience. The UX was upgraded, and they also increased their gaming portfolio. Now, CloudBet is one of the best crypto betting sites out there. The casinohas games from Microgaming, Betsoft, and Spinomenal providers, among others. Also, it is licensed by the E-Gambling Montenegro commission. https://elearning.imagomindful.com/community/profile/tereseramos6926/ Calling itself the paradise of Bitcoin gambling, 7Bit’s been a popular player in the crypto gambling scene since it began operation in 2014. Most bitcoin-based sportsbooks have gambling licenses issued by the governments of Malta, Curacao, and Gibraltar. These licenses give the user peace of mind that their money is secure. Aside from a safe environment, most Bitcoin sites offer generous bonuses to attract players. In addition, withdrawal limits are extremely low, while deposit limits are high. This makes Bitcoin a great option for bettors. However, before signing up for a Bitcoin sportsbook, make sure the site has a good reputation. Globally, most bitcoin betting sites allow casino players to place bets, wager and perform transactions using Bitcoin. New customers can avail of welcome bonuses, reload bonuses, and withdraw Bitcoin bonuses on an initial deposit. Additionally, they are eligible for a welcome bonus, Bitcoin bonus, and other rewards on placing bets or playing online on the gambling site.

  16. Greetings from California! I’m bored at work so I
    decided to browse your blog on my iphone during lunch
    break. I enjoy the knowledge you present here and can’t wait to take a look when I get home.
    I’m amazed at how quick your blog loaded on my phone ..

    I’m not even using WIFI, just 3G .. Anyhow, very good site!

  17. Howdy! This is kind of off topic but I need some advice from an established blog.
    Is it very hard to set up your own blog? I’m not very techincal but
    I can figure things out pretty fast. I’m thinking about
    making my own but I’m not sure where to begin. Do you have any
    points or suggestions? Thanks

  18. Players who enjoy online slots not on GamStop with more reels and modern features have plenty of options available at Patrick Spins Casino, Cyclops. Lets have a look at some of the most important and often asked questions about such bonuses, Griffon. What online gambling sites pay good reviews au there cant be any complaints about the structure of the site, Minotaur. The casino takes the safety and security of its website and players extremely seriously. In order to prevent any cyberattacks or data breaches, Booi casino implements a host of security measures which include encrypting financial information and protecting user data using industry-standard firewalls. The casino also regularly engages external auditors to test its security systems and identify any potential vulnerabilities. https://daltonjaoc097542.wizzardsblog.com/14549581/bitcoin-gambling-sites-no-money The thing about online casino safety is that you need to pick a reputable site in order to enjoy a safe experience. This means that you will be absolutely safe at a licensed casino that also offers SSL encryption. Your private data and transactions will be encrypted in this case, so it doesn’t matter if you use cryptocurrencies or fiat money. A wide range of online casinos also has a dedicated gamble BTC games section where all slots and games support this digital currency directly. Online gambling Bitcoin does not only boil down to casinos. Many other betting platforms support Bitcoin casino products, whether this is online poker or sports wagering. Once you have found a BTC gambling site that you can trust with your funds and information, you can follow these simple steps to get started.

  19. Holymoly that’s crazy man! Thank you so much I really
    appreciate for this man. Can i show love on change your life and if you want to have a checkout?
    I will definitly share info about how to become a millionaire I
    will be the one showing values from now on.

  20. Hi would you mind letting me know which hosting company you’re working with? I’ve loaded your blog in 3 completely different browsers and I must say this blog loads a lot faster then most. Can you suggest a good web hosting provider at a reasonable price? Thank you, I appreciate it!

    My homepage … http://okno-audio.ru/bitrix/redirect.php?event1=&event2=&event3=&goto=https://www.mkiwi.com/cgi-bin/search.cgi?NextLink=https://highpeakscbd.net

  21. Hello very cool website!! Man .. Excellent .. Wonderful .. I will bookmark your site and take the feeds additionally…I am glad to find so many helpful information right here in the submit, we need develop extra strategies in this regard, thanks for sharing.

  22. A Child Student visa is for 4 to 17 year olds who intend to study at
    an independent college. Each year 2 lack occupation lists are released, one
    for the UK overall and also one for Scotland only. Following the profession of the whole of
    Malaya and also Singapore by the Japanese, Tokugawa recommended a reform strategy whereby
    the 5 kingdoms of Johor, Terengganu, Kelantan, Kedah-Penang and also Perlis
    would certainly be recovered as well as federated. Under New
    Zealand regulation, anybody founded guilty of an offence which lugs a jail sentence of 5 years
    or longer will not get a visa, though discernment is admitted some
    situations. Applications received after the closing day will certainly not
    generally be considered. Visabot has launched a name Facebook Messenger chat AI that assists you full
    United States visa applications. “Following today’s Federal Circuit and Family members Court decision on a step-by-step ground, it remains within Immigration Priest Hawke’s discretion to think about terminating Mr Djokovic’s visa under his individual power of cancellation within section 133C( 3) of the Movement Act,” the representative claimed,
    in the very first remarks from the priest’s office after the
    court subdued an earlier visa termination.

  23. Hi! I know this is kinda off topic nevertheless I’d figured I’d ask.
    Would you be interested in trading links or maybe guest authoring a blog article or vice-versa?
    My site discusses a lot of the same topics as
    yours and I believe we could greatly benefit from each other.
    If you are interested feel free to send me an e-mail. I look forward to hearing from you!

    Excellent blog by the way!