Truthy and Falsy
rzwitserloot posted in programming on November 13th, 2006
A number of languages have a ‘truthy/falsy’ system. Such a system infers on all possible values a notion that they are ‘truthy’ or ‘falsy’ - that they act as boolean true or boolean false if used in a situation where a boolean is needed. For example, Python and Javascript both have ‘truthy’/'falsy’ rules.
I never really thought too much about the notion, but today Oliver pointed out a bug he spent quite some time chasing down which got me thinking.
Truthy/Falsy - what IS the point? Does anyone know?
Oliver’s bug in question looked like this (python):
if checkbox.isSelected:
doStuff
Spot the problem? Yup, that will ALWAYS ‘doStuff’ regardless of the state of the checkbox, because ‘isSelected’ is a function, not a variable. And non-null objects, unless they specifically defined themselves otherwise, are truthy. functions do not have any code in them to somehow be ‘falsy’ if when called they so happen to return false.
In fact, this is simply an overlap in purposes. The (apparent?) reason in this particular case for truthy/falsy is that the ‘truthy’ nature of functions vs. the ‘falsy’ nature of unidentified names allows you to check if a given object has a function available to it. An exists() built-in would be a much better choice though. It highlights exactly what you are trying to do, and it would avoid multi-hour bughunts.
I’ll say it again, folks: Saving yourself 3 keystrokes so that you have a bunch of multi-hour bug hunts to look forward to in the future is bad language design.
Is there any serious application of truthy/falsy besides ‘look pretty’ that I missed?

November 17th, 2006 at 23:48
> Is there any serious application of truthy/falsy?
Yes, anaphoric conditionals in Lisp.
November 21st, 2006 at 21:29
You have pointed out something that has caused jillions of bugs in my own programming career: implicit type conversions.
Most of programming C++ correctly seems to come down to knowing when and how the compiler will manufacture and destroy objects silently as it coerces objects from type to type.
The truthiness problem is a mild version of this affliction. I personally like it, because I often use it for testing existence, as in these Ruby idioms:
foo ||= ‘manchu’
# make foo ‘manchu’ if it is nil
and
foo = bar && bar.to_s || ‘none’
# make foo the value of bar converted to a string if it is not nil. If it is nil, make foo ‘none’.
But I agree that you can get tripped up, and you might prefer being explicit, as in:
foo = bar.nil? ? ‘none’ : ‘bar.to_s