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 ..
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.).
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.
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.
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())){ ... };
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With