There’s a line attributed to Phil Karlton that every programmer eventually learns the hard way: “there are only two hard things in computer science: cache invalidation and naming things”. And naming is, by far, the one you face most often.
A name is documentation
A good name removes the need for a comment. Compare:
// days since last login
const d = (Date.now() - u.l) / 86400000;
with:
const daysSinceLastLogin = (Date.now() - user.lastLogin) / MS_PER_DAY;
The second needs no explanation. Code is read far more often than it’s written; optimize for the reader.
Rules I follow
- Avoid abbreviations except the universal ones (
id,url,iin a short loop). - Name length should scale with scope. A three-line variable can be
x; a global cannot. - Booleans read like questions:
isLoading,hasAccess,canEdit. - Functions are verbs:
fetchUser,parseDate,normalizeInput. - Be consistent: if it’s
removein one place, don’t call itdeletesomewhere else.
The quick test
If you need a comment to explain what a variable holds, the name is probably wrong. Fix the name before adding the comment.
Naming well isn’t aesthetics: it’s the difference between code that maintains itself and code you have to decode every time.