I am trying to perform validation using Spring validation. I am wondering what is the best practice to perform validation that depends mainly on user's action, hereafter, I have three different approaches but I don't know which one is best.
Assume, we have the following class Foo to validate and many different rules of validation depending on action performed by user.
public class Foo {
private String name;
private int age;
private String description;
private int evaluation;
// getters, setters
}
What is the best way to perform these validations (for instance: during creation only name and age are required, during evaluate action, I only need evaluation to be validated and so on)
solution 1: one validator class per validation rule
public class CreateFooValidator implements Validator {
//validation for action create
}
public class EvaluateFooValidator implements Validator {
//validation for evaluate action
}
solution 2: one validator class with several methods
public class FooValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Foo.class.equals(clazz);
}
//the default validate method will be used to validate during create action
@Override
public void validate(Object target, Errors errors) {
//validation required
}
//method to validate evaluate action
public void validateFooEvaluation(Object target, Errors errors) {
//validation required
}
//other validation methods for other actions
}
solution 3: Additional property action in class Foo, one validator
public class Foo {
private String name;
private int age;
private String description;
private int evaluation;
private String actionOnFoo;
// getters, setters
}
public class FooValidator implements Validator {
private final Foo foo = (Foo) target;
@Override
public boolean supports(Class<?> clazz) {
return Foo.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
//test which action is performed by user
if ("create".equals(foo.getActionOnFoo())) {
//call for private method that performs validation for create action
}
}
//all private methods
}
What is the best solution among the 3 or other solution if any? Thanks!