DEV Community

Tips on naming boolean variables - Cleaner Code

Michael Z on October 03, 2019

Originally posted at michaelzanggl.com. Subscribe to my newsletter to never miss out on new content. There is a convention to prefix boolean var...
Collapse
 
stepanstulov profile image
Stepan Stulov • Edited

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:

// Same order, erase the dot and you got yourself a variable name.
bool userIsActive = user.isActive;

// Order changed, statement suddenly became a question.
// Also have to bother about moving words around.
bool isUserActive = user.IsActive;
Enter fullscreen mode Exit fullscreen mode

The only standard you really need for booleans is an affirmative statement that evaluates to either true or false. That's it. Hello, Propositional Calculus. Is, are, has, was, did, will, should, must, can: 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

Collapse
 
azclau profile image
A-ZC-Lau • Edited

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.

Seems very pedantic. The word is isn't asking you, it's invoking a question with a binary answer.

userIsActive is a statement. It makes it sound like a constant.

Take for example "Is it 5 o'clock" would invoke a yes/no answer in your mind immediately. If your brain suddenly thinks that the computer is talking to you, rather than you realizing that the variable is actually saving a boolean, it's a problem between chair and keyboard.

Conversely, with your format, "It is 5 o'clock" would be a statement. You don't answer a statement, which makes it seem like a constant.

In fact, I would argue that statements are invocation of action. Because you wouldn't have a statement of "It is 5 o'clock" and then do nothing with it. So the name userIsActive would be a function i.e. userIsActive(), which you would use as in

if (isUserActive) { 
    userIsActive()
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stepanstulov profile image
Stepan Stulov • Edited

For invocation of actions in the imperative programming paradigm, with which you (arguably) unbeknownst to yourself operate, imperative mood of verbs is conventionally used. This is what gave imperative programming paradigm its very name.

if (userIsActive)
    SetUserActive(false); // Imperative mood of the word "set"
Enter fullscreen mode Exit fullscreen mode

PS: In an educated and intelligent community such as ours we do not call people "a problem between the chair and the keyboard" just because we disagree. Disagree one may. Insult one may not. Assuming education and intelligence are there in the first place, of course.

Collapse
 
dvddpl profile image
Davide de Paolis • Edited

absoulutely agree. i understand the need for the convention, since ( expecially at the beginning of your career) you are able to immediatly find or recogninze a boolean variable by the fact that starts with is or has, but was never bought into this.
exactly for the reason you mentioned,

is it a question? are you asking me? i don't know, you should tell me!

and because of the many exceptions that make some variables seriously grammatically terrible. I found this post because I was looking for alternatives or way of telling in a Pullrequest that isUserAlreadyExist is a complete NOPE for me...

imho, dimply use conventions when it makes sense, ( possiblly in thex affermative format - like useIsActive - which in my case would become a more natural userAlreadyExists)

Collapse
 
qodunpob profile image
Konstantin • Edited

What about the point that no code ask you but you have asked the data about something and store answer in variable with the same name?

Collapse
 
aryzing profile image
Eduard BardajΓ­ Puig

isExistingUser

Collapse
 
raulinlee profile image
Lee Raulin

I've been wasting more time than I should agonizing over this, but I agree with Stephan. I prefer everyUserIsOnline over isEveryUserOnline. That way I can write: "if (everyUserIsOnline)" and it reads like an English sentence. Couldn't be more clear what's happening.

I was tempted to go along with the original post, but when trying to actually use something like, "if (isEveryUserOnline)"... Just... No. Just feels wrong. Is every user online? I dunno. "If is every" wtf does that even mean? And you rule out other options for being ungrammatical?

Yes, I'm a programmer and know how booleans work, I could understand if it was named oaentuh0296eoau, especially with the help of VSCode Intellisense, so then why bother with any of this? Seems to me the more it reads like an actual sentence, the more clear it is what's going on.

And why insist on having is as a prefix? For the sake of adhering to some pseudo-Hungarian notation style that we use nowhere else? At the expense of clarity? I don't see the point.

Collapse
 
rob2d profile image
Robert Concepcion III • Edited

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.

Collapse
 
niemeier23 profile image
niemeier23

I created an account here just to <3 this comment.

It's not important at all that the auxiliary verb (is, has, was, etc) is a prefix, or not. It's not important that it be singular, and not plural. It's not important what temporal tense it's in.

It's about expressing a boolean value so that any English reading person could understand it, even if s/he doesn't know any programming principles. Make it literal and readable.

everyUserIsActive
someUsersAreActive
wasSuccessfullyUpdated
user.isAdmin

The variable should not beg the question, "what does this even mean?" or "what is this referring to?" It should be perfectly clear by simply reading it.


My other boolean pet peeve is this:

if($user->isAdmin) {
return true;
}
else {
return false;
}

Why not:
return $user->isAdmin;
?

Collapse
 
bsides profile image
Rafael Pereira

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

In english, a sentence beginning with a verb is a question most of the time. So for foreigners, it's a no brainer a variable starting with a questioning verb is a boolean.

I get it that native english speakers don't really talk the way the grammar is technically but this is how non native people learn the language, by learning and studying grammar first. And reading is different than speaking. We're reading code every day, not speaking. To simply ignore it because of use is a cultural thing and not really in the rules of the language.

Just my thoughts and point of view, from other perspective, to add to the conversation. But in the end of the day, it's good to be consistent. That's all.

Collapse
 
liutkin profile image
Volodymyr Liutkin

Thank you, exactly how I’ve been feeling. Affirmative names are also great at negating: !user.online, !sessionActive, !changesSaved.

Collapse
 
stepanstulov profile image
Stepan Stulov

Don't forget the verb "to be": user.isOnline, sessionIsActive, changesAre/WereSaved.

Collapse
 
bryndyment profile image
Bryn Dyment

I would say that the variable name is indeed a question and the variable value is the answer to said question.

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

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.

Collapse
 
thecodingalpaca profile image
Carlos Trapet

if (!hasDibberInDoofer)

I love it!

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

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.

Thread Thread
 
anitagraham profile image
Anita Graham

I am from the South West of Australia (and not dyslexic, to the point of pedantry), and we would say "doover" for that sort of placeholder word. (Mum had Irish grandparents on all sides, so I assumed it came from there).

The full name of a doover is a "dooverlacky". Mentally I associate "doover" with "horse doover", which is a variation of "hors d'oeuvres", so not at all connected.

Thread Thread
 
adam_cyclones profile image
Adam Crockett πŸŒ€

Woah this wouldn't surprise me if doofer is one and the same thing. Today I learned 😁

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

You my friend have invented the new foo bar!

Collapse
 
yuvala profile image
Yuval

Should replace foo and bar :)

