我正在处理的项目的一部分得到更新,并且在某个时候有人开始发送空集合而不是 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 以指定出了点问题,您总是有可能抛出异常.