Prefer Positive Booleans
It is oftentimes difficult to understand how a conditional will resolve if the boolean logic is complex. The mental gymnastics needed to figure out all the edge cases soak up developer time and creates room for error.
For example, when does this conditional pass?
if (!user.notAuthorized || !user.isNotAdmin()) {
setPermissions();
}
Itβs not easily understandable because the double negatives are confusing. One way to greatly simplify this logic is to use positive booleans like such:
if (authorized || isAdmin()) {
setPermissions();
}
This provides a much clearer understanding about what the conditional is trying to accomplish. Furthermore, we favor terms that are natural to the language (authorized
vs isAuthorized
) to remove the use of redundant prefixes. There are many of these special (but common) cases such as:
Enabled
vsDisabled
Active
vsInactive
Complete
vsIncomplete
hasValues
vsEmpty
Finally, it’s a good convention to name and set booleans in a way that defaults them to false
. Developers will gain insight and understand that this conditional only runs when the variables are not in their default states, which is a great mental model for logic flow in general.
Conventional naming and structure for your booleans are effective and impactful ways to improve code readability and avoid logical errors.
General rules when using booleans:
- Use positive booleans to avoid confusion from double negatives
- Implicitly default boolean logic to false
- Use consistent and appropriate language when defining booleans
π Additional Resources
Here are some additional resources about simplifying boolean statements:
- Serendipidata: Naming Guidelines for Boolean Variables