3

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.

7
  • 2
    Are you using the if statements to test for only one variable or multiple variables, post an example of what you verify with the if statements. Commented Jan 2, 2019 at 15:04
  • 1
    Tell us more about your exact task. 20 if statements in a row sounds like a poor overall design. Commented Jan 2, 2019 at 15:05
  • 1
    Do you want to use your validators dynamically, or these are just 20 static 'if's? Commented Jan 2, 2019 at 15:06
  • 4
    If you have 20 completely distinct conditions, you will have 20 if statements, 20 classes, or 20 somethings. You can't just turn 20 conceptually different things into fewer than there actually are. Commented Jan 2, 2019 at 15:14
  • @Michael Thanks for your answer. In that case, I may need to think how to manage these 20 classes or 20 if statements in better way. Commented Jan 2, 2019 at 15:19

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. It inspire me a lot. I think this is a good way to manage my Validators.
Image
@daniu Is it mandatory that the variables values have already been initialized ?
1

these days what you should not probably care about is performance because of power of computers. now most programmers try to write readable and clean codes.

so i believe if writing 20 ifs makes your code easier to understand and more flexible its not bad to implement that.

BTW you can use switch case too.

switch (variable){
     case 1:{
     //block 1
      }
      case 2:{
      //block2
      }
      ...
}

if your cases are not similar and have different aspects using that Validator pattern will lead to inflexibility(It may lead to this point, it depends on situation).

2 Comments

I agree with your first two points, but the switch case is not the same as OP's example. If you put in the breaks in each case, it behaves like a sequence of if-else-if's, not as a sequence of if's.
In many cases, particularly if the value of variable is set by code that you maintain, much more readable, concise, and maintainable code is achieved by replacing switch-case blocks by an enum with a constant specific method or stored lambda.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.