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:

toggle code line numbers...
   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.

What actually seems to be wrong

I'm not going to delve too much into upper code but there are immediately two problems that pop into my eyes:

  • repetitive code writing and
  • magic strings
First one is problematic because it takes some time type all this code and second one is problematic because you may easily mistype these strings. Not too much of a problem but your exceptions would refer to invalid parameter names.

Avoiding magic strings - the simple way

There are other elegant ways of null auto-checking techniques of which I like the one written by who else than Jon Skeet but mine isn't so sophisticated and also avoids mistyping magic strings by automating their generation.

I'm using development tool's capabilities to do this. Namely Visual Studio code snippets. So instead of manually typing all those if statements you can just type in checknull press TAB and Visual Studio will replace that with a complete if statement and put your editing caret in place of parameter name in the if condition. Intellisense will then assist you to get the name right and by pressing the ENTER key Visual Studio will also automatically populate magic string in exception constructor. Voila. As simple as that. So instead of writing all that code, you can just write two things:

  1. checknull snippet word and
  2. method parameter name
And that's it. Nothing else.

Do we always check parameters for null?

Looking at my own code there are two most frequent parameter checks:

  • null checking
  • string null and empty string checking
Therefore I'm providing here two code snippets for each of them. One being activated by checknull and the other by checkstring.

Get snippets

You have to save snippets in the Visual Studio snippets folder. Following folder path is the default. Adjust version accordingly to yours. %HomePath%\Documents\Visual Studio {version}\Code Snippets

Parameter checking using Code snippets

Don't write the same code over and over again and rather save these two code snippets to simplify your coding. YOu will still have the same code in your methods, but will gain two main things:

  1. You will be faster doing this as code snippet template will do majority of typing for you
  2. You won't misspell parameter name when providing its testual name to exception constructor

So until we get Visual Studio 2014 with new C# ?. operator this is the simplest way without additional code in the form of either extension methods or other things.

There are two snippets

ONe is for null parameter checking and the other for strings that they're not null or whitespace.

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Parameter check for objects (not string type)</Title>
<Author>Robert Koritnik</Author>
<Description>Template that adds a parameter check code block.</Description>
<Shortcut>checknull</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>param</ID>
<ToolTip>Replace with parameter name.</ToolTip>
<Default>value</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[if ($param$ == null) {
throw new ArgumentNullException("$param$");
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Parameter check for strings</Title>
<Author>Robert Koritnik</Author>
<Description>Template that adds a parameter check code block for strings.</Description>
<Shortcut>checkstring</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>param</ID>
<ToolTip>Replace with parameter name.</ToolTip>
<Default>value</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[if (string.IsNullOrWhiteSpace($param$)) {
throw new ArgumentException("String '$param$' should not be null, empty or whitespace only.", "$param$");
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

No comments:

Post a Comment

This is a fully moderated comments section. All spam comments are marked as spam without exception. Don't even try.

Note: only a member of this blog may post a comment.