0

When I use a method that return an IEumerable, First i check it for Null value and then check it for, Is there any Item.

public IEnumerable<Order> GetOrdersByServiceName(string serviceName)
{
     if (IsValidService(serviceName))
        return null;

     var orders = GetValidOrder(serviceName);

     return orders;
}

Usage:

var orders=GetOrdersByServiceName("TestService");

if(orders == null or !orders.any())
   //do something

If GetOrdersByServiceName return Null and I forget Null checking, Code will throw Null Reference Exception at some condition.I want eliminate orders == null and just use !orders.any() in If statement. I think two condition has same semantic and tell me result is nothing (Null Object pattern):

  • !orders.any()
  • orders == null

To realize that all Developer at my team must make sure every method which return IEnumerable , return `Enumerable.Empty() instead of Null value.

My Question Is: Are there any scenario that result of called method -Null or Empty Array- have different semantic for caller method?

Mazaher Bazari
  • 421
  • 5
  • 12
  • 1
    `To realize that all Developer at my team must make sure every method which return IEnumerable , return Enumerable.Empty() instead of Null value.` Yes. They must not return `null`. LINQ methods will never return `null` - always `Enumerable.Empty` - you should do the same. – mjwills Mar 26 '18 at 09:55
  • If you return `null` you're saying that the specified service is not valid. If you change that to return an empty Enumerable instead of null, then you've lost that information. However it seems to me that the code should be throwing an exception if the service is invalid. – Matthew Watson Mar 26 '18 at 09:58
  • 1
    I guess this is a bug: `if (IsValidService(serviceName)) return null` – Tim Schmelter Mar 26 '18 at 10:03
  • 1
    change the implementation for GetValidOrder and GetOrdersByServiceName ! null daoesn't say what's wrong! "**GetValidOrder**" should always return a list (or IEnumerable). Here's the pattern I would follow: public IEnumerable GetOrdersByServiceName(string serviceName) { if (!IsValidService(serviceName)) { throw new Exception("invalid servicename"); } return GetValidOrder(serviceName); } – Sunny Sharma Mar 26 '18 at 10:05

0 Answers0