I keep seeing code that does checks like this
if (IsGood == false)
{
DoSomething();
}
or this
if (IsGood == true)
{
DoSomething();
}
I hate this syntax, and always use the following syntax.
if (IsGood)
{
DoSomething();
}
or
if (!IsGood)
{
DoSomething();
}
Is there any reason to use '== true
' or '== false
'?
Is it a readability thing? Do people just not understand Boolean variables?
Also, is there any performance difference between the two?
We tend to do the following here:
or
The reason for this is because we've got some legacy code written by a guy that is no longer here (in Delphi) that looks like:
This has caused us much pain in the past, so it was decided that we would always try to check for the positive; if that wasn't possible, then compare the negative to false.
For some reason I've always liked
more than
and that's why I kind of like Ruby's unless (but it's a little too easy to abuse):
and even more if used like this:
Occasionally it has uses in terms of readability. Sometimes a named variable or function call can end up being a double-negative which can be confusing, and making the expected test explicit like this can aid readability.
A good example of this might be strcmp() C/C++ which returns 0 if strings are equal, otherwise < or > 0, depending on where the difference is. So you will often see:
Generally however I'd agree with you that
is clearer to read.
The
!IsGood
pattern is eaiser to find thanIsGood == false
when reduced to a regular expression.vs
You forgot:
According to Code Complete a book Jeff got his name from and holds in high regards the following is the way you should treat booleans.
I use to go with actually comparing the booleans, but I figured why add an extra step to the process and treat booleans as second rate types. In my view a comparison returns a boolean and a boolean type is already a boolean so why no just use the boolean.
Really what the debate comes down to is using good names for your booleans. Like you did above I always phrase my boolean objects in the for of a question. Such as