Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 713
26071986 Avatar asked Dec 13 '22 17:12

26071986


2 Answers

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.

like image 81
kemiller2002 Avatar answered Jan 05 '23 03:01

kemiller2002


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.

like image 41
Brian Rasmussen Avatar answered Jan 05 '23 02:01

Brian Rasmussen