Should I use `!IsGood` or `IsGood == false`?
Asked Answered
F

41

48

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?

Fugere answered 10/12, 2008 at 14:24 Comment(11)
If this really bothers you this much, it is going to be a long, hard life for you.View
It's a fair question the OP doesn't seem too riled about to me.Makepeace
Yeah, it's valid. I doubt myself with simple things from time to time and occasionally find a good reason to change my ways...Amora
Since the same question applies in at least c/c++/Java do you want to retag it language-agnostic?Cyano
It really doesn't bother me much, I just see it a lot and wondered if there was any reason... that said, I certainly prefer one over the other.Fugere
It applies to VB and it's variations, php, and other languages that are not typed.Alina
It seems to me the question you're asking isn't exactly language-agnostic if you assume Boolean is a type in all languages.Palish
My question was originally intended to be C# specific.Fugere
Every language that supports variables and branching is going to have a similar structure. It doesn't matter if the language is "Typed" or not.Alina
Chris, it's not a question of branching structure. C is typed, but it doesn't have a boolean type. "if(good)" is different than "if(good == TRUE)". The first means good is non-zero. The second means good is exactly equal to TRUE, which is a particular integer value. See MikeB's answer for more.Palish
The main problem in my opinion is it makes the developer look like they don't really understand booleansHardtack
S
103

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.

Shirlyshiroma answered 10/12, 2008 at 14:24 Comment(13)
It's not just beginners who prefer it; anyone who's interested in maximizing code readability prefers it. What's the cost?Suspect
I found it more readable the shorter way... what is the goal to right == true when the left side is already true/false... Do not say "anyone"... I agree with Daok, I was doing that few months ago than realize my mistakePicture
@litb : I know it's the first time I see the vote going that much fast up :P in the last 20 minutes it got around 15 votes. AmazingShirlyshiroma
If you name your variables properly then adding operator actually decreases readability. I.e. When you read it "if is good" is more readable than "if is good is true". I go with "if (isGood)" its as clear as it can be.Namara
@Christopher: unless you're doing "true == myVar" or "false == myVar", you're setting yourself up for subtle bugs like "if (myVar = true) {}".Hussy
A worse offender is a name like NotInSet... if (! NotInSet) ????? sometimes the name forces the choice.Cohlier
I don't find it annoying, but I do find the concise form more readable. Likewise, I prefer to avoid the "Is" prefix. I read !IsGood as "Not Is Good", but I read !Good as "Not Good". @Cohlier is correct, it's important to avoid the negative form in a variable name to avoid double negatives.Maloy
The more verbose the greater chance of a typo.Havelock
56 votes for an almost trivial opinion? Ha, this site is out of control.Varityper
I agree, it's generally beginners or people who don't name their variables nicely who prefer the longer version.Bully
I always use == because it's too easy for someone else to make a mistake, which has happened more than once to me. When I started doing that the confusion left. Whatever makes my life easier is what I use.Aside
I am curious to see if a serious answer can reach 100 votes. Usually I only see that in "what is your best xyz"...Shirlyshiroma
When I see == for boolean types, I think that it is an indicator that the person who uses == does fully understand boolean logic and what it means.Jessamyn
D
39

I always chuckle (or throw something at someone, depending on my mood) when I come across

if (someBoolean == true) { /* ... */ }

because surely if you can't rely on the fact that your comparison returns a boolean, then you can't rely on comparing the result to true either, so the code should become

if ((someBoolean == true) == true) { /* ... */ }

but, of course, this should really be

if (((someBoolean == true) == true) == true) { /* ... */ }

but, of course ...

(ah, compilation failed. Back to work.)

Doer answered 10/12, 2008 at 14:24 Comment(1)
Shades of Monty Python and the Spam sketch... I want an If test with Spam, Spam, Spam, true, and Spam.....Schoolgirl
B
32

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

