当前位置:网站首页>返回一个零长度的数组或者空的集合,不要返回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返回值比零长度数组更好,因为它避免了分配数组
边栏推荐
猜你喜欢
![[TypeScript] OOP](/img/d7/b3175ab538906ac1b658a9f361ba44.png)
[TypeScript] OOP

MySQL---operator

Golang go-redis cluster模式下不断创建新连接,效率下降问题解决

【码蹄集新手村600题】通向公式与程序相结合

The new telecom "routine", my dad was tricked!

Go basic part study notes

21.支持向量机—核函数的介绍

使用 Flutter 和 Firebase 制作!计数器应用程序

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

【PIMF】OpenHarmony 啃论文俱乐部—盘点开源鸿蒙三方库【3】
随机推荐
OSPFv3的基本配置
Kotlin coroutines: continuation, continuation interceptor, scheduler
杰理语音芯片ic玩具芯片ic的介绍_AD14NAD15N全系列开发
go记录之——slice
spark报错OutOfMemory「建议收藏」
Poker Game in C# -- Introduction and Code Implementation of Blackjack Rules
【Yugong Series】July 2022 Go Teaching Course 020-Array of Go Containers
MySQL---聚合函数
学生管理系统第一天:完成登录退出操作逻辑 PyQt5 + MySQL5.8
Chinese encoding Settings and action methods return values
Flink_CDC搭建及简单使用
手把手教你学会部署Nestjs项目
【码蹄集新手村600题】通向公式与程序相结合
多线程之锁
idea中搜索具体的字符内容的快捷方式
MySQL---单行函数
leetcode 665. Non-decreasing Array
rj45对接头千兆(百兆以太网接口定义)
【luogu P8326】Fliper (Graph Theory) (Construction) (Eulerian Circuit)
&lt;artifactId&gt;ojdbc8&lt;/artifactId&gt;「建议收藏」