Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional method chaining in java

Tags:

java

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 ..
like image 384
user10821509 Avatar asked Dec 21 '18 19:12

user10821509


People also ask

What is method chaining in Java?

Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.).

Why do we use method chaining?

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.

Which creates a chain class by calling?

The calling of the constructor can be done in two ways: By using this() keyword: It is used when we want to call the current class constructor within the same class. By using super() keyword: It is used when we want to call the superclass constructor from the base class.


2 Answers

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())){ ... };
like image 32
Ousmane D. Avatar answered Oct 13 '22 03:10

Ousmane D.


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

like image 86
forpas Avatar answered Oct 13 '22 03:10

forpas