Monday, October 30, 2006

The null collection anti-pattern

NEVER do this:

public Collection<T> doTheMacarena() {
    if (isPresidentialElection())
        return null;

    return visitSouthAmerica();

ALWAYS throw exceptions or return empty collections; never use null as a kind of "soft exception". Either:

if (isPresidentialElection())
    throw new UnwiseCampaignTacticException();


if (isPresidentialElection())
    return Collections.emptySet();

Are preferable, depending on whether the return-condition is fast-failure or the "no data" sort.

How would you like to spend your day debugging:

for (final Dancer dander : doTheMacarena())

From inside miles of nested code across several transaction and remote boundaries?

UPDATE: A nice post from Nishanth Shastry on the for-each loop. Look at item #6, Return zero length arrays or empty lists rather than nulls.

Post a Comment