Nearly all mammals can walk, and the user of the Mammal class will probably expect a walk() function. “Remove the walk() function from the Mammal class and let the subclasses optionally implement it.” That has one tiny problem. This is a direct violation of the Liskov Substitution Principle. Are you seeing this? The user of our code can do this at any time.ĭolphins can walk now? I don’t think so! This is syntactically correct, but it certainly isn’t behaviorally correct. Then you might implement the Dolphin class like this. On your first instinct, you might code something like this. Now that you know all of that, let’s start coding the relationship between dolphins and mammals. This will create some interesting problems for us trying to model this relationship. However, they also have fins and live underwater. They have live births, have a backbone, and are warmblooded. “Wait, the classic dolphin/mammal thing! That’s it!” Light bulb moment □ I was thinking of a good example of this principle but couldn’t think of very many. I know that this can sound confusing, so let’s use an example to drive the point home. They should never take away features or add type validation that the parent class doesn’t have.Īs you’ll see soon, it also means that we shouldn’t have any behaviors in the parent class that the sub-class cannot implement. Or in other words, sub-classes should only extend the features given to them by their parent class. If object A is a sub-class of object B, then class A should always be a compatible substitution for object B. In simple terms, the Liskov Subsitution Principle tells us the following. I’ll discuss the basic idea of the principle, then run through some examples. We’re now halfway through SOLID principles, woo-hoo! Today we’ll be talking about Liskov Substitution Principle or LSP, and how that applies to your code.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |