不要返回 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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号