81

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.

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • 9
    I personally like the comparison against a literal for readability reasons - at high resolutions (and increasing age), the exclamation tends to be "absorbed" by many letters. – Uri Apr 18 '10 at 06:06
  • @Uri: a good enough IDE should be able to make `!` stand out as much as you'd like if that's truly a problem. – polygenelubricants Apr 18 '10 at 07:17
  • 57
    `if (b == false == true == true) {` You want to be sure. – Tom Hawtin - tackline Apr 18 '10 at 09:00
  • It comes down to whether it's faster to perform a logical negation on a boolean or compare one boolean value to another boolean constant, before the final resulting boolean is checked by the if statement. I'd imagine that the negation would be faster, because it could be issued directly on a memory address and handled by a hardware circuit that doesn't need to read or write or compare a thing. Just one way of thinking about it. – Triynko Mar 10 '11 at 23:33
  • @Uri, why not simply separate the ! with a space? e.g.: if ( ! x ) – Nacht Mar 06 '12 at 20:36
  • 2
    @Triynko, usually this kind of thing is optimized out, so that doesnt matter, and if it isnt, it's not going to cause a noticable difference. – Nacht Mar 06 '12 at 20:41
  • 10
    The truth is that people only use "== true" and the like because they haven't actually thought about it, and when it's pointed out to them they claim "readability" to save face. – Nacht Apr 05 '12 at 02:51

16 Answers16

73

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 9
    +1 for recommending long, descriptive variable names. However, I think "if (userIsAllowedToLogin())" is preferable to "if (userIsAllowedToLogin()==true)" as the former is more readable. – Michael Aaron Safyan Apr 18 '10 at 04:35
  • @Michael, did you forget a `!` ? – Thorbjørn Ravn Andersen Apr 18 '10 at 06:06
  • I'd prefer `if( canAuthenticate() )` or `if( isAuthorized() )`. I find `userIsAllowedToLogin` ambiguous. Does it mean that the user can view the login page (e.g., the IP address is not banned) or does it mean that the user has been authenticated (e.g., correct name and password)? – Dave Jarvis Apr 19 '10 at 16:04
  • 2
    @Dave: It was just a bit exaggerated example. As long as the variable name is self-explaining enough. – BalusC Apr 19 '10 at 16:32
  • 5
    @BalusC: I know; it's a pet peeve. Long method names -- like `isCurrentUserLoggedInAsRole` -- are sometimes a symptom of a larger problem: a misplaced method. (For example, the `User` class should know its assigned roles: `user.isAssigned( role )`.) – Dave Jarvis Apr 19 '10 at 16:54
51

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.

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
Thomas
  • 63,911
  • 12
  • 95
  • 141
