Better Syntax and New Rules for the .NET Validation Block
I've just updated Lokad Shared Libraries with slightly better syntax for composing validation rules.
The whole point was to make the code (like the one below) more self-documenting and readable even by .NET developers:
scope.Validate(e.Name, "Name", StringIs.Limited(1, 32), ValidName);
scope.Validate(e.Time, "Time", DateIs.SqlCompatible);
scope.Validate(e.Duration, "Duration",
Is.Within(0d, TimeSpan.MaxValue.TotalDays), DoubleIs.Valid);
Kudos go to Sean Kearon for pointing to the NUnitExtMethods for the idea.
So you can write assertion statements like:
Enforce.That(result, Is.Between(1,4));
And since, rule definitions are all the same, you could reuse your existing validation rules to run checks on the expected values within the unit tests.
Additionally, a couple of new rules have been added. Obviously, they are strongly-typed as any other rules in the library (as opposed to the NUnit assertions).
Description article of this Application Block has been updated and release (1.1.1552.1) has been made (see project page for the download links)
Sunday, November 30, 2008 at 20:24
Reader Comments (2)
Rinat,
This is a very interesting rules library I especially like that it really follows the KISS (Keep It Simple, Stupid) design philosophy, I have a suggestion that I think would be a very nice addition to this. To overload your validate method from taking a params argument of your Is.Methods and add a fluent interface to your project so you could do
scope.Validate(e.Name, "Name")
.Is.ValidName
.Is.Limited(1,32);
scope.Validate(e.Time, "Time", DateIs.SqlCompatible)
.Is.Not.Null
.Is.SqlCompatible
.Is.Not.GreaterThan(new DateTime(2010,1,1))
Hi Chris,
Thank you for raising this question. There are two reasons, why we didn't use a lot of fluent APIs here:
1. Using such API makes the code more complex (since we have to pass current Syntax down through the chain). What's more important, it makes designing rules more complex. One of the guidelines for Lokad Rules API was that rules should be extremely easy to create (by 3rd party dev's, too) and re-use consistently with any other pre-defined Lokad rules.
2. Using fluent API for defining rules sets either requires syntax terminator, using some rule builder class (like it is done in Autofac) or hacking to support builder behind the lines. That's just violates KISS.
3. This feature was not really needed in any production projects that actively use Lokad Shared Libraries.
Anyway, if your projects would benefit a lot from fluent API for Lokad Rules, you can extend that. Here's one example of adding custom Fluent API syntax to Rules (for DDD).