Skip to content
Velloreth
Programming 9 min read

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

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:

WeakStrongerWhy
data, info, objinvoicePayload, customerRecordNames the domain concept
temp, tmp, resnormalizedEmail, totalAfterDiscountSays what survived the transform
resultmatchedUsers, validationErrorsSays which result
val, x, thing(anything)Transfers zero context
handle1, conn2primaryDb, replicaDbSays 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, and index.ts that grows forever are junk drawers — they name where code was put, not what it is. pricingRules.ts, tokenRefresh.ts, formatDuration.ts name the idea.
  • One concept per file, and the file matches the name. user.ts exporting User, UserService, and UserSerializer is coherent; user.ts exporting a payment webhook handler is a search landmine.
  • Consistent shape across the tree. Pick plural or singular for directories (services/ vs service/), 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.ts with describe("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:

  1. Pronounceable and searchable. You will say it in code review and grep it in six months. cfg and svc are hostile to both.
  2. One concept, one word; one word, one concept. Never customer in one module and client in the next for the same entity.
  3. No ambient context. UserService inside services/ does not need Service to say it again in every import path; do not bake the layer into every variable (userObj, userData, userResult clutter).
  4. Reserve suffixes for real distinctions. Factory, Repository, Config, Result are load-bearing only if the team uses them precisely.
  5. No builders’ archaeology. newThing2, final_v3_REAL mean a rename did not happen. Rename immediately, or accept that the name documents your confusion instead of the design.
  6. Dates and statuses get tense. createdAt vs processedAt; pendingReview vs wasRejected. Ambiguity about when is a common source of bugs at call sites.
  7. Negative booleans are usually wrong. notFailed forces double negation at every use; prefer succeeded or isPending.

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 raw2 at 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 (adjustment vs the company’s refund), 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 load for database reads, your preference for fetch is 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 total2 to settlementTotal and 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.

Frequently asked questions

How long should a variable or function name be?
Long enough to answer 'what is this?' without opening the body, and no longer. Scope matters more than character count: a loop index can be `i`, but something returned across modules needs to explain itself without surrounding context.
Should I abbreviate names?
Only where the abbreviation is more standard than the full word — `id`, `db`, `url`, `i` for an index. Invented shorthand like `mgr`, `cfgPtr`, or `tmpRes` saves typing and costs every future reader the decoding step.
Is a long function a naming problem?
Often, yes. Functions that resist a good single name are usually doing several jobs, and the fix is splitting it so each part can be named for its own job. The name is a symptom check on the design.
When should I rename things?
On sight, whenever a name turns out to be wrong — during review, while debugging, the moment you understand the code better than its author did. Use refactoring tools so references update safely, and treat it as normal work, not scope creep.