chills42
chills42

Reputation: 14533

Should I use `!IsGood` or `IsGood == false`?

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?

Upvotes: 48

Views: 6991

Answers (30)

Chris
Chris

Reputation: 3712

The two forms are semantically identical, and produce the same machine code, so why not use the one that's more readable?

if (IsGood == false) is better than if(!IsGood).

When scanning code, it's easy to mistake the "!" preceding a bool variable for a character in the bool variable.

Upvotes: 0

Murthy
Murthy

Reputation: 310

As long as we have either if (isGood) or if (!isGood) it is fine.

Sometimes I come across code like this...

if (!getGreatGrandFateher.getGrandFather().getFather().getFirstChild().isMale())
{
   doSomething();
}

At first sight this misleads that doSomething is called if it is Male. The small '!' after "if" is getting lost in big code construct like the above.

Explicit check like below provides better readability

if(getGreatGrandFateher.getGrandFather().getFather().getFirstChild().isMale() == false)
{
   doSomething();
}

Upvotes: 0

hhafez
hhafez

Reputation: 39810

In a language like C where there is no "Boolean" type then I recommend the longer way ie

if (is_good == True)
{
}

The reason is is_good isn't only true/false (most likely implemented as a char) and hence can get corrupted by other values or not set correctly.

So what good is this? Your code will be able to pick up any problems with is_good being set incorrectly because with out the == True or == False check anything will go for a true ;) And if you really mean a boolean then that's bad.

Upvotes: 0

Kyle
Kyle

Reputation: 990

One could argue that test like if isValidDate==true can lead to overnesting. Consider a block of code that's validating that we have valid data from a user, for instance:

if (isValidDate == true) {
    if (isValidQuantity == true) {
         if (isOtherThingValid == true) {
              bool result = doThing();
              if (result == true) {
                   thatWorked();
         } // long block of code that tries to compensate for OtherThing's invalidness
    } // obtuse function call to a third party library to send an email regarding the invalid quantity
} // is this the function close brace or the if...

This drives me crazy, which is partially why I've developed a habit of doing things the other way round:

if (isValidDate == false) {
    logThisProblem("Invalid date provided.");
    return somethingUseful;
}

if (isValidQuantity == false) {
    logThisProblem("Invalid quantity provided.");
    return somethingUseful;
}

if (isOtherThingValid == false) {
    logThisProble("Other thing not valid.");
    return somethingUseful;
}

// OK ... we've made it this far...
bool result = doThing(date, quantity, otherThing);

Upvotes: 0

Cybis
Cybis

Reputation: 9883

Coding in C#/C++/Java/etc... I always prefer

if (something == true)
if (something == false)

over

if (something)
if (!something)

because the exclamation point is just difficult to see at a glance unless I used a large font (but then I'd see less code on the page - not all of us can afford 24"+ monitors). I especially don't like being inconsistent and using if (something) and if (something == false)

When I code in Python, however, I almost always prefer

if something:
if not something:

because the 'not' is plainly visible.

Upvotes: -1

OscarRyz
OscarRyz

Reputation: 199333

I would

if (isGood) {
  doSomething();
}

and

if (isNotGood) {
    doSomethngElse();
}

Reads better.

Upvotes: -2

Michael Haren
Michael Haren

Reputation: 108376

I agree with you (and am also annoyed by it). I think it's just a slight misunderstanding that IsGood == true evaluates to bool, which is what IsGood was to begin with.

I often see these near instances of SomeStringObject.ToString().

That said, in languages that play looser with types, this might be justified. But not in C#.

Upvotes: 13

Bob
Bob

Reputation: 99824

I prefer !IsGood because to me, it is more clear and consise. Checking if a boolean == true is redundant though, so I would avoid that. Syntactically though, I don't think there is a difference checking if IsGood == false.

Upvotes: 3

Brian Genisio
Brian Genisio

Reputation: 48167

For readability, you might consider a property that relies on the other property:

public bool IsBad => !IsGood;

Then, you can really get across the meaning:

if (IsBad)
{
    ...
}

Upvotes: 3

mookid8000
mookid8000

Reputation: 18628

Personally, I prefer the form that Uncle Bob talks about in Clean Code:

(...)
    if (ShouldDoSomething())
    {
        DoSomething();
    }
(...)

bool ShouldDoSomething()
{
    return IsGood;
}

where conditionals, except the most trivial ones, are put in predicate functions. Then it matters less how readable the implementation of the boolean expression is.

Upvotes: 1

Pokus
Pokus

Reputation: 11763

I do not use == but sometime I use != because it's more clear in my mind. BUT at my job we do not use != or ==. We try to get a name that is significat if with hasXYZ() or isABC().

Upvotes: 1

IgorK
IgorK

Reputation: 906

I would prefer shorter variant. But sometimes == false helps to make your code even shorter:

For real-life scenario in projects using C# 2.0 I see only one good reason to do this: bool? type. Three-state bool? is useful and it is easy to check one of its possible values this way.

Actually you can't use (!IsGood) if IsGood is bool?. But writing (IsGood.HasValue && IsGood.Value) is worse than (IsGood == true).

Play with this sample to get idea:

bool? value = true; // try false and null too

if (value == true)
{
    Console.WriteLine("value is true");
}
else if (value == false)
{
    Console.WriteLine("value is false");
}
else
{
    Console.WriteLine("value is null");
}

There is one more case I've just discovered where if (!IsGood) { ... } is not the same as if (IsGood == false) { ... }. But this one is not realistic ;) Operator overloading may kind of help here :) (and operator true/false that AFAIK is discouraged in C# 2.0 because it is intended purpose is to provide bool?-like behavior for user-defined type and now you can get it with standard type!)

using System;

namespace BoolHack
{
    class Program
    {
        public struct CrazyBool
        {
            private readonly bool value;

            public CrazyBool(bool value)
            {
                this.value = value;
            }

            // Just to make nice init possible ;)
            public static implicit operator CrazyBool(bool value)
            {
                return new CrazyBool(value);
            }

            public static bool operator==(CrazyBool crazyBool, bool value)
            {
                return crazyBool.value == value;
            }

            public static bool operator!=(CrazyBool crazyBool, bool value)
            {
                return crazyBool.value != value;
            }

            #region Twisted logic!

            public static bool operator true(CrazyBool crazyBool)
            {
                return !crazyBool.value;
            }

            public static bool operator false(CrazyBool crazyBool)
            {
                return crazyBool.value;
            }

            #endregion Twisted logic!
        }

        static void Main()
        {
            CrazyBool IsGood = false;

            if (IsGood)
            {
                if (IsGood == false)
                {
                    Console.WriteLine("Now you should understand why those type is called CrazyBool!");
                }
            }
        }
    }
}

So... please, use operator overloading with caution :(

Upvotes: 32

Patrick Desjardins
Patrick Desjardins

Reputation: 141003

I follow the same syntax as you, it's less verbose.

People (more beginner) prefer to use == true just to be sure that it's what they want. They are used to use operator in their conditional... they found it more readable. But once you got more advanced, you found it irritating because it's too verbose.

Upvotes: 103

Michael Burr
Michael Burr

Reputation: 340506

The technique of testing specifically against true or false is definitely bad practice if the variable in question is really supposed to be used as a boolean value (even if its type is not boolean) - especially in C/C++. Testing against true can (and probably will) lead to subtle bugs:

These apparently similar tests give opposite results:

// needs C++ to get true/false keywords
// or needs macros (or something) defining true/false appropriately
int main( int argc, char* argv[])
{
    int isGood = -1;

    if (isGood == true) {
        printf( "isGood == true\n");
    }
    else {
        printf( "isGood != true\n");
    }

    if (isGood) {
        printf( "isGood is true\n");
    }
    else {
        printf( "isGood is not true\n");
    }

    return 0;
}

This displays the following result:

isGood != true
isGood is true

If you feel the need to test variable that is used as a boolean flag against true/false (which shouldn't be done in my opinion), you should use the idiom of always testing against false because false can have only one value (0) while a true can have multiple possible values (anything other than 0):

if (isGood != false) ...  // instead of using if (isGood == true)

Some people will have the opinion that this is a flaw in C/C++, and that may be true. But it's a fact of life in those languages (and probably many others) so I would stick to the short idiom, even in languages like C# that do not allow you to use an integral value as a boolean.

See this SO question for an example of where this problem actually bit someone...

Upvotes: 15

Tim
Tim

Reputation: 2419

If you happen to be working in perl you have the option of

unless($isGood)

Upvotes: 1

jon hanson
jon hanson

Reputation: 9408

If you really think you need:

if (Flag == true)

then since the conditional expression is itself boolean you probably want to expand it to:

if ((Flag == true) == true)

and so on. How many more nails does this coffin need?

Upvotes: 1

Reputation:

I like to use different styles depending on the naming of the variables, for example:

Variables named with a prefix like Is, Has etc. with which by looking at the name is obvious that are booleans I use:

if(IsSomething)

but if I have variables that do not have such a prefix I like to use

if(Something == true)

Which ever form you use, you should decide based on the programing language you use it in. The meaning of

if(Something) and if(Something == true)

can have very different meaning in different programing languages.

Upvotes: 0

J.T. Hurley
J.T. Hurley

Reputation: 521

One size doesn't fit all. Sometimes a more terse form can be made plain or is idiomatic, like !(x % y) , which returns "True" if y is a factor of x.

Other times, a more explicit comparison would be more useful. [(x, y) for x in range(10) for y in range(10) if not (x and y)] is not as plain as [(x, y) for x in range(10) for y in range(10) if (x == 0 or y == 0)]

Upvotes: 0

Calyth
Calyth

Reputation: 1673

I think it really depends on the language.

Say, in PHP, certain functions could either return false, and return non-negative numbers.

Then the:

if(foo(bar)) { ... }

scheme won't work too well, because you can't tell between return of false or 0.

In other languages that doesn't have this nasty little FUBAR, I think either form is acceptable.

Upvotes: 0

P Daddy
P Daddy

Reputation: 29547

You forgot:

if(IsGood == FileNotFound)

Upvotes: 2

Marc
Marc

Reputation: 1356

Cybis, when coding in C++ you can also use the not keyword. It's part of the standard since long time ago, so this code is perfectly valid:

if (not foo ())
   bar ();

Edit: BTW, I forgot to mention that the standard also defines other boolean keywords such as and (&&), bitand (&), or (||), bitor (|), xor (^)... They are called operator synonyms.

Upvotes: 1

yogman
yogman

Reputation: 4131

The !IsGood pattern is eaiser to find than IsGood == false when reduced to a regular expression.

/\b!IsGood\b/

vs

/\bIsGood\s*==\s*false\b/
/\bIsGood\s*!=\s*true\b/
/\bIsGood\s*(?:==\s*false|!=\s*true)\b/

Upvotes: 3

Reputation:

I've seen the following as a C/C++ style requirement.

if ( true == FunctionCall()) {
  // stuff
}

The reasoning was if you accidentally put "=" instead of "==", the compiler will bail on assigning a value to a constant. In the meantime it hurts the readability of every single if statement.

Upvotes: 5

Wavel
Wavel

Reputation: 966

Only thing worse is

if (true == IsGood) {....

Never understood the thought behind that method.

Upvotes: 3

Sydius
Sydius

Reputation: 14307

In many languages, the difference is that in one case, you are having the compiler/interpreter dictate the meaning of true or false, while in the other case, it is being defined by the code. C is a good example of this.

if (something) ...

In the above example, "something" is compared to the compiler's definition of "true." Usually this means "not zero."

if (something == true) ...

In the above example, "something" is compared to "true." Both the type of "true" (and therefor the comparability) and the value of "true" may or may not be defined by the language and/or the compiler/interpreter.

Often the two are not the same.

Upvotes: 2

user43706
user43706

Reputation:

I prefer to use:

if (IsGood)
{
    DoSomething();
}

and

if (IsGood == false)
{
    DoSomething();
}

as I find this more readable - the ! is just too easy to miss (in both reading and typing); also "if not IsGood then..." just doesn't sound right when I hear it, as opposed to "if IsGood is false then...", which sounds better.

Upvotes: 6

chills42
chills42

Reputation: 14533

From the answers so far, this seems to be the consensus:

  1. The short form is best in most cases. (IsGood and !IsGood)
  2. Boolean variables should be written as a positive. (IsGood instead of IsBad)
  3. Since most compilers will output the same code either way, there is no performance difference, except in the case of interpreted languages.
  4. This issue has no clear winner could probably be seen as a battle in the religious war of coding style.

Upvotes: 7

Jonas Elfström
Jonas Elfström

Reputation: 31468

For some reason I've always liked

if (IsGood)

more than

if (!IsBad)

and that's why I kind of like Ruby's unless (but it's a little too easy to abuse):

unless (IsBad)

and even more if used like this:

raise InvalidColor unless AllowedColors.include?(color)

Upvotes: 1

PhiLho
PhiLho

Reputation: 41162

Ah, I have some co-worked favoring the longer form, arguing it is more readable than the tiny !

I started to "fix" that, since booleans are self sufficient, then I dropped the crusade... ^_^ They don't like clean up of code here, anyway, arguing it makes integration between branches difficult (that's true, but then you live forever with bad looking code...).

If you write correctly your boolean variable name, it should read naturally:
if (isSuccessful) vs. if (returnCode)

I might indulge in boolean comparison in some cases, like:
if (PropertyProvider.getBooleanProperty(SOME_SETTING, true) == true) because it reads less "naturally".

Upvotes: 1

Herms
Herms

Reputation: 38868

There are some cases where doing that is actually useful, though not often.

Here's an example. In Actionscript 2, booleans have 3 possible values:

  • true
  • false
  • null/undefined

I'll generally do something like this in methods that take optional boolean arguments:

function myFunc(b:Boolean):Void {
  if(b == true) {
    // causes b to default to false, as null/undefined != true
  }
}

OR

function myFunc(b:Boolean):Void {
  if(b != false) {
    // causes b to default to true, as null/undefined != false
  }
}

depending on what I want to default the value to. Though if I need to use the boolean multiple time I'll do something like this:

function myFunc(b:Boolean):Void {
  b = (b == true); // default to false
}

OR

function myFunc(b:Boolean):Void {
  b = (b != false); // default to true
}

Upvotes: 0

Related Questions