Conditional method chaining in java

  • A+
Category:Languages

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 .. 

 


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).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: