The Data Asylum

Programming, Databases and People

Speak the Truth

Improper uses of Booleans causes headaches for people who are reviewing your code. Lets take a look at some good, and not so good uses.

Don’t be negative

if $notLoggedIn then

Looks simple and readable right? Wrong. It's one step away from being misused.

if ! $notLoggedin then

Not not logged in. Double negatives are a gotcha in language and coding and should be avoided. Fortunately the solution is an easy one. Remove the negative prefix (such as not, doNot, dont) from the variable name.

if $loggedIn then

if ! $loggedIn then

Hide Literals

if $hidden == false then

Is it really necessary to compare the variable to false? Imagine this conversation.

You are at Subway and they ask you
'Would you like your sandwich toasted?'
Would you reply with
'Toasted equals false'
'Not Toasted'

Avoid comparing with a literal true or false. The correct way to express this is :-

if ! $hidden then

A Boolean Flag?

if $reportFlag then

$reportFlag is a little vague. In this case it is determining if an object is included in a report. So if $reportFlag is true, does that mean that the object is included or excluded? If you have to ask yourself the question then you have already failed and need to rethink what this variable should be called.

if $report then

This is okay as long we are using the word ‘report’ as a verb. ‘If we report this then’ is how you would read this. Some people may not be able to make that leap so if you want to be more precise you could make it :-

if $includeInReport then


So to sum up, these three things will go a long way to making your code readable.

  • Remove the negative prefix (such as not, doNot, dont) from variable names.
  • Avoid comparing with a literal true or false.
  • Avoid vague terms like flag for Boolean values.

Consider these ideas when choosing

  • Variable names
  • Object properties
  • Database field names
  • Method or function parameter names

Anything Else?

Is there something i’ve missed? A hole you could drive a double-decker bus through? Leave a comment below.