返回null或空集合更好嗎?

這是一個廣泛的問題(可是我正在使用C#),最好的方法是什麼(最佳實踐),對於以集合爲返回類型的方法,您是否返回null或空集合? 數組


#1樓

我想在這裏舉例說明。 函數

在這裏考慮一個案例。 spa

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

在這裏考慮我正在使用的功能.. code

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

我能夠輕鬆地使用ListCustomerAccountFindAll代替。 對象

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不爲null ,因此Sum()函數將不會返回null 。,所以我能夠直接使用它。 get


#2樓

空集合。 老是。 it

這很爛: io

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

最好的作法是在返回集合或可枚舉null時永遠不要返回null老是返回一個空的可枚舉/集合。 它能夠防止上述的廢話,並防止您的汽車被班上的同事和用戶所困擾。 foreach

在談論屬性時,請始終設置一次屬性,而後忘記它 List

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>()能夠被認爲比返回例如新的空集合或數組更有效。


#3樓

返回null可能更有效,由於不會建立新對象。 可是,它一般也須要進行null檢查(或異常處理)。

從語義上講, null和空列表並不意味着同一件事。 差別是細微的,在特定狀況下,一種選擇可能會比另外一種更好。

不管您選擇哪一種方式,都要記錄在案,以避免形成混淆。


#4樓

取決於您的合同具體狀況 。 一般,最好返回空集合 ,但有時( 不多 ):

  • null可能意味着更具體;
  • 您的API(合同)可能會迫使您返回null

一些具體的例子:

  • 一個UI組件(來自控件以外的庫),若是傳遞了一個空集合,則可能正在呈現一個空表,若是傳遞了null,則可能根本沒有表。
  • 在Object-to-XML(JSON / whatever)中,其中null表示元素丟失,而空集合則表示冗餘(可能不正確) <collection />
  • 您正在使用或實現一個API,該API明確指出應返回/傳遞null

#5樓

若是一個空集合在語義上有意義,那就是我但願返回的內容。 爲GetMessagesInMyInbox()返回空集合將傳達「您的收件箱中確實沒有任何消息」,而返回null可能對傳達可用數據不足以說明可能返回的列表應該是什麼樣子頗有用。

相關文章
相關標籤/搜索