当前位置:网站首页>返回一个零长度的数组或者空的集合,不要返回null
返回一个零长度的数组或者空的集合,不要返回null
2022-07-31 18:48:00 【y_bccl27】
1、返回一个零长度的数组
private final List<Cheese> cheesesInStock = ...;
public Cheese[] getCheeses(){
if (cheesesInStock.size() == 0)
return null;
} 把没有奶酪(Cheese)可买的情况当做一种特例,这是不合常理的。这样做会要求客户端必须有额外的代码来处理null的返回值,例如:
Cheese[] cheeses = shop.getCheeses();
if(cheeses != null && Arrays.asList(cheeses).contains(Cheese.STILTON)){
System.out.println("非常好,正好") ;
}而不是下面的这段代码:
if( Arrays.asList(cheeses).contains(Cheese.STILTON)){
System.out.println("非常好,正好") ;
}这样做很容易出错,因为编写客户端程序的程序员可能会忘记写这种专门的代码来处理null返回值,这样的错误也许几年都不会被注意到。
有时候会有人认为:null返回值比零长度数组更好,因为它避免了分配数组
边栏推荐
- Masterless Replication System (3)-Limitations of Quorum Consistency
- Verilog实现占空比为5/18的9分频
- 1161. 最大层内元素和 : 层序遍历运用题
- Performance optimization: remember a tree search interface optimization idea
- 架构师04-应用服务间加密设计和实践
- API for JD.com to obtain historical price information of commodities
- 【Yugong Series】July 2022 Go Teaching Course 023-List of Go Containers
- 九齐ny3p系列语音芯片替代国产方案KT148A性价比更高420秒长度
- 迁移学习——Domain Adaptation
- 浅谈网络安全之算法安全
猜你喜欢
![[Network Communication 3] Advantech Gateway Modbus Service Settings](/img/ec/e9e1d9a374183ecaa8a8c9437ec82c.png)
[Network Communication 3] Advantech Gateway Modbus Service Settings

高通cDSP简单编程例子(实现查询高通cDSP使用率、签名),RK3588 npu使用率查询

35 MySQL interview questions and diagrams, this is also easy to understand

2022 Android interview summary (with interview questions | source code | interview materials)

C# 之 扑克游戏 -- 21点规则介绍和代码实现
![leetcode: 6135. The longest ring in the graph [inward base ring tree + longest ring board + timestamp]](/img/91/284de3dcbb8d143d85775b314dd41c.png)
leetcode: 6135. The longest ring in the graph [inward base ring tree + longest ring board + timestamp]

Golang 小数操作之判断几位小数点与四舍五入

IP protocol from 0 to 1

Introduction of Jerry voice chip ic toy chip ic_AD14NAD15N full series development

Three.js入门
随机推荐
Bika LIMS 开源LIMS集—— SENAITE的使用(检测流程)
广汽本田安全体验营:“危险”是最好的老师
给定一个ip地址,子网掩码怎么算网络号(如何获取ip地址和子网掩码)
Performance optimization: remember a tree search interface optimization idea
1161. Maximum Sum of Elements in Layer: Hierarchical Traversal Application Problems
JD.com searches for products by keyword API
Handling write conflicts under multi-master replication (3) - Convergence to a consistent state and custom conflict resolution logic
Three.js入门
ResNet的基础:残差块的原理
全平台GPU通用AI视频补帧超分教程
C# 之 扑克游戏 -- 21点规则介绍和代码实现
1161. 最大层内元素和 : 层序遍历运用题
Batch (batch size, full batch, mini batch, online learning), iterations and epochs in deep learning
IP protocol from 0 to 1
MySQL---运算符
Get Douyin Video Details API
基于WPF重复造轮子,写一款数据库文档管理工具(一)
新型电信“套路”,我爸中招了!
Masterless replication system (1) - write DB when node fails
【码蹄集新手村600题】不通过字符数组来合并俩个数字