Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Erik
Erik

Posted on • Edited on

     

Liskov Substitution Principle in 3 Minutes

The Liskov Substitution Principle is theL inSOLID object oriented design, and despite having one of the more intimidating sounding names of the 5 principles, it's actually pretty easy to wrap your head around.

It's so simple, in fact, that you're going to understand it in about 3 minutes.

What Is It?

The LSP, in simple terms, states that objects of the same superclass should be able to be swapped with each other without breaking anything.

If we have aCat and aDog class derived from anAnimal class, any functions using theAnimal class should be able to useCat orDog and behave normally.

Let's do an example!

Even that definition doesn't quite explain it very well, so let's put it into practice. All will become clear with the code.

In true OOP fashion, let's make anAnimal superclass, and aDog andCat subclass and capture their favorite kinds of food.

publicstaticclassAnimal{publicStringfavoriteFood;publicAnimal(StringfavoriteFood){this.favoriteFood=favoriteFood;}}publicstaticclassDogextendsAnimal{publicDog(StringfavoriteFood){super(favoriteFood);}}publicstaticclassCatextendsAnimal{publicCat(StringfavoriteFood){super(favoriteFood);}}
Enter fullscreen modeExit fullscreen mode

Now we want to make a method that will let us give these cuties some treats. I don't want to put this method in theAnimal classes though, because it'sme feeding the animals, not a behavior intrinsic to the animals. Something likeDog.feed might get the point across, but I thinkfeed(Dog) is better, don't you?

Let's make this method and call itGiveTreatTo:

publicstaticvoidGiveTreatTo(Animalanimal){Stringmsg="You fed the "+animal.getClass().getSimpleName()+" some "+animal.favoriteFood;System.out.println(msg);}
Enter fullscreen modeExit fullscreen mode

See here thatGiveTreatTo takes anyAnimal as a parameter. Since ourAnimal constructors assign the animal's favorite food, we can pretty much count on that data always being there.

This means we don't have to make a method for each animal, i.e.,GiveTreatToDog andGiveTreatToCat. Because we implemented LSP, we have one method. Let's see it in action:

publicstaticvoidmain(String[]args){Dogrover=newDog("bacon");Catbingo=newCat("fish");GiveTreatTo(rover);GiveTreatTo(bingo);}
Enter fullscreen modeExit fullscreen mode

Now, if we properly implemented the LSP, this program should run just fine. Let's check the output:

You gave the Dog some baconYou gave the Cat some fish
Enter fullscreen modeExit fullscreen mode

Amazing. Another benefit of this principal is we can add more and more subclasses ofAnimal and theGiveTreatTo method won't need any tinkering.

Wrap Up

Pretty non-intimidating right? As with many things in programming and computer science, the name belies its simplicity. Now, go out there and make your subclasses swappable, and thank Dr. Barbara Liskov for such a useful principle.

Top comments(9)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
pareshjoshi profile image
Paresh
Engineering Leader - trying to improve at everything I do.
  • Location
    Remote
  • Education
    Bachelor of Engineer - Computers
  • Work
    Independent Consultant at Self-employed
  • Joined

Can you expand your example that breaks LSP? I guess, that way entry level programmers will be able compare it.

CollapseExpand
 
danielrusnok profile image
Daniel Rusnok
Interested in software architecture, design, unit testing, clean code.
  • Location
    Frýdek-Místek, Czechia
  • Work
    Software developer at Frýdek-Místek, Czechia
  • Joined
• Edited on• Edited

Nice example of violation the LSP could be to make an animal purr. Everybody knows that only one who can purr in our domain are cats, that is why method Purr could not be in Animal class. Dog dont purr, dogs cant inherit such a behavior.

CollapseExpand
 
pareshjoshi profile image
Paresh
Engineering Leader - trying to improve at everything I do.
  • Location
    Remote
  • Education
    Bachelor of Engineer - Computers
  • Work
    Independent Consultant at Self-employed
  • Joined

That makes perfect sense!

CollapseExpand
 
swarupkm profile image
Swarup Kumar Mahapatra
  • Joined

LSP also makes sure thatOpen Close principal is followed

CollapseExpand
 
sketchydev profile image
Shane Booth
  • Location
    UK
  • Work
    Software Engineering Contractor at Uk
  • Joined

Although the two are related and support each other, it is possible to violate either of them while maintaining the other - have a look heresoftwareengineering.stackexchange.... for a worked example

CollapseExpand
 
swarupkm profile image
Swarup Kumar Mahapatra
  • Joined

Thanks Shane.

That was a super big explanation and a helpful one.

CollapseExpand
 
schwarzwald profile image
schwarzwald
  • Joined
• Edited on• Edited

I think this is more an example of the strategy pattern than the LSP. If I understand it correctly LSP is about not breaking the contract of superclass with the implementation of subclass.

CollapseExpand
 
erikwhiting88 profile image
Erik
Sr. Software Engineer at CallRail building microservices to support 3rd party integrations. PhD student at the University of Nebraska studying bioinformatics, machine learning, and algorithms.
  • Email
  • Location
    Omaha, NE
  • Education
    BS CIS (2018), MS Software Engineering (2020), PhD Computer Science (in progress)
  • Pronouns
    He/Him
  • Work
    Sr. Software Engineer
  • Joined

You're right. I would argue, though, that the strategy pattern adheres to the Liskov Substitution Principle and is thus a good example for conceptualizing the principle, especially quickly

CollapseExpand
 
augustas profile image
Augustas
  • Joined

Helpful! Thanks!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Sr. Software Engineer at CallRail building microservices to support 3rd party integrations. PhD student at the University of Nebraska studying bioinformatics, machine learning, and algorithms.
  • Location
    Omaha, NE
  • Education
    BS CIS (2018), MS Software Engineering (2020), PhD Computer Science (in progress)
  • Pronouns
    He/Him
  • Work
    Sr. Software Engineer
  • Joined

More fromErik

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp