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

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 was

3 Reasons Why Progressive Web Apps (PWAs) Won’t Replace Native Apps

Many people believe Progressive Web Apps (PWAs) are the future of the mobile web, but in my opinion, PWAs are not a replacement for native mobile apps. Here are three reasons why: 1. Native mobile apps provide a smoother & faster experience  Mobile websites, progressive or otherwise are slower and not as smooth. 90% of the time spent is spent using apps vs the browser . The single most significant contributing factor to a smooth experience on mobile is the speed of the network and latency of the data downloaded and uploaded. When you visit websites on desktop or mobile, there is a lot of third-party code/data that gets downloaded to your device, which more often than not has zero impact on the user experience. This includes: CSS (Cascading Style Sheets) JavaScript Ad network code Facebook tracking code Google tracking code The median number of requests a mobile website makes is a shocking  69 . On the other hand, native apps only get the data that is requi

Consuming the SSRS ReportExecutionService from a .NET Client

  I’ve just finished writing a nice wrapper which internally calls the SSRS ReportExecutionService to generate reports. Whilst it was fairly simple to implement there has been some major changes between 2005 and 2008 and the majority of online and documentation is based on the 2005 implementation. The most important change is that the Report Server and Report Manager are no longer hosted in IIS which will be a welcomed change to Sys Admins but makes the security model and hosting model vastly different. So far I’ve yet to figure out how to allow Anonymous Access, if anyone knows how to do this leave a comment and it will be most appreciated. Getting Started To get started you’ll want to add a service reference to http://localhost/ReportServer_SQL2008/ReportExecution2005.asmx where ReportServer_SQL2008 is the name you configure in the Reporting Services Configuration Manager. The Web Application files are located in C:\Program Files\Microsoft SQL Server\MSRS10.SQL2008\R