One of the new features I’m working on for Smart Device Framework 2.0 is a couple of classes to ease the pain of code validation during development. The principle I’m using to achieve this is the design by contract concept from Eiffel.
For those unfamiliar with DBC, it provides a way for developers to validate their code by defining constraints over the parameters a method can accept and its return values. In DBC-talk, these are known as pre-conditions and post-conditions. For example, when I’m writing code, I often find myself writing something like this:
public int GetNormalizedNameLength(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
// .
// .
// .
if (returnValue <= 0)
{
throw new ArgumentException("returnValue must be greater than zero");
}
return returnValue;
}
This is a very simple example of DBC where I am mandating that name cannot ever be null and the return value must always be greater than zero. The principles of DBC don’t really apply to the code at runtime, but can be used during development and testing to ensure that your code is passing the right parameters with the right values. Simple enough, however, wouldn’t it be great if you could quickly & easily validate parameters and return values without having to repetitively write those if…throw blocks? Sure it would and that’s where SDF 2.0 comes into play. How about having something as simple as this:
public int GetNormalizedNameLength(string name)
{
Require.IsNotNull(name, "name");
// .
// .
// .
Ensure.IsGreaterThanZero(returnValue, "returnValue");
return returnValue;
}
For Smart Device Framework 2.0, I’ve currently spec’ed up the following conditional checks detailed in the class diagram below. Take a look at it and let me know if you have any more checks that you would like to see in there. Also, let me know about those that shouldn’t be included.
