差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

Both sides previous revision 前次修改
下次修改
前次修改
java:effective_java:methods:return_empty_collections_or_arrays_not_nulls [2020/08/30 19:09]
tony [Introduction]
java:effective_java:methods:return_empty_collections_or_arrays_not_nulls [2023/06/25 09:48] (目前版本)
行 1: 行 1:
 {{tag>​java effective_java}} {{tag>​java effective_java}}
 ====== Effective Java - Return empty collections or arrays, not nulls ====== ====== Effective Java - Return empty collections or arrays, not nulls ======
-===== Introduction ​& My Opinion ​===== +===== Introduction ===== 
-這個item是要告訴你要回傳空collection或array,而不要回傳null;因為這會讓你client需要多處理null的情況,也多了需要被測試的路徑。+這個item是要告訴你要回傳空collection或array,而不要回傳null;因為這會讓你client需要多處理null的情況,也多了需要被測試的路徑,而且也不會比較快以書中的範例來說,針對collections回傳值的處理,會建議你使用以下方式:​ 
 +<code java> 
 +public List<​Cheese>​ getCheeses() { 
 +    return new ArrayList<>​(cheesesInStock);​ 
 +
 +</​code>​ 
 +Note. 這裡我不清楚作者為何要使用ArrayList,如果要immutable應該要用Collections.unmodifiableList。\\ 
 +\\ 
 +作者提到有些反對這種做法的人,是基於產生empty collection的開銷,所以又提供了另外一種方式:​ 
 +<code java> 
 +public List<​Cheese>​ getCheeses() { 
 +    return cheesesInStock.isEmpty() ? Collections.emptyList() 
 +        : new ArrayList<>​(cheesesInStock);​ 
 +
 +</​code>​ 
 +透過Collections.emptyList取得的empty collection,是可以減少產生的開銷,但也代表你要多寫單元測試代碼;作者認為如果沒有證據表明這真的是一個效能問題,就請忽略它,以避免增加不必要的困擾。\\ 
 +\\ 
 +針對Array的情況也是類似:​ 
 +<code java> 
 +public Cheese[] getCheeses() { 
 +    return cheesesInStock.toArray(new Cheese[0]);​ 
 +
 +</​code>​ 
 +假如在意new Cheese[0]會造成效能問題,就用空間換時間吧! 另外作者有提到,千萬別寫以下方式,會因而產生效能問題:​ 
 +<code java> 
 +return cheesesInStock.toArray(new Cheese[cheesesInStock.size()]);​ 
 +</​code>​ 
 +Note. 可以參考[[https://​stackoverflow.com/​questions/​174093/​toarraynew-myclass0-or-toarraynew-myclassmylist-size|此篇]]詳細說明。 
  
 ===== Note ===== ===== Note =====