Is returning null bad design?

koen picture koen · Aug 13, 2009 · Viewed 77.8k times · Source

I've heard some voices saying that checking for a returned null value from methods is bad design. I would like to hear some reasons for this.

pseudocode:

variable x = object.method()
if (x is null) do something

Answer

Adamski picture Adamski · Aug 13, 2009

The rationale behind not returning null is that you do not have to check for it and hence your code does not need to follow a different path based on the return value. You might want to check out the Null Object Pattern which provides more information on this.

For example, if I were to define a method in Java that returned a Collection I would typically prefer to return an empty collection (i.e. Collections.emptyList()) rather than null as it means my client code is cleaner; e.g.

Collection<? extends Item> c = getItems(); // Will never return null.

for (Item item : c) { // Will not enter the loop if c is empty.
  // Process item.
}

... which is cleaner than:

Collection<? extends Item> c = getItems(); // Could potentially return null.

// Two possible code paths now so harder to test.
if (c != null) {
  for (Item item : c) {
    // Process item.
  }
}