Skip to content

Deeply Nested Null Checking in C# verses Assert with no nesting

Updated: at 06:34 PM

One of the code smells that particularly bothers me (though I often find myself doing it anyhow) is when I defensively program against nulls in C# (though could be any other language).  That is, I do something like the following

var rec = getRecord(..);
if (rec != null)
{
   var rec1 = getAnotherRecord(..);
   if (rec1 != null) 
   {
       rec2 = getAThridRecord(..);
       if (rec2 != null)...

The code gets ugly quick and the nesting does not help the readability, and if anything, hurts it.

Today, while using a daily build of Resharper7, I noticed that when I asked resharper to do the null check for me, instead of doing the above, it did the following:

var rec = getRecord(..);
Debug.Assert(rec != null,"rec != null");

var rec1 = getAnotherRecord(..); Debug.Assert(rec1 != null,“rec1 != null”);

var rec2 = getAThirdrRecord(..); Debug.Assert(rec2 != null,“rec2 != null”);

I think I like this better.  Still to early to decide such a big shift in my coding style.

What do you think?