Uncle Bob‘s aptly coined SOLID Design Principles form the basis of a robust software application. Today, I want to talk about one of those principles, the Liskov’s Substitution Principle (LSP) because it’s easy to deviate from, and a few conscious design choices can prevent us from doing so.
In the simplest terms, LSP suggests that:
Any change that makes a subtype not replaceable for a supertype, should be avoided.
Suppose, we have a class hierarchy like so:
At the first glance, the relationships here seem fine, but if we carry out an
IS-A test, the issue becomes obvious: that
Tea isn’t necessarily a
CaffeinatedDrink (for instance: there’s decaf!).