The Art of Naming: Variables, Functions, and Files
Practical naming rules for code: how to name variables, functions, and files so readers get context at the point of use without reading the body.
By Velloreth
A name is compression. While you write code you hold a whole model in your head — why this exists, what the weird edge case was, which of the three similar concepts this one is. The reader gets none of that. A good name is how you transfer a piece of your context into the file, so it arrives with every read.
This is also why naming feels hard: you are not labeling, you are explaining, under uncertainty, about code you understand less than you will five minutes from now. A few consistent rules make it much less of a guessing game.
What a name must answer
At the point of use, a reader should be able to continue without inspecting the definition. Concretely:
- Variables: what does this hold, and is it the raw or the processed version?
- Functions: what does calling it accomplish, in business terms?
- Files/modules: what set of responsibilities lives here?
What the name should not do is describe implementation — that is what the body is for — or restate the type system (userAsString next to a : string annotation is noise in a typed language).
Variables: name the thing, not the container
The reliable pattern: nouns for values, questions for booleans.
// what it holds // what it means
const orderTotal const hasRefund
const pendingInvoices const canRetry
const userId const isExpired
const retryCount const shouldSendEmail
Booleans deserve special attention because they are the names readers lean on most in conditionals. if (flag) costs a jump to the definition; if (user.hasActiveSubscription) costs nothing. Prefixes like is, has, can, should, and was carry the tense for free — wasExpired and isExpired are different facts and should look different.
Avoid the empties — names that say something exists but not what:
| Weak | Stronger | Why |
|---|---|---|
data, info, obj | invoicePayload, customerRecord | Names the domain concept |
temp, tmp, res | normalizedEmail, totalAfterDiscount | Says what survived the transform |
result | matchedUsers, validationErrors | Says which result |
val, x, thing | (anything) | Transfers zero context |
handle1, conn2 | primaryDb, replicaDb | Says the role, not the order |
Scope sets the required specificity. Inside a three-line loop, n is fine; the same n at module scope or as a parameter is a defect. The heuristic: the wider the reach, the more the name must carry — parameters, return values, and anything crossing a function boundary must be self-explanatory, because their context is gone.
Special cases that need extra care
Some categories of value are systematically misnamed, and pinning them down early prevents whole classes of confusion:
Collections. A name should say whether it is one or many, and ideally what it contains after any filtering: userIds (a list of ids), activeUsers (full records, filtered), userById (a map keyed by id), userCount (a number). users2, usersList, usersFinal all suggest the author was unsure which of the three they had.
Time. Give every timestamp a tense and a reference point: createdAt, expiresAt, lastSyncedAt, nowMs vs startedAt. Durations carry their unit in the name — timeoutMs, ttlSeconds, retryDelayMs — because timeout: 30 in a codebase that mixes units is a bug waiting for a reviewer who blinks.
Booleans with history. Prefer names that make the transition explicit: wasCancelled (a state that ended), isCancelled (a state now), hasEverFailed. In conditionals, if (payment.wasRefunded) reads as a fact; if (payment.refundFlag) reads as trivia.
Negatives and defaults. disableNonEssentialCookies forces readers through a double take; essentialCookiesOnly states the policy. Where a default matters, encode it: preferLocalCache, not cacheMode with a comment saying which value is the default.
Functions: verbs that survive being skimmed
A function name is a claim about behavior. The failure modes are predictable:
def handle(data): # what handling? what data?
def process_payment(): # process, or successfully charge?
def do_thing(): # worse: an apology
def get_user(id): # fetch from DB? from cache? throw if missing?
def charge_card(card, amount) -> ChargeResult # does, states, returns
def load_user(id) -> User | None # null on miss, no throw
def user_exists(id) -> bool # cheap check, no hydration
Three rules do most of the work:
1. Name the outcome, not the activity. handle, process, manage, do, and run describe that code exists, not what it achieves. If you cannot find a better verb, the function is probably doing several things — and the naming struggle just told you where to split.
2. Make the contract visible. Readers care about three things before they read the body: what goes in, what comes out, and what happens on failure. The name plus the signature should answer them — charge_card vs refund_charge vs load_user_or_null. Distinguishing get/load/fetch/find is only useful if you pick one meaning per verb and keep it: say load when it queries storage, find when it may return nothing, and do not drift between them across modules.
3. Say what, not how — until the how is the point. calculateTotals() tells the reader why they are here; loopThroughItemsAndSum() narrates line one of the body. The exception: when the implementation choice is the contract (binarySearch, paginate, streamLines), the how is information the caller needs.
Watch for boolean parameters at call sites — they are naming failures deferred to the reader:
sendInvoice(invoice, true); // true doing what?
sendInvoice(invoice, { attachPdf: true }); // self-describing
The same discipline applies across a whole surface. A quick way to audit one: list the public functions of a module and read only the names, skipping bodies. If the list does not tell the story of what the module is for, the names are describing plumbing, not purpose:
audit read-only: tells a story: tells plumbing:
validate() loadInvoice() handle()
doStuff() applyDiscounts() process()
update() issueInvoice() doUpdate()
check() voidInvoice() checkStuff()
Files and modules: the index of your system
Files get the least attention and cost the most, because a wrong file name misdirects every search before anyone reads a line.
- Name by responsibility, not by origin.
utils.ts,helpers.ts,misc.ts, andindex.tsthat grows forever are junk drawers — they name where code was put, not what it is.pricingRules.ts,tokenRefresh.ts,formatDuration.tsname the idea. - One concept per file, and the file matches the name.
user.tsexportingUser,UserService, andUserSerializeris coherent;user.tsexporting a payment webhook handler is a search landmine. - Consistent shape across the tree. Pick plural or singular for directories (
services/vsservice/), kebab or camel for files, and stick to it. Inconsistency here doubles the cost of every navigation. - Prefer the domain word the whole team uses. If support calls them “refunds” and the code calls them “adjustment transactions,” every conversation now needs a translation layer.
- Let tests inherit the name.
chargeCard→chargeCard.test.tswithdescribe("chargeCard"). Mismatches between production and test names are a small ongoing tax on finding things.
Before and after
# hard to read: names carry no domain meaning
def f(d, flag):
r = []
for x in d:
if x[3] > 0 and flag:
r.append(x[0])
return r
# same code, context restored
def active_subscription_ids(subscriptions, include_trial) -> list[str]:
eligible = [
sub.account_id
for sub in subscriptions
if sub.days_remaining > 0 and (include_trial or not sub.is_trial)
]
return eligible
Neither version is smarter. The second one can be reviewed without opening the other functions it touches — which is the entire job of a name.
Heuristics worth internalizing
A compact checklist, in rough order of value:
- Pronounceable and searchable. You will say it in code review and grep it in six months.
cfgandsvcare hostile to both. - One concept, one word; one word, one concept. Never
customerin one module andclientin the next for the same entity. - No ambient context.
UserServiceinsideservices/does not needServiceto say it again in every import path; do not bake the layer into every variable (userObj,userData,userResultclutter). - Reserve suffixes for real distinctions.
Factory,Repository,Config,Resultare load-bearing only if the team uses them precisely. - No builders’ archaeology.
newThing2,final_v3_REALmean a rename did not happen. Rename immediately, or accept that the name documents your confusion instead of the design. - Dates and statuses get tense.
createdAtvsprocessedAt;pendingReviewvswasRejected. Ambiguity about when is a common source of bugs at call sites. - Negative booleans are usually wrong.
notFailedforces double negation at every use; prefersucceededorisPending.
Naming as a review habit
Code review is the natural place to fix names, because a fresh reader is present — they are experiencing exactly the confusion a bad name causes, in real time.
Practical habits that keep reviews about substance:
- Comment on names the way you comment on logic. “What is
raw2at this point?” is a legitimate review finding, not bikeshedding — if the reviewer stumbled, the next reader will too. - Ask for the domain word. When a name and a meeting disagree (
adjustmentvs the company’srefund), the code loses. The team’s shared vocabulary is the source of truth. - Approve-with-nit is fine for names. Renames are cheap, mechanical, and tool-assisted; block only when the name hides a real ambiguity about behavior.
- Do not rename on a whim after merge. Consistency beats local taste: if the codebase says
loadfor database reads, your preference forfetchis not an improvement, it is drift. Change the convention everywhere or not at all.
There is also a reading practice worth adopting: when you join a codebase, keep a running list of names you had to open another file to understand. That list is a map of the system’s least transferable context — and after a month, it is the highest-quality refactoring backlog you can assemble, because every item was paid for by a real reader.
Renaming is maintenance, not scope creep
The cheapest readability improvement in any codebase is a rename, and the second-chearest is deleting a dead name. Treat “the name turned out wrong” as a normal finding:
- Rename on sight. When you learn what a function really does — during review, debugging, or reading it fresh — fix the name while the understanding is hot.
- Use refactoring tools, not find-and-replace, so references, tests, and docs move together. This removes the main historical excuse for keeping bad names.
- Do it in a separate commit. Mechanical renames mixed with behavior changes make both unreviewable.
- Add the domain term when you learn it. If a meeting reveals that finance calls this number “the settlement total,” rename
total2tosettlementTotaland the codebase now matches the company’s language.
The long game is compounding. Every good name reduces the context a future reader must reconstruct, and every bad one silently taxes everyone who opens the file. Since naming is also the part of programming you cannot delegate to a machine — it requires knowing what the code is for — it remains one of the few places where craft shows immediately.
Write the name you would want to read at 2 a.m., while debugging, with no memory of why the code exists. That reader is usually you.