A comment on this question: Calling A Method that returns a boolean value inside a conditional statement says that you should use !boolean instead of boolean == false when testing conditions. Why? To me boolean == false is much more natural in English and is more explicit. I apologise if this is just a matter of style, but I was wondering if there was some other reason for this preference of !boolean?

It's like doing boolean == true: it doesn't make sense. Expressions inside if statements are just that: expressions. If something already evaluates to a boolean expression, why would you add a check to force it to evaluate to that?
–
MaxpmFeb 25 '12 at 20:43

17 Answers
17

When I see a line like if (!lateForMeeting()), I read that as "If not late for meeting", which is quite straight-forward to understand, as opposed to if (lateForMeeting() == false) which I'd read as "If the fact that I'm late for meeting is false".

They're identical in meaning, but the former is closer to how the equivalent English sentence would be constructed.

== false is NOT redundant, just more verbose than !. OTOH, == true is redundant.
–
dan04Feb 25 '12 at 23:44

4

@dan04 You're right. However, in the sense I meant it, it remains a bad idea. Consider (exp1 != exp2) vs ((exp1 == exp2) == false). Admittedly, these are contrived scenarios, but still you should almost never write explicit comparisons to true or false. Just as you should use operator !=, so you should use !.
–
Andres F.Feb 26 '12 at 4:56

21

@dan04: It is redundant when the language already offers !.
–
DeadMGFeb 26 '12 at 7:19

4

@dan04: Any time you write bool_expression == bool_literal, the == ... is redundant. Whether you're testing for true or false is irrelevant. It's just a change in the order of the consequent/alternative blocks. Andres' examples illustrate this point perfectly. Most modern compilers will optimize away the redundancy, but it's still redundant.
–
Lèse majestéFeb 27 '12 at 10:40

In C and some similar languages, comparing boolean expressions for equality to false or true is a dangerous habit.

In C any scalar expression (numeric or pointer) can be used in a boolean context, for example as the condition of an if statement. The C rule is that if (cond) is equivalent to if (cond != 0) -- i.e., zero is false, and any non-zero value is true. If cond is of pointer type, 0 is treated as a null pointer constant; if (ptr) means if (ptr != NULL).

This means that

if (cond)

and

if (cond == true)

do not mean the same thing. The first is true if cond is non-zero; the second is true only if it's equal to true, which in C (if you have #include <stdbool.h>) is simply 1.

For example, the isdigit() function declared in <ctype.h> returns an int value, 0 if the argument is a digit, non-zero if it isn't. It can return 42 to indicate that the condition is true. Comparing 42 == true will fail.

It happens that 0 is the only value considered to be false, so comparison for equality to false will work; if (!cond) and if (cond == false) do the same thing. But if you're going to take advantage of that, you have to remember that comparing to false is ok, and comparing to true is not. Worse yet, comparing to true will work most of the time (for example, the equality and relational operators always yield either 0 or 1). This means that any bugs you introduce by using this still could be difficult to track down. (Don't worry, they'll show up as soon as you demo the code to an important client.)

C++ has slightly different rules; for example, its bool type is a bit more tightly integrated into the language, and if (cond) converts cond to type bool. But the effect is (mostly) the same.

