Naming boolean variables

productivity / webdev

Whether you’re naming human babies or variables in code, the struggle is real. Okay, that maybe was a little exaggerated — naming babies is much easier. So, let’s take a look at a naming rule for boolean that most folks follow and is kinda awesome.

Boolean is a data type that says whether an assumption is true or false.

For example, let’s say, you upload, read and save a file (I know, such an original example!). You kinda write the code to save it assuming it has been read fully, correctly and it doesn’t have something fishy in it — Hmmm… let me rephrase that, you write that code after confirming it has been read fully, correctly and so on.

Those assumptions you made have to be tested and the results of those tests almost always dwindle down to their outputs and whether they match what you expected them to. If they didn’t match, the results show your assumptions have failed, otherwise, bring out the champagne 🥂

We often assign the result of checking a test’s output to a boolean variable that takes away any grey area in the result that might haunt you and gives a clear-cut white or black answer. “Yes, it’s true, the file has been fully read.”

So, being thoughtful about naming the boolean variable matters! and the formula I find most simple to form a boolean name is: “is” + [object] + a state. I just may have made that sound more complicated than it is, but I swear it’s simple.

  • A) You begin the name with “is”
  • B) Follow that with an adjective that depicts a state (preferably, a positive state): open, loaded, sent, saved, free…
  • C) An optional noun in between the above two that might tell you what is open, loaded, or sent: isMessageSent, isConnectionOpen, isElementLoaded…

The reason I say C is optional is because if a boolean variable is not global and is scope-bound to a small block of code, it usually is pretty easy to know what the variable is indicating. Suppose a block of code is establishing a connection to a server, a variable name “isOpen” in it would suffice for anyone to understand what is open? the gateway to hell or the connection to the server?

The Author

Web developer and writer. @rpsthecoder in Twitter.