首页 > 图灵资讯 > 技术篇>正文

Item - 返回空集合或数组而不是 null

2024-09-18 15:42:02

item - 返回空集合或数组而不是 null

不要返回 null:

  • 返回 null 需要额外的客户端处理来避免异常,而不是空集合或数组。

null 问题:

  • 如果客户需要添加冗余检查(如果需要检查) null)。
  • 这些检查中的遗漏可能会被忽视,导致错误。
  • 这使得很难实现返回集合或数组的方法。

反对 null 的论证:

  • 除非被证明是瓶颈,否则不要担心分配空集合或数组的性能。

高效替代方案:

  • 使用空集合或数组而不是 null。
  • 不可变集合可重复返回(例如:collections.emptylist()、collections.emptyset())。
  • 空数组也能有效返回。

优化性能:

  • 采用可重用的空不可变集合,避免不必要的新分配。
  • 回到相同的空数组,而不是每次创建一个新的数组

代码示例: 返回 null 错误方法:

// exemplo incorreto
public list<cheese> getcheeses() {
    return cheesesinstock.isempty() ? null : new arraylist(cheesesinstock);
}

</cheese>

客户待遇不足:

list<cheese> cheeses = shop.getcheeses();
if (cheeses != null &amp;&amp; !cheeses.isempty()) {
    // lógica para lidar com queijos disponíveis
}

</cheese>

返回空集合的正确方法:

// exemplo correto
public list<cheese> getcheeses() {
    return cheesesinstock.isempty() ? collections.emptylist() : new arraylist(cheesesinstock);
}

</cheese>

使用不可变的空集合:

public list<cheese> getcheeses() {
    return cheesesinstock.isempty() ? collections.emptylist() : new arraylist(cheesesinstock);
}

</cheese>

使用空数组:

// 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 - 返回空集合或数组,而不是 请关注图灵教育的其他相关文章!

上一篇 免费软件:Java实用程序包(已发布版本
下一篇 返回列表

文章素材均来源于网络,如有侵权,请联系管理员删除。