105

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?

apaderno
  • 4,014
  • 8
  • 42
  • 53
JoelFan
  • 7,025
  • 4
  • 38
  • 53
  • 1
    What language is this? If it has a real boolean type, this works, although it is annoying. If it uses another type as a boolean (like an integer type), with an arbitrary value either for true or false, this can yield the wrong result. – David Thornley Oct 18 '10 at 20:21
  • 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 00: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 02: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 03:15
  • 1
    @waiwai933 I wouldn't trust a programmer that overly relies on PHP's automatic type conversions. It's inconsistent and arbitrary. – grahamparks Oct 19 '10 at 07:20
  • @Chris - yeah, it's only you :) To be honest, it is a big deal. Looking at a single statement by itself looks like it's nothing. But when you see the pattern spread all over your code (or in methods with high cyclomatic complexity and poor variable naming), oh boy, it hurts, and it is a big deal in terms of maintenance, refactoring, and most painful of all, bug finding. – luis.espinal Oct 19 '10 at 13:20
  • @ Mike Seymour - you are assuming SpashHit's colleage is actually capable of understanding that `someBool == true` is a boolean expression itself :) – luis.espinal Oct 19 '10 at 13:21
  • 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
  • 1
    The old CDC6000 PASCAL and PASCAL2 compilers used -0 for TRUE and +0 for FALSE. (The CDC6000 series were 1's complement machines, with two legal values for zero.) For integer comparison, -0 == +0, at the hardware level. This caused (the PASCAL equivalents of) if (bool_value) to work correctly, and if(bool_value == FALSE to fail when bool_value was TRUE. This bit LOTS of students, EVEN THOUGH THEY WERE WARNED IN CLASS ABOUT IT!!!, and taught them NOT TO DO THAT. (This is the advantage of being old and grey and wrinkled: we have LOTS of war stories to tell!) – John R. Strohm Oct 19 '10 at 18:33
  • Just delete it when you see them, and check in – AndreasN Oct 22 '10 at 20:25
  • 1
    It only really means something with === (3 equals) since that checks type as well as value, at least in most languages. – Scott Oct 31 '10 at 06:29
  • 1
    @GSto: depends a lot on the language, it might make an implicit cast to boo explicit. It's better than `var=!!expression;` – peterchen Nov 27 '10 at 19:51

47 Answers47

126

It's only redundant code, not life or death. However....

If it's happening a lot, it could be a problem with how someBool is being named. A good name can go a long way towards eliminating the need for the ==true

if(IsSomeCondition)

or

if(hasCondition)

or

if(somethingExists)

for example.

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
  • This rings most true to me. Its all about clarity and the art of naming, the original syntax is not that bad but this is the right path to better code. – TJB Oct 19 '10 at 03:41
  • 2
    Beat me to it! Without appropriate naming, the more succinct equivalency makes no sense at all. – Troy Hunt Oct 19 '10 at 03:42
  • 4
    I have had to used `someBool == true` for legacy code several times for clarity. But if I write from scratch I name the variable accordingly and use `if (isSomething)` – nimcap Oct 19 '10 at 06:38
  • I agree, Even though naming would solve this, assuming the name was SomeBool, it could mean anything and be of any type (an integer equal to the quantity of booleans in an array perhaps?). Booleans need some sort of existential verb, or they will always be hard to read on their own. – Morgan Herlocker Oct 19 '10 at 06:45
  • I agree, it is all about readability. If variables are named well, you don't need it. If the expression reads better with it I'd go for "== true", also it is consistent if you use "== false" instead of (the ugly) "if (!())". – Ronny Brendel Oct 19 '10 at 08:07
  • +1 for sure. is, has, exists, enabled (or any -ed ending) makes it read like natural language. – bogeymin Oct 19 '10 at 21:28
  • I agree, but sometimes I'd keep the different name and `== true`. A variable may have a boolean type without (in most contexts) intuitively representing a testable condition, so it may make some consistency sense to follow a compare-with-value pattern. It may be closely related to other variables with different types, so that it should share a naming pattern. In these kind of rare cases (maybe only one case, with both issues going together), the `== true` (and `== false` rather than `!`) may be the best option. I wouldn't worry about `if (previous_result == true)`, for example. –  Dec 06 '10 at 22:29
71

When I see someBool == true, I can't help but feel like the programmer hasn't internalized the idea of evaluation, which is a pretty fundamental deficiency.

However, my perspective is skewed because I spent several summers in college teaching programming to kids, who frequently wrote expressions like this because they genuinely hadn't mastered the mental exercise of evaluating an expression. Once they grokked the concept, the redundancy became obvious.

For an otherwise competent professional programmer, this is probably not the case. It's probably just a bad habit they developed in their early days of programming and never quite shook. But it would still scare me a bit if it was the first thing I saw someone do in an interview.

Tim Goodman
  • 2,644
  • 2
  • 28
  • 25
  • I wouldn't so quickly chalk this up to habit. I've heard some truly stunning things out of professional programmers' mouths. Usually followed shortly thereafter by one of the grokkers, "how did this *ever* work?" – dash-tom-bang Oct 18 '10 at 23:18
  • 12
    Agree wholeheartedly about evaluation. On occassion I've wondered, "Where does it stop?" if ((((x == true) == true) == true) != false) // and so on... – yawmark Oct 19 '10 at 03:52
  • 1
    Sometimes I would write `if (c == true) return true; else return false;`, but 99% of the time (the 1% is there since I can never be sure that I didn't miss some) I'll immediately notice and replace the whole thing with `return c`. I'll expect most competent programmers should do something similar if they developed the habit early on their career. What I wouldn't expect is a wtf response. – Lie Ryan Oct 19 '10 at 11:54
  • 1
    Oh boy, the art of thinking. I *literally* came across this in our codebase last week. `if (!someCondition) { someCondition = false; }` I've seen some (er, many) redundancies as well as some impossibilities in our code, but this one was so simple yet so aggravating to think that somebody actually wrote it. Multiple times, even. – Anthony Pegram Oct 20 '10 at 19:26
  • 1
    Just note that I have seen a few cases of `if(x) x=true;` which were NOT redundant, but rather the equivalent of `x=!!x;` (normalizing x to 0/1) – jkerian Oct 20 '10 at 20:02
58

That drives me crazy too, but I'd say mention the redundancy to them in a constructive way and then drop it even if they don't concur.

Alternatively you could try this approach:
You: Can you start using the following code convention for evaluating Booleans?

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

Them: Why would we do that? The second half of that statement is redundant, it would always evaluate to true.

You: By George, you are right. Silly me. Let's just go with a version without all the redundancy then. How about?

if (someBool) {}
Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
JohnFx
  • 19,052
  • 8
  • 65
  • 112
  • 6
    Yeah, agreed. It's silly, but you gotta pick your fights, and this code is indeed doing what your colleague things it will. Mention it in a non-"What the hell is WRONG with you?!" kind of way, then drop it. Though if they start pulling crap like "if (someBool != true)" or "if (!someBool == true)" or other such convolutions, that might be a fight worth picking.... – BlairHippo Oct 18 '10 at 20:11
  • 3
    How is (someBool == false) any worse than if (someBool == true)? – FinnNk Oct 18 '10 at 20:16
  • 5
    `true=true` does not compile, you cannot *assign* to `true` ;-) – fredoverflow Oct 18 '10 at 21:41
  • 1
    I've gotten used to `if(somebool == false)` or `!=`, but always against false and not true. I find it redundant, but since the coding standard insists that `if()` looks like a function call the whitespace between the parens helps me read it. On my own, a bool is a bool, but `if (somePointer)` doesn't fly; I prefer `if (somePointer != NULL)` since a pointer is not a bool. – dash-tom-bang Oct 18 '10 at 23:05
  • 5
    It's about readability, not illogic or (micro)-redundancy – Ronny Brendel Oct 19 '10 at 08:14
  • he he nice script for a Play by the way – GoodSp33d Oct 19 '10 at 08:26
  • I like this. Ask why not this: `if ( (expr == 0) == true )`? Or why not this: `if ( (expr+0 == 0) == true )`? How much redundancy is enough? – S.Lott Jan 18 '11 at 21:31
  • Shouldn't this be `if (someBool==true)==(true==true) {}`? – Paŭlo Ebermann Sep 18 '11 at 01:01
44

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

apaderno
  • 4,014
  • 8
  • 42
  • 53
GrandmasterB
  • 37,990
  • 7
  • 78
  • 131
  • 5
    Well put, its good to strive for perfection but surely there are bigger fish to fry – TJB Oct 19 '10 at 03:43
  • 3
    I think you say this about every problem that merits discussion. – Dave Van den Eynde Oct 19 '10 at 06: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
42

You should definitely stop this bad habit. Gently...

It's easy to forget to write the double equal signs, turning the code into:

if (someBool = true)

In C# for example this will only produce a warning, not an error. So unless you treat warnings as errors the code will run, set the variable to true and always enter the condition.

Guffa
  • 2,990
  • 20
  • 16
  • 6
    This isn't a relevant argument. If you're working in a language like that, you could just move the true to the other side. The question is about whether or not to include the true at all. – Cam Oct 18 '10 at 20:18
  • 8
    @Cam: Missing the point are you. Backwards logic I not am suggesting. – Guffa Oct 18 '10 at 20:36
  • 15
    @Cam - He is giving a real world example of when this can be a problem. I would say this is quite relevant. – ChaosPandion Oct 18 '10 at 20:39
  • This may be a good or bad argument depending on the level of automated tests that are written – Joe Phillips Oct 19 '10 at 00:40
  • Yoda conditions this reminds me of. `if(true = someBool) {}` – Benbob Oct 19 '10 at 04:19
  • Switch to Java, it insists on "someBool = true" not being a boolean... –  Oct 19 '10 at 08:09
  • 1
    @Guffa Cam is very right. This is not a reason to stop using == (anyType) in if blocks. – Ronny Brendel Oct 19 '10 at 08:10
  • 1
    @Ronny: You are missing the point too. I have never said that you shouldn't use the `==` operator in `if` statements, only that you shouldn't use it for booleans. – Guffa Oct 19 '10 at 09:43
  • @Guffa but this can happen with any type. Solving it for bools, doesn't solve anything. – Ronny Brendel Oct 19 '10 at 09:53
  • 2
    @Ronny: No, it can't happen with any type (unless the language actually allows any type as a condition). The statement `if (answer = 42) {}` simply doesn't compile because the expression is not a bool. – Guffa Oct 19 '10 at 14:08
  • 1
    ugh, you're right. Not any. But ints do work e.g. Mh, so my argument isn't as strong as I thought. – Ronny Brendel Oct 19 '10 at 14:36
  • I was under the impression that C# wouldn't compile that statement because 99% of the time (statistic generated from the reliable source known as "out of thin air"), no one really intends to assign a value in an if statement. – Matt DiTrolio Oct 19 '10 at 16:23
  • The solution http://stackoverflow.com/questions/2349378/2430307#2430307 – John K Oct 20 '10 at 02:50
  • 1
    @John K: That's the third time someone suggests that in these comments, and it's still not the solution. – Guffa Oct 20 '10 at 09:25
  • @Guffa, yes but the provided link is my original question which I'm plugging, and a comment is not a solution otherwise it would have been provided as an answer. We are simply engaging in commenting, nothing more, nothing less. – John K Oct 20 '10 at 14:26
  • 1
    @John K: Ok, so you are not commenting because you want to contribute, but just because you want to spam the site with irrelevant links? – Guffa Oct 20 '10 at 16:27
  • @Guffa: I don't consider cross-linking between SO programming questions as spam. Put another way, if I look at what constitutes spam this is not it. However we can agree to disagree on this one. I have no need to move your opinion. – John K Oct 20 '10 at 16:53
  • @John K: It's completely irrelevant if the link is internal to SO or not. There is no point in repeating what's been said in multiple comments before. – Guffa Oct 21 '10 at 18:44
  • @Guffa: That's the second time you posted the same sentiment in a comment. Now would you quit comment spamming yourself and get back on topic. ;) – John K Oct 21 '10 at 19:02
  • 1
    FYI- Sorry everybody about @Guffa and myself engaging in combative chatter here. We should really be over on meta discussing this item rather than cluttering up the flow with off topic discussion. Learn from our mistake. :) – John K Oct 21 '10 at 19:19
  • if (answer = 42) DOES pass in Ruby. I have been bitten by this many times. – philosodad Nov 27 '10 at 20:50
21

I agree with you, but I'm going to play devil's advocate here:


Depending on the language and the variable's name, x==true is appropriate:

Consider the following situation in a language with static typing and type coercion for integral types:

if (actionsAllowed){
    //do actions, since they are allowed
    //...
}

Someone reading this section of the code might not realize immediately that actionsAllowed is a boolean variable - it could also be an integer, representing the number of allowed actions. So by adding == true, it becomes clear that x is a boolean, and not an integer being coerced to a boolean:

if (actionsAllowed == true){
    //do actions, since they are allowed
    //...
}
Cam
  • 526
  • 2
  • 13
15

What about nullable bools?

bool? MyFlag = null;

if (MyFlag == true)
    ;  

if (MyFlag)  // error, doesn't compile!
    ; 
Steve Wellens
  • 241
  • 1
  • 4
11

Typically, you don't want to make a big deal out of coding conventions unless said convention is somehow impeding the project in a significant way. I've seen many a heated argument escalate over things as small as code regions and leading underscores.

That being said, I see no issue with adding == true to a conditional statement. As a matter of fact, I am in the habit of using == false as opposed to a leading exclamation point when testing for negative conditions. I think it's more readable.

If there is an established convention, I say follow it unless there is reason to change. However, it's not really worth raising a big stink about.

