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.

Comments

Popular posts from this blog

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\TempDelete all EventViewer logs Save to another Disk if you want to keep themRemove any unused programs, e.g. FirefoxRemove anything in C:\inetpub\logsRemove any file/folders C:\Windows\System32\LogFilesRemove any file/folders from C:\Users\%UserName%\DownloadsRemove any file/folders able to be removed from C:\Users\%UserName%\DesktopRemove any file/folders able to be removed from C:\Users\%UserName%\My DocumentsStop Windows Update service and remove all files/folders from C:\Windows\SoftwareDistributionDeleting an Event Logs Run COMPCLN.exe Move the Virtual Memory file to another disk However this wasn’t enough & I found the most space was cleared by using the Disk Cleanup to…

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 graduated rate, b…

Implementing Custom Castle Windsor Facilities

If you’ve been following my posts you would know that I love Castle Windsor. One of the many useful features I have found is the Facility and I’m going to try and give a good example how you can make use of this. In a recent post I showed how you can add Cross-Cutting concerns to your application by using Interceptors.Now when configuring the Container you can explicitly configure each Interceptor per Service but when you have lot’s of components it can get pretty hard to maintain after a while and can also introduce subtle issues if someone forgets to configure it correctly.Below is how you would configure your Container without using a Facility. On the last line we are specifying the Interceptor explicitly. public void Configure() { container = new WindsorContainer(); container.Register( Component.For<CacheInterceptor>(), Component.For<ICacheProvider>() .ImplementedBy<WebCache…