Taming the Madness


Iterator getParameter(Map params, String key)
{
  Object o = params.get(key);

  if(o == null)
    return new NullIterator();

  if(o instanceof String[])
    return new ArrayIterator((String[])o);

  if(o instanceof List)
    return ((List)o).iterator();

  return new SingletonIterator(o);
}
We make everything look like an iterator. For the list, we use its built in iterator. For the other possibilites, null, object, array, we return an iterator of our own. I

The point here is that we're using the Iterator interface to shield client code from the specifics of our collection - if indeed we have a Collection. We can make different types of container, or none, appear the same. We've isolated a rather nasty typeswitch, which is always good, and simplified the client code.

I'll grant this is an extreme and unfortunate example, but it does demonstrate the point I think.