Some other languages have what one might call better behaved booleans, such that cond == true and cond == false (or whatever the syntax happens to be) is safe. Even so, every language I've seen has a not or ! operator; it's there, so you might as well use it. Using cond == false rather than !cond or not cond does not, in my opinion, improve readability. (It's true that the ! character can be difficult to see at a glance; I sometimes add a space after the ! to avoid this.)

And often you can avoid the issue and improve clarity by rearranging the code slightly. For example, rather than:

if (!cond) {
do_this();
}
else {
do_that();
}

you might write:

if (cond) {
do_that();
}
else {
do_this();
}

That's not always better, but it doesn't hurt to look for opportunities where it is.

Summary: In C and C++, equality comparisons to true and false are dangerous, overly verbose, and poor style. In many other languages, such comparisons might not be dangerous, but they're still overly verbose and poor style.

@Dervall: assuming something that's simply not the case is also no good. There are a few corner cases in certain languages where equality comparison of booleans is not only safe but in fact appropriate, for instance in Haskell, which has a strong implicit-cast-free type system with bidirectional type inference, one might write (==True) . f to clarify that we want the -> Bool instantiation of the return-polymorphic function f. That's clearer than not . not . f and less awkward than (f :: a -> Bool).
–
leftaroundaboutFeb 27 '12 at 12:48

1

@leftaroundabout: That's fine if you know that pred(x) and pred(y) use the same value to denote truth, which is a safe assumption in some languages but not in others. In C, for example, you might write !!pred(x) == !!pred(y).
–
Keith ThompsonFeb 27 '12 at 18:36

For this very reason, a C++ project I worked on for some medical device software had a coding standard which mandated == false instead of ! for this same reason (to make it stand out). However there was no requirement to use == true, so any non-zero value still worked as it should.
–
tcrosleyFeb 26 '12 at 0:43

7

I've always found this argument unconvincing - there are other places in C/C++/C#/Java/etc where failing to see a single character has a similarly significant impact on the interpretation of the code; singling out "!" as the only bad one doesn't make sense to me.
–
BevanFeb 27 '12 at 8:18

3

@bevan Apparently you have not been bitten yet.
–
user1249Feb 27 '12 at 11:46

5

@ThorbjørnRavnAndersen Quite the reverse - I've been bitten often enough over the years that I've taught myself to read every character. I'm not the author of all (or even most) of the code I have to read day to day, so any personal convention as we're discussing here has minimal value: I need to correctly understand all the code I read, not just the stuff I've written.
–
BevanFeb 27 '12 at 18:00

If condition == false is indeed “much more natural in English” for you then I must assume that you are not a native speaker. Otherwise I cannot explain this, because nobody speaks like that:

If the sun is shining is false I stay at home.

Compare that to

If the sun is not shining I stay at home.

That said, I agree that the single, slender ! character is easily overlooked in code. For that reason, I prefer the keyword not when supported by the language. C++ for instance does allow this although many programmers are not aware of it.

For languages that require !, I put a space between operator and operand. This makes the negation much harder to overlook:

if (! condition) { … }

Notice that every programmer should translate this automatically, without second thought, to “not condition” in their head. Acquiring this kind of fluency in reading code idioms is among the first steps in becoming a good programmer.

When I see var == false I always wonder whether var is boolean or of a logic type with more than two values (with, for example, a maybe and an undefined as well as true and false, or something like the nine values of IEEE 1164).

!true means not true. !boolean means either not false or not true depending on the value of the boolean, which itself is logical inversion.
–
S.RobinsFeb 26 '12 at 0:53

1

@S.Robins I find stupid name of boolean for a boolean variable. Something like for example isVisible would be a better example. Then if (!isVisible) would mean if not visible - which is simpler to understand then if (isVisible==false), which is an inverse logic. Hope it's clearer now. Or, did I misunderstood your comment?
–
BЈовићFeb 26 '12 at 1:02

In (much) older compilers, I believe they would break (boolean == false) into 2 register assignments and a compare code in machine language. The first example would be broken into one assignment and a NOT operator. In terms of performance, the compare operation would take a number of clock cycles, depending on the size of the register being compared, compared to a bitwise invert (1 clock) and would be slower to execute.

That being said, I believe newer compilers do away with this, so it should be OK to go with either.

if value == true then there's no reason to check that it's not null. If the value == null it should never trigger the if statement in the first place, so if (value) should be sufficient.
–
zzzzBovFeb 25 '12 at 22:27

1

Booleans are objects (in java) and can therefore be null so just saying if (value) throws an exception. I'd appreciate it if people who downvote give a reason.
–
WuHoUnitedFeb 26 '12 at 4:16

3

I just happen to see this, didnt downvote. Boolean null is not good practice. Why? because boolean usually represents a state of something turned on on off. In most cases you would want to declare it false at the beginning and then change it along with behaviour. It is very uncommon to see boolean not being initialised.
–
AubergineFeb 26 '12 at 5:18

2

@WuHoUnited, even if the value was null, value == true would be sufficient.
–
zzzzBovFeb 27 '12 at 4:49

When you're testing the true condition, it makes sense to do just if (condition), especially when you apply the convention of naming boolean variables beginning with 'is': if (isOpen) is perfectly clear and using != false would be redundant.

For a C/C++/Java/etc. programmer, the meaning of the '!' operator is completely assimilated, to the point that we automatically have 'not' in our minds when we see it. So having if (!isOpen) is as clear as if (_NOT_ isOpen) for me. But you're not familiar enough, in C/C++ you could create a macro with #define _NOT_ !. But trust me, after a few years this is completely unnecessary.

Aside that, it's always preferable to test boolean values without comparing them with literals. For instance, it's dangerous to test if (x == true) because a boolean value is considered true if it's not zero, and the literal true has just one specific value, so x could be 'true' (i.e. nonzero) and still the comparision evaluate to false (because it contains 2 and the literal true is, say, 1.) Of course that doesn't apply to a comparision with false, but if you don't use it when testing for true, why use it when testing for false?

Based from my experience and the answers from my quesion that you have linked to.

Some people prefer to use if(condition), for the reason is that one it is shorter to write. and for me it actually makes sense, for example (! isValidated()) I read this as Not Validated. but for me it's all based on personal preferences, and it depends on the logical structure of isValidated() method, if it either returns true or false

For those folks having "if ! ..." compares faster to "if ..." then having to read through the entire condition (which could actually be pretty long, e.g. (thisThing = thatThing or something = the other thing) OR (thinga = thingb and thinga = thingd), etc.) just to find the ==false at the end.

Having the ! (I actually prefer a not when the language allows it) right up front gets the english 'not' for this condition in there sooner.

This issue also leads to consideration for using until in languages that support it, e.g. do 'common stuff' until thing completes. As others say, natural language expression is the goal. I like the "sun is shining" example above.

In Software-Engineering-I class we were taught to write code that is much clearer and much more readable. Few months later when you see your code and find !boolean you might not see ! when going through the code. But if you see boolean == false, it will make much more sense.

I can say that code bool working = true; if (working == false) is much more readable than if (!working)

. Both can be applied and both are correct. If I had to choose I would choose code that is more readable and easy to understand.

Your GPA is irrelevant to the discussion. Your point about readability has some validity but can easily be disarmed by putting a space between operator and operand: if (! condition) or by using the appropriate keyword in languages which support that: if (not condition).
–
Konrad RudolphFeb 26 '12 at 15:05

1

How does one develop a GPA for a single class?
–
Adam RobinsonFeb 27 '12 at 13:39

1

@A-Cube if you cannot cope with criticism from people who are more experienced with you, you are going to have a very hard time when you leave school and have to do this for a living.
–
user1249Feb 28 '12 at 15:35

1

@A-Cube you completely misunderstand my point. If your responses to people are generally along the lines of "why do I even bother" and "these guys will never listen" AND they are more experienced than you, you will generally end up having a hard time when you need to actually work with these people.
–
user1249Feb 28 '12 at 17:32