Return empty collection instead of null

In the solution I’m currently working on I see the following code a lot:

public IEnumerable<Order> GetOrdersByStatus(OrderStatus status)
{
    DataSet orderSet;

    // Get orders from database

    if (DataHelper.IsEmpty(orderSet))
    {
        return null;
    }
    List<Order> orders = new List<Order>();
    
    // convert to Orders

    return orders;
}

As you see on line 9 the method returns a null value if there are no results. There is a problem with this and that becomes obvious when you use the method:

IEnumerable<Order> orders = GetOrdersByStatus(OrderStatus.Open);
if (orders != null)
{
    foreach(Order order in orders)
    {
        // do something with orders
    }
}

The caller of the method always has to check for a null value. If one forgets, you end up with a NullReferenceException, which is a pain to debug.

I prefer to always to return an empty collection when there are no orders, for instance

public IEnumerable<Order> GetOrdersByStatus(OrderStatus status)
{
    DataSet orderSet;

    // Get orders from database

    if (DataHelper.IsEmpty(orderSet))
    {
        return Enumerable.Empty<Order>();
    }
    List<Order> orders = new List<Order>();
    
    // convert to Orders

    return orders;
}

This will make it much easier for the caller to process the result:

IEnumerable<Order> orders = GetOrdersByStatus(OrderStatus.Open);
foreach(Order order in orders)
{
    // do something with orders
}

The behavior will be the same, but it’s easier to get right.

Leave a Reply

Your email address will not be published. Required fields are marked *