登录
首页 >  文章 >  java教程

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

来源:dev.to

时间:2024-09-14 08:46:03 158浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习文章的朋友们,也希望在阅读本文《Item - 返回空集合或数组而不是 null》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新文章相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

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);
}

客户待遇不足:

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》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>