Java avoid using too many if statement or too many validator classes

Kun Liu :

I am using lot of if statements to check.Like:

if(statement 1){ 
   block 1;
}
if(statement 2){
   block 2;
}
...//about at least 20 if
if(statement n){
   block n;
}

To avoid using too many if-statement, I have tried to use strategy pattern which would create validator class for each if-statement.Like:

public interface Validator<SomeObejct>{
    public Result validate(SomeObject o);
 } 

public class SomeValidator implements Validator<SomeObject> {
   @Override
    public boolean validate(SomeObject o) throw Exception{
        if(statement 1){ 
            block 1;
         }  
}

Because I may have at least 20 if-statement, it may need at least 20 validator classes. So if there is any better solution for that? Or how can I manage these 20 validotor classes?

Edit:

To be more specific, I am writing some code for checking the problem on my schedule. For example:

 if(currentDate > mustFinishDate){
     warning();
 }
 if(NotScheduleADateForThisTask){
    warning();
 }
 if(DateFormatNotCorrect){
    error();
 }

Above the date check may also be the if-statement block.

daniu :

You can use the Composite pattern to maintain a list of all validators:

class ValidatorComposite<T> implements Validator<T> {
    List<Validator<T>> validators = new ArrayList<>();
    public void addValidator(Validator<T> add) { validators.add(add)); }

    public Result validate(T toValidate) {
        Result result = Result.OK;
        for (Validator<T> v : validators) {
            result = v.validate(toValidate);
            if (result != Result.OK) break;
        }
        return result;
    }
}

and since Validator only has one method, for Java 8 it's a functional interface, so you don't really need "20 classes" but can create a list on the fly using lambdas.

ValidatorComposite<SomeObject> val = new ValidatorComposite<>();
val.addValidator(so -> condition1 ? block1(so) : Result.OK);
val.addValidator(so -> condition2 ? block2(so) : Result.OK);

and so on.

Your code sample isn't really consistent because first you declare Validator to return Result and later let the implementation return boolean (and even throws an Exception), so I kind of intergrated both by ignoring the exception and using a Result.OK value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134857&siteId=1