Name Your Booleans Like Questions
Here's a tiny habit that quietly makes code easier to read: name every boolean so it reads like a yes/no question. Compare these: if ( user . active && ! loading && permission ) { ... } if ( user . isActive && ! isLoading && hasPermission ) { ... } Same logic. The second one reads almost like a sentence: "if the user is active, and we're not loading, and they have permission." The first makes you…
Naming boolean variables in a way that reads like a yes/no question can greatly enhance code readability. For example, if (user.active && !loading && permission) {...} can be rewritten as if (user.isActive && !isLoading && hasPermission) {...}.
The second version reads almost like a sentence: "if the user is active, and we're not loading, and they have permission." This makes it clear what the condition is checking, while the first version leaves ambiguity about what "permission" refers to - a flag, a string, or an object.
To maintain consistency, a few naming prefixes can be used for most cases:
- "is" for state: isOpen, isValid, isEmpty
- "has" for possession: hasChildren, hasError
- "can" for ability: canEdit, canRetry
- "should" for decisions: shouldRefetch, shouldShowBanner
Avoid negative names such as isNotDisabled, as they force the reader to perform double-negation math and make the code harder to understand. Similarly, avoid names that misleadingly suggest a specific type, such as user.admin, which could refer to a boolean, a role object, or an ID. Instead, use a more specific name like user.isAdmin to ensure clarity.
This simple naming convention benefits not only the original author but also anyone reading the code in the future. It eliminates confusion and simplifies the process of understanding the code, making it easier to maintain and collaborate on. By making code read like questions, developers can minimize moments of uncertainty and streamline the reading experience, ultimately saving time and effort for everyone involved.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to