Bassoon answered 10/12, 2008 at 14:24 Comment(10)
(IsGood == true) won't work either, if IsGood is a nullable bool. You would have to write (IsGood.HasValue && IsGood.Value == true), which is still more verbose and arguably less clear than (IsGood.HasValue && IsGood.Value)Linnlinnaeus
Charles, I think you are wrong. For Nullable<T> you will get T as type of property Value (bool in our case, so (... && IsGood.Value) should work). Also you can use shortest form too. Try to play with sample I just added to answer.Bassoon
IgorK, I agree, [IsGood.Value] would work, (if IsGood has a value...) I was saying that just writing IsGood == true will not work if IsGood is Nullable<bool> In this case IsGood is NOT a bool, it is Nullable<bool> so you cannot compare it with "true" that would create a type mismatchLinnlinnaeus
Charles, first sample works for all three cases (when IsGood typed bool? is initialized with true, false or null). I have checked it one more time. Are you saying that first sample will not compile using C# 2.0 compiler? It actually does... No exceptions in null case too :)Bassoon
i really doubt that, going to try it myself ;pJennajenne
Try it, Shawn :) WPF has IsChecked property with bool? type on CheckBox (inherited from ToggleButton) and I had to implement check/uncheck behavior in tree control, so this one is tested :)Bassoon
If you want to do this, use (false == value) instead of (value == false) since you might screw up and accidentally write (value = false) which might or might not cause a compiler warning.Infestation
mehrdad, I believe many C/C++ coders like this concept. C# has very strict rules what can be included in if condition. For plain bool it would work but as already said boolVar == false is too verbose, and for bool? variable if (boolOptVar = false) just doesn't compile!!! 'cause of error CS0266.Bassoon
Mehrdad!!! You just found yet another reason NOT to write ` if (boolVar == false)` - this seems to be real case where you can damage value :) May be there are other ones but I suppose this could be possible only with types that allow implicit cast to bool.Bassoon
I would prefer if(IsGood.GetValueOrDefault()), which have the same effect and be faster (execution time) than if(IsGood.HasValue && IsGood.Value). Note that if(!IsGood.GetValueOrDefault()) is NOT the same as if(IsGood.HasValue && !IsGood.Value).Vagrom
T
18

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.

if (IsGood)
if (!IsGood)

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

  • IsGood
  • HasValue
  • etc.
Tympanitis answered 10/12, 2008 at 14:24 Comment(0)
R
15

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

Rutherford answered 10/12, 2008 at 14:24 Comment(0)
A
13

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

Amora answered 10/12, 2008 at 14:24 Comment(2)
Good point on this showing up near String.ToString(), but I would be curious to see if it might be force of habit for some developers that are used to languages that are looser with their data types.Lambdoid
True about it evaluating to a bool, which is what you started with. Where do you stop then? ((isGood == false) == true)? No, that's a bool too, (((isGood == false) == true) == true) and so on... Comparing bools to bools just means you're doing it wrong... :pShankle
B
9

Some people find the explicit check against a known value to be more readable, as you can infer the variable type by reading. I'm agnostic as to whether one is better that the other. They both work. I find that if the variable inherently holds an "inverse" then I seem to gravitate toward checking against a value:

if(IsGood) DoSomething();

or

if(IsBad == false) DoSomething();

instead of

if(!IsBad) DoSomething();

But again, It doen't matter much to me, and I'm sure it ends up as the same IL.

Blanton answered 10/12, 2008 at 14:24 Comment(2)
This is what I do. If I'm looking for a false, I do an == false, but I try not to. I'd much rather not invert the conditional at all. It usually makes more sense to re-factor isBad to isGood, or swap your if/else blocks to make more sense, or whatever.Solitude
If you see if(IsGood) you can also infer it's a boolean, otherwise it would not compile! ;) Anyways, you're right, beginners tend to see it clearer this way.Heterosexuality
F
7

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.
Fugere answered 10/12, 2008 at 14:24 Comment(2)
I disagree that there is no clear winner - especially in C/C++. It's not just a style issue, there can be semantic differences. Using the longer form can cause subtle bugs.Rutherford
But using the longer form can cause subtle bugs. if (isGood = false) could've been avoided by just using !Stegodon
F
7

