Effective Java 43 Return empty arrays or collections, not nulls

时间:2022-06-30 05:49:52

Feature

Return empty arrays or collection

Return nulls

Avoids the expense of allocating the array

N

Y

Return value is immutable which may be shared freely

Y

N

Standard idiom for dumping items from a collection into a typed array

public class Shop {

// The right way to return an array from a collection

private final List<Cheese> cheesesInStock = new ArrayList<Cheese>();

// This prevent allocating an new Array every time which handles the expense issue.

private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];

/**

* @return an array containing all of the cheeses in the shop.

*/

public Cheese[] getCheeses() {

return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);

}

public static void main(String[] args) {

Shop shop = new Shop();

// User don't have to check the null of the returned array since it always returns an empty array

if (Arrays.asList(shop.getCheeses()).contains(Cheese.STILTON))

System.out.println("Jolly good, just the thing.");

}

}

A collection-valued method can be made to return the same immutable empty collection every time it needs to return an empty collection.

/**

* The right way to return a copy of a collection

* @return an array containing all of the cheeses in the shop.

*/

public List<Cheese> getCheeseList() {

if (cheesesInStock.isEmpty())

return Collections.emptyList(); // Always returns same list

else

return new ArrayList<Cheese>(cheesesInStock); // This is defensive copy to avoid the mutable object to be modified by the client.

}

Summary

There is no reason ever to return null from an array or collection-valued method instead of returning an empty array or collection.