Conditional method chaining in java

Viewed 5507

What is the best possible way to chain methods together? In my scenario, there are four methods. If the output of the first method is true, it has to call the second method.

For Example:

flag = method1();
if (flag){
  flag = method2();
}
if (flag){
  method3();
} 
// and so on for next methods ..
7 Answers

Use the && logical AND operator:

if (method1() && method2() && method3() && method4()) {
    ........
}

Java evaluates this condition from left to right.
If any of the methods returns false, then the evaluation stops, because the final result is false (Short Circuit Evaluation).

if flag is not needed somewhere later on then @forpas's answer is the way to go otherwise I'd do:

flag = method1() && method2() && method3() && method4()

First and foremost I'd like to state that this answer is by no means more efficient than this answer or this answer rather it's just another way in which you can accomplish the task at hand while maintaining the short-shircuting requirement of yours.

So first step is to create a method as such:

public static boolean apply(BooleanSupplier... funcs){
      return Arrays.stream(funcs).allMatch(BooleanSupplier::getAsBoolean);
}

This function consumes any number of functions that have the signature () -> boolean i.e. a supplier (a function taking no inputs and returns a boolean result).

Then you can call it as follows using a method reference:

if(apply(Main::method1, 
         Main::method2, 
         Main::method3, 
         Main::method4)){ ... };

Where Main is the class where the methods are defined.

or lambda:

if(apply(() -> method1(), 
         () -> method2(), 
         () -> method3(), 
         () -> method4())){ ... };

To use the short circuit but keep it more readable, you can do

boolean flag = method1();
flag = flag && method2();
flag = flag && method3();

And so on. Note you can't use flag &= methodX() because that doesn't short circuit.

Nested conditional operators would solve this:

flag = method1() ? (method2() ? method3(): false): false;

You can use the && operator :

boolean flag = method1() && method2() && method3() && method4() && ...;

Do whatever with flag.

incase the methods truth values have to be saved or other side-effects have to happen:

boolean flag;
switch(1){
  case 1: flag = method1();  
          //additional code goes here

          if(!flag) break; 
  case 2: flag = method2();
          //additional code goes here

          if(!flag) break; 
     ....
  default: flag = method10();
          if(!flag) break; 
}

you shouldn't want this and it's... unexpected. but this is a readable way of adding additional statements to each code path.

otherwise: do it differently or fall back on ifs.

Related