Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I manage the onslaught of null checks?

Tags:

Quite often, in programming we get situations where null checks show up in particularly large numbers. I'm talking about things like:

if (doc != null) {   if (doc.Element != null)   {     ... and so on   }   else     throw new Exception("Element cannot be null"); } else {   throw new Exception("document cannot be null"); } 

Basically, the whole thing turns into an unreadable nightmare, so I'm wondering: is there an easier way to describe what I'm trying to do above? (In addition to null checks, I get things like string.IsNullOrEmpty from time to time.)

Accepted answer: I accepted the answer that has this link because the approach described is innovative, and is precisely what I want. Thanks Shawn!

like image 220
Dmitri Nesteruk Avatar asked Jan 09 '09 18:01

Dmitri Nesteruk


People also ask

Is it good practice to check for null?

It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.

What are null checks?

A null indicates that a variable doesn't point to any object and holds no value. You can use a basic 'if' statement to check a null in a piece of code. Null is commonly used to denote or verify the non-existence of something.

Where do you put null checks?

If you have implemented layering in your project, good place to do null checks are the layers that receives data externally. Like for example: the controllers, because it receives data from the user... or the gateways because it receives data from repositories.


2 Answers

Check out this article: A fluent approach to C# parameter validation

It's written by one of the Paint.NET Developers. He uses extension methods to simplify and clean up null checking code.

like image 161
Shawn Avatar answered Sep 21 '22 15:09

Shawn


Push them forward to the beginning of the function, and keep them out of the part of the code that does the work. Like this:

if (doc == null)     throw new ArgumentNullException("doc"); if (doc.Element == null)     throw new ArgumentException("Element cannot be null"); AndSoOn();  
like image 28
Dan Monego Avatar answered Sep 18 '22 15:09

Dan Monego