In my opinion, there can be be a small readability advantage if that someFuncThatReturnsBool
functions name reads like it's just some value, not particularly a boolean. Thousands (perhaps most people) would call me an idiot for that.
Normally, boolean variables and functions would be named is_whatever
or has_whatever
. So normally, an if
statement reads as if (is_whatever)
or if (has_whatever)
. If I don't see that, or of course a relative operator, it seems a bit smelly to me.
But sometimes boolean variables and functions don't use that name formula, especially if the boolean type is specified via a template parameter. In that case, I might well use if (whatever == true)
. Or, using Yoda conditions, that's if (true == whatever)
.
Possible example...
std::map<int,bool> items;
...
if (items.at (key) == true)
{
...
}
Neither at
nor items
expresses that the value is boolean. if (item)
doesn't read right - if anything, it suggests "if this is an item" which isn't the intent here. if (item == true)
doesn't have this smell.
A smell is a distraction every time you revisit that code even if the smelly code is correct, so a couple of extra tokens is IMO worthwhile to clear that smell.
This is a reason why I'd generally prefer to name something is_whatever
rather than whatever_flag
. While whatever_flag
is clearly intended to be a boolean, it still doesn't read quite right. It's the "grammar" of abbreviated English - "if flag" suggests "if this is a flag" rather than "if this flag is set".
Obviously, some newbies write if (whatever == true)
because they have this mental template where every if
needs a relative operator. This template is wrong, so this is one of those idiot-newbie stereotypes. There are some other similar cases, mostly obvious, like writing value + 0
, value * 1
or value && true
. A slightly surprising one from Haskell...
main = do putStrLn "Hello World"
In this, the "mental template" is that any sequence of monadic actions requires a do
. In this case, though, there's only one monadic action so there's no need to compose a sequence of actions into a single action. All that's needed is...
main = putStrLn "Hello World"
In this case, I'll reserve judgement on whether it's occasionally worth keeping the do
for readability - I don't have the experience.
Anyway, personally, I think that having ridiculed people for doing something, it's hard to accept that sometimes there's a valid case for doing it. After all, the mental template is that if (whatever == true)
is automatically ridiculous.
Certainly if you want a quiet life, it's best to never do that.