Terseness in Boolean Expressions
Have you seen or written code like this?
while (isAdvanced == true && isPremium() == false) {
...
}
Or this?
if (isAdvanced) then {
return true;
}
return false;
Or this?
return isAdvanced ? true : false;
How about this?
boolean isBasicUser = isPremium() == false ? true : false;
While they will all compile and work as you expect, they could certainly be shortened. Your code reviewers would appreciate terseness. The less time they spend on your pull request, the happier they are.
The key thing to note here is that Boolean variables or Boolean-returning methods are already Boolean expressions themselves. There's no need to compare them with true or false. That would be redundant.
In the first example, the variable "isAdvanced" is equivalent to "isAdvanced == true" and the return value of isPremium() can be negated to become equivalent to "isPremium() == false".
With that said, the first example could be shortened to:
while (isAdvanced && !isPremium()) {
...
}
I don't know about you, but to me, that's so much more readable. It's closer to English (or whatever language you choose to use for your variable names).
The next two examples would both collapse to:
return isAdvanced;
Finally, the last example would just be:
boolean isBasicUser = !isPremium();
There you go.
boolean happyCodeReviewer = isShort(pullRequest);
Subscribe to my newsletter
Read articles from Ever A. Olano directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ever A. Olano
Ever A. Olano
Inspired by a computer that printed "Hello, Ever" on the monitor at a science field trip. Fascinated by Basic in high school, then Turbo Pascal in college for starters. The rest is history. And yes, that's the answer to "How do you say you're seasoned without saying you're seasoned?"