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

eqhtpx
9/20/2018

comprar viagra generico en mexico http://canadian-pharmacie.com
<a href=http://canadian-pharmacie.com>cheap viagra uk</a>

staletyqhy
9/20/2018

<a href="http://canadian-pharmabuy.com">generic viagra 50mg</a> order generic viagra http://canadian-pharmabuy.com

xtaletrlbz
9/20/2018

<a href="http://missreplicawatches.com">cheap cialis online usa</a> cheap cialis usa http://missreplicawatches.com

fyavnu
9/20/2018

cialis online kaufen in deutschland http://canada-pharmaci.com
<a href=http://canada-pharmaci.com>cheap cialis online canadian pharmacy</a>

rtaletubkj
9/21/2018

<a href="http://istanbulexpressonline.com">viagra online</a> canadian viagra online http://istanbulexpressonline.com

xtaletwqya
9/21/2018

<a href="http://canadian-pharmasale.com">cialis online usa</a> cialis online coupon http://canadian-pharmasale.com

fhicrw
9/21/2018

<a href=http://canadian-pharmacyon.com>homemade viagra</a>
what is herbal viagra http://canadian-pharmacyon.com

rkyywh
9/22/2018

<a href=http://cialisn.com>cialis tadalafil</a>
order cialis online with prescription http://cialisn.com

gtaletlibn
9/24/2018

<a href="http://timsbmw.com">levitra and viagra together</a> levitra 20 mg price http://timsbmw.com

vtaletojwg
9/24/2018

<a href="http://buycialisonl1ne.us">order cialis without perscription</a> generic cialis online pharmacy http://buycialisonl1ne.us

ataletbzyv
9/24/2018

<a href="http://canadian-pharmacyisale.com">mail order viagra canada</a> buy viagra pills http://canadian-pharmacyisale.com

Jazeserymn
9/25/2018

india drug manufacturers levitra http://levitragtr.com - levitra 20 mg levitra bph <a href="http://levitragtr.com">levitra 20mg </a> - levitra from canada with a prescription reply #6 on levitra 10mg vs 20mg

wtaletytzi
9/25/2018

<a href="http://canadian-pharmacyionline.com">generic viagra canada</a> buy viagra online no prescription http://canadian-pharmacyionline.com

Olizerwex
9/25/2018

diabetes viagra http://viagrawithoutdoctorpharm.com - viagra without a doctor prescription how to cure ed <a href="http://viagrawithoutdoctorpharm.com">viagra without a doctor prescription </a> - can viagra and viagra treat other health issues? what happens if a woman takes viagra what happens if a woman takes viagra

ltaletodyw
9/26/2018

<a href="http://viciolatino.com">generic viagra online pharmacy</a> order viagra online usa http://viciolatino.com

ctaletvcge
9/26/2018

<a href="http://canadian-pharmakgae.com">viagra cheap prices</a> order pfizer viagra http://canadian-pharmakgae.com

zeknlf
9/27/2018

<a href=http://camadian-pharmacya.com>buy viagra 25mg</a>
viagra doc generici online http://canadian-pharmacya.com

jhwosb
9/27/2018

<a href=http://cialisn.com>buy sale cialis</a>
bangkok cialis where to buy http://cialisn.com

eplxuo
9/28/2018

<a href=http://canadian-pharmasy.com>side effects of cialis</a>
buy cialis online cheap http://canadian-pharmasy.com

ytaletfpbh
9/29/2018

<a href="http://viciolatino.com">best place to order viagra online</a> buy generic viagra cheap http://viciolatino.com

etaletjnzz
9/29/2018

<a href="http://canadian-pharmacyisale.com">order generic viagra</a> order pfizer viagra http://canadian-pharmacyisale.com

wtaletzckh
9/30/2018

<a href="http://canadian-pharmaorder.com">brand cialis online</a> cheap cialis 5mg http://canadian-pharmaorder.com

htaletwruh
9/30/2018

<a href="http://rabbitinahat.com">generic viagra professional</a> order viagra online http://rabbitinahat.com

ktaletdxui
9/30/2018

<a href="http://canadian-pharmakgae.com">best place to buy viagra online</a> order viagra now http://canadian-pharmakgae.com

dtaletvdss
10/2/2018

<a href="http://waltzweekend.com">viagra pills cvs</a> generic sildenafil 100mg http://waltzweekend.com

stxxob
10/2/2018

<a href=http://camadian-pharmacya.com>order viagra online overnight delivery</a>
viagra united states online http://canadian-pharmacya.com

rtaletxwnd
10/2/2018

<a href="http://canadian-pharmacyibuy.com">order cialis uk pharmacy</a> cialis generic price http://canadian-pharmacyibuy.com

staletaoka
10/4/2018

<a href="http://canadian-pharmapills.com">best herbal viagra for women</a> viagra price per pill http://canadian-pharmapills.com

