java - 将代码设计为以不同方式处理空集合和 null 值是好事还是坏事?

标签 java design-patterns collections

<分区>

我正在处理的项目的一部分得到更新,并且在某个时候有人开始发送空集合而不是 null 作为方法的参数。

这首先导致了一个错误,然后导致我将 if (null == myCollection) 更改为 if (CollectionUtils.isEmpty(myCollection)),这最后导致了一系列的错误。通过这种方式,我发现很多代码对这些集合的处理方式不同:

  • 当集合为空时(即用户特别希望此处没有)
  • 当集合为null时(即用户未在此处提及任何内容)

因此,我的问题是:这是好的还是坏的设计实践?

最佳答案

在他的(非常好的)书 Effective Java 中,Joshua Bloch 针对方法的返回值处理了这个问题(不像您的问题那样“一般”):

(About use of null) It is errorprone, because the programmer writing the client might forget to write the special case code to handle a null return.

(...)

It is sometimes argued that a null return value is preferable to an empty array because it avoids the expense of allocating the array. This argument fails on two counts. First, it is inadvisable to worry about performance at this level unless profiling has shown that the method in question is a real contributor to performance problems (Item 55). Second, it is possible to return the same zero-length array from every invocation that returns no items because zero-length arrays are immutable and immutable objects may be shared freely (Item 15).

(...)

In summary, there is no reason ever to return null from an array- or collection-valued method instead of returning an empty array or collection. (...)

就我个人而言,在我的代码中使用集合时,我将此推理作为经验法则。当然,在某些情况下 null 和 empty 之间的区别是有意义的,但根据我的经验,这种情况很少见。

尽管如此,正如 BionicCode 在评论部分所述,如果方法返回 null 而不是 empty 以指定出了点问题,您总是有可能抛出异常.

关于java - 将代码设计为以不同方式处理空集合和 null 值是好事还是坏事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56490515/

相关文章:

java - spring boot无法加载css文件

java - 使用 java 8 转换数组列表 -> 映射

design-patterns - Hexagonal Architecture中的 "Hexagonal"是什么意思?

c - 在函数内部使用静态变量

java - Java中如何找到多个Map的共同部分?

java - Android Fragment不显示

java - FCM 数据消息无法正常工作

design-patterns - 您紧急打破可能的无限循环的模式是否有一个名称?

hibernate - 当集合没有改变时停止 Hibernate 更新集合

java - Java 中 ArrayList 和 LinkedList 的区别——性能的原因