How to Better Name Your Functions and Variables
We all know the struggle of naming things. Sometimes a perfect name arrives in seconds; sometimes you spend an hour and settle for tmp or value. Next time it comes up, keep a few simple ideas in mind. You'll write more readable code and make life easier for the next person, including your future self.
Functions, variables, and classes all follow the same principle. Think of a name as a tiny comment.
Pack information into names.
Choose a word with meaning
Pick a specific word and avoid empty ones. Imagine an API that returns books:
function get(url) { ... }
get says almost nothing. What are we getting, and from where?
function getBooks(url) { ... }
Better. And if the source matters:
function fetchBooks(url) { ... }
// or, when you have several services
function getBooksFromAPI(url) { ... }
It's better to be clear and precise than to be cute.
Think about what the function actually does or what the variable holds, but don't overthink it.
Avoid generic names
tmp, x, a, obj, foo are usually synonyms for "I don't know how to name this." Sometimes generic is fine:
if (right > left) {
const tmp = right
right = left
left = tmp
}
Here tmp is exactly right: short-lived temporary storage is the most important fact about it. But not here:
let tmp = user.firstName()
tmp += ' ' + user.lastName()
return tmp
fullName carries more meaning. Loop counters i, j, k are understood, but nested loops read better as c for classes and s for students.
If you're going to use a generic name like
tmp,it, orretval, have a good reason for doing so.
Attach additional information
Any extra information you squeeze into a name can have a big impact on readability. Add units:
const startMs = Date.now()
// ...many lines below...
const elapsedMs = Date.now() - startMs
Do this any time there is something dangerous or surprising about the value. When handling sensitive data, plainPassword and hashedPassword beat a bare password. Reserve this for places where a bug can sneak in from someone using a value the wrong way.
Make the name the right size
Too long is hard to read and remember:
newNavigationControllerWrappingViewControllerForDataSourceOfClass()
Shorter names are okay for shorter scope.
function checkPassword(password) {
const s = password.length
if (s < 8) {
// ...
}
}
s is fine in a tiny scope. If the function grew complex, it would lose its meaning. Beware abbreviations too: BEManager saves keystrokes over BackendManager but can confuse a new teammate.
Consistent formatting
Capitalization and underscores carry information: an initial capital often marks a class, all-caps marks a constant, a leading or trailing underscore often means private. The main goal is consistency, so pick a convention and stick to it.
Summary
Pack information into your names.
The reader should be able to extract as much as possible from the name alone.
Originally published on Medium.