Design Principle Kata 3 - Liskov Substitution Principle

Like my last post, this post introduces a code kata (coding exercise) that is designed to reinforce the Liskov Substitution Principle.

The idea behind the Liskov Substitution Principle is that subclasses should be able to be used wherever their parent class is used without having unexpected results. For example, you might have a Duck class that has a fly method. You might be tempted to subclass Duck to get a RubberDuck. The RubberDuck class would get all of the functionality of the Duck class, but there's an issue. Rubber ducks can not fly.

Software that uses Duck expects to be able to call fly but that does not make sense if a RubberDuck has been used.

One way to remedy situations like this is to favor composition over inheritance. So, instead of making RubberDuck inherit from Duck we could make a DuckAppearance that both Duck and RubberDuck have and can use to get what they should look like. Then we could have a Flyable class that just Duck has to handle flying behavior. We might even be able to use Flyable on classes that have nothing to do with ducks, like Airplane.

You can find the code for the kata on github.