Tuesday, January 10, 2012

Inline Specifications


A powerful feature of SpecExpress is it's ability to automatically generate user readable error messages for broken rules, and gather all of them up to display. In order to use this functionality, you need to create a Specification with the rules defined, add that specification to the ValidationCatalog, call Validate, and handle the ValidationNotification that is returned. But, sometimes specifications can be overkill for your needs. You might not need the reuse of a specification, or you might have rules that only need to be applied in a specific context.

We've recently add a new feature called Inline Specifications to SpecExpress that allows you to use SpecExpress to create your validation rules and messages, and not need the ValidationCatalog or just let you throw an exception. Here's what they look like in action.

Assert Inline Specification
public void DoWork(Request request)
{


//Before we do our work, validate the request, and throw an exception if invalid
Specification.Assert(sp => 
{
sp.Check(s => request.Field1).Required().EqualTo("Yellow"));
sp.Check(s => request.Field2).Required().EqualTo("Blue"));
})
}




Will create a ValidationNotificationException with all the broken rules.

Validate Inline Specification
public void DoWork(Request request)
{

//Before we do our work, validate the request
var validationNotification = Specification.Validate(sp => 
{
sp.Check(s => request.Field1).Required().EqualTo("Premium"));
sp.Check(s => request.Field2).Required().EqualTo("Blue"));
})

if (!validationNotification.IsValid)
{
//Log error and state then precede
}
}




No comments:

Post a Comment