这是一个一般性的问题(但我使用c#),最好的方法(最佳实践)是什么,对于一个有集合作为返回类型的方法,你返回null集合还是空集合?


当前回答

框架设计指引第二版(第256页):

不返回空值从 集合属性或方法 返回集合。返回空 集合或空数组。

这是另一篇关于不返回null的好处的有趣文章(我试图在Brad Abram的博客上找到一些东西,他链接到了这篇文章)。

编辑-正如Eric Lippert现在对原始问题的评论,我也想链接到他的优秀文章。

其他回答

空的对消费者更友好。

有一个明确的方法来创建一个空的枚举:

Enumerable.Empty<Element>()

有人可能会说,空对象模式背后的原因与支持返回空集合的原因类似。

空集合。总是这样。

这糟透了:

if(myInstance.CollectionProperty != null)
{
  foreach(var item in myInstance.CollectionProperty)
    /* arrgh */
}

在返回集合或枚举对象时,NEVER返回null被认为是最佳实践。ALWAYS返回一个空的可枚举/集合。它可以防止前面提到的废话,并防止你的车被同事和你的类的用户怂恿。

在谈论属性时,总是设置一次属性,然后忘记它

public List<Foo> Foos {public get; private set;}

public Bar() { Foos = new List<Foo>(); }

在.NET 4.6.1中,你可以将这些内容进行大量压缩:

public List<Foo> Foos { get; } = new List<Foo>();

当谈论返回枚举对象的方法时,你可以很容易地返回一个空的枚举对象而不是null…

public IEnumerable<Foo> GetMyFoos()
{
  return InnerGetFoos() ?? Enumerable.Empty<Foo>();
}

使用Enumerable.Empty<T>()可以被视为比返回一个新的空集合或数组更有效。

Go似乎是首选nil而不是空数组的一种语言。

https://github.com/golang/go/wiki/CodeReviewComments#declaring-empty-slices

当声明一个空切片时,优先使用var t []string而不是t:= []string{}。前者声明一个nil切片值,而后者非nil但长度为0。它们在功能上是等价的——它们的len和cap都是0——但是nil片是首选样式。

I call it my billion-dollar mistake…At that time, I was designing the first comprehensive type system for references in an object-oriented language. My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. – Tony Hoare, inventor of ALGOL W.

See here for an elaborate shit storm about null in general. I do not agree with the statement that undefined is another null, but it is still worth reading. And it explains, why you should avoid null at all and not just in the case you have asked. The essence is, that null is in any language a special case. You have to think about null as an exception. undefined is different in that way, that code dealing with undefined behavior is in most cases just a bug. C and most other languages have also undefined behavior but most of them have no identifier for that in the language.