开发者

Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

Is it bad to write:

if (b == false) //...

while (b != true) //...

Is it always better to instead write:

if (!b) //...

while (!b) //...

Presumably there is no difference in performance (or is there?), but how do you weigh the explicitness, the conciseness, the clarity, the readability, etc between the two?

Update

To limit the subjectivity, I'd also appreciate any quotes from authoritative coding style guidelines over which is always 开发者_运维百科preferable or which to use when.


Note: the variable name b is just used as an example, ala foo and bar.


It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example if (userIsAllowedToLogin) over if (b) or even worse if (flag).

As to the performance concern, the compiler optimizes it away at any way.

As to the authoritative sources, I can't find something explicitly in the Java Code Conventions as originally written by Sun, but at least Checkstyle has a SimplifyBooleanExpression module which would warn about that.


You should not use the first style. I have seen people use:

  • if ( b == true )
  • if ( b == false )

I personally find it hard to read but it is passable. However, a big problem I have with that style is that it leads to the incredibly counter-intuitive examples you showed:

  • if ( b != true )
  • if ( b != false )

That takes more effort on the part of the reader to determine the authors intent. Personally, I find including an explicit comparison to true or false to be redundant and thus harder to read, but that's me.


This is strongly a matter of taste.

Personally I've found that if (!a) { is a lot less readable (EDIT: to me) than if (a == false) { and hence more error prone when maintaining the code later, and I've converted to use the latter form.

Basically I dislike the choice of symbols for logic operations instead of words (C versus Pascal), because to me a = 10 and not b = 20 reads easier than a == 10 && !(b==20), but that is the way it is in Java.

Anybody who puts the "== false" approach down in favour of "!" clearly never had stared at code for too long and missed that exclamation mark. Yes you can get code-blind.


The overriding reason why you shouldn't use the first style is because both of these are valid:

if (b = false) //...

while (b = true) //...

That is, if you accidentally leave out one character, you create an assignment instead of a comparison. An assignment expression evaluates to the value that was assigned, so the first statement above assigns the value false to b and evaluates to false. The second assigns true to b, so it always evaluates to true, no matter what you do with b inside the loop.


I've never seen the former except in code written by beginners; it's always the latter, and I don't think anyone is really confused by it. On the other hand, I think

int x;
...
if(x) //...

vs

if(x != 0) //...

is much more debatable, and in that case I do prefer the second


IMHO, I think if you just make the bool variable names prepended with "Is", it will be self evident and more meaningful and then, you can remove the explicit comparison with true or false

Example:

isEdited  // use IsEdited in case of property names
isAuthorized // use IsAuthorized in case of property names

etc


I prefer the first, because it's clearer. The machine can read either equally well, but I try to write code for other people to read, not just the machine.


In my opinion it is simply annoying. Not something I would cause a ruckus over though.


The normal guideline is to never test against boolean. Some argue that the additional verbosity adds to clarity. The added code may help some people, but every reader will need to read more code.

This morning, I have lost 1/2 hour to find a bug. The code was

    if ( !strcmp(runway_in_use,"CLOSED") == IPAS_FALSE)
      printf(" ACTIVE    FALSE \n");   else
      printf(" ACTIVE    TRUE \n");

If it was coded with normal convention, I would have seen a lot faster that it was wrong:

    if (strcmp(runway_in_use, "CLOSED"))
      printf(" ACTIVE    FALSE \n");   else
      printf(" ACTIVE    TRUE \n");


I prefer the long approach, but I compare using == instead of != 99% of time.

I know this question is about Java, but I often switch between languages, and in C#, for instance, comparing with (for isntance) == false can help when dealing with nullable bool types. So I got this habbit of comparing with true or false but using the == operator.

I do these:

if(isSomething == false) or if(isSomething == true)

but I hate these:

if(isSomething != false) or if(isSomething != true)

for obvious readability reasons!

As long as you keep your code readable, it will not matter.


Personally, I would refactor the code so I am not using a negative test. for example.

if (b == false) {
   // false
} else {
   // true
}

or

boolean b = false;
while(b == false) {
  if (condition)
      b = true;
}

IMHO, In 90% of cases, code can be refactored so the negative test is not required.


This is my first answer on StackOverflow so be nice... Recently while refactoring I noticed that 2 blocks of code had almost the exact same code but one used had

for (Alert alert : alerts) {
    Long currentId = alert.getUserId();

    if (vipList.contains(currentId)) {
        customersToNotify.add(alert);

        if (customersToNotify.size() == maxAlerts) {
            break;
        }
    }
}

and the other had

for (Alert alert : alerts) {
    Long currentId = alert.getUserId();

    if (!vipList.contains(currentId)) {
        customersToNotify.add(alert);

        if (customersToNotify.size() == maxAlerts) {
            break;
        }
    }
}

so in this case it made sense to create a method which worked for both conditions like this using boolean == condition to flip the meaning

private void appendCustomersToNotify(List<Alert> alerts
        List<Alert> customersToNotify, List<Long> vipList, boolean vip){

    for (Alert alert : alerts) {
        Long currentId = alertItem.getUserId();

        if (vip == vipList.contains(currentId)) {
            customersToNotify.add(alertItem);

            if (customersToNotify.size() == maxAlerts) {
                break;
            }
        }
    }
}


I would say it is bad.

while (!b) {
    // do something 
}

reads much better than

while (b != true) {
    // do something 
}


One of the reasons the first one (b==false) is frowned upon is that beginners often do not realize that the second alternative (!b) is possible at all. So using the first form may point at a misconception with boolean expressions and boolean variables. This way, using the second form has become some kind of a sjiboleth: when someone writes this, he/she probably understands what's going on.

I believe that this has caused the difference to be considered more important than it really is.


While both are valid, to me the first feels like a type error.

To me b == false looks as wrong as (i == 0) == false. It is like: huh?

Booleans are not an enum with 2 possible values. You don't compare them. Boolean are predicates and represent some truth. They have specific operators like &, |, ^, !.

To reverse the truth of an expression use the operator '!', pronounch it as "not".

With proper naming, it becomes natural: !isEmpty reads "not is empty", quite readable to me.
While isEmpty == false reads something like "it is false that it is empty", which I need more time to process.


I won't go into all of the details at length because many people have already answered correctly.

Functionality-wise, it gives the same result.

As far as styling goes, it's a matter of preference, but I do believe !condition to be more readable.

For the performance argument, I have seen many say that it makes no difference, but they have nothing to justify their claims. Let's go just a bit deeper into that one. So what happens when you compare them?

First, logically:

if(condition == false)

In this case, if is comparing its desired value to execute with the value between the parentheses, which has to be computed.

if(!condition)

In this case, if is directly compared to the opposite(NOT) of the condition. So instead of 2 comparisons, it is one comparison and 1 NOT operation, which is faster.

I wouldn't just say this without having tested it of course. Here is a quick screenshot of the test I did. !condition is nearly twice as fast over 10 million iterations. https://imgur.com/a/jrPVKMw

EDIT: I tested this in C#, compiled with visual studio. Some compilers may be smarter and optimize it properly, which would make the performance the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