Don't return null for functions returning collections/iterables

Usually when a method returns a collection and the method has no result to return, we have two options:

Return null: This results in breakage of client code if it doesn't check for that null.

public List<Order> getOrders() {
	//..
}
.
.
List<Order> orders = getOrders();
for(Order order : orders) { //NullPointerException here if getOrders returned null!
	System.out.println(order);
}

So the client will be forced to write:

if(orders != null) { //guard
	for(Order order : orders) { //NullPointerException here if getOrders returned null!
		System.out.println(order);
	}
}

Return an empty list: Client code will not break and no need to introduce a guard! Much cleaner code! So the below code will suffice:

List<Order> orders = getOrders();
for(Order order : orders) {
	System.out.println(order);
}

EDIT : Best way to return an empty list is to return one that is immutable by returningCollections.emptyList() from the concerned function.

Note: The above example dealt with lists but you can extend this discussion to anything that is a Collection/Iterables.

Comments (6)