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?
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.
someBool == true
for legacy code several times for clarity. But if I write from scratch I name the variable accordingly and use if (isSomething)
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.
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.
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.
Commented
Oct 20, 2010 at 19:26
if(x) x=true;
which were NOT redundant, but rather the equivalent of x=!!x;
(normalizing x to 0/1)
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) {}
true=true
does not compile, you cannot assign to true
;-)
Commented
Oct 18, 2010 at 21:41
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.
Commented
Oct 18, 2010 at 23:05
I think that, if something so trivial is your biggest problem with your co-workers, you should consider yourself pretty lucky.
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.
if (answer = 42) {}
simply doesn't compile because the expression is not a bool.
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
//...
}
if (x) { ...
you are already asserting that x
is a boolean or is convertible to a boolean. What you call it is irrelevant.
Commented
Oct 19, 2010 at 10:28
What about nullable bools?
bool? MyFlag = null;
if (MyFlag == true)
;
if (MyFlag) // error, doesn't compile!
;
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.
(9 == True)
evaluates to false in Python and I would imagine similar in C++.
Commented
Oct 18, 2010 at 23:06
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.
remind me of "boolean madness code", its like these
if(someBool == true)
otherBool = false;
else
otherBool = true
Instead of:
otherBool = !someBool
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
.
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.
Commented
Oct 21, 2010 at 7:28
not
is not an option.
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.
if (b == true) {
is not just redundant. It is also a bit risky, because you might accidentally assigned true
to b
.
Commented
Oct 19, 2010 at 8:34
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.
Commented
Oct 19, 2010 at 18:02
==
.
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!
if (!bNotVal)
or if (bNotVal)
even in the first place. Ugh negatives in names makes everything harder to read.
Commented
Oct 18, 2010 at 23:48
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.
You think that's bad? How about:
if(someCondition) {
return true;
} else {
return false;
}
How about
if (x == "true")
WHY IS THAT A STRING?!
if(preg_match('/title/', implode($_POST))){
. PHP, enough said, I need to find a better job.
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"]
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.
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.
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.
bool b;
only initializes to false when b
is a field. You must initialize local variables explicitly.
Commented
Oct 19, 2010 at 5:55
true
or just "true". For instance ie any non-empty string is considered == true
but not === true
in some languages.
Commented
Oct 29, 2010 at 7:22
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)
{...}
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 :)
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.
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
.
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.
By cleaning up code not conforming to the new style, I've identified and corrected a few more instances of such subtle bugs.
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.
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.
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!
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).
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.
if (some_flag == true)
but the implicitif (is_something)
orif (has_something)
. Note the variable names.someBool == true
is also boolean, so by the same logic it should beif ((someBool == true) == true)
.$var = (bool) some_expression
. And in most cases, it won't even matter as PHP will do the necessary conversions dynamically.