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


当前回答

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

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

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

其他回答

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

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

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

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

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

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

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

我喜欢在这里用适当的例子来解释。

考虑一个案例。

int totalValue = MySession.ListCustomerAccounts()
                          .FindAll(ac => ac.AccountHead.AccountHeadID 
                                         == accountHead.AccountHeadID)
                          .Sum(account => account.AccountValue);

这里考虑我使用的函数..

1. ListCustomerAccounts() // User Defined
2. FindAll()              // Pre-defined Library Function

我可以很容易地使用ListCustomerAccount和FindAll代替。

int totalValue = 0; 
List<CustomerAccounts> custAccounts = ListCustomerAccounts();
if(custAccounts !=null ){
  List<CustomerAccounts> custAccountsFiltered = 
        custAccounts.FindAll(ac => ac.AccountHead.AccountHeadID 
                                   == accountHead.AccountHeadID );
   if(custAccountsFiltered != null)
      totalValue = custAccountsFiltered.Sum(account => 
                                            account.AccountValue).ToString();
}

注意:由于AccountValue不为空,Sum()函数不会为空 返回null。因此我可以直接使用它。

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

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

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

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