Skip to main content

Defensive Programming & Argument Validation

 

The other day I found myself debugging the dreaded NullReferenceException “Object Reference not set to an instance of an object” on a piece of code written by a fairly Senior Developer.  

If you’ve been developing on .NET for more than 5 minutes then I’m sure you have come across this in your daily work and it is incredibly frustrating to try and debug.

With this post I hope to demonstrate how by using Defensive Programming you can make your API’s more robust and as a result reduce the number of bugs in your code.

If you’re a bit hazy on Defensive Programming and it’s cousins then I suggest you read the following:

Defensive Programming
Fail Fast
Design by Contract (DbC)

Validating method arguments for public methods should be a very simple concept to grasp and for most skilled developers is a  as natural as writing If statements.

The guiding principle I follow is to trust no single input and ensure that code only executes when the supplied arguments satisfy the requirements (pre-conditions). If it does not it should Fail Fast and throw an exception.

Take One

Here’s an example of what I consider to be a poorly written method.

        public OperationResult ChangeProductName(int productId, string name)
        {
            using (var uow = uowFactory.Create())
            {
                var product = productRepository.Get(productId);

                product.ChangeName(name); 

                uow.Commit(); 
            }

            return new OperationResult {WasSuccessful = true}; 
        }

Now what’s going to happen if the productId supplied is less than zero?

Well either the ProductRepository is going to throw an ArgumentOutOfRangeException or it will return a null Product and the call to Product.ChangeName is going to throw a NullReferenceException.

Either way an exception will be thrown after we have created a new Unit Of Work, which in practice could be an expensive operation.        

Take Two

So here is an example of how you could write the same method in a better way by first checking the arguments supplied satisfy the needs of the method.

        public OperationResult ChangeProductName(int productId, string name)
        {
            if (productId < 1)
            {
                throw new ArgumentOutOfRangeException();
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException();
            }

            using (var uow = uowFactory.Create())
            {
                var product = productRepository.Get(productId);

                if (product == null)
                {
                    throw new ProductNotFoundException(); 
                }

                product.ChangeName(name);

                uow.Commit();
            }

            return new OperationResult { WasSuccessful = true }; 
        }

 

Take Three

Now the previous approach is bounds better than the first but we can reduce the lines of code by making use of some Extension Methods like so:

        public OperationResult ChangeProductName(int productId, string name)
        {
            productId.ValidateArgumentRange(1);
            name.ValidateArgumentNull(); 

            using (var uow = uowFactory.Create())
            {
                var product = productRepository.Get(productId);

                if (product == null)
                {
                    throw new ProductNotFoundException(); 
                }

                product.ChangeName(name);

                uow.Commit();
            }

            return new OperationResult { WasSuccessful = true }; 
        }

 

Extension Methods

Here are the extension methods that I use to take care of this.

   public static class ArgumentExtensions
   {
       public static void ValidateArgumentNull(this object value)
       {
           if (value == null)
           {
               throw new ArgumentNullException();
           }
       }

       public static void ValidateArgumentRange(this int value, int min)
       {
           if (value < min)
           {
               throw new ArgumentOutOfRangeException();
           }
       }

       public static void ValidateArgumentRange(this int value, int min, int max)
       {
           if (value < min || value > max)
           {
               throw new ArgumentOutOfRangeException();
           }
       }
   }

 

You maybe thinking to yourself that this is really simple stuff and I’d agree, but I felt it needed to be shared for those Devs who are still learning.

There is a new project called Code Contracts which provides a way to explicitly define pre-conditions and post-conditions, this also allows to make use of Automatic testing tools such as Pex.

IMO a few years from now Code Contracts will be as fluent to a developer as Boolean operators and we will end up with better quality API’s because of it, however right now it is only a Research project so I’m hesitant to depend too highly on it until it’s finalised and becomes part of the core .NET Framework.

There are also ways to approach this problem using Aspect-Oriented Programming but I will leave that to another post.

Till next time.

Popular posts from this blog

ASP.NET MVC Release Candidate - Upgrade issues - Spec#

First of all, great news that the ASP.NET MVC Release Candidate has finally been released.  Full credit to the team for the hard work on this.  You can get the download here  However this is the first time I have had upgrade issues.  Phil Haack has noted some of the issues here   If like me you have lot's of CTP's and Add-Ins then you might experience some pain in Uninstalling MVC Beta on Vista SP1  This is the list of Add-Ins / CTP's I had to uninstall to get it to work  Spec# PEX Resharper 4.1  Sourcelinks ANTS Profiler 4   Can't say I'm too impressed as it wasted over an hour of my time.  As it turned out Spec# turned out to be the offending culprit, it's forgiveable to have issues with a third party product but a Microsoft one? Guess no-one on the ASP.NET team has Spec# installed. 

Freeing Disk Space on C:\ Windows Server 2008

  I just spent the last little while trying to clear space on our servers in order to install .NET 4.5 . Decided to post so my future self can find the information when I next have to do this. I performed all the usual tasks: Deleting any files/folders from C:\windows\temp and C:\Users\%UserName%\AppData\Local\Temp Delete all EventViewer logs Save to another Disk if you want to keep them Remove any unused programs, e.g. Firefox Remove anything in C:\inetpub\logs Remove any file/folders C:\Windows\System32\LogFiles Remove any file/folders from C:\Users\%UserName%\Downloads Remove any file/folders able to be removed from C:\Users\%UserName%\Desktop Remove any file/folders able to be removed from C:\Users\%UserName%\My Documents Stop Windows Update service and remove all files/folders from C:\Windows\SoftwareDistribution Deleting an Event Logs Run COMPCLN.exe Move the Virtual Memory file to another disk However this wasn’t enough & I found the most space...

CPF Contribution Rates for new Singapore Permanent Residents (SPR’s)

Recently my wife and I applied and got approved for Singapore Permanent Residency. After completing the formalities the most significant immediate change is the contribution to CPF which is Singapore’s mandatory social security savings scheme requiring contributions from employers and employees. CPF contributions start from the date you obtain SPR status, which is the date of the entry permit.   Being a relentless budgeter I needed to know exactly how much I and my employer would have to contribute so that I could adjust my budget accordingly as the employee contributions get deducted from the monthly salary. After doing some research I discovered that there is a “graduated” approach to CPF contributions for new SPR’s where the contributions gradually increase in the first and second year and then upon reaching the third year are at the full amount. Note: There is an option for employers to contribute the full amount for year 1 and year 2 and the employee can use the gra...