Which is clearer form: if(!value) or if(flag == value)?
Asked Answered
W

19

60

I understand this is a subjective question, so I apologize if it needs to be closed, but I feel like it comes up often enough for me to wonder if there is a general preference for one form over the other.

Obviously, the best answer is "refactor the code so you don't need to test for falsehood" but sometimes there's no easy way to do so and the "else" branch is simply to continue processing. So when you must have an "if not false" construct, which is the preferred standard:

The not operator

if (!value)

Or the test for false

if (value == false)
Wooden answered 4/6, 2010 at 19:57 Comment(9)
There's also the possibility of if (value != true). Personally I don't find any particular one less desirable than the others.Lathrop
An advantage of the first is that you can't do if (shouldLaunchMissiles = false)Dissenter
It occurs that this being a subjective question, assuming the community feels the answers are valuable and wants to keep it, could someone make this a wiki question? I don't feel like giving anyone an "answer" credit for this question is really fair, since there's no absolutely correct answer.Wooden
I don't think testing for falsehood is a problem. A bigger problem would be booleans that expresses a negative condition. if (!detonated) is much clearer to me than if (unDetonated) for example.Scaler
@CodexArcanum: Subjective, but I'm not seeing any argumentiveness coming out of it, and it's a valid question of programming style. So far, I'm seeing no "close" votes, and I'm not going to vote to close.Irs
@Jeffrey: It gets worse. How about if (!unDetonated)? That would make me pause while reading the code for sure.Irs
There's a near-duplicate here, though: #356717Irs
@David Thornley - Exactly! That's where booleans of negative meaning inevitably lead!Scaler
Variable Naming! Variable Naming! Variable Naming! You can easily, in the class where value is declared, add a computed variable as in (say value is LaunchMissile), public bool AbortLaunch => !LaunchMissile, then all you need is if (AbortLaunch) ..., and then it is terse, eminently readable, and avoids the negation operator.Endodontist
U
76

if (!value) is easier/faster to follow. Subjective as you said. As long as you are consistent, this is the main thing.

EDIT

One other point to add - omitting the true/false keywords should also (hopefully) force the coder to use better named variables. Bool variables should always indicate meaning or state purpose, such as:

if (MyWallet.IsEmpty)

There is no reason with the above to use == false or == true as it's redundant. The above is human readable immediately.

Far better than having to decipher:

if (MyWallet.EmptyStatus == true) or something ridiculous like this.

Unnumbered answered 4/6, 2010 at 19:58 Comment(10)
True, consistency is the most valuable thing.Wooden
@CodexArcanum: But being consistently wrong or consistently unreadable is a Bad Thing.Unguiculate
@KP: Up-voted. Great point about variable names. Your answer shows how one decision in coding style can easily affect other decisions in coding style and help someone who sees the code for the first time to understand it as quickly as possible.Unguiculate
He added 10 upvotes appending my answer to his answer while I got nothing. No complains, I think these are the rules of the game :-)Winder
I find it much easier to read the == false in certain situations depending on your variable names, and I find it easier to miss a ! in front of a variable as well. For example, if(!log.DeviceOn.IsValid) vs if(log.DeviceOn.IsValid == false) - I prefer the second.Kerstinkerwin
@Claudio: while on the same thought pattern I beg to differ that I 'copied' your answer. My point was about better coding practice, and the fact that if a team has a policy that ==false and ==true shall not be used, it forces the coder to practice better naming conventions. You touched on code elegance which is a wide sweeping term. Upvoted your answer as it is valid and a good one as well. Copy however I disagree with.Unnumbered
using wallet example, enums could be used, as in.. if(Wallet.Status == WalletStatus.Empty) would be just fine and eminently readable...Endodontist
@Charles. Yup. Good example with enums. My argument still holds when using true/false IMO.Unnumbered
I code it with the explicit comparison these days, but I'm comfortable reading it either way.Taft
@CrimsonX: That's the only argument against using negation I can agree with. My typical suggestion probably sounds silly (it is definitely outside the domain): use a font with a mroe prominent exclamation mark.Psychokinesis
E
30

I personally like

if ((value == false) == true) ...

cause this is verifying that the statement value is false is actually evaluating to a boolean true...

and, then, obviously, covering both posssibilites adds even more clarity,

if ((value == false) == true && (value == false) != false)

<grin/>

and for those of you who are real gluttons for clarity, and demand incontrovertible readability, I'd suggest

if (((value == false) == true && (value == false) != false) == true)

But seriously, and I just thought of adding this, creating appropriate and meaningful variable Names is the key to this issue. You can easily, in the class where value is declared, add a computed variable as in (say "value "is actually "LaunchMissile"),
public bool AbortLaunch => !LaunchMissile,
then all you need is
if (AbortLaunch) ...,
and then it is terse, eminently readable, and avoids the negation operator.

Endodontist answered 4/6, 2010 at 20:3 Comment(9)
Ah, ye olde Pattern of Redundancy Pattern.Qatar
if (((value == false) == true).ToString().Length == 4) ... :)Frowsty
And to be even clearer, you might want to add && (value == false) != falseEndodontist
Nag wins! we must check the length of the toString of our boolean! Obviously if it's true we'll get "True" and if its false we'll get "False". You win.Heaviness
perhaps off topic, but it should be <grin/> ;-)Caravan
I am absolutely positive I've come across some tortured logic like this once or twice.Fries
As an alternative to Debug.Fail(), you can always Debug.Assert(p && !p). The latter has more interesting existential consequences if a future compiler decides it's an acceptable assertion.Curacy
You've missed a spot: if((value == false) == true && (value == false) != FileNotFound))Klatt
I prefer: IF TRUE and If ISMORETRUEPauli
D
23
if (!value)

This is always clearer in my opinion.

if (value == false)

I hate to say this, because it sounds kind of mean, but this normally shows that the person writing the code doesn't really understand the use of boolean values. You don't need to re-validate what a boolean is in an if statement. It's redundant.

(Personally, I would be annoyed at the person too if they named the variable value instead of something more meaningful. I have a feeling what you posted is just psuedo code, I would definitely ding that on a review.)

Edit (in response to a comment below):

It may look trivial, but often it is a sign of much bigger things. Truthfully, most people who do use var == true etc. don't understand. It's just a fact. I'm not saying their stupid or they shouldn't be programmers just that there is probably something that they need to review and learn. The problem is that when logic gets much more complex, not understanding concepts like this can lead to much much bigger problems down the road. Some people say "it's a style." That's fine. The real question in this case is, "How is it beneficial for me to do it this way? What do I or other people get from it?" If you can't solidly answer that question, then you need to ask yourself "Why is this a good idea?"

Demonstrator answered 4/6, 2010 at 19:59 Comment(8)
+1 for the comment on understanding. I agree that developers with less conceptual understanding of code tend to lean toward using == false over allowing the boolean value speak for itself, especially when I see if(value == true).Unnumbered
I acknowledge that the second form looks silly and is redundant, but I often see it in example code. The reason given is usually that it makes it very clear on a quick scan of the code what is being tested, on the assumption that a quick scan might miss the '!'. The intent being, I assume, the remove a stumbling block that might cause the reader to pause and waste a few seconds looking closer at the statement.Wooden
Ok now, if(value == true) is just silly. In c# anyway, it may have merit in a language like Javascript where if(value) is testing for both boolean truth AND null checking.Wooden
If I had to do it in JavaScript I would write if(true == value), that way I wouldn't accidently assign a value to value.....not that I've done that before....ever.Demonstrator
I don't think outside of javascript if(someVariable == true) is ever a good code structure. The name of the bool variable should be self-explanatory, such as if(someClassInstance.IsEmpty)Unnumbered
@Kevin: Watch out for those Yoda Conditions! #2349878Transcendental
-1. I'm sorry, but it IS mean. Such variations in coding style are meaningless, especially when you compare them with the numerous other things you can learn from someone else's code.Retrenchment
I have been programming for 45+ years and I have always used if (!value) until I read "Clean Coding" by Uncle Bob Martin. He convived me that (if (value == false) was much easier to read. It also can be missed ie: if (!Ibingo) or if (Ibingo)Wicket
V
13

I would never use if(value == true), so just for consistency I would also not use if(value != false).

Vaccination answered 4/6, 2010 at 20:3 Comment(2)
if(value != false) ... Nice!Gapin
@KP, your method is fool-proof for when they add the third boolean value of FileNotFound.Fries
W
13

if(!value) is clearer and more "elegant", specially if you name boolean variables correctly

  • isWhatever
  • hasWhatever
  • etc

Something like

if (Page.IsPostback == true)

seems redundant to me

Winder answered 4/6, 2010 at 20:3 Comment(1)
+1. e.g., while(!done) Reads as "while not done", which is much clearer than while(done == false) which in turn reads as "while done equal to false". Conventional coding style has its own language.Directory
A
12

Dissenting opinion (kind of)

From a compilation standpoint, you're going to get the same IL, so it really only matters from a readability standpoint.

From that standpoint, the if(value == false) is more obvious to a casual reader, and there is less chance of missing the ! before the bool.

Honestly, I use both approaches, and most times, I make it depend on my variable name. If it still sounds ok to say "not" in place of the "bang", I'm likely to use the bang notation

e.g.

if(!gotValue) {}
//if (I've) not gotValue

//but

if(checkValue == false){}
//If (I've) not checkValue doesn't quite work here grammatically.
Allhallowtide answered 4/6, 2010 at 20:9 Comment(0)
D
6

I use Not value when coding in VB but tend to use value == false when coding in C#. I find that the exclamation point can sometimes be lost in the name of the variable (e.g. !legal). Maybe it's because I'm, uh, a seasoned veteran.

Demonetize answered 4/6, 2010 at 20:7 Comment(2)
I've got so much seasoning, it's starting to make my hair look grey and get stuck in my wrinkles.Allhallowtide
Too bad that C# does not have a not keyword (like C++), which stands out quite well.Pod
U
2

I would favor using if(!value) because, depending on the names of the variables involved, the "true" case makes much more sense according to English semantics.

Consider one of the examples in this MSDN article:

if(pane.IsChecked)

reads in English as, "If the pane is checked".

However, if(pane.IsChecked == true) reads in English as "If whether the pane is checked is true". That statement that is far less clear in English than it should be.

One of the reasons why we don't write C# code in binary is human readability. If you're given the choice between code that flows well when you read it and code that doesn't, side with the one that is more readable. I don't think adding the "== true" makes this example more readable, and MSDN doesn't think so either.

Granted, this is a rather small example to worry about. But as some of the other answers have indicated, not applying this way of thinking to larger-scale cases can hurt readability.

Unguiculate answered 4/6, 2010 at 20:31 Comment(0)
B
2

I would normally prefer if (!value) too, when I know for sure that value is a boolean. But many times it can be a string, or a number.

The number zero would evaluate to false in conditionals in a lot of languages (not all, though); however, the string "0" would evaluate to true. This is a problem particularly in JavaScript, particularly if you receive JSON strings from the server, particularly if the server is written in PHP (because most PHP developers are careless enough to just take values from the DB and call json_encode on them, not knowing that the DB yields strings and not having a clue that all those zeros and ones that they use as boolean fields will be encoded as strings on the other end, thus all treated as true in conditionals).

Rant over. My suggestion: be explicit, especially if your language is the “very dynamic” type (i.e. JavaScript, PHP, Perl).

Brittabrittain answered 4/6, 2010 at 21:1 Comment(0)
A
1

Whatever one you prefer. Pick one and stick to it.

Apodictic answered 4/6, 2010 at 20:0 Comment(3)
Bad idea, when there's more than one developer on the same codebase.Sagesagebrush
@Pavel - that kind of falls under Pick one and stick to it :).Apodictic
to some extent, yes :) it's more like pick one global, and stick to it, which is what SO is so good for, which is why the question. This makes this question valid.Sagesagebrush
S
1

I am sorry to say, the second just looks stupid to me.

I'd add an extra level, if someone prefers it:

if( (value==false) == true )

:)

Sagesagebrush answered 4/6, 2010 at 20:10 Comment(0)
H
1

I don't think it's all that subjective. I have never seen it recommended in the longer form. Actually all the books and coding guides and "How to be a good programmer" HowTos I've read discourage it.

It falls in the same category as

if (value) {
  return true;
} else {
  return false;
}

OTOH, all the answers given here make my first statement kinda equal not true.

Heckman answered 4/6, 2010 at 20:28 Comment(0)
G
1

I favour the if (!value) style at least for evaluating variables or common properties like Page.IsPostback and the like. For anything more complex I tend to parenthesise the expression like thus:

if (!(SomeType.SomeProperty.CallingAMethod(input).GetSomething.BooleanProperty))

Just to draw a little more attention to it.

All in all, it's an argument for Perl-style unless and until keywords.

Grayback answered 7/6, 2010 at 2:51 Comment(1)
This is what i'm also doing. When i use a ! to negate an expression, i always encase the expression in parentheses, as you said to draw a little more attention to it. I think it adds to readability especially when using private variables/classes which start with underscore: if(!_whateverThisThing.TriesToDo()) would be written as: if(!(_whateverThisThing.TriesToDo())). IMHO missing the ! is harder on the latter.Hehre
W
0

If the condition is just a check of a single value, then !value is quicker.

However, when the condition contains multiple value checks, I find it much easier to read value == false. Somehow it is easier to parse multiple checks for equality than multiple negations of values.

Waddington answered 4/6, 2010 at 20:5 Comment(0)
H
0

I actually many of forms possible.

This is not actually how it is written to standards, but this is how I see it:

//if foo is(or exists)
if(foo)

//if foo is true
if(foo == true)

//if foo doesn’t exist
if(!foo)

if foo is false
if(foo == false)

Hence I don’t see == false is redundant.

Handicraftsman answered 4/6, 2010 at 20:44 Comment(2)
Your variablenaming is the problem. Give foo a name that is like a question that you can answer with YES or NO. like e.g. "IsFoo" or "FooExists" or even "FooIsTrue" then you just need to say: "If FooExists then dosomething". You can see that "If Foo" alone is not a question, there is something missing to be a really question andPauli
Imho this answer contains really bad advice. First and third example is misleading especially for beginners. This has nothing to do with "is" or "exists".Gall
R
0

I prefer the second option, the if (value == false) one. I gladly use if (~value) or if (not value) in languages that support it, but that ! just merges waaaaay too easily either with the variable name or opening braces or | or || operators... at least in my opinion.

Also, two things:

  1. I never do if (value == true), and I'm aware I'm inconsistent. And although consistency is very important in my opinion, that pesky ! is simply worse.
  2. I think it's really a matter of personal taste, just like the brace-on-a-newline debate. I would never criticize a teammate for silly little things like that, and I have a hard time understanding the people who will.
Retrenchment answered 7/6, 2010 at 15:57 Comment(0)
D
0

I use if (value == false) The ! in if (!value) is so small I sometimes miss it.

Duplication answered 26/1, 2018 at 9:19 Comment(1)
I am not sure why this got downvotes, because he is right. I just fixed a bug the other day where it was missed.Wicket
I
0

Whatever condition an if block should evaluate in order to execute must evaluate to true.

Hence, when value is false, the reason why if (!value) allows an if block to execute is because the ! operator essentially flips the false value of value to true, thus making the resultant condition within the parentheses evaluate into a true one that an if block needs in order to execute.

if (value), if (!value), if (flag == value), if (value == true), if (value == false), depending on what's to be achieved, are valid code. E.g. if (value == true) is very useful when value is a nullable boolean, because if (value) will give a syntax error, and if (value.Value == true) will throw exception if you didn't ensure that value is not null before the if block is executed.

Icao answered 10/8, 2018 at 21:18 Comment(0)
U
0

I am also of the opinion that using == inside an if is redundant and I have another suggestion, at least visually, by introducing spaces:

if ( ! created)

Even using OpenDyslexic as font, the not sign ! next to the opening bracket ( can be too close to distinguish it at a glance if(!created).

Underpinning answered 15/4, 2020 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.