(^118) 97 Things Every Programmer Should Know
Missing Opportunities for Polymorphism ................
Kirk Pepperdine
POLYMORPHiSM iS ONE OF THE GRAND iDEAS that is fundamental to OO.
The word, taken from Greek, means many (poly) forms (morph). In the con-
text of programming, polymorphism refers to many forms of a particular class
of objects or method. But polymorphism isn’t simply about alternate implemen-
tations. Used carefully, polymorphism creates tiny localized execution contexts
that let us work without the need for verbose if-then-else blocks. Being in a
context allows us to do the right thing directly, whereas being outside of that
context forces us to reconstruct it so that we can then do the right thing. With
careful use of alternate implementations, we can capture context that can help
us produce less code that is more readable. This is best demonstrated with
some code, such as the following (unrealistically) simple shopping cart:
public class ShoppingCart {
private ArrayList<Item> cart = new ArrayList<Item>();
public void add(Item item) { cart.add(item); }
public Item takeNext() { return cart.remove(0); }
public boolean isEmpty() { return cart.isEmpty(); }
}
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:
public class Shipping {
public boolean ship(Item item, SurfaceAddress address) { ... }
public boolean ship(Item item, EMailAddress address { ... }
}
When a client has completed checkout, we need to ship the goods:
while (!cart.isEmpty()) {
shipping.ship(cart.takeNext(), ???);
}