loading...

Tips on naming boolean variables - Cleaner Code

michi profile image Michael Z Updated on ใƒป2 min read

Originally posted at michaelzanggl.com. Subscribe to my newsletter to never miss out on new content.

There is a convention to prefix boolean variables and function names with "is" or "has". You know, something like isLoggedIn, hasAccess or things like that.

But throughout my career I have seen and written code where this convention was just thrown out the window. So let's check out some of these edge cases.

As with all rules, there are exceptions and it might be better to go with that rather than enforcing a convention.

Boolean that verifies that every case is true

const XXX = users.every(user => user.isActive)

XXX will only be true if every user is active. How could we name the variable?

variable Any good? Reason
isUsersLoggedIn ๐Ÿคจ Grammatically incorrect
areUsersLoggedIn ๐Ÿค” Custom prefix
isEveryUserLoggedIn ๐Ÿ‘ Fits with Array.prototype.every
isEachUserLoggedIn ๐Ÿฅฐ Comes off more natural than "every" (depends)

Boolean that verifies that one of many cases is true

const XXX = users.some(user => user.isActive)

XXX will only be true if at least one user is active.

variable Any Good? Reason
isUsersActive ๐Ÿ™ Grammatically incorrect & ambiguous
isAtLeastOneUserActive ๐Ÿ˜ต Too wordy
isOneUserActive ๐Ÿคฅ Lie. This could imply that there is only one user active. Avoid confusion!!!
isSomeUserActive ๐Ÿ‘ Fits with Array.prototype.some
isAnyUserActive ๐Ÿค— Comes off more natural than "some" (depends)

Avoid custom prefixes

We covered this in one of the examples before already, but there are more...

variable Any good? Reason
wasPaidFor ๐Ÿค” Custom prefix
paidFor ๐Ÿ˜ฃ No prefix
areBillsPaidFor ๐Ÿค” Custom prefix
hadHaveHadBeenPaidFor ๐Ÿ˜ถ Ok, I'm just joking at this point
isPaidFor ๐Ÿ˜Š

Affirmative names

variable Any good? Reason
isDisabled ๐Ÿง Negative
isNotActive ๐Ÿคฏ Just imagine !isNotActive
hasNoBillingAddress ๐Ÿ˜ž No need for "no"
isEnabled / isActive / hasBillingAddress ๐Ÿ˜ And use it like this !isActive to get the negative

The problem with negative variable names becomes most apparent when you have something like this

if (!account.isDisabled) {
  // ...
}

Just see how much easier this reads

if (account.isEnabled) {
  // ...
}

Finally let's take a look at a more complex example.

const isAnyUserOffline = users.some(user => !user.isOnline)

if (isAnyUserOffline) {
  // ...
}

While this works, because of the combination of some and !, it just takes a little more brain power to process this code. An alternative would be:

const isEveryUserOnline = users.every(user => user.isOnline)

if (!isEveryUserOnline) {
  // ...
}

It behaves the same and as long as the data set is small enough I would not worry about the small performance impact.


I am sure there is a lot I missed, but I think these are some of the more common cases.

Posted on Oct 3 '19 by:

Discussion

markdown guide
 

isGrammaticallyIncorrect

I think this is cultural, I'm a dyslexic programmer from the south west of englind, a place with its own dilect, where "dibber" and "doofer" exist to fill in the names of things we can't remember the name of. A variable assistant if you will. I am fine with the first of each. What I am not fine with is this program not working.

 

if (!hasDibberInDoofer)

I love it!

 

Shall I use it in a sentence.

Wife of mine: "pass me the doofer"

Me: ๐Ÿฅบ

