Is there a pattern to execute a chain of methods based on the result of the previous in Java?

cmn :

The use case is there is a set of methods which need to be executed based on whether the previous one has returned true or not. For example:

class Test {
    boolean method1() {...}
    boolean method2() {...}
    boolean method3() {...}

    ...

    void callAll() {
        if(method1()) {
             if(method2() {
                 if(method3() {
                     ...
                 }
             }
        } else {
            error();
        }
    }
}

There has to be an else for all the ifs. Is there a better way of handling this scenario?

Mick Mnemonic :

I would just do it like this:

void callAll(){
    if(method1() && method2() && method3()){
        // all passed
    } else {
        error();    
    }
}

Java short-circuits the && logical operation so failure in a previous method here will prevent running the next one.

If in error() you need to know which of the methods failed, you could declare an error message field for storing the information within the class and set its value corresponding the failure:

private String errorMessage;

//...

boolean method2() {

    // something went wrong
    errorMessage = "Failed to do method2 stuff";
}

Are more elegant way to achieve the same would be to use the Chain of responsibility design pattern and encapsulate the boolean methods in their own handler objects. Doing this would however require more refactoring to the code you currently have and more information about your specific use case.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84531&siteId=1