What the Hack is Liskov Substitution Principle? And What Breaks it?

Yu-Song Syu
Sep 4, 2018 · 2 min read

Ok, I know. I know we all learned about “Liskov Substitution Principle”. We all put correct answer in our Programming Language class.

You put the correct answer because you memorized it. The thing is, do you really understand it? Let’s check out Wikipedia:

Hmm… I don’t think it’s that easy to understand…

Let’s put it this way: I think, the Liskov Substitution Principle asks us to define a self-explaining interface (of Father), so that when we invoke the method in the son, we then don’t have to know much about the implementation detail.

Or, we can simply check out what “breaks” the principle:

When you have no choice but to “downcast” some classes, you are breaking the principle.

Easy to see, isn’t it? You have to downcast to son to invoke a method? It means that and you rely on the son’s implementation detail too badly. I mean, you know too much…

source: google

To me, it’s a typical misusage of “Polymorphism”.

Here’s another case:

When you find something that the father can do but the son doesn’t, the father-son bonding is… well, you know…

source: google

Check if you put lots of “downcasts” in your project. Reconstruct it.

Seriously.

Kuma老師的軟體工程教室

Welcome to the Kingdom of Software Engineering

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade