Should you return `null` or an empty list?

  Subscribe
8/8/2014 - Marco (updated on 11/13/2017)

I've seen a bunch of articles addressing this topic of late, so I've decided to weigh in.

The reason we frown on returning null from a method that returns a list or sequence is that we want to be able to freely use these sequences or lists with in a functional manner.

It seems to me that the proponents of "no nulls" are generally those who have a functional language at their disposal and the antagonists do not. In functional languages, we almost always return sequences instead of lists or arrays.

In C# and other functional languages, we want to be able to do this:

var names = GetOpenItems()
  .Where(i => i.OverdueByTwoWeeks)
  .SelectMany(i => i.GetHistoricalAssignees()
    .Select(a => new { a.FirstName, a.LastName })
  );

foreach (var name in names)
{
  Console.WriteLine("{1}, {0}", name.FirstName, name.LastName);
}

If either GetHistoricalAssignees() or GetOpenItems() might return null, then we'd have to write the code above as follows instead:

var openItems = GetOpenItems();
if (openItems != null)
{
  var names = openItems
  .Where(i => i.OverdueByTwoWeeks)
  .SelectMany(i => (i.GetHistoricalAssignees() ?? Enumerable.Empty<Person>())
    .Select(a => new { a.FirstName, a.LastName })
  );

  foreach (var name in names)
  {
    Console.WriteLine("{1}, {0}", name.FirstName, name.LastName);
  }
}

This seems like exactly the kind of code we'd like to avoid writing, if possible. It's also the kind of code that calling clients are unlikely to write, which will lead to crashes with NullReferenceExceptions. As we'll see below, there are people that seem to think that's perfectly OK. I am not one of those people, but I digress.

The post, Is it Really Better to 'Return an Empty List Instead of null'? / Part 1 by Christian Neumanns serves as a good example of an article that seems to be providing information but is just trying to distract people into accepting it as a source of genuine information. He introduces his topic with the following vagueness.

If we read through related questions in Stackoverflow and other forums, we can see that not all people agree. There are many different, sometimes truly opposite opinions. For example, the top rated answer in the Stackoverflow question Should functions return null or an empty object? (related to objects in general, not specifically to lists) tells us exactly the opposite:

Returning null is usually the best idea ...

The statement "we can see that not all people agree" is a tautology. I would split the people into groups of those whose opinions we should care about and everyone else. The statement "There are many different, sometimes truly opposite opinions" is also tautological, given the nature of the matter under discussion -- namely, a question that can only be answered as "yes" or "no". Such questions generally result in two camps with diametrically opposed opinions.

As the extremely long-winded pair of articles writes: sometimes you can't be sure of what an external API will return. That's correct. You have to protect against those with ugly, defensive code. But don't use that as an excuse to produce even more methods that may return null. Otherwise, you're just part of the problem.

The second article Is it Really Better to 'Return an Empty List Instead of null'? - Part 2 by Christian Neumanns includes many more examples.

I just don't know what to say about people that write things like "Bugs that cause NullPointerExceptions are usually easy to debug because the cause and effect are short-distanced in space (i.e. location in source code) and time." While this is kind of true, it's also even more true that you can't tell the difference between such an exception being caused by a savvy programmer who's using it to his advantage and a non-savvy programmer whose code is buggy as hell.

He has a ton of examples that try to distinguish between a method that returns an empty sequence being different from a method that cannot properly answer a question. This is a concern and a very real distinction to make, but the answer is not to return null to indicate nonsensical input. The answer is to throw an exception.

The method providing the sequence should not be making decisions about whether an empty sequence is acceptable for the caller. For sequences that cannot logically be empty, the method should throw an exception instead of returning null to indicate "something went wrong".

A caller may impart semantic meaning to an empty result and also throw an exception (as in his example with a cycling team that has no members). If the display of such a sequence on a web page is incorrect, then that is the fault of the caller, not of the provider of the sequence.

  • If data is not yet available, but should be, throw an exception
  • If data is not available but the provider isn't qualified to decide, return an empty sequence
  • If the caller receives an empty sequence and knows that it should not be empty, then it is responsible for indicating an error.

That there exists calling code that makes assumptions about return values that are incorrect is no reason to start returning values that will make calling code crash with a NullPointerException.

All of his examples are similar: he tries to make the pure-data call to retrieve a sequence of elements simultaneously validate some business logic. That's not a good idea. If this is really necessary, then the validity check should go in another method.

The example he cites for getting the amount from a list of PriceComponents is exactly why most aggregation functions in .NET throw an exception when the input sequence is empty. But that's a much better way of handling it -- with a precise exception -- than by returning null to try to force an exception somewhere in the calling code.

But the upshot for me is: I am not going to write code that, when I call it, forces me to litter other code with null-checks. That's just ridiculous.

ctlhut
5/9/2018

<a href=http://canadian-pharmacye.com>buy viagra from canada</a>
buy viagra in mexico http://canadian-pharmacye.com

dghzjl
6/10/2018

how to get viagra cheap
<a href=http://viagrasy.com>cialis viagra</a>
how long does viagra last http://viagrasy.com

iiabdj
7/9/2018

<a href=http://viagrasy.com>buy viagra usa</a>
viagra online in india http://viagrasy.com

nlxtal
8/7/2018

<a href=http://canadian-pharman.com>free viagra</a>
viagra online prescription required http://canadian-pharman.com

nxuluo
8/12/2018

dove comprare cialis online sicuro http://cialisn.com
http://cialisn.com - cialis generic name

vgoyjq
8/15/2018

<a href=http://canadian-pharmacyon.com>buy viagra in the usa</a>
viagra online kaufen ohne rezept forum http://canadian-pharmacyon.com

staletshka
8/23/2018

<a href="http://mphasset.com">viagra meaning</a> do u need a prescription for viagra http://mphasset.com

dtaletwibc
8/23/2018

<a href="http://mphasset.com">where can i find viagra</a> viagra 1 http://mphasset.com

ztaletuwoe
8/23/2018

<a href="http://baymontelreno.com">average cost of cialis per pill</a> cialis 10mg daily http://baymontelreno.com

italetogvg
8/23/2018

<a href="http://baymontelreno.com">should i take cialis everyday</a> where can i buy cialis online safely http://baymontelreno.com

ntaletyixm
8/23/2018

<a href="http://rabbitinahat.com">cialis headache relief</a> cheap cialis prices http://rabbitinahat.com

etaletgvbo
8/23/2018

<a href="http://baymontelreno.com">free trial cialis</a> cialis 20 milligrams http://baymontelreno.com

ptaletapuv
8/23/2018

<a href="http://bullsac.com">viagra levitra cialis comparison</a> levitra 20 mg duration of action http://bullsac.com

italetrfht
8/23/2018

<a href="http://psychologytweets.com">cialis com free offer</a> cialis romania http://psychologytweets.com

ftaletgyvp
8/24/2018

<a href="http://mphasset.com">viagra for male</a> where to buy generic viagra http://mphasset.com

jtaletsgip
8/24/2018

<a href="http://mphasset.com">good viagra alternative</a> where can you buy viagra in stores http://mphasset.com

ctaletglbx
8/24/2018

<a href="http://missreplicawatches.com">cialis user experiences</a> walmart cialis price http://missreplicawatches.com

ntaletoyeh
8/24/2018

<a href="http://rabbitinahat.com">cialis dizziness</a> cialis for bph http://rabbitinahat.com

ftaletqyim
8/24/2018

<a href="http://gigawatt6.com">flomax and cialis</a> can i get cialis online http://gigawatt6.com

htaletspxe
8/24/2018

<a href="http://gigawatt6.com">cialis substitute over the counter</a> directions for cialis http://gigawatt6.com

kvmvag
8/24/2018

<a href=http://propecial.com>propecia depression</a>
propecia doctor advice http://propecial.com

ttaletbtxo
8/25/2018

<a href="http://baymontelreno.com">cialis cheap</a> cheap cialis pills http://baymontelreno.com

ftaletynbf
8/26/2018

<a href="http://istanbulexpressonline.com">where can i buy viagra without a prescription</a> vigora vs viagra http://istanbulexpressonline.com

ktaletwhqd
8/26/2018

<a href="http://istanbulexpressonline.com">can you buy viagra without prescription</a> best online viagra http://istanbulexpressonline.com

vtaleturnt
8/26/2018

<a href="http://baymontelreno.com">cheapest pharmacy to buy cialis</a> order cialis http://baymontelreno.com

rtaletdaex
8/26/2018

<a href="http://baymontelreno.com">cialis commercial music</a> walgreens cialis price http://baymontelreno.com

htaletozvv
8/26/2018

<a href="http://baymontelreno.com">cialis best price canada</a> cialis grapefruit http://baymontelreno.com

mtaletbowo
8/26/2018

<a href="http://mphasset.com">can you buy viagra at walmart</a> levitra or viagra http://mphasset.com

staletcnda
8/26/2018

<a href="http://mphasset.com">viagra and blood sugar</a> cost of cialis vs viagra http://mphasset.com

ztaletbgqd
8/26/2018

<a href="http://psychologytweets.com">cialis by mail canada</a> buy generic cialis online http://psychologytweets.com

fyqnsk
8/26/2018

<a href=http://canada-pharmaci.com>can i buy cialis over the counter</a>
generic cialis usa buy http://canada-pharmaci.com

uqchmq
8/28/2018

i want to order viagra online http://canadian-pharmacya.com
<a href=http://camadian-pharmacya.com>viagra new york</a>

otaletuejj
8/29/2018

<a href="http://gigawatt6.com">when will cialis be available in generic form</a> best place to buy cialis online http://gigawatt6.com

ntaletothu
8/29/2018

<a href="http://psychologytweets.com">best place to order cialis online</a> can cialis stop working http://psychologytweets.com

italetpufy
8/29/2018

<a href="http://mphasset.com">what is viagra tablet used for</a> will expired viagra still work http://mphasset.com

ztaletaewq
8/29/2018

<a href="http://istanbulexpressonline.com">is there a herbal alternative to viagra</a> how to get rid of viagra side effects http://istanbulexpressonline.com

xbzjpu
9/2/2018

does cialis work http://canadian-pharmasy.com
<a href=http://canadian-pharmasy.com>buy cialis online reviews</a>

mpwyxu
9/5/2018

<a href=http://cialisn.com>cialis 20</a>
where can buy cialis online http://cialisn.com

xrkica
9/5/2018

<a href=http://canadian-pharmacyon.com>buy discount viagra</a>
buying viagra online in the usa http://canadian-pharmacyon.com

ghsftq
9/8/2018

viagra comprar online http://canadian-pharmacya.com
<a href=http://camadian-pharmacya.com>what is herbal viagra</a>

htaletmhgw
9/11/2018

<a href="http://baymontelreno.com">side effects of cialis for daily use</a> active ingredient in cialis http://baymontelreno.com

ktaletweqb
9/13/2018

<a href="http://usedrestaurantequipmentaz.com">best online cialis</a> order cialis uk http://usedrestaurantequipmentaz.com

ytaletnura
9/13/2018

<a href="http://istanbulexpressonline.com">female viagra pill</a> viagra for sale online http://istanbulexpressonline.com

ntaletakwv
9/13/2018

<a href="http://motechautomotive.com">generic cialis canada</a> cheap cialis black http://motechautomotive.com

italetglqv
9/13/2018

<a href="http://bullsac.com">levitra generic</a> levitra vs sildenafil http://bullsac.com

etaletjxes
9/14/2018

<a href="http://valladium.com">order cialis online cheap</a> cialis 5mg online http://valladium.com

gtaletnqit
9/14/2018

<a href="http://rabbitinahat.com">cheap cialis in canada</a> canadian online pharmacy generic cialis http://rabbitinahat.com

rtalettpyb
9/15/2018

<a href="http://buycialisonlineglka.com">order cialis online in canada</a> order generic viagra cialis http://buycialisonlineglka.com

ftaletrhfc
9/16/2018

<a href="http://canadian-pharmasale.com">order cialis canadian pharmacy</a> buy cialis now http://canadian-pharmasale.com

ytalettqxk
9/18/2018

<a href="http://canadian-pharmasale.com">how to order cialis online safely</a> cialis online paypal http://canadian-pharmasale.com

ftaletypqc
9/18/2018

<a href="http://missreplicawatches.com">cheap cialis from canada</a> cheap cialis uk http://missreplicawatches.com

ttaletmhfg
9/18/2018

<a href="http://h-m-j.com">generic viagra online usa</a> order brand viagra http://h-m-j.com

Sign up for our Newsletter