I am developing my project on spring+hibernate+annotations. I need to apply some set of validations on the data.
presently the code seems like this.
public class SomeClass{
boolean error = false;
if(!error){
check condition1
if(fails) {
error = true;
}
}
if(!error){
check condition2
if(fails) {
error = true;
}
}
if(!error){
check condition3
if(fails) {
error = true;
}
}
// similarly i have 5 to 10 validations.
}
Is there any design pattern that can replace the above scenario.
Thanks.
spring offers validation classes, see org.springframework.validation
the reference supplies a full tutorial of the way spring handles validation errors. http://static.springsource.org/spring/docs/2.5.x/reference/validation.html
On my current project we went a bit further, we crated a ValidationTemplate class that is abstract. We have 2 methods, a validate method that calls an abstract method with a List<Error>
When we want to validate we can just create an anonymous instance of that abstract class and implement the doInValidation method. This allows you to
you can implement the validation method as you want, you could throw an exception or return the list with errors if you want a more elegant result.
Unfortunately I cannot post the exact source instead of this piece of pseudo code.