ValidationCodingTechniques

May 07, 2004
PragDave offered up this bit of advice to handling a string of validations to a query of mine on the PragProg mailing list:
In Ruby, a nice way of handling this is to have a class that contains the details of an error. Your validation methods then return an object of this class if validation fails, or ‘nil’ if it succeeds. You then write the actual validation as

error = validate_thing_one ||
validate_thing_two ||
validate_thing_three ||
. . . ||
validate_thing_n

The chain of calls terminates the first time a validation method returns an error object, and that object becomes the value of the expression. I like the compactness and symmetry of this approach, and I also quite often end up reusing the validation routines in different places in the code, which this supports.

Of course, it isn't quite this simple in Java, but it's still doable. Have your validation routines return a boolean (true if validation fails) and pass in it to each or them an error object which they can fill with the error details.

ErrorDetail error = new ErrorDetail;
validateThingOne(error) ||
validateThingTwo(error) ||
validateThingThree(error);

if (error.occurred()) {
...

Of course, this is logically pretty similar to using exception handling.

try {
validateThingOne();
validateThingTwo();
validateThingThree();
}
catch (ValidationError e) {
...
}


Michael Josephson tacked this useful bit on:
A variation of this technique could also be used in cases where you don't want to stop at the first validation error. i.e. do

validateThingOne(error);
validateThingTwo(error);
...


in sequence and have each validateThingN add an error to a list inside your ErrorDetail if that validation check fails.

then if (error.numberOfErrors() > 0) { ...


tags: ComputersAndTechnology