Best Practices: Avoid Returning Null

Don’t Return Null





Your method shouldn't return NULL


public void registerItem(Item item) {
if (item != null) {
ItemRegistry registry = peristentStore.getItemRegistry();
if (registry != null) {
Item existing = registry.getItem(item.getID());
if (existing.getBillingPeriod().hasRetailOwner()) {
existing.register(item);
}
}
}
}


When we return null,
  • We are essentially creating work for ourselves and foisting problems upon our callers.
  • One missing null check is enough to send an application spinning out of control.
Did you notice the fact that there wasn’t a null check in the second line of that nested if statement? What would have happened at runtime if persistentStore were null? We would have had a NullPointerException at runtime, and either someone is catching NullPointerException at the top level or they are not. Either way it’s bad.


What should we do in response to a NullPointerException thrown from the depths of your application?


TODO:
  • If you are tempted to return null from a method, consider throwing an exception or returning a SPECIAL CASE object instead.
  • If you are calling a null-returning method from a third-party API, consider wrapping that method with a method that either throws an exception or returns a special case object.


Example:-


List<Employee> employees = getEmployees();
if (employees != null) {
for(Employee e : employees) {
totalPay += e.getPay();
}
}


Right now, getEmployees can return null, but does it have to? If we change getEmployee so that it returns an empty list, we can clean up the code:


List<Employee> employees = getEmployees();
for(Employee e : employees) {
totalPay += e.getPay();
}

Java has Collections.emptyList(), and it returns a predefined immutable list
that we can use for this purpose:


public List<Employee> getEmployees() {
if( .. there are no employees .. )
return Collections.emptyList();
}
If you code this way, you will minimize the chance of NullPointerExceptions and your code will be cleaner.

References : - Chapter 7,  Clean code by Robert C Martin

Comments