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

1
if $notLoggedIn then

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

1
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.

1
2
3
if $loggedIn then

if ! $loggedIn then

Hide Literals

1
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'
    Or
'Not Toasted'

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

1
if ! $hidden then

A Boolean Flag?

1
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.

1
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 :-

1
if $includeInReport then

Summary

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.

Comments