首頁 > Java > java教程 > 主體

Item - 傳回空集合或陣列而不是 null

DDD
發布: 2024-09-13 06:19:06
原創
589 人瀏覽過

Item - Retorne coleções ou arrays vazios, em vez de nulos

不回傳 null:

  • 傳回 null 代替空集合或陣列的方法需要額外的客戶端處理以避免異常。

null 問題:

  • 客戶端需要新增冗餘檢查(如果要檢查 null)。
  • 這些檢查中的遺漏可能會被忽視,從而導致錯誤。
  • 這使得傳回集合或陣列的方法很難實現。

反對 null 的論證:

  • 不要擔心分配空集合或陣列的效能,除非它被證明是瓶頸。

高效替代方案:

  • 使用空集合或陣列而不是 null。
  • 不可變集合可以重複回傳(例如:Collections.emptyList()、Collections.emptySet())。
  • 空數組也可以高效率回傳。

最佳化效能:

  • 使用可重複使用的空不可變集合來避免不必要的新分配。
  • 傳回相同的空數組,而不是每次建立一個新數組

程式碼範例:
傳回 null 的錯誤方法:

// Exemplo incorreto
public List<Cheese> getCheeses() {
    return cheesesInStock.isEmpty() ? null : new ArrayList<>(cheesesInStock);
}

登入後複製

客戶待遇不足:

List<Cheese> cheeses = shop.getCheeses();
if (cheeses != null && !cheeses.isEmpty()) {
    // Lógica para lidar com queijos disponíveis
}

登入後複製

傳回空集合的正確方法:

// Exemplo correto
public List<Cheese> getCheeses() {
    return cheesesInStock.isEmpty() ? Collections.emptyList() : new ArrayList<>(cheesesInStock);
}

登入後複製

使用不可變的空集合:

public List<Cheese> getCheeses() {
    return cheesesInStock.isEmpty() ? Collections.emptyList() : new ArrayList<>(cheesesInStock);
}

登入後複製

與空數組一起使用:

// Retorno de array vazio corretamente
public Cheese[] getCheeses() {
    return cheesesInStock.toArray(new Cheese[0]);
}

登入後複製

最佳化空數組的使用:

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

public Cheese[] getCheeses() {
    return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
}

登入後複製

結論:
永遠不要傳回 null:總是更喜歡空集合或陣列。這簡化了 API,防止錯誤,並且很少對效能產生負面影響。

以上是Item - 傳回空集合或陣列而不是 null的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!