Google analytics script

Latest jQuery CDN with code tiggling.

Wednesday, 27 August 2014

Simplifying method parameter checking

Next version of C# that will be coming with Visual Studio (supposedly version 2014) will have a new operator called the null-propagating operator (?.) allowing us to write null conditional statement expressions. This will help us simplify our code tremendously by collapsing several lines of conditional blocks to a single statement. Combining it with null-coalescing operator makes it even more powerful as seen in this example: string username = GetUser()?.name ?? "anonymous"; Object will be null checked before trying to access its members so we'll avoid the infamous null reference exception. It will therefore automatically continue to null coalescing part of the statement. You can read more about it on this link.

Parameter null value checking code is something we frequently write at the beginning of method body to avoid null reference runtime exceptions. You know these if statements right at the beginning of your methods:

   1:  public string DoSomething(Model data)
   2:  {
   3:      if (data == null)
   4:      {
   5:          throw new ArgumentNullException("data");
   6:      }
   7:      
   8:      // actual processing
   9:  }

Even static code analysis tools complain if you don't do these checks and to be honest this is a very good practice to avoid many future bugs in your code. The problem isn't this code per se, but rather that we're writing these seemingly same lines over and over again. Many developers tried simplifying this process using different techniques but the one I'm going to show here is a bit different.