Is it bad to explicitly compare against boolean co

2019-01-03 02:45发布

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.

14条回答
趁早两清
2楼-- · 2019-01-03 03:05

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.

查看更多
时光不老,我们不散
3楼-- · 2019-01-03 03:06

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.

查看更多
甜甜的少女心
4楼-- · 2019-01-03 03:10

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

查看更多
\"骚年 ilove
5楼-- · 2019-01-03 03:10

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.

查看更多
爷的心禁止访问
6楼-- · 2019-01-03 03:10

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;
            }
        }
    }
}
查看更多
劳资没心,怎么记你
7楼-- · 2019-01-03 03:11

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.

查看更多
登录 后发表回答