這是本文件的舊版!


Effective Java - Return empty collections or arrays, not nulls

這個item是要告訴你要回傳空collection或array,而不要回傳null;因為這會讓你client需要多處理null的情況,也多了需要被測試的路徑。以書中的範例來說,針對collections回傳值的處理,會建議你使用以下方式:

public List<Cheese> getCheeses() {
    return new ArrayList<>(cheesesInStock);
}

Effective Java第三版Item 54。

  • Effective Java, 3/e