ikvenu2000
ikvenu2000

Reputation: 341

design pattern for validations

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.

Upvotes: 2

Views: 1890

Answers (2)

jelle
jelle

Reputation: 770

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

new ValidationTemplate(){
  doInValidation(List<Error> errors){
    if(!condition) { 
      errors.add(new Error("reason");
    }
  }.validate();

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.

Upvotes: 4

Gedrox
Gedrox

Reputation: 3612

You should be looking Hibernate Validator.

Upvotes: 4

Related Questions