Collapse
 
samuraiseoul profile image
Sophie The Lionhart

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!

Collapse
 
thebrenny profile image
Jarod Brennfleck

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! πŸ€™

Collapse
 
liutkin profile image
Volodymyr Liutkin

enter.pressed

Collapse
 
nzawirski profile image
Nikodem Zawirski

This would imply the key is constantly pressed.

Collapse
 
crhain88 profile image
Christian

enter.keyWasPressed

Collapse
 
michi profile image
Michael Z

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.

Collapse
 
mattgic profile image
Matthieu L.

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

Collapse
 
stepanstulov profile image
Stepan Stulov

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

Collapse
 
crhain88 profile image
Christian • Edited

I prefer to leave verbs for functions, such as getters.

let empty = true;

const isEmpty = () => empty;
const getEmpty = () => empty;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
michi profile image
Michael Z • Edited

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.

Collapse
 
paddy3118 profile image
Paddy3118

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

Collapse
 
paddy3118 profile image
Paddy3118

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

Collapse
 
crhain88 profile image
Christian

oof. I read this as "Le Three Active"

Collapse
 
kamalhm profile image
Kamal

hadHaveHadBeenPaidFor
this made me chuckle on the middle of the day, thank you :))

Collapse
 
luigiminardim profile image
Luigi Minardi

isTwoLoggedIn?
areTwoLoggedIn?
isThereTwoLoggedIn?

What should it be? Any other option?

Collapse
 
stepanstulov profile image
Stepan Stulov • Edited

Two of whom? :)

twoUsersAreLoggedIn

Collapse
 
ultrox profile image
Marko Vujanic • Edited

You changed my mind with

Code is set of comands, it dosent ask questions it answers them.

Following that logic, you don't really need is as prefix, and naming of boolean follows the logic nicelly, much more readable, becouse I tryed changing all is to 'command', suprisingly it's just much more readable and parsable in by my head.

isSendEmailFetching -> (request is made to job to send email)
sendingEmail

I wonder what do you think about using transitive verb like this?

Thank you

Thread Thread
 
stepanstulov profile image
Stepan Stulov

Alternatively, in passive voice, emailIsBeingSent.

Collapse
 
dlattynjt profile image
David Latty

Good stuff

Collapse
 
michi profile image
Michael Z

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

Never ran into this case before though :D

Collapse
 
dlattynjt profile image
David Latty

Horrid

Collapse
 
bradtaniguchi profile image
Brad

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 πŸ˜„

Collapse
 
nikitaargov profile image
NikitaArgov

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?

Collapse
 
crhain88 profile image
Christian

contactsAreShown, contactsAreVisible, or create an object: contacts.visible

Collapse
 
michi profile image
Michael Z

Thanks!

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

Collapse
 
invious profile image
Aymon Fournier

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

Collapse
 
crhain88 profile image
Christian

answering what should save would be easier to understand. recordShouldSave

Collapse
 
marcospb19 profile image
JoΓ£o Marcos Bezerra

Great article, very useful, thanks

Collapse
 
motss profile image
Rong Sen Ng

Sometimes, one can be prefixed with has or did.

Collapse
 
amberjones profile image
AmberJ

Love it!

Collapse
 
manishrawat4u profile image
manishrawat4u

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

Collapse
 
liutkin profile image
Volodymyr Liutkin

β€œwhen user logs in everytime” isn’t the part of assertion but rather a descriptive requirement. The assertion here is something like fileShouldBeGenerated.

Collapse
 
michi profile image
Michael Z

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

Collapse
 
samuelhutauruk2 profile image
Samuel Huaturuk

Great !