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


当前回答

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.

其他回答

总是为你的客户端着想(他们正在使用你的api):

返回'null'通常会导致客户端不能正确处理null检查的问题,这会导致运行时出现NullPointerException异常。我曾经见过这样的情况,缺少空检查会导致优先级生产问题(客户端对空值使用foreach(…))。在测试期间,问题没有发生,因为所操作的数据略有不同。

这取决于你的合同和具体情况。 通常最好返回空集合,但有时(很少):

Null可能意味着更具体的东西; 你的API(合约)可能会强制你返回null。

一些具体的例子:

一个UI组件(来自一个不受你控制的库),如果传递一个空集合,可能会呈现一个空表,或者如果传递null,则根本不呈现表。 在Object-to-XML (JSON/其他)中,null表示元素缺失,而空集合将呈现冗余(可能不正确)<collection /> 你正在使用或实现一个明确声明null应该返回/传递的API

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

返回null可能更有效,因为不会创建新的对象。然而,它也经常需要一个空检查(或异常处理)。

从语义上讲,null和空列表的意思是不同的。这些差异是微妙的,在特定的情况下,一种选择可能比另一种更好。

不管你的选择是什么,记录下来以避免混淆。

还有一点尚未被提及。考虑下面的代码:

    public static IEnumerable<string> GetFavoriteEmoSongs()
    {
        yield break;
    }

在调用此方法时,c#语言将返回一个空枚举数。因此,为了与语言设计(以及程序员的期望)保持一致,应该返回一个空集合。