Casey
  • 527
  • 2
  • 6
  • 1
    Depending on your language, someValue might not necessarily be the equivalent of true even if it evaluates to true. For instance, `(9 == True)` evaluates to false in Python and I would imagine similar in C++. – dash-tom-bang Oct 18 '10 at 23:06
  • code regions and leading underscores make me want to punch people in the face. – MGOwen Oct 19 '10 at 03:42
10

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.

Scott Fletcher
  • 161
  • 1
  • 1
  • 5
  • 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 08:18
10

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

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

Instead of:

 otherBool = !someBool
  • That's funny, I had to maintain a system that had those littered all over. It drove me insane. – Tjaart Oct 20 '10 at 09:15
8

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.

  • 3
    C++ actually *has* the `not` operator, and so does C (once you include the standard header ``). 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 07:28
  • 1
    I do Java. `not` is not an option. –  Oct 21 '10 at 08:13
6

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.

AShelly
  • 5,793
  • 31
  • 51
  • Actually, in languages where the assignment operator returns a value ... like C++ ... `if (b == true) {` is not just redundant. It is also a bit risky, because you might accidentally assigned `true` to `b`. – Stephen C Oct 19 '10 at 08:34
  • 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
  • @DavidThornley, turn on warnings in your compiler. Treating warnings as errors is better defensive programming technique rather than avoiding `==`. – Abyx Dec 08 '11 at 16:12
