Boolean checking in the 'if' condition

后端 未结 10 1982
陌清茗
陌清茗 2020-12-03 07:40

Which one is better Java coding style?

boolean status = true;
if (!status) {
    //do sth
} else {
    //do sth
}

or:

相关标签:
10条回答
  • 2020-12-03 07:58

    My personal feeling when it comes to reading

    if(!status) : if not status
    
    if(status == false) : if status is false
    

    if you are not used to !status reading. I see no harm doing as the second way.

    if you use "active" instead of status I thing if(!active) is more readable

    0 讨论(0)
  • 2020-12-03 08:02

    Former, of course. Latter is redundant, and only goes to show that you haven't understood the concept of booleans very well.

    One more suggestion: Choose a different name for your boolean variable. As per this Java style guide:

    is prefix should be used for boolean variables and methods.

    isSet, isVisible, isFinished, isFound, isOpen

    This is the naming convention for boolean methods and variables used by Sun for the Java core packages.

    Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.

    Setter methods for boolean variables must have set prefix as in:

    void setFound(boolean isFound);

    There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

    boolean hasLicense();
    boolean canEvaluate();
    boolean shouldAbort = false;
    
    0 讨论(0)
  • 2020-12-03 08:03

    The former. The latter merely adds verbosity.

    0 讨论(0)
  • 2020-12-03 08:03

    First style is better. Though you should use better variable name

    0 讨论(0)
  • 2020-12-03 08:05

    The first one. But just another point, the following would also make your code more readable:

    if (!status) {
        // do false logic
    } else {
        // do true logic
    }
    

    Note that there are extra spaces between if and the (, and also before the else statement.

    EDIT

    As noted by @Mudassir, if there is NO other shared code in the method using the logic, then the better style would be:

    if (!status) {
        // do false logic
    }
    
    // do true logic
    
    0 讨论(0)
  • 2020-12-03 08:13

    I would suggest that you do:

    if (status) {
        //positive work
    } else {
        // negative work
    }
    

    The == tests, while obviously redundant, also run the risk of a single = typo which would result in an assignment.

    0 讨论(0)
提交回复
热议问题