Wife of mine: "you know that doofer over there" (she doesn't point)

Me: bring an assortment of just about anything in reach.

Wife of mine: "for god sake, do I have to do everything myself"

Me: ๐Ÿ˜ค๐Ÿคฆโ€โ™‚๏ธ๐Ÿšถ

So there you go, never visit Bristol, it's confusing just like naming variables.

 

You my friend have invented the new foo bar!

 

This whole naming of booleans is one of the simplest yet most misunderstood conventions in programming.

You seem to be a proponent of naming booleans as affirmative statements, yet you name your booleans as questions. This seems contradictory to me.

isEveryUserOnline? Is he? I don't know, maybe? Are you asking me? Or is anyone standing behind me? Why is code talking to me and making me decide? Code is a set of commands. It answers questions. It doesn't ask them.

Purely linguistically, you don't say "If am I a developer". You say "If I am a developer".

Your isEveryUserOnline variable should be named everyUserIsOnline or allUsersAreOnline. This would truly be affirmative, according to your own standard. This will also read well in English and go well with order of words when using dot notation. Compare:

bool userIsActive = user.isActive (word order preserved)
bool isUserActive = user.IsActive (re-arranged, statement suddenly became a question)

In short: good (although cumbersome) standards but wrong interpretation of them. The only standard you really need for booleans is an affirmative statement that evaluates to either true or false. That's it. Is, are, has, was, did, has been, will, should, must, can, wants, beats, is extrapolating, will have been jeopardized: all just flavors.

As for prefixing for the sake of prefixing, I thought that was called Hungarian notation and is more or less dead, with a few relics still roaming the Earth.

Hope this helps,
Cheers

 

I mostly agree with you that code readability should be one of the #1 priorities, but at the tend of the day it depends on the context -- also the whole "when in rome" thing.

I'll give you just another perspective: in my situation, I don't use Typescript at my every-day-work, so things are weakly typed, and the IDE auto-prediction works relatively well with VSCode.

Because of that, using is/has/should gives several benefits (magnified in a weakly typed language):
-> auto-prediction is actually very helpful when there's no ESDoc annotation written in common code.
-> consistency, and knowing immediately what something is (though I'd agree and enjoy to work on more other-people's code which is thought out to read-well and flow well as you seem to encourage). There's an aspect of things where if you learn to speed read, the effect when you're glancing over words implies that you catch the first-and-last-part-of-words.
-> when interfacing APIs/other things, getters/setters are easy to automate code with (at least for JS/Ruby), and it's easy to write linter rules on weakly typed languages.

 

Nice! I normally don't find anything valuable in a lot of the more 'basic' articles of advice for newer devs anymore as I've been a dev for over 5 years, but sometimes the right way to name booleans with an 'is', 'has', or whatever eludes me. This is a great little bit of advice and guide! Thanks for the write up and keep up the good work!

 

I don't think it actually should matter how your variable names are prefixed. Particularly with "custom prefixes" if it sounds more correct for the usage of the variable, then use it!

If the boolean is a confirmatory boolean and is reset when accessed, the by all means, use "was": enter.wasKeyPressed.

Just my 2ยข. Otherwise, a fun read! ๐Ÿค™

 

Yes that's true, I added it to the article that going with an exception is better than enforcing a convention where it makes sense.

 

You have the signal of micro-management boss. Good luck for any developer who works under your supervision. They will be forced to fix every single grammar/comma/space/tab in their code.

(Experience from working with a boss has exactly the same point of view with this post.)

 

That was not the intention of this article and I am sorry you feel that way. I wanted to share tips for something I personally struggled with in the past and know others have too.

I try not to be picky in code review and don't bother with the things (grammar, spaces, semicolons, commas, etc.) you mentioned.
If a name is confusing I might leave a comment with a suggestion, but by no way enforce any of this stuff, it's all subjective.

 

Great article, thanks !
Question, how do you name boolean getters ?
I've seen people using booleans like "empty" and getters like "isEmpty()", but I prefer having is/has prefixes for booleans as you say.
I use getters like "getIsEmpty()" for an "isEmpty" boolean, but many people find it akward..

 

Many people do but stand your ground, it's good.

 

Technically, being disabled is not the same thing as being active

 

Ah yea, I was kind of mixing examples in the last one.

 

As they say, one of the hardest things with programming is naming stuff. Great article, I'll have to re-think my naming conventions in the future now ๐Ÿ˜„

 
 

what about shouldSave as a boolean prop to a component that would fire the useEffect?

 

Great article, thank you!

Found it, trying to find idea for naming of boolean "AreContactsShown". Name "isEachContactShown" would be weird - there are no separate contact items.

Any suggestions?

 

Thanks!

Where are the contacts displayed in? You could maybe use that instead, e.g. isContactListShown

 

Sometimes, one can be prefixed with has or did.

 

isTwoLoggedIn?
areTwoLoggedIn?
isThereTwoLoggedIn?

What should it be? Any other option?

 

That's a tough one.
What came to my mind was also
isPairLoggedIn
isPairOfUsersLoggedIn

Never ran into this case before though :D

 

Two of whom? :)

twoUsersAreLoggedIn

 

How about naming something which really cannot be smaller? Like an option for
Generate file when user logs in everytime

 

Since it is a group of things that may be active, I'd use allActive, anyActive, noneActive, oneActive,...

 

You can also use gt, ge, lt, le, eq then a number as prefixes for greater-than, greater-than-or-equal, less-than, less-than-or-equal, equal

Something like:

le3Active = activeCount(active) <= 3
gt4Active = activeCount(active) > 4