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:
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.