Boolean checking in the 'if' condition

2019-01-11 13:45发布

Which one is better Java coding style?

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

or:

if (status == false) {
    //do sth
} else {
    //do sth
}

10条回答
放荡不羁爱自由
2楼-- · 2019-01-11 14:16

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

查看更多
姐就是有狂的资本
3楼-- · 2019-01-11 14:27

The former. The latter merely adds verbosity.

查看更多
三岁会撩人
4楼-- · 2019-01-11 14:28

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;
查看更多
太酷不给撩
5楼-- · 2019-01-11 14:28

It really also depends on how you name your variable.

When people are asking "which is better practice" - this implicitly implies that both are correct, so it's just a matter of which is easier to read and maintain.

If you name your variable "status" (which is the case in your example code), I would much prefer to see

if(status == false) // if status is false

On the other hand, if you had named your variable isXXX (e.g. isReadableCode), then the former is more readable. consider:

if(!isReadable) { // if not readable
  System.out.println("I'm having a headache reading your code");
}
查看更多
登录 后发表回答