Skip to main content
Source Link
Job
  • 6.4k
  • 3
  • 34
  • 54

The young know the rules, but the old know the exceptions ;)

In latest C#, if you are dealing with a null-able bool, then you have to:

bool? x = null;
bool? y = true;
bool? z = false;
if (x == true || y == true || z == true) {
    // That was the only way that is reasonably readable that I know of
    // to accomplish this expression.
}

If tristate is not a problem, then there usually should not be a reason to compare something to true/True. However, in Python and several other languages such as C/C++ you can perform an if on a non-bool expression. These languages have unique rules for interpreting integers, pointers, lists, etc. as either true or false. Sometime you do not want that. For example, in this Python snippet:

x = True
y = 'abcdef'
z1 = x and y
z2 = (x == True) and (y == True)

Here z should be True, but z2 should be False. Now, a Clojure language approaches this in yet another way - there and function does not necessarily evaluate to a bool, but the if can handle that.

Regardless of the language, any time you find yourself comparing something to True or False, it is probably worth commenting.

Post Made Community Wiki