Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better java syntax: if (isSomething() == false) { or if (!isSomething()) { [closed]

If you look at

if (!x) {
if (x == false) {

It looks like !x is better, but

if (!isSomething()) {
if (isSomething() == false) {

you can easily oversee the !

What to do? Is there a recommendation?

like image 366
Igor Mukhin Avatar asked Dec 16 '10 13:12

Igor Mukhin


People also ask

What does if false mean Java?

if (false) means peace of code which is never executed. If some of your code is unused you should remove it.

Can we use or in Java?

So the statement " a equals 5 or a equals 7" is true. The || operator can only be used, in Java, where a boolean (true or false) expression is expected, such as in an if statement like the above. So pretty much in an if or a conditional operator (that ?...: thing, sometimes called the ternary operator).


3 Answers

The hidden third option is to name your variables and methods properly.

Instead of

if (!isDisabled()) {
    ...
}

use

if (isEnabled()) {
    ...
}

or if you want to check for the negative:

boolean disabled = !isEnabled();
if (disabled) {
    ...
}

or add both methods:

boolean isDisabled() {
    return !isEnabled();
}

Edit: I found this question: Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

like image 83
Christoffer Hammarström Avatar answered Nov 15 '22 06:11

Christoffer Hammarström


I would stick with the notation if (!isSomething()) {. If you or others find it hard to read you can always add a little whitespace around the '!' in order to make it stand out:

if ( ! isSomething()) { or if ( !isSomething()) {

Furthermore, multiple conditional statements can become overwhelming with the following notation

if (isSomething() == false && isSomethingElse() == false && ..),

whereas its alternative is short and succinct. After a while it becomes natural to read the '!' along with the statements as "not isSomething() and not isSomethingElse()".

like image 45
McStretch Avatar answered Nov 15 '22 07:11

McStretch


I don't think there is any recommendation that everyone would follow.

Do it your way, personnally, I would choose the if (!isSomething()) style :)

Especially since I already chose the if (!x) style.

like image 22
LaGrandMere Avatar answered Nov 15 '22 05:11

LaGrandMere