开发者

Is it better to return null or an empty collection?

Suppose I have a method that returns an array or list or some other collection. If something goes wrong inside or when there is simply no data to return, what is better - to return null 开发者_开发知识库or to return array (list, etc.) that has length (count) equal to 0?

In fact is it important, or it is just a matter of developer's preferences?


It's better to return an empty collection. This way when someone calls the function like so:

foreach(var i in items)
{

}

it doesn't throw a null reference exception on them.

Technically, you could argue empty vs. null means, but in reality a lot of people (myself included at times) forget to be defensive and don't check to see if the object is null before using it. It's playing into what other people assume is going to happen, which means less bugs and less angry users.


Your iteration code will be a lot easier if you return empty collections instead of null.

However, it may be important to distinguish between an empty collection and no collection of data, so it depends on the semantic of the actual type.


If something "goes wrong" you should throw an exception. If there is no data to return, return an empty collection. Developers generally should not be surprised with a NullReferenceException when they ask for a list of items and there just happen to be none to return.


I could see this going either way. Ultimately an array or collection with have a larger footprint, but is "Safer" in the sense that if the result is being used in future foreach/iterations the result will skip over the code block and not end up with a null object exception.


Well, null and empty have two different meanings. An empty collection effectively means "nothing is here", and could be valid. How would you know if something went wrong based on an empty collection?

While it is safer for the calling method, that doesn't make it better than returning null. Good practice states you should check for null before doing operations on an object. It is cheap anyway.

If something truly went wrong, why cant you throw an exception?


It is developer's preference really.

Returning an empty list

Normally I'd return an empty list so that the receiver of the method's return object doesn't need to check for null and avoid any possible NullReferenceException.

So anyone that expects a list can iterate through the list even though the list is empty (that will be a very quick for-each loop).

Returning null

If you are in an environment where running out of memory is a large issue you could optimize to return null value instead. However that means that everyone that uses the method in question always need to check for null and doesn't solve the problem of possible memory leaks.


If something goes wrong then you shouldn't be returning anything, rather throwing an exception.

You need to agree a consistent approach for the project as to the meaning of NULL and {} and stick to it. Either you are going to use NULL or not, if you are everyone needs to know to check.

I like to think of NULL - not tried to or see if there is anything, there might be some but who knows.

Empty collection - tried to populate and as far as the system is concerned there are no items, which is quite a strong statement.

e.g. Wallet.Notes collection.

  • NULL - I haven't opened my wallet, so I don't know if I have any notes in it.
  • List={} - I've checked and I definitely don't have any notes cos I spent it all on beer.


Here is an article by Josh Bloch explaining the same. It's written in Java's context but it should apply to C# equally well. Return zero-length arrays, not nulls


Although I'd say it's mostly a matter of developer's preference, to return an empty collection might be a better approach.

Let's say you have an object which contains a collection member.

public class Customer {
    private IList<Order> _orders;

    public Customer() {
        _orders = new List<Order>();
    }

    public IList<Order> Orders {
        get {
            return _orders;
        } 
    }
}

One generally will prefer to have this member as a readonly property so that its customer's orders don't get lost without any apparent reason. So, returning null is not an option. You would likely work better with an empty collection than a null reference. As such, instantiating the collection within the class constructor is a better approach.

And most importantly, when using DataBinding, for instance, you might get strange behaviour when returning null collection reference, as it will best work with an empty collection instead.

Another example, when iterating through a collection such as:

foreach (Order o in c.Orders) {
    // Do something here...
}

This foreach loop will simply not get executed when the collection is empty, without you having to check whether it is a null reference first. It simplifies the code and minimizes its complexity.

This depends on the scenario you're wokring in.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