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
}
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
}
This is more readable and good practice too.
I would suggest that you do:
The
==
tests, while obviously redundant, also run the risk of a single=
typo which would result in an assignment.My personal feeling when it comes to reading
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
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).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.
The first one. But just another point, the following would also make your code more readable:
Note that there are extra spaces between
if
and the(
, and also before theelse
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: