alex in a nutshell

November 14, 2007

Creating business objects validation with Enterprise Library Validation Block

Filed under: — Alex Salamakha @ 11:01 PM

I’ve been using MS Enterprise Library on a number of projects. There are several blocks that used more often than others. I find validation block particularly useful. However, I usually like to tweak it a bit. The thing I don’t like is when you want to validate an object you require to write a substantial amount of code:

Validator<Customer> validator = ValidationFactory.CreateValidator<Customer>();

ValidationResults results = validator.Validate(customer);

Also it’s possible to create a validator for another type and validate an object with it without any problems, errors or exceptions:

Validator<WRONGCLASS> validator = ValidationFactory.CreateValidator<WRONGCLASS>();

ValidationResults results = validator.Validate(customer);

This feature is for flexibility, however, I haven’t found a need to use it the way it was intended. On the other hand I have encountered a number of situations where developers copy-pasted code responsible for creation of a validator without changing the type of a target object. This results unexpected behaviour during testing.
In order to fix this every business object is derived from a common parent BaseBusinessObject class, which has the following method defined:

public ValidationResults Validate()

{

Validator validator = ValidationFactory.CreateValidator(this.GetType());

return validator.Validate(this);

}

As a result, validating an object is now a lot simpler:

customer.Validate();

Usually it makes sense to have a base business object class anyway, so it’s not much of an overhead.

Copyright © 1997-2015 Alexei Salamakha. All rights reserved
email: alex@salamakha.com    Alex Salamakha on Facebook    Alex Salamakha on LinkedIn