Tips on naming boolean variables - Cleaner Code
Published 10/3/2019
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) |
Check out my e-book!
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 | ๐ง | Non-affirmative |
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 non-affirmative 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.