In The craft
Simplifying Null Checks
I have checks for nulls littered throughout my codebase. We see this in all C# codebases it’s just comes with the territory. So much so, we don’t see it as an issue. We are numb to the pain.
An example of a null check.
if (source != null)
{
return source.Select(s => base.Convert(s));
}
return null;
It’s trivial code, no doubt about that, but my issue is it doesn’t provide much in the way of intent. Can we make it better? I think so. Lets make it more compact with a ternary operator. Here is the result.
return (source != null ? source.Select(s => base.Convert(s)) : null);
This is more succinct, but it lacks readability. We’ve squeezed the if-statement into one line. It feels harder to read than the previous form.
How can we make this more succinct and maintain readability? What if we used an extension method for the null check, instead of comparing the object to null?
if (source.IsNotNull())
{
return source.Select(s => base.Convert(s));
}
return null;
Ok, I like this. There is meaning to the if-statement evaluation. If it’s not null then we enter the if-statement.
Here is the code for the IsNotNull() extension method.
public static bool IsNotNull(this object val)
{
return val != null;
}
This is good, but I am bothered by the if-statement. I wonder if we can get rid of the if-statement all together. Maybe if we use a little of C#‘s functional magic we can eliminate the if-block.
return source.IsNotNull(() => source.Select(s => base.Convert(s)));
Ahh, that’s better.
When the object is not null is executes the passed in lambda expression. If you aren’t familiar with lambda expressions this might have you scratching your head. The code is below. Take a look at it, hopefully it will clean things up.
public static T IsNotNull<T>(this object val, Func<T> result) where T : class
{
if (val != null)
{
return result();
}
return null;
}
It’s a constant challenge keeping code readable. Most of us write code like this all day without a thought to making it better. We’ve been walking on glass for so long that we don’t feel the pain. Each little nugget helps.
On a side note, the next version of C# will have null-conditional operators making the extension method I created irrelevant. Here is an example.
return source?.Select(s => base.Convert(s));