• (nodebb)

    if ( booleanvaluedthing == true )is epically awful when it is in C:

    if ( booleanvaluedthing == TRUE ) ==> what happens if the boolean-valued thing is 3? It isn't false, but it will be treated as false by this test - TRUE is almost always #defined in a way that makes it 1.

    And no, inverting the comparison and making it compare against FALSE isn't right either.

  • ray10k (unregistered)

    To me, stutter-comparisons are just one of those things you encounter from time to time. Everyone that I know of had some period of time where they were learning the ropes, and would write some conditional fitting the (bool == true) format. Still, this is almost prank-levels dense.

  • Oliver Jones (google)

    This is the 21st century. Decent IDEs warn about this kind of nonsense and offer to correct it. New programmers can stand on the shoulders of--crowdsurf--the tall people who have gone before.

    And decent compilers (combined with decent languages) make it vanish.

    IDE Autocorrect? No. IDE Find next problem? Yes.

  • (nodebb)

    Unless a Boolean is implemented as a single bit, there are possible values which are equal to neither true nor false. The there are cases where explicit comparison of a variable to (at least one) the constant value can yield different results than the implicit.

    As to the separated return, this is a handy way to be able to easily set a debugger breakpoint. For many implementations a fully optimized build will eliminate the redundancy.

  • someone (unregistered) in reply to Steve_The_Cynic

    "Epically" or "especially"?

  • Yes, but... (unregistered)

    The if(booleanValue == true) syntaxe actually have an explanation that makes sense : Readability.

    It is easier to make a quick visual distinction between if(booleanValue == true) and if(booleanValue == false) than between if(booleanValue) and if(!booleanValue). And so, it is easier to avoid buggy code that can be kind hard to identify.

    Anyway, I have to agree that "if (booleanValue == true) return true" is total non-sens.

  • Drak (unregistered)

    if ( booleanvaluedfunction() == true ) is exceptionally clear. If you are doing a code review of only a specific file and have no fancy IDE help to tell you that the function returns a boolean, this way you know that the intention is that it returns a boolean, and not just a pointer-to-something.

  • Brian (unregistered) in reply to Drak

    That's where good variable naming conventions come into play. If your bool variables & functions are named sensibly, the code becomes clear and self-documenting. Conversely, if they're name non-sensibly, even an explicit comparison is difficult to understand.

    example: "if (Thingy.IsValid()) ... " vs. "if (Thingy.Get() == true) ..."

  • MIBman (unregistered)

    This is extra fun when dealing with SNMP booleans where true is 1 and false is 2. Because of course it is...

  • (nodebb) in reply to Yes, but...
    if (boolval) return true;
    makes sense when you want finish this function if everything has worked so far. If not, you have have some sort of oops-recovery in the following code that should only be executed if earlier stuff failed/indicated a problem, etc. The other way of handling it would be to have a big block of
    if (!boolval) // skip it above stuff worked.
    {
    ...
    }
  • masseyis (unregistered)

    Oh no! And they've gone and lost the type checking. This is pretty close to my nails-blackboard Java antipattern if(SomeEnum.Value.equals(AnotherEnum.Value)) -- never true, but using == would have had the compiler tell you that.

  • (nodebb) in reply to someone

    Epically.

  • 🤷 (unregistered)

    I recently developed the habit of writing

    if (booleanValueThingy == false)

    after spending a few hours on some code where I wondered why it doesn't do what it is supposed to be doing... and then realized I missed a tiny littly "!" in front of a rather complex if statement.

    if (booleanValueThingy == true)

    can be helpful in this regard, too. However, if you train your dev's to always write "== false" when checking for false, there's no need to check for true. Either, the "false" is present or not, in which case we check for true. Or, to put it in different terms:

    if (ifStatement.Contains("false")) return checkForFalse = true;
    else return checkForFalse = false;
    

    Hopefully some people are biting their keyboard now. :P

  • RandomStranger (unregistered)

    I've used the "if (Boolean.TRUE.equals(...)) {...}" idiom myself before, because when the thing of which you want to know the "true-ness" is of type "Boolean" (which may be null) just doing an "if (someBoolean) {...}" can throw a NPE, and "if (someBoolean != null && someBoolean) {...}" is even uglier, IMO.

  • Java twist (unregistered)

    This may not be a WTF if the function returns a Boolean value (the java Object version of a boolean), as it may be Boolean.TRUE, Boolean.FALSE or null. If that is the case the code is NPE-safe and equivalent to those (uglier) 2 lines :

    Boolean nullableBoolean = functionReturningBooleat(pa, isUpdateNetRevenue); if(nullableBoolean != null && nullableBoolean) {…}

  • Harrow (unregistered)

    New interview question: say "nullableBoolean" ten times real fast.

  • giammin (unregistered)

    fluent-like syntax is more readable LMAO

  • .Net Dude (unregistered)

    For sure the punchline here is that in most languages the official Boolean datatype isn't a single bit and so has four possible value categories: null, exactly true, exactly false, all other non-null values.

    The [null] case should always be interpreted as unknown / unknowable. By definition, once your code gets to the null case, you have undefined internal state and there's not much you can correctly do except shut down. Though often bool-valued functions return null to mean something else, in which case you can safely proceed. Provided you know exactly what circumstances return that null to mean that something else. Good luck with that.

    The [all other non-null values] case can be interpreted as either true or false depending on both the language conventions, and more scarily, how you construct the value test.

    This corner-case intricacy is not well-appreciated by a lot of devs and API designers. If you work in multiple languages it gets worse. In weakly typed languages (including C) it gets even worse than that; you may not be able to actually know which convention the API designer applied except by testing = reverse engineering. Which amounts to taking a dependency on undocumented implementation details.

    In all, the problem for us in the WTF audience is deciding whether the example code's author understood none of this and was just slinging ignorant garbage at the compiler, or understood all of it and was coding for deep correctness, not shallow correctness.

    ==== As CPUWizard mentioned I've used the idiom if (BoolValue) return true else return false

    simply as a way to be able to set breakpoints on the two separate cases. Yes, conditional breakpoints are available in any modern debugger.

  • Drak (unregistered) in reply to Brian

    But what if your function could also return file_not_found? There are cases were validity could be an enumeration of something like 'valid', 'invalid', 'unknown'. In that case the nice function name could be misleading.

  • Jimmy Smitts (unregistered) in reply to Harrow

    I tried this while looking in the mirror and the ghost of my Data Structures teacher appeared and slapped me.

  • GDB fan (unregistered) in reply to TheCPUWizard
    TheCPUWizard:
    As to the separated return, this is a handy way to be able to easily set a debugger breakpoint.

    Or you could just use a break ... if .

  • Object delete. (unregistered)

    if (b == true) return true; else return false; is better than return b; ? if ((b == true) != false) return true == true; else false != false; must be even better!

  • Ducky (unregistered) in reply to Steve_The_Cynic

    Re: booleanvaluedthing == true in C

    Actually, that depends on the platform you're on, and the version of the language we're talking about.

    There used to be specific architectures that #defined TRUE and FALSE "backwards" -- where FALSE was 1 and TRUE was 0. So, you'd have to do "BoolThing == FALSE" to be sure you're doing the right thing on that platform.

  • Baboon (unregistered) in reply to RandomStranger

    Totally agree - without seeing the method that's being called it's hard to see if it's a real WTF - it could be they are calling out to a third party API or not

  • Pedantic Panda (unregistered)

    I actually wrote that line of code, thank you. I can't believe my own code shows up here.

    The SOAP service due to the way the CXF binding works returns Boolean (wsdl2java outputs the code that way). In fact the old code was just if(x), and were the service to return null, null pointer exception occurs. The Boolean.TRUE.equals fixes that. I figured it was more readable than the alternative that places the call into a temporary variable (calling the function twice is not a reasonable option to keep it one line as it is a SOAP call). If there is any issue here it is that the SOAP method returns true/false instead of a SOAP fault message.

    I use this pattern commonly to convert a Boolean into a boolean in a null-safe way, especially when processing foreign JSON documents or HTTP get query parameters bound to objects -- the DTO uses Boolean to allow a parameter to be unspecified (not exactly a "tri-state" boolean which is another WTF theme ... I know ..., then you interpret missing (null) parameter from JSON/HTTP GET as false, and false as false. As far as I know, boolean checkedParam = Boolean.TRUE.equals(json.foreignParam) is a perfectly fine approach to this? I suppose for a variable you can do checkedParam = json.foreignParam != null ? json.foreignParam : false. I don't think that's inherently more readable, though.

  • Sole Purpose of Visit (unregistered)

    Given a strict enough type system (and God knows, booleans cry out for a strict type system), all of the discussion above is pretty much moot. You want a tri-state or an "integer which isn't zero?" Use the appropriate type. Which in this case would, indeed, involve an if-else.

    OTOH, being a C-sharpie sort of guy, I'm confused about Remy's description of where the equality operator comes from. If it's boxed, I assume that Java has the moral equivalent of Boolean.Equals. In fact, i'd be very surprised if it didn't.

    If, effectively, unboxed, I would assume that the equivalence operator is by reference, rather than by value. And since the two objects do not have the same reference, the operation would always return false. Which means (I assume) that whatever Java does, it doesn't rely on "inheriting the base equality operator."

    I'm missing something here, aren't I?

  • DrPepper (unregistered)

    I truly despise the C idiom if (!someMethod()) -- too much cognitive load. I'd much rather see if (someMethod() == false).

    And if the variable name is poorly chosen, then comparing a boolean to true or false makes sense to me: if (hasError) { ... } works well;

    whereas if (tempInRange) { ... } is harder to read; I might write that as if (tempInRange == true) { ... }

    Who cares anyway, the compiler will remove that extra comparison for me.

  • Rodney (unregistered)

    Peak Java version would use Spring to inject the classes at run-time.

  • Tom (unregistered)

    Consider in kotlin: val myBool = user?.name // myBool is of type 'Boolean?', aka a nullable boolean if (myBool) // won't compile as if (null) does not make sense if (myBool == true) // compiles (null != true)

  • Olivier (unregistered)

    It seems that TRWTF is people considering boolean could be anything but true or false.

    Call it something else, but don't call that data type boolean if you want your code to remain readable.

  • His Derpiness (unregistered) in reply to masseyis

    My IDE certainly warns about comparing values of different enums like that in Java.

  • His Derpiness (unregistered) in reply to Drak

    If it is not valid, it is invalid. Even more so if the state is unknown. And if a function can return multiple states, it is not a boolean by definition, and a different name than isValid should be used.

  • kirby (unregistered)

    Comparing booleans to true/false is useful and descriptive in a dynamically typed language - it provides a hint as to what the programmer is expecting the variable to be.

    This doesn't excuse this example, or the weird double redundancy in the return statements, of course.

  • HK-47 (unregistered)

    Boolean is not a Boolean if it can be null or file-not-found. Java is a solution looking for a problem.

  • WTFGuy (unregistered) in reply to Olivier

    Ref Olivier - "It seems that TRWTF is people considering boolean could be anything but true or false."

    I don't disagree, but an underlying WTF is that many languages already define their so-called "Boolean" datatype as having more than two states. And once that messy idiom is anywhere in your language, every developer is stuck dealing with how it infiltrates your own code via APIs you consume. As Pendantic Panda (the code author) says, his problem is the API he called can return either null or an actual two-state Boolean, but still labels the result as a Boolean. So he's stuck dealing with a tri-stated Boolean.

    As the great Joel Spoelsky so famously said way back in 2002 https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/ , all abstractions leak. The idea that an actual compiler/interpreter level Boolean reference is always equivalent to the Platonic Form of a single bit is inherently false. The ideal Platonic Form is two-stated; the physical bits in RAM are anything but once you inject all the rest of the layers of complexity, references, objects, addressing, failures, bugs, etc.

  • if-you-smell-what-the-rock-is-cooking (unregistered)

    Junior developers tend to shorten boolean comparisons via ! -- while experienced ones like to expand it to == false. I don't like == true, but it's ok to me as well. Simple as that. I would propose to all language designers to remove that tiny tiny !. It's just stupid to have that thing in code.

    If the article is to make fun of the expression, it failed.

    Without knowing full context when the original developer coded that line, I'm pretty sure it's a perfect expression. I faced same problems a lot of times.

    Now if people read the original developer Pedantic Panda's comment here, you will agree that he's right: https://thedailywtf.com/articles/comments/the-truth-about-comparisons#comment-495537

  • gws (unregistered) in reply to Java twist

    I just recently fixed a defect that was messing with reports - nulls in a bit column. In the application, I re-set the Boolean (boxed Java type, capital B) field doTheThing = (doTheThing == true) to force out nulls before saving to the database.

  • Little Bobby Tables (unregistered)

    "The if (boolean == true) return true; pattern is my personal nails-on-the-chalkboard code block"

    What do you prefer?

    "if (boolean) return true;" is just slightly more streamlined, and can be argued as preferable if you're not too worried about readability.

    Then there's always:

    "if (boolean) return boolean;"

    which, I'm sorry, looks gnomically smartsy.

    You weren't suggesting you can replace it by:

    "return boolean"

    were you?

  • isthisunique (unregistered)

    On the one hand we always hate seeing... return a == true ? true : false; Or the longer variant. However in loosely typed languages it's a bit more complex.

    The might be cases where === false or === true are valid so to rule out other types that might loosely evaluate to true or false.

    If I'm going to be fair to the author of the code shown here then I might assume that this is a quirk that came out of Enums turning out to be booleans or part of a dynamically typed system within a strictly typed OOP language which does sometimes happen and can often be valid. It's questionable if you should use it in code you're writing but they might have figured the type might change later or might not have wanted to be inconsistent.

    More realistically someone has probably been reading GoF and other OOP theoretical discussions and have not understood any of it, naively doing things like object calisthenics all over the code.

  • Zug (unregistered)

    I always quite liked the Alogol68 approach which was that booleans didn't support comparisons. If you wanted to have something like if (flag == true) then you would have to type if (flag.eq.true). This made you think, "why are you doing comparisons on booleans anyway?". Of course if what you're getting back is an object then you really should be pretending that it's a boolean....

Leave a comment on “The Truth About Comparisons”

Log In or post as a guest

Replying to comment #:

« Return to Article