」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Item - 傳回空集合或陣列而不是 null

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

發佈於2024-11-06
瀏覽:384

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 getCheeses() {
    return cheesesInStock.isEmpty() ? null : new ArrayList(cheesesInStock);
}

顧客待遇不足:

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

傳回空集合的正確方法:

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

使用不可變的空集合:

public List 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,防止錯誤,並且很少對效能產生負面影響。

版本聲明 本文轉載於:https://dev.to/giselecoder/item-54-retorne-colecoes-ou-arrays-vazios-em-vez-de-nulos-1ej6?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3