37

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.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
  • 4
    I agree, I too prefer to use ==false compared to (!) from a readability point of view - when maintaining other peoples code, as you say, code blindness IS a thing and does happen. if (K) {} or if (!K) {} sometimes you can spend ages working out why something isn't working then spot the ! in the condition. – Harag Oct 16 '15 at 13:34
  • The best way to solve this is to have the boolean expression test for true instead of false, and order the if-then-blocks accordingly. This may look weird if the true block is empty though. – Thorbjørn Ravn Andersen Apr 12 '18 at 14:41
  • Since nobody has mentioned yet: C and C++ actually allow `not` as a synonym of `!` as part of the [alternative operator representations](https://en.cppreference.com/w/cpp/language/operator_alternative), it's just the case that nobody ever uses it for whatever reason. (In C++ they're built into the language, [in C the header `iso646.h` must be included](https://en.wikipedia.org/wiki/C_alternative_tokens?useskin=vector).) So if one's issue is with `!` being less readable than `not` then for C and C++ (at least) there is another alternative to using `== true` or `== false`. – Pharap May 16 '23 at 10:43
  • @Pharap then you run into maintainability issues. – Thorbjørn Ravn Andersen May 16 '23 at 13:44
  • @ThorbjørnRavnAndersen Alright, I'll bite. How does using `not` instead of `!` make the code less maintainable than using `== false`? – Pharap May 19 '23 at 22:10
27

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.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
  • 8
    I wouldn't say "overriding" reason. Unless you time travel to 15 years ago your compiler will warn about this typo. – John Kugelman Apr 18 '10 at 04:52
  • `while (b = false)` is valid Java syntax (if `b` is a `boolean`) and a compiler will not catch it. – mob Apr 18 '10 at 05:49
  • 1
    John probably meant your IDE. Note this is not valid in C#... jab! – Stephen Swensen Apr 18 '10 at 05:57
  • 1
    Yes, IDE's and style checkers will warn you about this kind of thing. I wouldn't be surprised if the command-line compiler can detect it as well, although it doesn't warn you by default. My point is that this isn't *just* a style choice. – Alan Moore Apr 18 '10 at 06:08
  • 1
    @John and @mobrule - Eclipse warns about this, but only if you set the "Parameter assignment" option true (it defaults to false). – CPerkins Apr 19 '10 at 11:33
  • 3
    @StephenSwensen it is valid in C#, but it will generate a warning. `Assignment in conditional expression is always constant; did you mean to use == instead of = ?` – user247702 Jun 15 '12 at 07:42
  • 3
    An easy way to prevent this is to instead compare the constant value (lhs) to the variable (rhs). So `while (true == loggedIn)`. This way it throws a compile-time error rather than runtime. – Adam Brinded Jan 14 '18 at 00:25
13

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

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • 5
    @Michael, Java doesn't implicitly convert int to boolean like in C++, but otherwise agree 100%; the former is sloppy newbie syntax, and the latter is preferred. – Michael Aaron Safyan Apr 18 '10 at 04:32
  • 2
    Well, now you know, thanks to this post, that some experienced programmers write "== false"--not just "beginners", and you can clearly read their reasons why, as given multiple times in the replies here. (Hmmm...was that a subconscious ad hominem? "I like this, and the only people I've ever seen who don't agree with my preference are merely 'beginners'.") – M.Bearden Dec 19 '14 at 17:19
  • 1
    @M.Bearden Seriously? All I was saying was that I, personally, have almost never seen experienced programmers directly compare with `true` or `false`, whereas when I was a TA in college I would see it all the time from novices who simply didn't realize it was redundant. That doesn't mean if you do that you're a bad person, it's just uncommon. You took quite a lot of offense to a random remark from five years ago that wasn't directed at anybody; write code however you like – Michael Mrozek Dec 19 '14 at 18:45
  • @MichaelMrozek. Yes, that was overly sensitive of me. My point is: Better to discuss issues like conciseness and readability, and realize that the differences in opinion are probably due to the different weights different people place on those. Here is another discussion on exact same topic that I hit while searching on this, that calls out those issues pretty well, and it again indicates that it's not "sloppy beginner-ness" to think one way or the other: http://stackoverflow.com/questions/13763386/what-is-the-preferred-coding-style-for-checking-if-something-is-false – M.Bearden Dec 19 '14 at 20:34
8

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

Mahesh Velaga
  • 21,633
  • 5
  • 37
  • 59
4

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.

Head Geek
  • 38,128
  • 22
  • 77
  • 87
2

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");
BOC
  • 1,109
  • 10
  • 20
  • I think there is a more significant readability issues in that code that the condition. Look at strcmp. Not exactly effortless IMO. – Preza8 Dec 23 '17 at 01:15
  • @Preza8 I don't disagree that `strcmp` is a terrible name, but C and C++ are stuck with it for historical reasons, and creating a more nicely named wrapper function would likely violate the [principle of least surprise](https://en.wikipedia.org/wiki/Principle_of_least_astonishment?useskin=vector), so it can't really be helped. (Assuming that this was C code, which seems likely.) – Pharap May 16 '23 at 10:52
2

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.

Joel
  • 7,401
  • 4
  • 52
  • 58
1

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

ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
1

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • but don't take it to far. believe it or not, I have already seen code like this: if (a) ; else doSomething(); – Axel May 30 '10 at 20:38
  • In which case I would prefer if (!a) doSomething(); But it likely you will find that you can change the code so that 'b' stores true instead of false and false instead of true and there is no need for a negation. IMHO it is fairly rare you need if (a) in one place *and* if (!a) in an unrelated block of code. – Peter Lawrey Jun 01 '10 at 12:24
1

I would say it is bad.

while (!b) {
    // do something 
}

reads much better than

while (b != true) {
    // do something 
}
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
1

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;
            }
        }
    }
}
lifesoordinary
  • 123
  • 2
  • 9
1

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

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 '!', pronounced 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.

Coding style guidelines in Java and other language generally discourage "== true/false" style.

Sonar
https://rules.sonarsource.com/java/RSPEC-1125

CheckStyle
https://checkstyle.sourceforge.io/config_coding.html#SimplifyBooleanExpression

TSLint
https://palantir.github.io/tslint/rules/no-boolean-literal-compare/

C#
https://www.c-sharpcorner.com/article/common-code-smell-mistakes-in-c-sharp-part-1/

C# queries
https://help.semmle.com/wiki/display/CSHARP/Unnecessarily+complex+Boolean+expression

But the following Codeshare blog entry shows cases in javascript where "b == true" can be useful. This might explain why people do it.
https://codeshare.co.uk/blog/please-tell-me-you-dont-write-if-true-equals-true/

Florian F
  • 1,300
  • 1
  • 12
  • 28
1

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://i.stack.imgur.com/EKUIz.jpg

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.

poipoi300
  • 11
  • 3
0

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.