Kezlyscowl
10/4/2018

is cialis better than cialis ? http://viagrawithoutdoctorx.com - viagra without prescription order generic cialis <a href="http://viagrawithoutdoctorx.com">viagra without a doctor prescription </a> - cialis 20mg side effects board index cheapest cialis in uk

ttaletlyqy
10/6/2018

<a href="http://canadian-pharmausa.com">generic viagra paypal</a> cheap viagra overnight http://canadian-pharmausa.com

ouimcc
10/7/2018

<a href=http://canadian-pharmasy.com>cialis 20mg</a>
when will cialis be generic http://canadian-pharmasy.com

JerezyPew
10/9/2018

making viagra http://gtviagracan.com - viagra for men for sale abrupt discontinuence of viagra <a href="http://gtviagracan.com">viagra for sale for men </a> - viagra 20 mg coupon views daily viagra

Mezfinmog
10/10/2018

levitra vs levitra forum joyfulyy.cgi http://levitragtr.com - levitra 20mg levitra i forgot my password <a href="http://levitragtr.com">levitra 20mg </a> - levitra 5 mg coupon joined compare prices levitra

Tezryzef
10/10/2018

write my economics paper http://writemyessayhelpcenter.com - write my paper for me best custom writing services <a href="http://writemyessayhelpcenter.com">write my essay </a> - writing essay services choosing a thesis topic

BruzeCer
10/11/2018

ed treatments http://viagrawithoutdoctorpharm.com - viagra without a doctor prescription pharmshop <a href="http://viagrawithoutdoctorpharm.com">viagra without doctor prescription </a> - viagra online overnight view all shout box latest message viagra

wtaletvepr
10/11/2018

<a href="http://zbloggers.com">propecia warnings</a> propecia lawyer http://zbloggers.com

btaletkuym
10/12/2018

<a href="http://viciolatino.com">order viagra online</a> viagra 100mg price http://viciolatino.com

ataletikue
10/12/2018

<a href="http://usedrestaurantequipmentaz.com">order cialis canada</a> cialis price http://usedrestaurantequipmentaz.com

btaletrqtv
10/13/2018

<a href="http://valladium.com">buy cialis doctor online</a> usa medical card cialis http://valladium.com

WalzacePinly
10/13/2018

help writing a thesis statement for a research paper http://essayfasthelp.com - write my paper creative writing coursework <a href="http://essayfasthelp.com">write my paper </a> - writing website paraphrasing strategies

ktaletzxoy
10/14/2018

<a href="http://canadian-pharmacyibuy.com">buy cialis online singapore</a> buy cialis online overnight shipping http://canadian-pharmacyibuy.com

dtaletgmwa
10/14/2018

<a href="http://usedrestaurantequipmentaz.com">cheap cialis</a> cialis 20 mg http://usedrestaurantequipmentaz.com

italethsgs
10/14/2018

<a href="http://canadian-pharmacheap.com">buy cialis online canada pharmacy</a> buy cialis online usa http://canadian-pharmacheap.com

TzomasKen
10/14/2018

levitra dosage 40 mg forums http://levitragls.com - levitra 20mg one a day levitra <a href="http://levitragls.com">levitra 20mg </a> - buy canada levitra levitra 20mg dosage topics

SazuelFap
10/17/2018

viagra 10 mg effectiveness faq http://viagrawithoutdoctorpres.net - viagra without a doctor prescription usa viagra from canada online login with username password and session length <a href="http://viagrawithoutdoctorpres.net">viagra without a doctor prescription usa </a> - uy viagra 20mg viagra

Olizermal
10/19/2018

essay editing software http://essaypromaker.com - write my essay essays for money <a href="http://essaypromaker.com">write my essay </a> - buy essay paper online cheap paper writing service

kweqxt
10/19/2018

<a href=http://propecial.com>boots order propecia canada</a>
order propecia online usa http://propecial.com

vblapr
10/21/2018

<a href=http://canada-pharmaci.com>cialis 5mg</a>
canadian cialis online http://canada-pharmaci.com

ZalterSnoke
10/23/2018

cialis 1 dollar 99 cents special offer http://tadalafilatwalmart.net - generic cialis at walmart cialis v cialis review <a href="http://tadalafilatwalmart.net">cialis over counter </a> - side effects of cialis penis erection that is painful or lasts 4 hours or longer buying cialis in philippines

pwsyzk
11/2/2018

<a href=http://canadian-pharmacyon.com>best place to buy viagra</a>
buy viagra where http://canadian-pharmacyon.com

plrlgm
11/2/2018

<a href=http://propecial.com>cheap generic propecia online</a>
propecia online http://propecial.com

bdjneo
11/3/2018

<a href=http://canadian-pharman.com>buy generic viagra professional</a>
viagra philippines prescription http://canadian-pharman.com
<a href=http://canadian-pharman.com>buy viagra online usa</a>

Sign up for our Newsletter