Missing Opportunities for Polymorphism
Let’s say our webshop offers items that can be downloaded and items that need to be shipped. Let’s build another object that supports these operations:
The ??? parameter isn’t some new fancy elvis operator, it’s asking should I email or snail-mail the item? The context needed to answer this question no longer exists. We have could captured the method of shipment in a boolean or enum and then use an if-then-else to fill in the missing parameter. Another solution would be create two classes that both extend Item. Let’s call these DownloadableItem and SurfaceItem. Now let’s write some code. I’ll promote Item to be an interface that supports a single method, ship. To ship the contents of the cart, we will call . Classes and will both implement ship.
While there are cases where it’s much more practical to use if-then-else instead of polymorphism, it is more often the case that a more polymorphic coding style will yield a smaller, more readable and less fragile code base. The number of missed opportunities is a simple count of the if-then-else statements in our code.