Effective Java 43 Return empty arrays or collections, not nulls
2014-04-06 19:44 小郝(Kaibo Hao) 阅读(603) 评论(0) 编辑 收藏 举报
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.
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。