The Next Generation of Defensive Coding

If you’re a Software Developer, hopefully you understand the concept of Defensive Coding. If you’re not familiar with the term here is a quick example to explain the concept.

public string SomeMethod(string prefix, string rootWord, string suffix)
{
	// Ensure Parameters contain values.
	if(string.IsNullOrEmpty(prefix))
		throw new ArgumentNullException("Prefix cannot be null");

	if(string.IsNullOrEmpty(rootWord))
		throw new ArugmentNullException("RootWord cannot be null");

	if(string.IsNullOrEmpty(suffix))
		throw new ArugmentNullException("Suffix cannot be null");

	return string.Format("{0}{1}{2}", prefix, rootWord, suffix);
}

Defensive coding gives the benefit of ensuring that your method is being used properly by who ever is implementing your code, if the proper requirements aren’t met the code throws an exception and warns the Developer what particular parameters expects in order for the function to complete properly.

This concept has been used for years and has suited its purpose well. However there are certain things that this method doesn’t provide. Wouldn’t it be nice if these conditions could be validated by the IDE, before compiling your project? Enter Code Contracts.

codecontracts_sm Code Contracts were added to .NET 4, but are available to be used in previous versions of the .NET Framework by installing them from the Microsoft DevLabs Project Site. To use Code contracts you will have to Add a Reference to the System.Diagnostics.Contracts namespace.

 

Static Checking which is the feature of Code Contracts that works without explicitly compiling your code [Visual Studio Background Compilation is necessary], is unfortunately only available in Visual Studio 2010. [Aside: I use the term unfortunately here lightly, you really should Upgrade to Visual Studio 2010, Microsoft has done an amazing job, and you won’t be sorry]

To Mimic the code that I’ve shown above, however this time leveraging the Code Contracts.

public string SomeMethod(string prefix, string rootWord, string suffix)
{
	// Ensure Parameters contain values.
	Contract.Assert(!string.IsNullOrEmpty(prefix));
	Contract.Assert(!string.IsNullOrEmpty(rootWord));
	Contract.Assert(!string.IsNullOrEmpty(suffix));

	return string.Format("{0}{1}{2}", prefix, rootWord, suffix);
}

As you can see the implementation is much neater and easier to read than the blocks of if statements.  This is not the only functionality of Code Contracts either, you can let the contract pass the value through by using the Assume Method which assumes that the value is valid. Other Advantages include Code Based Documentation [Outlining what is expected by the method (in Code, because no one likes making XML Comments)], Business Rule Validation, Can be evaluated on TFS Gated Check-in.

Once I start using Code Contracts in more depth, I’ll be sure to start giving you more real life implementation scenarios. As always be sure to check back!

Until then, Happy Coding!

2 Responses

  • Code contracts rock! I was never a fan of doing multiple if (…) throw checks in methods. It always seemed too repetitive and wasteful. Now if only they were version-backwards compatible…

  • @Steve – You can actually download the appropriate bits off of the DevLabs site for ASP.NET 3.5.

    "Code Contracts were added to .NET 4, but are available to be used in previous versions of the .NET Framework by installing them from the Microsoft DevLabs Project Site"

    The Url is beside the image.

Leave a Reply