4

I prefer

if (bVal)

or

if (!bVal)

too, but I'm afraid that bringing it up would piss people off, so my advice is to forget it. Sorry!

grokus
  • 7,536
  • 4
  • 31
  • 46
  • 4
    For the love of all that is holy, as long as it's *not* `if (!bNotVal)` or `if (bNotVal)` even in the first place. Ugh negatives in names makes everything harder to read. – dash-tom-bang Oct 18 '10 at 23:48
  • 2
    I knew a dev who would bool isNotConnected; if (isNotConnected==true) ... yuck – johnc Oct 19 '10 at 02:04
4

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.

Display Name
  • 769
  • 4
  • 13
4

You think that's bad? How about:

if(someCondition) {
  return true;
} else {
  return false;
}
3

How about

if (x == "true")

WHY IS THAT A STRING?!

atfergs
  • 171
  • 3
  • I'm working on some legacy php code right and occasionally I find something like `if(preg_match('/title/', implode($_POST))){`. PHP, enough said, I need to find a better job. – Benbob Oct 19 '10 at 05:23
  • 4
    yea, I also see if (x == "1"), but that's usually do to poor db design. – atfergs Oct 19 '10 at 12:53
  • I've used similar constructs when `x` came from user input (configuration file or web service, for example). However, I usually allow other truish values, so it ends up more like `if x.lower().strip() in ["true", "yes", "on", "1"]` – eswald Oct 19 '10 at 17:17
3

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.

Ronny Brendel
  • 201
  • 1
  • 6
  • 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
  • "in many cases". Yes, you are right. Renaming is fine, too. With "if (QWidget::acceptDrops() == true)" you don't have the possibility to rename. perhaps it would be good to name it doesAcceptDrops() ... It's too much of a hassle (and it's impossible to be consistent using that omission-rule in any API), so being consistent with other "== whatever"-ifs, I strongly suggest not omitting it, so it doesn't "look" different, thus looks consistent. – Ronny Brendel Oct 19 '10 at 13:34
2

Generally will omit the '== true', but it's hardly worth even a minute discussing it unless you have it included in your team's coding standards.

FinnNk
  • 5,799
  • 3
  • 28
  • 32
2

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.

statichippo
  • 111
  • 1
  • `bool b;` only initializes to false when `b` is a field. You must initialize local variables explicitly. – Matthew Flaschen Oct 19 '10 at 05:55
  • +1 agreed. Its the same issue with other (scripting) languages as well. You must be explicit if you want to test for boolean `true` or just "true". For instance ie any non-empty string is considered `== true` but not `=== true` in some languages. – Martin Wickman Oct 29 '10 at 07:22
2

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

Matt Sherman
  • 131
  • 1
  • 5
2

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)
{...}
2

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 :)

cdkMoose
  • 1,775
  • 9
  • 12
2

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.

