Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

There is a colleague of mine who constantly writes:

if (someBool == true)

It drives me up the wall! Should I make a big deal of it or just drop it?

share

locked by Yannis Rizos Mar 13 '12 at 20:42

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

12  
I prefer the explicit if (some_flag == true) but the implicit if (is_something) or if (has_something). Note the variable names. –  FredOverflow Oct 18 '10 at 21:44
69  
Remind your colleague that the type of someBool == true is also boolean, so by the same logic it should be if ((someBool == true) == true). –  Mike Seymour Oct 19 '10 at 0:00
2  
@GSto: I suppose you know it, but in PHP you can do that to "cast" anything to a bool and can be actually useful. –  zneak Oct 19 '10 at 2:21
2  
@zneak Or you could be clearer and use $var = (bool) some_expression. And in most cases, it won't even matter as PHP will do the necessary conversions dynamically. –  waiwai933 Oct 19 '10 at 3:15
4  
always check the constant first, if (true == someBool), in case you accidentally typed = instead of == [yes i'm kidding!] –  Steven A. Lowe Oct 19 '10 at 17:45
show 8 more comments

47 Answers

I think that, if something so trivial is your biggest problem with your co-workers, you should consider yourself pretty lucky.

share
5  
Well put, its good to strive for perfection but surely there are bigger fish to fry –  TJB Oct 19 '10 at 3:43
3  
I think you say this about every problem that merits discussion. –  Dave Van den Eynde Oct 19 '10 at 6:40
2  
It's potentially indicative of much larger problems. A small brown stain on the ceiling in your garage may not seem like a big deal, but it could mean you have a major water leak. –  Josh Oct 19 '10 at 12:52
add comment

One can develop this habit when do a lot of programming in WPF. It uses lots of bool? (nullable bool) variables to you have to write either if (someBool == true) or if (someBool ?? false)

share
add comment

The young know the rules, but the old know the exceptions ;)

In latest C#, if you are dealing with a null-able bool, then you have to:

bool? x = null;
bool? y = true;
bool? z = false;
if (x == true || y == true || z == true) {
    // That was the only way that is reasonably readable that I know of
    // to accomplish this expression.
}

If tristate is not a problem, then there usually should not be a reason to compare something to true/True. However, in Python and several other languages such as C/C++ you can perform an if on a non-bool expression. These languages have unique rules for interpreting integers, pointers, lists, etc. as either true or false. Sometime you do not want that. For example, in this Python snippet:

x = True
y = 'abcdef'
z1 = x and y
z2 = (x == True) and (y == True)

Here z should be True, but z2 should be False. Now, a Clojure language approaches this in yet another way - there and function does not necessarily evaluate to a bool, but the if can handle that.

Regardless of the language, any time you find yourself comparing something to True or False, it is probably worth commenting.

share
show 1 more comment

Consider yourself lucky, my half-monkey colleague writes

if (true)

I found it many times in his code. And that's not the worst thing I found. I found GOTOs. And we use C#. Now calm down and hold back your homicidal instincts.

share
add comment

One issue in C is that there's a tradition of using values other than 0 and 1 for booleans.

typedef enum { WHATEVER = 1 << 4 } MyFlags;
if (flags & WHATEVER) {
}

or even relying on -1 being true.

The problem is say you're writing an API:

struct foo { 
  unsigned int bar : 1;
};

void myapi_foo_set_bar(struct foo *foo, int bar) {
   foo->bar = bar;
}

Here if bar isn't canonicalized to 0 or 1 it won't fit in the bitfield and it breaks:

myapi_foo_set_bar(foo, flags & WHATEVER); /* broken */

You can find other ways non-canonical bools break as well, such as comparing them to TRUE or FALSE as in the question!

Anyway what I'm coming around to is that it often makes sense to canonicalize a bool:

foo->bar = bar != FALSE;

This is a C-specific weirdness, of course.

share
add comment

Funny because I always replace code like:

