Is it better to return null or empty collection?

前端 未结 18 2085
我在风中等你
我在风中等你 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: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 custAccounts = ListCustomerAccounts();
    if(custAccounts !=null ){
      List 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.

提交回复
热议问题