像下面这样的方法并不少见:
// Returns null to indicate an empty collection. Don’t do this!
private final List<Cheese> cheesesInStock = ...;
/**
* @return a list containing all of the cheeses in the shop,
* or null if no cheeses are available for purchase.
*/
public List<Cheese> getCheeses() {
return cheesesInStock.isEmpty() ? null : new ArrayList<>(cheesesInStock);
}
把没有奶酪(cheese)可买的情况当作是一种特例,这是不合常理的。这样做会要求客户端中必须有额外的代码来处理null返回值,例如: