69

A comment on this question: Checking if a method returns false: assign result to temporary variable, or put method invocation directly in conditional? says that you should use !boolean instead of boolean == false when testing conditions. Why? To me boolean == false is much more natural in English and is more explicit. I apologise if this is just a matter of style, but I was wondering if there was some other reason for this preference of !boolean?

gnat
  • 21,442
  • 29
  • 112
  • 288
ell
  • 966
  • 1
  • 10
  • 14
  • 30
    It is shorter to write. – Zenon Feb 25 '12 at 20:41
  • 41
    It's like doing `boolean == true`: it doesn't make sense. Expressions inside `if` statements are just that: expressions. If something already evaluates to a boolean expression, why would you add a check to force it to evaluate to that? – Maxpm Feb 25 '12 at 20:43
  • 1
    Because that's how most (C-style) programers do it, and consistency is important. – zzzzBov Feb 25 '12 at 20:44
  • @zzzzBov I haven't programmed in C in ages... is that the idiomatic way of evaluating a boolean expression? In any case, consistency is relative to specific languages. In Java it's idiomatic to write `if (condition) {...}` rather than `if (condition == true) { ... }` (same with `false`). – Andres F. Feb 25 '12 at 20:49
  • @AndresF., Java is a C-style language, as is C#, C, C++, JavaScript, ActionScript, php, and numerous others. – zzzzBov Feb 25 '12 at 20:51
  • 13
    @zzzzBov: Um, no. That's not how most (C-style) programmers do it. – amara Feb 25 '12 at 21:04
  • @zzzzBov: It's true that Java's syntax resembles C, but its conventions and best practices are different in many ways. – Andres F. Feb 25 '12 at 21:35
  • 4
    @ell I suggest this isn't "language-agnostic". Pick a language and follow its conventions! – Andres F. Feb 25 '12 at 21:39
  • 11
    @zzzzBov: Your comment is ambiguous. If you meant that `!boolean_variable` is the way most C programmers do it, I agree. – Keith Thompson Feb 25 '12 at 23:06
  • 6
    @sparkleshy, I would venture to guess that more than 50% of C-style programmers use `!foo` over `foo == false`. Are you disagreeing with this? – zzzzBov Feb 25 '12 at 23:19
  • 31
    And more importantly, how come nobody wants to write `boolean != true`? –  Feb 26 '12 at 00:00
  • 5
    @zzzzBov Oops, I completely misread your comment as if it was advocating boolExp == false. My bad! – Andres F. Feb 26 '12 at 05:03
  • 2
    @zzzzBov: OH. No! I totally agree with you! I also completely misread your comment o//o – amara Feb 26 '12 at 05:06
  • @AndresF., sparkleshy, it wasn't until Keith Thompson mentioned the ambiguity that I realized it that I hadn't been explicit with my comment, and it looked odd in comparison next to Maxpm's comment, which was a couple seconds ahead of my own. – zzzzBov Feb 26 '12 at 05:15
  • @zzzBov I completely disagree with your sweeping statement of languages which are C style. Java, Javascript/Actionscript are ECMAScript based languages. Java I think might be the closest bet you have here to classifying it as "c-style" but I wouldn't agree still and wouldn't agree with C# either. They're based on ECMA and and I would say that aside from the odd similar similar syntactic expressions, they're not styled after C. –  Feb 26 '12 at 11:43
  • 2
    @Andres, you should have said to zzzzBov, "Oops (...). !YourBad" –  Feb 26 '12 at 11:44
  • 10
    If you named your variable properly, then `!boolean` is more natural. It reads as `not boolean` to anyone who's enough of a programmer to _read code_ mentally. – Lightness Races in Orbit Feb 26 '12 at 13:02
  • In JavaScript, !___ is actually better form because it forces ___ to be converted to a boolean value (it might not be initially). In fact, you often see !!___ used as a shorthand typecast to boolean. – Mike DeSimone Feb 26 '12 at 17:48
  • 8
    I personally prefer `if(boolean?true:false)` – mowwwalker Feb 26 '12 at 19:08
  • 2
    @AscensionSystems Java isn’t ECMAScript. And you better not mention Java and JavaScript together in the same sentence like that. They are unrelated. – Needless to say that all the mentioned languages are indeed influenced by C (directly or indirectly). – poke Feb 27 '12 at 01:10
  • 7
    I think part of the distaste for "boolean == false" is the lingering suspicion it arises in the experienced reader that the programmer in question hasn't quite grasped boolean logic. – Dan Diplo Feb 27 '12 at 08:43
  • 9
    Real programmers write !!!boolean. !!! is called the "really not"-operator. – ThomasX Mar 06 '12 at 15:35
  • 1
    Possible duplicate of [Make a big deal out of == true?](http://softwareengineering.stackexchange.com/questions/12807/make-a-big-deal-out-of-true) – gnat Feb 28 '17 at 12:50
  • 1
    Just for the record, PEP 8 [suggests](https://www.python.org/dev/peps/pep-0008/#programming-recommendations) to use `if var:`. The use of `if var == True:` is marked as bad. – john c. j. Jul 22 '19 at 19:53
  • 1
    Because `if (!IsVisible...` is easy to misread and creates defects, and `if (IsVisible == false)` does not risk that. – StingyJack Dec 09 '20 at 05:20

17 Answers17

170

When I see a line like if (!lateForMeeting()), I read that as "If not late for meeting", which is quite straight-forward to understand, as opposed to if (lateForMeeting() == false) which I'd read as "If the fact that I'm late for meeting is false".

They're identical in meaning, but the former is closer to how the equivalent English sentence would be constructed.

kba
  • 976
  • 2
  • 10
  • 19
  • 29
    +1 In Python you actually write `if not late_for_meeting` :) – phunehehe Feb 26 '12 at 13:04
  • 49
    I contend that if "if ___ is false" sounds more natural than "if not ___", then the name of ___ needs improvement. – Mike DeSimone Feb 26 '12 at 17:45
  • 2
    +1. You usually don’t care about the *boolean value*, so you don’t compare with boolean values. You just use the expression and evaluate its trueness. Not to mention that leaving off a direct comparison eliminates the need to care about the expression’s type in many languages. – poke Feb 27 '12 at 01:14
  • 13
    In Perl you can write `unless late_for_meeting` – Henrik Ripa Feb 27 '12 at 07:21
  • 7
    @HenrikRipa: It seems like just about anything you can type is legal code in Perl. Whether or not it does what you want is another question ;) – Adam Robinson Feb 27 '12 at 13:22
  • How would you write this. if (!notDone), if not not done? is this natural too? This is easier to read, if not done is false. – A-Cube Feb 27 '12 at 15:28
  • 5
    @A-Cube I wouldn't have a method like that to begin with. Instead, I'd have a method called `done()`. Double negatives are bad. – kba Feb 27 '12 at 15:34
  • Yes, but its my company, and you are just a guy who maintains the code and add new modules, which was written in the 1990s, either you check and rewrite 2000,000 lines of code or you do what I recommend! – A-Cube Feb 27 '12 at 15:44
  • This is not a method, its a boolean variable. – A-Cube Feb 27 '12 at 15:45
  • 5
    @A-Cube Are you saying that `if (notDone == false)` is any more understandable? If anything it's even more confusing. The condition needs to be `if (notDone)` or `if (!done)`, a double negative is *always* confusing. – deceze Feb 28 '12 at 11:33
  • Well you're ignoring the fact that there is a concrete technical reason for why `==` comparisons with booleans are discouraged... namely the fact that it is dangerous in C and C++ – daniel gratzer Mar 01 '12 at 00:43
  • @phunehehe You can write that in C/C++, too. https://en.wikipedia.org/wiki/C_alternative_tokens – endolith Oct 27 '16 at 18:44
  • I prefer the *yoda style* `if (false == lateForMeeting())`, because the `!` may be overseen so easily. This may look strange, but after some time, I got used to it. Otherwise to make it better English, you could add a method `isInTimeForMeeting()` or `isLateForMeeting()`. Having the prefix `is`, `has`, `can` makes it clear it returns a boolean. – Markus Zeller Feb 15 '23 at 16:33
105

Writing == false and == true is redundant. It can be taken to arbitrary extremes, too. If you start writing

if (condition == false) { ... }

Then why not

if ((condition == false) == true) { ... }

Or why not

if ((someExp == anotherExp) == true) { ... }

The moral of this story is that if condition is a boolean expression, then you don't need to add == false; that's what operator ! is for ;)

Deduplicator
  • 8,591
  • 5
  • 31
  • 50
Andres F.
  • 5,119
  • 2
  • 29
  • 41
  • Didn't think of this! – ell Feb 25 '12 at 21:40
  • 64
    `== false` is NOT redundant, just more verbose than `!`. OTOH, `== true` is redundant. – dan04 Feb 25 '12 at 23:44
  • Exactly. Very well said. – Kevin Wang Feb 26 '12 at 00:39
  • 4
    @dan04 You're right. However, in the sense I meant it, it remains a bad idea. Consider `(exp1 != exp2)` vs `((exp1 == exp2) == false)`. Admittedly, these are contrived scenarios, but still you should almost never write explicit comparisons to true or false. Just as you should use operator `!=`, so you should use `!`. – Andres F. Feb 26 '12 at 04:56
  • 27
    @dan04: It is redundant when the language already offers `!`. – DeadMG Feb 26 '12 at 07:19
  • 6
    @dan04: Any time you write `bool_expression == bool_literal`, the `== ...` is redundant. Whether you're testing for true or false is irrelevant. It's just a change in the order of the consequent/alternative blocks. Andres' examples illustrate this point perfectly. Most modern compilers will optimize away the redundancy, but it's still redundant. – Lèse majesté Feb 27 '12 at 10:40
  • `if (!!condition)` – Fabio Feb 19 '20 at 02:41
84

In C and some similar languages, comparing boolean expressions for equality to false or true is a dangerous habit.

In C any scalar expression (numeric or pointer) can be used in a boolean context, for example as the condition of an if statement. The C rule is that if (cond) is equivalent to if (cond != 0) -- i.e., zero is false, and any non-zero value is true. If cond is of pointer type, 0 is treated as a null pointer constant; if (ptr) means if (ptr != NULL).

This means that

if (cond)

and

if (cond == true)

do not mean the same thing. The first is true if cond is non-zero; the second is true only if it's equal to true, which in C (if you have #include <stdbool.h>) is simply 1.

For example, the isdigit() function declared in <ctype.h> returns an int value: non-zero if the argument is a digit, 0 if it isn't a digit. It can return 42 to indicate that the condition is true. Comparing 42 == true will fail.

It happens that 0 is the only value considered to be false, so comparison for equality to false will work; if (!cond) and if (cond == false) do the same thing. But if you're going to take advantage of that, you have to remember that comparing to false is ok, and comparing to true is not. Worse yet, comparing to true will work most of the time (for example, the equality and relational operators always yield either 0 or 1). This means that any bugs you introduce by using this still could be difficult to track down. (Don't worry, they'll show up as soon as you demo the code to an important client.)

C++ has slightly different rules; for example, its bool type is a bit more tightly integrated into the language, and if (cond) converts cond to type bool. But the effect is (mostly) the same.

Some other languages have what one might call better behaved booleans, such that cond == true and cond == false (or whatever the syntax happens to be) is safe. Even so, every language I've seen has a not or ! operator; it's there, so you might as well use it. Using cond == false rather than !cond or not cond does not, in my opinion, improve readability. (It's true that the ! character can be difficult to see at a glance; I sometimes add a space after the ! to avoid this.)

And often you can avoid the issue and improve clarity by rearranging the code slightly. For example, rather than:

if (!cond) {
    do_this();
}
else {
    do_that();
}

you might write:

if (cond) {
    do_that();
}
else {
    do_this();
}

That's not always better, but it doesn't hurt to look for opportunities where it is.

Summary: In C and C++, equality comparisons to true and false are dangerous, overly verbose, and poor style. In many other languages, such comparisons might not be dangerous, but they're still overly verbose and poor style.

Keith Thompson
  • 6,402
  • 2
  • 29
  • 35
  • 1
    +1 for this being the one answer with the actual useful technical explanation. – Mike Nakis Feb 26 '12 at 10:19
  • I still think this way, regardless of programming language I always assume that `== true` is unsafe. Feels better that way. – Dervall Feb 26 '12 at 12:06
  • 1
    @Dervall: assuming something that's simply not the case is also no good. There are a few corner cases in certain languages where equality comparison of booleans is not only safe but in fact appropriate, for instance in Haskell, which has a strong implicit-cast-free type system with bidirectional type inference, one might write `(==True) . f` to clarify that we want the `-> Bool` instantiation of the return-polymorphic function `f`. That's clearer than `not . not . f` and less awkward than `(f :: a -> Bool)`. – leftaroundabout Feb 27 '12 at 12:48
  • Also, it's certainly appropriate to do stuff like `pred(x)==pred(y)` for a bool-returning function `pred`. The alternative would be `pred(x)? pred(y) : !pred(y)` which you will agree is hardly acceptable. – leftaroundabout Feb 27 '12 at 12:50
  • 1
    @leftaroundabout: That's fine if you know that `pred(x)` and `pred(y)` use the same value to denote truth, which is a safe assumption in some languages but not in others. In C, for example, you might write `!!pred(x) == !!pred(y)`. – Keith Thompson Feb 27 '12 at 18:36
  • [Citation Needed] re: unsafe in C++. C++'s `true` and `false` are, as you say, actual boolean values, which means anything else that can be converted to a boolean (i.e. used with `!`) is going to be safely comparable to those literals. – KRyan Nov 29 '15 at 14:38
  • @KRyan: That doesn't appear to be correct. This: `std::cout << (2 == true ? "yes\n" : "no\n");` prints `no`. The usual arithmetic conversions don't convert `int` to `bool`. – Keith Thompson Nov 30 '15 at 08:12
  • 2
    @KRyan: Equality comparison to `false` happens to be "safe", since `0` is the only "false" value -- but it's IMHO better to avoid equality comparison to either `true` or `false` in general. – Keith Thompson Nov 30 '15 at 21:59
18

The two are functionally identical, so which one to use is a matter of taste.

The major reason that I use == false is that I have found that !is too easy to overlook, when looking at code.

Having been bitten severely by this, I've made a habit of making it very clear when testing for false.


Had the operator been named not as in Pascal, I do not think this would have become an issue.

  • 8
    For this very reason, a C++ project I worked on for some medical device software had a coding standard which mandated `== false` instead of `!` for this same reason (to make it stand out). However there was no requirement to use `== true`, so any non-zero value still worked as it should. – tcrosley Feb 26 '12 at 00:43
  • 14
    I've always found this argument unconvincing - there are other places in C/C++/C#/Java/etc where failing to see a single character has a similarly significant impact on the interpretation of the code; singling out "!" as the only bad one doesn't make sense to me. – Bevan Feb 27 '12 at 08:18
  • 6
    @bevan Apparently you have not been bitten yet. –  Feb 27 '12 at 11:46
  • 2
    While I agree that overlooking `!` is probably the most troublesome mistake of this kind, this should IMO not give rise to making a habit of writing `==false` but of writing better unit tests. – leftaroundabout Feb 27 '12 at 13:04
  • 8
    @ThorbjørnRavnAndersen Quite the reverse - I've been bitten often enough over the years that I've taught myself to *read every character*. I'm not the author of all (or even most) of the code I have to read day to day, so any personal convention as we're discussing here has minimal value: I need to correctly understand *all* the code I read, not just the stuff I've written. – Bevan Feb 27 '12 at 18:00
  • 1
    @Bevan if the code you need to read on a day to day basis is not hidden behind an API, then it should either 1) be put behind an API or 2) fixed. –  Feb 28 '12 at 15:32
  • @leftaroundabout so you want to write a lot of tests instead? Now where is the real effort spent? –  Feb 28 '12 at 15:32
  • 1
    @ThorbjørnRavnAndersen is there really an "instead" here? There are plenty of other errors which are found by unit tests, making them worth the effort; and missing `!`s are a kind of error that, because it's so severe and always changes the result to the _opposite_ whenever evaluated at all, should become obvious in most of these tests. – leftaroundabout Feb 28 '12 at 18:08
  • "Had the operator been named `not` as in Pascal" Just `#include ` [and you can use `not`](https://en.wikipedia.org/wiki/C_alternative_tokens). – endolith Oct 27 '16 at 19:23
  • in C and C++ languages it's sometime useful to check if a binary value has a bit set. Then you can write ``if (binary_value & THE_BIT)`` to check if THE_BIT is set but you cannot write ``if ((binary_value & THE_BIT) == true)``. Therefore, taking the habit of comparing something to ``true`` or ``TRUE`` is dangerous. By extension, comparing against ``false`` or ``FALSE`` while normally OK, is not a good idea becuase then you might be tempted to comapre against a true value. – PRouleau Jul 23 '23 at 18:53
14

If condition == false is indeed “much more natural in English” for you then I must assume that you are not a native speaker. Otherwise I cannot explain this, because nobody speaks like that:

If the sun is shining is false I stay at home.

Compare that to

If the sun is not shining I stay at home.

That said, I agree that the single, slender ! character is easily overlooked in code. For that reason, I prefer the keyword not when supported by the language. C++ for instance does allow this although many programmers are not aware of it.

For languages that require !, I put a space between operator and operand. This makes the negation much harder to overlook:

if (! condition) { … }

Notice that every programmer should translate this automatically, without second thought, to “not condition” in their head. Acquiring this kind of fluency in reading code idioms is among the first steps in becoming a good programmer.

Deduplicator
  • 8,591
  • 5
  • 31
  • 50
Konrad Rudolph
  • 13,059
  • 4
  • 55
  • 75
  • 2
    the problem with your analogy is that you can't split 'the sun' and 'shining' and insert a not in the middle. correct comparison would be 'if not the sun shining i stay home' which, if you're not yoda, you'd never say in english. – controlbox Oct 05 '20 at 09:31
  • @controlbox This isn’t a *problem* with my analogy. But, like all analogies, it is limited and when you try to take it too far, it breaks. The point of the analogy (and for which is completely sufficient) is that it makes no sense in boolean algebra to add a comparison to a literal. It neither adds clarity nor reads naturally when “translated” into English. – Konrad Rudolph Oct 05 '20 at 09:40
  • Do you happen to know if there's a editorconfig rule for the extra whitespace after _!_ ? – janv8000 Sep 30 '22 at 07:07
8

because sometimes you might write boolean = false (with the obvious errors) and false == boolean doesn't seem natural (no matter how good of a practice it is)

ratchet freak
  • 25,706
  • 2
  • 62
  • 97
  • 1
    A long time ago when I first started programming, a mentor of mine suggested I get in the habit of doing `if( INVALID_HANDLE_VALUE == hFile )` to avoid things like that. That way if you slip up and use one equals sign instead of two, you'll get a compiler error. Obviously this only works when the left-expression is a constant, but it has saved me more head-aches than I can count. – Drew Chapin Feb 26 '12 at 03:07
  • if you use a static analysis tool, it would save you hundred times more head-aches, and you are able to restore the nature `hFile==INVALID_HANDLE_VALUE` writing. – Gqqnbig Jul 10 '18 at 23:04
7

When I see var == false I always wonder whether var is boolean or of a logic type with more than two values (with, for example, a maybe and an undefined as well as true and false, or something like the nine values of IEEE 1164).

TRiG
  • 1,170
  • 1
  • 11
  • 21
AProgrammer
  • 10,404
  • 1
  • 30
  • 45
  • 9
    The 3rd value is usually "File not found". http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx – Groky Feb 26 '12 at 01:29
4

if (!boolean_variable) translates to if the condition is not true.

if (boolean == false) translates to if the condition not false is true. Because that is inversed logic, it is harder to understand.

BЈовић
  • 13,981
  • 8
  • 61
  • 81
  • 3
    !true means not true. !boolean means either not false *or* not true depending on the value of the boolean, which itself is logical inversion. – S.Robins Feb 26 '12 at 00:53
  • 1
    @S.Robins I find stupid name of boolean for a boolean variable. Something like for example `isVisible` would be a better example. Then `if (!isVisible)` would mean if not visible - which is simpler to understand then `if (isVisible==false)`, which is an inverse logic. Hope it's clearer now. Or, did I misunderstood your comment? – BЈовић Feb 26 '12 at 01:02
  • you are inserting the 'not' where it can't actually go to suit your argument. your first example translates to 'if not the condition is true'. – controlbox Oct 05 '20 at 09:37
3

In (much) older compilers, I believe they would break (boolean == false) into 2 register assignments and a compare code in machine language. The first example would be broken into one assignment and a NOT operator. In terms of performance, the compare operation would take a number of clock cycles, depending on the size of the register being compared, compared to a bitwise invert (1 clock) and would be slower to execute.

That being said, I believe newer compilers do away with this, so it should be OK to go with either.

lcllam
  • 1
  • 1
  • Generating machine code is the compiler's job, not the high-level-language programmer's... – user Feb 27 '12 at 09:34
  • For historical reasons, this may very well be one of the reasons one method became preferred over the other. – Legolas Feb 27 '12 at 13:43
1

When you're testing the true condition, it makes sense to do just if (condition), especially when you apply the convention of naming boolean variables beginning with 'is': if (isOpen) is perfectly clear and using != false would be redundant.

For a C/C++/Java/etc. programmer, the meaning of the '!' operator is completely assimilated, to the point that we automatically have 'not' in our minds when we see it. So having if (!isOpen) is as clear as if (_NOT_ isOpen) for me. But you're not familiar enough, in C/C++ you could create a macro with #define _NOT_ !. But trust me, after a few years this is completely unnecessary.

Aside that, it's always preferable to test boolean values without comparing them with literals. For instance, it's dangerous to test if (x == true) because a boolean value is considered true if it's not zero, and the literal true has just one specific value, so x could be 'true' (i.e. nonzero) and still the comparision evaluate to false (because it contains 2 and the literal true is, say, 1.) Of course that doesn't apply to a comparision with false, but if you don't use it when testing for true, why use it when testing for false?

Fabio Ceconello
  • 831
  • 6
  • 7
  • It's not necessary to make the C++ macro you propose as C++ already understands 'not'. Related: http://stackoverflow.com/questions/2393673/c-and-or-not-xor-keywords – frozenkoi Feb 26 '12 at 20:34
  • That's true, but it's a keyword for the C++ 0X standard only. Before that, it was just another macro. – Fabio Ceconello Feb 26 '12 at 23:24
0

At work I often am dealing with Booleans which can be null so I'll often code this case as

if (value != null && value == true) {
        //do something
}

because I personally feel the symmetry makes it easier to read. Especially if there are other Booleans being tested as well.

I don't really care one way or the other.

Deduplicator
  • 8,591
  • 5
  • 31
  • 50
WuHoUnited
  • 1,400
  • 1
  • 9
  • 13
  • 5
    if `value == true` then there's no reason to check that it's not null. If the `value == null` it should never trigger the if statement in the first place, so `if (value)` should be sufficient. – zzzzBov Feb 25 '12 at 22:27
  • 2
    Booleans are objects (in java) and can therefore be null so just saying `if (value)` throws an exception. I'd appreciate it if people who downvote give a reason. – WuHoUnited Feb 26 '12 at 04:16
  • 3
    I just happen to see this, didnt downvote. Boolean null is not good practice. Why? because boolean usually represents a state of something turned on on off. In most cases you would want to declare it false at the beginning and then change it along with behaviour. It is very uncommon to see boolean not being initialised. – Aubergine Feb 26 '12 at 05:18
  • I have to agree with Aubergine here, I myself have fallen into the bad habit (especially in Java) of leaving bools uninitialized and then end up checking for null. I think this is more of a flaw of the language, however which imposes that flaw on the user. When declaring a new bool variable it should default to false without initialization in my opinion. –  Feb 26 '12 at 11:39
  • In my situation null Booleans are pretty much always coming from a database without a not null constraint. If it were up to me I'd add the constraint or default the value to 0/1 accordingly, but I can't. – WuHoUnited Feb 26 '12 at 15:02
  • 2
    @WuHoUnited, even if the value was null, `value == true` would be sufficient. – zzzzBov Feb 27 '12 at 04:49
  • In some languages like javascript `null == true` is sufficient. In other languages like java, it will throw an exception. – WuHoUnited Feb 28 '12 at 00:40
  • @zzzzBov In Java if the value is null `value == true` is NOT sufficient because the program throws an exception. See https://onlinegdb.com/rkpAcXsm8 for examples. The answer specifically says that he is using "Booleans" which makes it definitely Java so I am confused why you think otherwise. – Jerry Jeremiah Feb 19 '20 at 21:41
  • In Swift, if (value) for value of type optional bool is not allowed (anymore). The language used to allow if (x) as a nil check for optionals. Then they figured out that for optional bool wit value false the “if” would be executed which is a big trap. – gnasher729 Aug 30 '21 at 11:26
0

Size matters ;)

In mixed expressions it is easier to read:

boolean1 = false
boolean2 = true

p ! boolean1 and ! boolean2
p boolean1 == false and boolean2 == false

And especial for ruby an example where it is a big difference:

boolean = nil
p ! boolean         #-> true
p boolean == false  #-> false

nil is not false, but it is also not true.

knut
  • 1,398
  • 1
  • 10
  • 16
0

Based from my experience and the answers from my quesion that you have linked to.

Some people prefer to use if(condition), for the reason is that one it is shorter to write. and for me it actually makes sense, for example (! isValidated()) I read this as Not Validated. but for me it's all based on personal preferences, and it depends on the logical structure of isValidated() method, if it either returns true or false

KyelJmD
  • 971
  • 5
  • 10
  • 20
  • I don't think it should be based on personal preference; it should be based on the understanding of the nitty gritty details of the programming language you use. Explicitly comparing against ``true`` or ``TRUE`` in C or C++ can generate invalid code. For example: ``if (binary_value & BITMASK))`` can be used to check if any of the bits in BITMASK are set in the binary_value variable. But if you write ``if ((binary_value & BITMASK) == TRUE)`` then the expression will work only for the bit in the TRUE value, and it's not the intent. – PRouleau Jul 23 '23 at 18:59
0

If you named your variable properly, then !boolean is more natural. It reads as not boolean to anyone who's enough of a programmer to read code mentally.

Lightness Races in Orbit
  • 8,755
  • 3
  • 41
  • 45
0

For some folks, the sooner a meaning is expressed the better.

For those folks having "if ! ..." compares faster to "if ..." then having to read through the entire condition (which could actually be pretty long, e.g. (thisThing = thatThing or something = the other thing) OR (thinga = thingb and thinga = thingd), etc.) just to find the ==false at the end.

Having the ! (I actually prefer a not when the language allows it) right up front gets the english 'not' for this condition in there sooner.

This issue also leads to consideration for using until in languages that support it, e.g. do 'common stuff' until thing completes. As others say, natural language expression is the goal. I like the "sun is shining" example above.

junky
  • 840
  • 5
  • 12
0

Another reason is that if you are working in a codebase that uses several languages, if there's one idiomatic way to do something that's safe in all of the languages, it's a pretty good idea to do it that way everywhere so that you form a good habit and are less likely to trip up.

I can't think of anywhere that if (!variable) (or equivalents such as if not variable depending on your language) is not safe, whereas e.g. if self.is_ready() == False: ... is not safe in python if self.is_ready() returns None, now or in the future, which would be a totally reasonable thing for it to do to indicate it wasn't ready since None is just as falsey as False.

daphtdazz
  • 101
  • 3
0

In newer languages, like Swift, you have “optional” types, including “optional bool”. An optional bool has values false, true, or nil. In that case, an explicit comparison gives exactly what you ask for. x == false tells you x is false, not true or nil. x != true tells you that x is not true, but either false or nil.

So in Swift, x == false would catch attention, because I will automatically assume that x might be nil.

gnasher729
  • 42,090
  • 4
  • 59
  • 119