In parts one and two I discussed the approach I'm going to make to create a fluent argument validation library. Now the implementation.
Well it turns out most of it is pretty straightforward. And a little boring. There are a couple of things that warrent comment, the first being numbers. There are a lot of number types in .NET. There are precise types; byte, 3 sizes of int and decimal. Plus of course their evil partners the unsigned ints and the signed byte. And then on top of that you have imprecise types, the single and double. For the sake of completeness I'm going to add validation methods for all of them. Which means a lot of code to write; numeric types don't have a common interface we could exploit, or anything like type classes we can operate on. How can we be lazy and write less code?
By auto-generating it of course. One of the best kept secrets in Visual Studio is the Text Template Transformation Toolkit, or just T4 for short. T4 is a code generator that builds code from templates. I first heard about it in a blog post by Scott Hanselman a while ago and it's nice to finally have a chance to use it!
But before we get generating, what sort of interfaces/methods will we need? Basic range checking, greater than, less than, etc., will be needed for all number types. I find myself having to validate numbers are positive a fair bit so I'm going to add quick methods to check for positive and negative. These are only necessary for the signed types; there is no point in checking to see if a uint is negative because it cannot be. It sounds like we immediately have two interfaces, one for signed types and one for unsigned. Both contain greater/less methods but the signed one also contains positive/negative methods
As discussed in part one one of the problems I had with some of the other fluent interfaces available is that they allow you to make non-sensical and/or pointless calls, e.g:
public static void SomeMethod(int number)
{
Validate.Argument(number, "number")
.IsPositive()
.IsNegative()
.IsNegative();
A number cannot be both positive and negative, and there is no point in checking a number is negative twice. Therefore my inteface needs to return the interface for validating unsigned types after a call to positive or negative. (Even for singles and doubles! So if I talk about unsigned doubles I am making sense. Honest.) Ideally we would also like to stop calls such as:
public static void SomeOtherMethod(int number)
{
Validate.Argument(number, "number")
.IsGreaterThan(5)
.IsGreaterThan(3)
.IsGreaterThan(3);
There is no point in checking if something is over both 3 and 5 as just checking 5 would be enough. Similarly checking 3 twice is not necessary. Unlike the positive/negative we cannot enforce this at compile time so I'm going to have to let this one slide. (Although I will come back to this in part five)
The only other methods I'm going to implement are for the imprecise types only. These will be overloads of all the methods so far but with a tolerance to allow us to check two imprecise numbers follow the condition within a given amount.
Now how does T4 come into play? Well I can define generic interfaces for all the methods but I will need concrete classes for each numeric type. These concrete classes basically have the same implementation (operator comparisons such as >, <=, etc.) so instead of duplicating the same code over and over I'll create a template that generates the methods for each numeric type. If we can define the various properties of our numeric types (e.g. signed/unsigned, precise/imprecise, etc.) then our template can query those definitions to work out what interfaces and methods need implemented.
Definitions of the numeric types could come in handy in future templates. Therefore I defined the details of the numeric types in a file called NumericTypeDefinitions.ttinclude, which looks something like:
<#
var numericTypes = new []
{
new
{
Name = "Byte",
Zero = "0",
CLSCompliant = true,
Signed = false,
Precise = true
},
new
{
Name = "Decimal",
Zero = "0m",
CLSCompliant = true,
Signed = true,
Precise = true
},
...
Sadly the syntax highlighting is mine; rather annoyingly VS2008 doesn't highlight .tt or .ttinclude files... We can include this file in our actual T4 template. Basic templates just have a blob of code. The include means our definitions will be added to this blob. (You can create custom generator classes for more complex templates) Our T4 file will look something like this: (the ASP.NETters amongst you will probably recognise some of the syntax)
<#@ template language="C#v3.5" #>
<#@ output extension="cs" #>
<#@ assembly name="System.Core.dll" #>
<#@ import namespace="System.Linq" #>
<#@ include file="NumericTypeDefinitions.ttinclude" #>
using System;
using KWatkins.Validation.Argument;
namespace KWatkins.Validation
{
public static partial class Validate
{
<#
// Partial part of Validate first.
foreach(var type in numericTypes.Where(t => t.Precise))
{
if (!type.CLSCompliant)
{
#>
[CLSCompliant(false)]
<#
}
#>
public static <#= GetInterfaceType(type.Signed, type.Name) #> Argument(<#= type.Name #> argument, string parameterName)
{
return new <#= type.Name #>Validation(argument, parameterName);
}
<#
}
#>
}
}
...
What's happening here? Well we're basically adding the method Argument(T argument, string parameterName) to our Validate class. The directives at the start of the template define what we need for the code in our template, e.g. the language our template uses, the assemblies and namespaces we want to use, etc. Then the template starts; the text in grey is the text that will appear in the generated .cs file. In the snippet above I am looping through all the precise numeric types. If they are not CLS compliant then I add a CLSCompliantAttribute to the method. I then spit out the method definition, which returns a validation class of the appropriate type, casted to an interface of the appropriate type. I'll spare you the rest of the details; you can have a look at the source when I've finished.
Now the tests! How on Earth are we gonna test generated code? We could I suppose test the generator itself, i.e. test the output created by our T4 template is correct. But this doesn't actually test our final validation code! We could write a test for each generated method. But that would take ages besides being a bit rubbish. We could auto-generate our tests using a T4 template. Not a bad idea, but I personally prefer to have my test code as different to my code being tested as possible. So how to avoid writing a thousand separate tests for all our generated methods?
Use NUnit 2.5's excellent new generic test fixtures! NUnit 2.5 allows you to use generic classes for your test fixtures. You can then specify multiple TestFixtureAttributes each with a different generic type. The fixture will be executed multiple times, one for each TestFixtureAttribute. Add a splash of reflection to create our T4 generated validation class and we can write test fixtures like this:
[TestFixture(typeof(Byte))]
[TestFixture(typeof(UInt16))]
[TestFixture(typeof(UInt32))]
[TestFixture(typeof(UInt64))]
public class UnsignedPreciseNumberTests<TNumber> : NumberTests<TNumber>
where TNumber : struct
{
[TestCase("5", "TestParameterName", "10",
ExpectedException = typeof(ArgumentOutOfRangeException),
ExpectedMessage = "Value must be greater than 10.\r\nParameter name: TestParameterName\r\nActual value was 5.")]
[TestCase("5", "TestParameterName", "5",
ExpectedException = typeof(ArgumentOutOfRangeException),
ExpectedMessage = "Value must be greater than 5.\r\nParameter name: TestParameterName\r\nActual value was 5.")]
[TestCase("5", "TestParameterName", "0")]
public void IsGreaterThan(string argument, string parameterName, string minimum)
{
IUnsignedPreciseNumber<TNumber> validator = IUnsignedPreciseNumber<TNumber>)CreateValidationType(argument, parameterName);
validator.IsGreaterThan(ConvertFromString(minimum));
}
...
Here we are testing the IsGreaterThan method for the unsigned, precise number types. The test method gets an instance of the validation type using the CreateValidationType which does some reflective magic to create the correct type. It then calls the method using the values passed into the method via NUnit 2.5's TestCaseAttribute which allows you to run the same test multiple times with different values.
So that is the numbers done. I urge you to have a play with T4 and NUnit 2.5; both are fantastic tools to have in your arsenal. In the next post I will get irritated with enumerations...