Java – how to use the if else statement returned by the function?

I always try to avoid nested statements

They guided me to put the code in curly braces When the amount of code in each condition becomes large, it is difficult to follow the code

if(condtion) {

} else if(condition2) {

} else {

}

So, if I have this Code:

void doSomething(){  
    if(condtion) {
        return;
    } else if(condition2) {
        return;
    } else {
        return;
    }    
}

I always change it to this form (I avoid else because each condition has a return statement):

void doSomething() {
    if(condtion) {
        return;
    }    
    if(condition2) {
        return;    
    }
    return;
}

But someone told me that my reading is a little difficult. Which is better?

Solution

If the condition is some quick case or prerequisite, I prefer to return immediately or throw no else statement For example:

void processArray(int[] array) {
    if(array == null || array.length == 0) {
        System.out.println("Empty input");
        return;
    }
    // do some complex computations
}

In this way, the rest of the method as the main course has no additional indentation and no additional parentheses at the end, which may be under the else statement

If the conditional branch is long and roughly the same length, the code will smell anyway You need to refactor it to extract branches into methods or (sometimes better) use something like command pattern to separate classes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>