if(foo) {

With:

if(true == foo) {
if(false == foo) {

But I got this habit because most of the time the code I worked with didn't have clear variable names.

share
show 1 more comment

Remember you are working as part of a team, so you need to work these things out together. "Plays nice with others" is still an important personality trait even after elementary school :)

share
add comment

Hopefully, you are using a sensible language, like VB.NET with Option Strict On, which doesn't allow coercion of other types to Boolean inside an If statement. Then there's no need to ever add the "== true" (or "= True" in VB), since the coercion case can't happen. If you want to check for non-zero then write that explicitly (ie., "If x <> 0").

share
add comment

Coleague of mine called if a loop. I lived to tell about it.

share
add comment

I have a colleague who will have some code like this:

if(something == true)

And then, for some sort of test/debugging, he will wish to not call this block so he'll change it to:

if(something == true && false)

And then occasionally he'll change it to:

if(false)

The worst thing is, this type of debugging has rubbed off on me on occasion and is really bad for other developers to read!

share
add comment

Comparing booleans can actually cause major problems. I recently ran into some intern code that read:

if(foo == false && bar == 2) {...}

Now, this seems pretty straight-forward, right? Just simplify it down to:

if(!foo && bar == 2) {...}

Wrong. In this case, order of operations dictates that the && gets evaluated first, meaning that this really evaluates to:

if(foo == (false && bar == 2))

also known as

if(!foo)

That extra thing we were supposed to be checking for, bar == 2, is totally gone. That is why I will never, ever approve a code review that contains someBool == [true|false].

(You can see how the reverse statement, == true and ||, would also cause problems.)

share
add comment

Ah yes, but what if the variable is nullable? (bool?)

Some languages (C#) will require and cast or comparison with 'true'.

bool? isAccepted = true;

if((bool)isAccepted)
{...}

if(isAccepted == true)
{...}
share
add comment

It depends on the language, but it's usually a bad idea...

In C, never do this. It's too easy to find a situation where the value you are testing is not false (non-zero), but also not equal to the single value defined as "true".

In Ruby, do this only if you are absolutely certain that you want to fail on everything except Boolean true.

In C++ and other static languages with a bool type, it's redundant, and can lead to programming errors when you mis-type = instead of ==, or promotion errors as mentioned in the comments.

share
4  
It's not just redundant in C++, it's dangerous. If you write if (b == true), and b isn't a bool, the type conversions go the wrong way. A bool is an integral type that is normally promoted to an appropriate integral type with value 1. If you write, say, int b(2); if (b == true) then true becomes an int with value 1 for purposes of the comparison, rather than b being coerced into type bool, which would give the right result. –  David Thornley Oct 19 '10 at 18:02
show 2 more comments

You think that's bad? How about:

if(someCondition) {
  return true;
} else {
  return false;
}
share
2  
Boy how many times I have seen this. This makes a good case for a tool like ReSharper. –  Job Nov 27 '10 at 19:12
show 1 more comment

remind me of "boolean madness code", its like these

if(someBool == true)
   otherBool = false;
else
   otherBool = true

Instead of:

 otherBool = !someBool
share
show 1 more comment

This may get some of your nickers in a wad.

We have extension methods for .IsTrue and .IsFalse for the bool type.

So we write

if(someBool.IsTrue())

-or-

if(someBool.IsFalse())

Yep! And I love them. When reading code it just becomes more obvious to me.

share
add comment

You can try approaching your colleague with the following example:

if ((x == 3) == true) {
    ...
}

He should say that the == true is redundant and should be rewritten as

if (x == 3) {
    ...
}

since x == 3 is already a boolean expression.

Now present him the someBool == true example, but slightly rewritten:

if ((someBool) == true) {
    ...
}

Since someBool is already a boolean, by comparison with the previous example, it should now be clear that the == true is redundant in this example, too. Thus, it should be rewritten as:

if (someBool) {
    ...
}
share
add comment

I write if(var==false) because after writing var i dont feel like backtracking and write ! behind it. Also i like how ==false makes it look more clear.

However == true is just weird. I dont know if there is a point of making a big deal. I wouldnt unless he is pushing others to use it or to make it a coding standard.

share
add comment

I agree. It's a redundant construction, specially in strong typed languages.

To add another misuse of booleans, I have found this kind of construction a bunch of times in Javascript, (specially at some spaghetti-like monster functions, as in 100+ lines):

//create the variable, not initializing it
var flag;
//...
//assing a value to the var, by the example 
flag=$("mycheckbox").selected;
//...

//and at the moment of use it:
if(flag!=true) {
   //code to execute when the checkbox is unchecked
}

It seems, that due to the lack of an strict type definition in this language, some programmers prefer not have to be messing around with the false|undefined values.

share
add comment

Programming conventions are not necessarily "right" or "wrong". They exist to give the program a familiar structure to those reading it, so that possible mistakes will stand out more clearly -- it is difficult to "see" a problem if everything is slightly wrong-looking to you.

The important thing is that conventions be clearly defined and agreed upon by all participants (even if the agreement is like "I agree to use this convention while I work here" :), otherwise it does more harm than good.

Of course, the particularly case of comparing a boolean to true is plain wrong and to be avoided at all costs. ;-)

share
add comment

Yes, it's a big deal because the name of the boolean should tell that it is boolean. Says if you have this piece of code:

bool arrayIsEmpty = array.length == 0;
if (arrayIsEmpty) { ... }

It is already easy to read so you won't need == true, even for the person or programmer with less sense of evaluation.

share
add comment

Personally, I strongly dislike the way to say "not" in C based languages. That little exclamation mark is too easy to overlook.

Hence I write it out in full:

if (someCondition == false) {

After reading that for a while, I want symmetry too with

if (someCondition == true) {

So consider it an artifact of C using ! instead of not.

share
3  
C++ actually has the not operator, and so does C (once you include the standard header <iso646.h>). If you don’t want to (or can’t) use this header (or if you’re stuck with Java or C#), I suggest putting a space after the exclamation mark: if (! condition). This makes it somewhat more conspicuous. –  Konrad Rudolph Oct 21 '10 at 7:28
1  
I do Java. not is not an option. –  user1249 Oct 21 '10 at 8:13
add comment

I write code like that!

Here is why:

"if bla == true" reads like a sentence, where as "if bla" does not in many cases. It just sounds wrong, when READING actual code.

Also the compiler warns about assignments in if blocks, so there is really no danger in using == true. (confusing it with =)

Also do guys that don't write "== true", use that "!()" for "== false"? I find it really ugly. And if you use "== false", it is only very consistent to also use "== true", instead of having two distinct ways of verifying truth.

share
3  
You say "if bla" does not read like a sentence... that means your variable is not named properly... what's wrong with this: if (userHasRights) doSomething() –  JoelFan Oct 19 '10 at 13:13
show 1 more comment

Yes, This is a kind of programmers mind set. All the time they considers "if condition" has no existence with out an expression with symbols =,<,>... I've seen situations people really get struggle as like "function return"

if(RowsAffected > 0) { return true; } else { return false; }

Programmers need to watch their code from the real time angle.. :)

share
1  
That means their understanding of the language is lacking, which is a real problem –  JoelFan Oct 19 '10 at 13:14
add comment

you should tell him that he is doing it wrong.

its

if (true == someBool) {

}

if he ever forget one = he is in big trouble in his writing style.

share
add comment

Ack. I'm that guy. The shame, the shame. It's how I learned, and it's how I "auto-format" in my head. The only time I use Joel's prefered syntax is when the bool variable has a verb prefix like "is." I need the verb, be it "is," "can," "did," or else I need the == to provide the verb "equals." I might never break that habit, so I'll understand if you don't say 'hello' to me on the street.

share
7  
It is not a bad thing. Code that reads like real text is far better, than implicit foo. Keep that habit for the sake of readability. –  Ronny Brendel Oct 19 '10 at 8:18
add comment

Research shows that code with many redundancies correlates strongly with errors. Here's an interesting paper on the matter (PDF alert).

share
add comment

use it as an opportunity to teach him. he will respect you more if you do. wouldn't you want someone to do the same for you?

share
show 1 more comment

Actually, if it's nullable, testing for x == true would be necessary. :)

share
add comment

While I agree as a mainly C# developer, I can't say this is always the case. For instance, in Javascript, the === will perform type coalescence. So assuming var x = 3 then:

if(x) --> true

while

if (x === true) --> false

I guess that's different than == since even in JS I wouldn't use if(x == true) but just something to think about.

This sort of touches on another point though which has come up in my office:

bool b = false;

In C#, bool b; would be enough and would initalize b to false. However, it is more explicit to write the above line and anyway should be ripped out by the compiler during optimization.

So I guess my point is it's not always so obvious what is and isn't good practice and a lot of it boils down to preference as well as language features/quirks.

share
show 2 more comments

Not the answer you're looking for? Browse other questions tagged or ask your own question.