97 Things Every Programmer Should Know

(Chris Devlin) #1

Collective Wisdom from the Experts 119


The ??? parameter isn’t some new fancy elvis operator; it’s asking whether I
should email or snail-mail the item. The context needed to answer this ques-
tion no longer exists. We have could captured the method of shipment in a
boolean or enum and then used an if-then-else to fill in the missing parameter.
Another solution would be to create two classes that both extend Item. Let’s
call these DownloadableItem and SurfaceItem. Now let’s write some code. I’ll pro-
mote Item to be an interface that supports a single method, ship. To ship the
contents of the cart, we will call item.ship(shipper). Classes DownloadableItem
and SurfaceItem will both implement ship:


public class DownloadableItem implements Item {
public boolean ship(Shipping shipper, Customer customer) {
shipper.ship(this, customer.getEmailAddress());
}
}
public class SurfaceItem implements Item {
public boolean ship(Shipping shipper, Customer customer) {
shipper.ship(this, customer.getSurfaceAddress());
}
}

In this example, we’ve delegated the responsibility of working with Shipping
to each Item. Since each item knows how it’s best shipped, this arrangement
allows us to get on with it without the need for an if-then-else. The code also
demonstrates a use of two patterns that often play well together: Command
and Double Dispatch. Effective use of these patterns relies on careful use of
polymorphism. When that happens, there will be a reduction in the number
of if-then-else blocks in our code.


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 codebase. The number of
missed opportunities is a simple count of the if-then-else statements in our code.

Free download pdf