Is it better to return null or empty collection?

前端 未结 18 1578
我在风中等你
我在风中等你 2020-11-22 07:56

That\'s kind of a general question (but I\'m using C#), what\'s the best way (best practice), do you return null or empty collection for a method that has a collection as a

相关标签:
18条回答
  • 2020-11-22 08:34

    If an empty collection makes sense semantically, that's what I prefer to return. Returning an empty collection for GetMessagesInMyInbox() communicates "you really do not have any messages in your inbox", whereas returning null might be useful to communicate that insufficient data is available to say what the list that might be returned ought to look like.

    0 讨论(0)
  • 2020-11-22 08:35

    One could argue that the reasoning behind Null Object Pattern is similar to one in favour of returning the empty collection.

    0 讨论(0)
  • 2020-11-22 08:38

    Depends on your contract and your concrete case. Generally it's best to return empty collections, but sometimes (rarely):

    • null might mean something more specific;
    • your API (contract) might force you to return null.

    Some concrete examples:

    • an UI component (from a library out of your control), might be rendering an empty table if an empty collection is passed, or no table at all, if null is passed.
    • in a Object-to-XML (JSON/whatever), where null would mean the element is missing, while an empty collection would render a redundant (and possibly incorrect) <collection />
    • you are using or implementing an API which explicitly states that null should be returned/passed
    0 讨论(0)
  • 2020-11-22 08:39

    Empty collection. Always.

    This sucks:

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

    It is considered a best practice to NEVER return null when returning a collection or enumerable. ALWAYS return an empty enumerable/collection. It prevents the aforementioned nonsense, and prevents your car getting egged by co-workers and users of your classes.

    When talking about properties, always set your property once and forget it

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

    In .NET 4.6.1, you can condense this quite a lot:

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

    When talking about methods that return enumerables, you can easily return an empty enumerable instead of null...

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

    Using Enumerable.Empty<T>() can be seen as more efficient than returning, for example, a new empty collection or array.

    0 讨论(0)
  • 2020-11-22 08:39

    Empty is much more consumer friendly.

    There is a clear method of making up an empty enumerable:

    Enumerable.Empty<Element>()
    
    0 讨论(0)
  • 2020-11-22 08:40

    I like to give explain here, with suitable example.

    Consider a case here..

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

    Here Consider the functions I am using ..

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

    I can easily use ListCustomerAccount and FindAll instead of.,

    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();
    }
    

    NOTE : Since AccountValue is not null, the Sum() function will not return null., Hence I can use it directly.

    0 讨论(0)
提交回复
热议问题