Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean checking in the 'if' condition

Tags:

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
}
like image 571
jasonfungsing Avatar asked Nov 26 '10 05:11

jasonfungsing


2 Answers

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.

like image 126
akf Avatar answered Oct 29 '22 01:10

akf


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;
like image 44
missingfaktor Avatar answered Oct 29 '22 00:10

missingfaktor