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条回答
倾城 Initia
2楼-- · 2019-01-11 14:05

This is more readable and good practice too.

if(!status){
//do sth
}else{
//do sth
}
查看更多
戒情不戒烟
3楼-- · 2019-01-11 14:07

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.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-11 14:07

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

查看更多
Emotional °昔
5楼-- · 2019-01-11 14:09

The first one, or if (status) { /*second clause*/ } else { /* first clause */ }

EDIT

If the second form is really desired, then if (false == status) <etc>, while uglier, is probably safer (wrt typos).

查看更多
放我归山
6楼-- · 2019-01-11 14:14

If you look at the alternatives on this page, of course the first option looks better and the second one is just more verbose. But if you are looking through a large class that someone else wrote, that verbosity can make the difference between realizing right away what the conditional is testing or not.

One of the reasons I moved away from Perl is because it relies so heavily on punctuation, which is much slower to interpret while reading.

I know I'm outvoted here, but I will almost always side with more explicit code so others can read it more accurately. Then again, I would never use a boolean variable called "status" either. Maybe isSuccess or just success, but "status" being true or false does not mean anything to the casual reader intuitively. As you can tell, I'm very into code readability because I read so much code others have written.

查看更多
男人必须洒脱
7楼-- · 2019-01-11 14:16

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
查看更多
登录 后发表回答