Boolean is a pretty cool data type which we often use in our conditionals.
The blog explains how they should be named properly for the sake of clean coding practices in our codebase.
Positive over Negative
Banish the confusion of double negatives! Instead of drowning in a sea of "not," embrace clarity.
❌ if (!isNotUser)
✅ if (isUser)
Adjectives, Not Actions
Break free from mundane verbs and nouns! Elevate your boolean game with descriptive adjectives or short, snappy phrases.
❌ if (sendEmail)
✅ if (emailIsSent)
Present Tense
Time-traveling through tenses adds unnecessary noise. Stick to the present tense for clean, coherent code.
❌ if (hasBeenSubscribed)
✅ if (isSubscribe)
Proper use of Prefix
Boost readability with prefixes like is/has/should/can. Your code will thank you later!
❌ if (membership)
✅ if (hasMembership)
Avoid confusing true/false - Employ Enums!
Wave goodbye to mysterious true/false values. Embrace the power of enums for self-documenting code.
❌ bookMeeting(customer, true)
❌ bookMeeting(customer, false)
✅ bookMeeting(customer, Discount.Applied)
✅ bookMeeting(customer, Discount.NotApplied)
Happy coding! 🎉💻✨
Follow me for more such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123
Top comments (10)
I personally love to use past tense for boolean, so it's reading like natural language
your first example would be better as
WRONG
if (isNotUser)
RIGHT
if (!isUser)
isNotUser evaluates to TRUE which is a confusing. Personally I don't like the ! logic reversal and will often write a separate not(boolean) function that reverses the boolean value
not(myBoolean) {
return !myBoolean
}
if (not(isUser)) {
...
}
Nicely done. This makes code simple to read. I like simplicity. These are the "little" things we take for granted.
We started doing this a few projects ago and it makes debugging so much easier.
In JS/TS I'd recommend setting up a naming lint via ESLint.
Notice the
prefix
configuration for boolean variable namesNow that's something cool. Thanks for sharing ✌️
sendEmail
andemailIsSent
don't have the same meaning, different tenses. You probably want something likeshouldSendEmail
Good article, but I personally think for the 3rd one I would lose context if I were to say “isSubscribe” rather than “subscribed” or “hasSubscribed”
And also doesn’t number 3 contradict number 2 ? You have mentioned to stick to present tense but you have used a past tense “sent” in 2.
Regarding the last:
Where applicable I to write two functions:
bookRegularMeeting(customer)
bookDiscountedMeeting(customer)
It is simpler than managing an additional enum.
Actually the last one means to have one function which handles two cases with a boolean conditional.
Your approach would require to have two separate functions. The approach is handy if they employ drastic different logic but not as much if logic is nearly the same.