Job
  • 6,459
  • 3
  • 32
  • 54
  • The first problem stems from a false premise IMO by using awful variable names. Suppose x,y,z were named `notExceptButHasX`, `exceptNotButIsntY`, `doNotUnlessIsExceptZ`? How does that make for readability in your problem? If x,y,z were named something like "isEnabled", "isEffective", "hasProperty", then your statement becomes `isEnabled || isEffective || hasProperty` which is far more readable than comparing to `true` or `false`. – Thomas Mar 20 '11 at 02:46
1

Such coding would have rubbed me the wrong way before too. Although your example identifier is named "someBool", using that coding style inadvertently on a variable which wasn't guaranteed to be a boolean could have unintended behavior. If the value of "someBool" isn't exactly "true" or "false", the result will be false.

I encountered a very subtle bug this past year caused by such a coding style which was difficult to identify because one's eyes gloss over such constructs. You'd think, "How could it be wrong?" The same holds true for such well-understood expressions as "(var)" or "(!var)", that you read or code them without verifying their behavior.

So I've introduced a couple of coding standards to reduce the existence of such bugs in the codebase and the likelihood that such subtle bugs will accidentally creep in sometime in the future.

  1. All expressions must be parenthesized per their intent.
  2. All boolean tests must be expressed in the negative, like "suchBool != false".

By cleaning up code not conforming to the new style, I've identified and corrected a few more instances of such subtle bugs.

Huperniketes
  • 2,205
  • 14
  • 17
  • 1
    Having some someBool able to be something other than TRUE/FALSE is bad coding practice. – AttackingHobo Oct 19 '10 at 00:20
  • @AttackingHobo, that's one of the pitfalls of not having boolean types in a language and/or not using a class to provide the exact behavior wanted. – Huperniketes Oct 19 '10 at 11:36
1

Had to use this all the time in ActionScript 2 (admittedly now a dead language), because:

var something:Boolean = org.black.box.unknown.ThisMightNotExistYet();

// this is slightly ambiguous
if(something)
{
}

// because if you allow undefined you might actually mean
if(false != something)
{
}

// which can mean something different than
if(true == something)
{
}

// and comparing against what you actually MEAN is less script than
if(undefined != value && value)
{
}

So it was almost always best to be specific.

bburbank
  • 11
  • 1
1

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.

Tomas Narros
  • 221
  • 2
  • 9
1

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!

ingh.am
  • 101
  • 3
0

I'd say consistency is king in a codebase. So you should use the style, that is mostly used in your organization. Try to make your preferred style part of official company coding guidelines. If it's already in the guidelines, just follow it.

(That being said, it would also really annoy me - but probably not enough to make a big deal out of it).

driis
  • 676
  • 5
  • 8
0

I prefer not placing the extra == true, but sometimes I accidentally include it and don't notice it. The person may not have noticed and accidentally placed them. I reread my code and sometimes notice that I placed the extra == true so I remove that == true. I sometimes don't notice it and would happily welcome someone telling me I placed it redundantly.

sange
  • 892
  • 6
  • 9
0

how about:

int j = 1;
for (int i=1; i>=j; i++) ...

Yep, I've seen it.

Dave
  • 427
  • 3
  • 7
0

It's a code smell for a novice developer. They have yet to master/internalize the boolean condition and must explicitly evaluate to the true or false condition.

Chuck Conway
  • 700
  • 1
  • 9
  • 14
0

In JavaScript, I prefer if(bool) when I have sufficient documentation explaining what the method expects... but when evaluation of true can mean the variable exists, equals the number 1 or the boolean true, it's tougher.

Strongly typing in JS also means less flexibility. Tough call. Strongly typed languages, lay down the hammer. Otherwise, ask why he does it?

Actually, there's your answer: ask him why. Then correct him.

0

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?

Rush Frisby
  • 109
  • 4
0

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

David Plumpton
  • 171
  • 3
  • 4
0

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.. :)

0

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.

tia
  • 965
  • 5
  • 9
0

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. ;-)

Daniel C. Sobral
  • 3,541
  • 1
  • 24
  • 21
0

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.

0

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) {
    ...
}
gablin
  • 17,377
  • 22
  • 89
  • 138
0

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.

ElGringoGrande
  • 2,913
  • 22
  • 20
0

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.)

tghw
  • 101
  • 2
0

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

0

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").

o. nate
  • 271
  • 2
  • 3
0

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.

  • I had this habit until I got yelled at by fellow co-workers for wasting time and mutilating their code. If you think about it, both kind of suck. – Job Nov 27 '10 at 19:10
0

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.

Havoc P
  • 918
  • 6
  • 11
0

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)

Poma
  • 101
  • 1
-1

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.

Matteo Mosca
  • 568
  • 3
  • 14