Readability only..

If anything the way you prefer is more efficient when compiled into machine code. However I expect they produce exactly the same machine code.

Fisken answered 10/12, 2008 at 14:24 Comment(0)
B
6

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.

Buckels answered 10/12, 2008 at 14:24 Comment(0)
G
5

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.

Graybeard answered 10/12, 2008 at 14:24 Comment(2)
I'm not following this. If you don't require '==' you don't accidentally type '='Nesto
This actually helps readability (after a getting used to it (doesn't take long)). Putting the shorter item at the start is always recommended (SomLongFunctionCall(*pointer[3], file == NOFILE, GetMyHeap(1, ALWAYS)) == E_NOERR is much easier on the eye the other way round: E_NOERR == SomLongFunctionCall(*pointer[3], NOFILE == file, GetMyHeap(1, ALWAYS)). YMMV as usual.Valvular
A
5

It's possible (although unlikely, at least I hope) that in C code TRUE and FALSE are #defined to things other than 1 and 0. For example, a programmer might have decided to use 0 as "true" and -1 as "false" in a particular API. The same is true of legacy C++ code, since "true" and "false" were not always C++ keywords, particularly back in the day before there was an ANSI standard.

It's also worth pointing out that some languages--particularly script-y ones like Perl, JavaScript, and PHP--can have funny interpretations of what values count as true and what values count as false. It's possible (although, again, unlikely on hopes) that "foo == false" means something subtly different from "!foo". This question is tagged "language agnostic", and a language can define the == operator to not work in ways compatible with the ! operator.

Anthony answered 10/12, 2008 at 14:24 Comment(1)
There's also the subtle behavior in C/C++ where anything non-zero is "true" but doesn't necessarily == TRUE.Hussy
T
4

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:

if(strcmp(string1, string2)==0) { /*do something*/ }

Generally however I'd agree with you that

if(!isCached)
{
    Cache(thing);
}

is clearer to read.

Tenterhook answered 10/12, 2008 at 14:24 Comment(5)
Once you understand strcmp this is better if( !strcmp(string1, string2) ) { /*do something*/ }Dusa
Doing !strcmp is worse because you are mixing logical operators with non-logical values. strcmp==0/!=0 is the more correct and clear method.Carom
I have got into trouble with strcmp in the past by not fully appreciating what it was returning, largely because of it being used as !strcmp() in most places. I find overall that it's not much more verbose to write ==0, and it makes it absolutely explicit what you are expecting from it.Tenterhook
Normally I use an inline function or macro called isEqual which calls !strcmp. In fact in my C++ code I now use a char* wrapper class called cStrBuff that has utility functions and operators.Dusa
Similarly to the strcmp, if a non boolean variable is tested in a boolean fashion like here: if(count) {count--;} it always takes me extra time to realize that count is not a boolean and we are testing something else here.Latoyalatoye
F
3

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/
Folkmoot answered 10/12, 2008 at 14:24 Comment(0)
Q
3

Only thing worse is

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

Never understood the thought behind that method.

Quietism answered 10/12, 2008 at 14:24 Comment(3)
I think it comes from C++. If you make a mistake and write 'if (x = 6)', it will be very hard to find this bug, whereas 'if (6 = x)' results in a compilation error.Witchy
Once you get use to looking at it, no problem reading it. Kind of like getting use to reading English?Pl
I hate seeing this. You wouldn't say, "Red was the color of the car," unless you're sound deep or fancy. You would just say, "The color of the car was red."Stegodon
L
3

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)
{
    ...
}
Lobectomy answered 10/12, 2008 at 14:24 Comment(4)
This is actually one of my pet peeves. Somewhere along the line, I was taught that booleans ought to represent positive conditions. Using negative conditions inevitably results in weird double-negative tests like "if (!IsBad || !Uninitialized)" putting the developer's brain into a mild pretzel.Guttersnipe
But, if you have the corollary IsGood and IsBad, then you shouldn't ever need to do something like !IsBadLobectomy
If you like your stack overflow exceptions... public bool IsBad { get { return !IsGood; } } public bool IsGood { get { return !IsBad; } }Hussy
What if you forgot that IsBad is a property or something? !IsGood should be read as Is not Good so it's built inStegodon
W
3

I prefer the !IsGood approach, and I think most people coming from a c-style language background will prefer it as well. I'm only guessing here, but I think that most people that write IsGood == False come from a more verbose language background like Visual Basic.

Wine answered 10/12, 2008 at 14:24 Comment(1)
even more so in Visual Basic, "Not IsGood" is more readable than "IsGood = False"Nesto
A
3

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.

Abbevillian answered 10/12, 2008 at 14:24 Comment(1)
I think you mean 'semantically'. Strictly speaking there is a difference between them because the used operators (including false) can be overridden. Also (depending on your semantics level), both describe different evaluations (although the compiler most likely uses the same for both).Bainbridge
V
2

You forgot:

if(IsGood == FileNotFound)

Vagrom answered 10/12, 2008 at 14:24 Comment(0)
M
2

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.

Modiolus answered 10/12, 2008 at 14:24 Comment(0)
G
1

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

unless($isGood)
Gersham answered 10/12, 2008 at 14:24 Comment(1)
This seems less ideal then !isGoodStegodon
N
1

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?

Nutriment answered 10/12, 2008 at 14:24 Comment(0)
P
1

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

Picture answered 10/12, 2008 at 14:24 Comment(0)
S
1

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.

Soutache answered 10/12, 2008 at 14:24 Comment(3)
You learn something new everyday. I've read TONS of C++ articles, tutorials, books, taken C++-oriented classes in university, yet have never seen this syntax before. Thanks.Festination
That must have happened when that VB guy joined the C++ standards committee!Vagrom
@P Daddy: yes, back in the 1980s when Bjarne Stroustrup was designing C++, he borrowed Knuth's time machine to jump forward to the 90s, when people trash on VB programmers. Or maybe you've never heard of ALGOL.Geneticist
S
1

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)
Scruple answered 10/12, 2008 at 14:24 Comment(0)
B
1

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

Brasil answered 10/12, 2008 at 14:24 Comment(0)
C
1

It seems to me (though I have no proof to back this up) that people who start out in C#/java type languages prefer the "if (CheckSomething())" method, while people who start in other languages (C++: specifically Win32 C++) tend to use the other method out of habit: in Win32 "if (CheckSomething())" won't work if CheckSomething returns a BOOL (instead of a bool); and in many cases, API functions explicitly return a 0/1 int/INT rather than a true/false value (which is what a BOOL is).

I've always used the more verbose method, again, out of habit. They're syntactically the same; I don't buy the "verbosity irritates me" nonsense, because the programmer is not the one that needs to be impressed by the code (the computer does). And, in the real world, the skill level of any given person looking at the code I've written will vary, and I don't have the time or inclination to explain the peculiarities of statement evaluation to someone who may not understand little unimportant bits like that.

Cheslie answered 10/12, 2008 at 14:24 Comment(1)
The compiler does not give a lick about the code. The programmer (and more importantly later programmers) need to be impressed. You could throw out all of the formatting and style rules and the compiler will not be bothered, but the mental toll on anyone reading the code will be enormousPl
A
1

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.

Aeromarine answered 10/12, 2008 at 14:24 Comment(6)
I don't want to have to go somewhere else to understand what "ShouldDoSomething" means.Shape
I disagree with the comment above. Normally one thinks in terms of workflow which is in many cases more important than the condition implementation itself.Mortar
My point exactly. If you consider the amount of brain-power spent when you are looking at your code, you save some when you are not bothered with too many details.Aeromarine
If the body of the statement is simply "do something", why would you need the condition to be "if should do something"... that's obvious. Unless the same condition is used elsewhere, I think this is unnecessary.Becalmed
This is stupid. Why throw another function on the stack just to return a single variable that could easily have been used directly? This being a simple method, you might as well make it a get only property, but that would just return IsGood so you might as well just use it directly and not make the reader worry if ShouldDoSomething is some expensive methodStegodon
Yeah well, first off I think you missed the "(...) except the most trivial ones (...)" part. Moreover, your suggestion of using a property will have the exact same runtime overhead as a method, because properties ARE methods. Lastly: Don't worry, be happy :)Aeromarine
I
0

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);
Isabel answered 10/12, 2008 at 14:24 Comment(1)
That's true, but you could still say: if (!isValidDate) { instead of if ( isValidDate==false) {Fugere
G
0

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.

Graybeard answered 10/12, 2008 at 14:24 Comment(0)
H
0

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.

Hemlock answered 10/12, 2008 at 14:24 Comment(0)
P
0

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

Prudence answered 10/12, 2008 at 14:24 Comment(0)
O
0

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();
}
Outofdoor answered 10/12, 2008 at 14:24 Comment(2)
This code is way too error prone even when using the '== false' syntax. I hope you don't come across code like this too often, or that you rewrite it entirely.Rosariarosario
Your code should never look like this in the first place.Stegodon
H
0

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.

Harbison answered 10/12, 2008 at 14:24 Comment(0)
M
0

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
}
Magree answered 10/12, 2008 at 14:24 Comment(0)
S
0

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.

Suspect answered 10/12, 2008 at 14:24 Comment(1)
More readable according to which mindset? I am rather accostumed to reading things like if x then do something as if x is true, then do something. And in the programming world, I am always irritated by things like isGood == false.Ineludible
S
0

While it's not a practical difference, I've always regards == as a numeric operator, and as such it is not applicable to boolean types. The closest boolean operator is "equivalence" (not exclusive or), which doesn't have a C style operator.

That way the strictly boolean test becomes

if (!(IsGood ^ true))

As an illustration of the problems with numeric operators on booleans, what is the boolean evalution of

true / 2
Stonwin answered 10/12, 2008 at 14:24 Comment(3)
As far as I know the C-style '^' is usually a numeric operator (i.e. bitwise xor). In fact, C-like languages often don't really have booleans. Note that !b in these languages is equivalent to b == 0. (Also, algebraically this isn't an issue at all.)Bainbridge
If you're using Python 3.0, True / 2 evaluates as True. If Python 2.X, True / 2 evaluates as False. What makes the difference is left as an exercise for the reader. :)Prudence
== is not a numeric operator. You can use it with boolean types, too, at least in C++. Thus, you can write if (oneBool == anotherBool)...Elohim
P
0

The only time I can think where the more vebose code made sense was in pre-.NET Visual Basic where true and false were actually integers (true=-1, false=0) and boolean expressions were considered false if they evaluated to zero and true for any other nonzero values. So, in the case of old VB, the two methods listed were not actually equivalent and if you only wanted something to be true if it evaluated to -1, you had to explicitly compare to 'true'. So, an expression that evaluates to "+1" would be true if evaluated as integer (because it is not zero) but it would not be equivalent to 'true'. I don't know why VB was designed that way, but I see a lot of boolean expressions comparing variables to true and false in old VB code.

Pitchfork answered 10/12, 2008 at 14:24 Comment(0)
G
0

We tend to do the following here:

if(IsGood)

or

if(IsGood == false)

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:

if not IsNotGuam then

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.

Gorey answered 10/12, 2008 at 14:24 Comment(0)
F
-1

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.

Festination answered 10/12, 2008 at 14:24 Comment(2)
In python, 'if something:' and 'if something==True:' mean different things. In C++, true can implicitly convert to 1, so should 'something' be an integer holding value 2, then 'something==true' is false, but '(!something)== true' is also false!Geneticist
I know it's technically different, but I'm referring to boolean variables. "if isGood:", or "if not isGood:". But your right, this idiom won't work if I need to distinguish None from, e.g., empty list. I try to avoid having to do that though.Festination
C
-2

I would

if (isGood) {
  doSomething();
}

and

if (isNotGood) {
    doSomethngElse();
}

Reads better.

Cowardice answered 10/12, 2008 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.