不返回 null:
null 问题:
反对 null 的论证:
高效替代方案:
优化性能:
代码示例:
返回 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中文网其他相关文章!