Naming Conventions: How to Name Things in Code
Good names make code readable without comments. Learn the conventions for variables, functions, classes and files, and the habits that produce them.
By Velloreth
Why names matter
Names are the primary way code communicates. A function’s name is read far more often than its body, and a misleading name costs every reader, every time.
The test for a good name: can a reader understand what the thing is or does without reading its implementation?
// Bad: what is d? what does this return?
const d = 86400000;
function calc(x) { /* ... */ }
// Good: intent is clear
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
function calculateOrderTotal(items) { /* ... */ }
The second version needs no comment. The name is the documentation.
The core rules
Reveal intent
A name should say what the thing is for, not how it works.
// Bad: describes implementation
const list1 = users.filter((u) => u.status === 'active');
const flag = user.age >= 18;
// Good: describes meaning
const activeUsers = users.filter((u) => u.status === 'active');
const isAdult = user.age >= 18;
Be pronounceable
If you cannot say it in a conversation, it is a bad name.
// Bad
const usrLst = [];
const genymdhms = new Date();
// Good
const userList = [];
const generatedAt = new Date();
Be searchable
A name that appears in many unrelated places cannot be found by searching.
// Bad: "e" appears everywhere
catch (e) { }
// Good: searchable
catch (error) { }
Single letters are acceptable only in very short scopes, like a loop index in a three-line loop.
Match length to scope
The larger the scope, the more descriptive the name should be.
// Tiny scope: short is fine
items.map((x) => x * 2);
// Module scope: be descriptive
export const MAX_RETRY_ATTEMPTS = 3;
A variable used in one line can be x. A constant used across a codebase should be MAX_RETRY_ATTEMPTS.
Conventions by kind
Variables and constants
Use nouns. The name describes the value.
const userName = 'Ada';
const activeUsers = users.filter(isActive);
const MAX_CONNECTIONS = 100; // constants in SCREAMING_SNAKE_CASE
Functions and methods
Use verbs. The name describes the action.
function calculateTotal(items) { }
function sendEmail(to, subject) { }
function isValidEmail(value) { } // predicate
Avoid vague verbs that do not say what happens:
| Vague | Better |
|---|---|
handleData | parseUserRecord |
process | validateAndSave |
manage | scheduleRetry |
doStuff | (anything specific) |
Booleans
Use is, has, can, should, or was.
const isActive = true;
const hasPermission = false;
const canEdit = user.role === 'admin';
const shouldRetry = attempts < MAX_RETRIES;
A boolean named status or flag does not read well in a condition: if (status) says nothing.
Classes and types
Use nouns, usually singular.
class UserRepository { }
class OrderProcessor { }
interface PaymentGateway { }
type UserId = string;
Avoid suffixes that add nothing: UserManager, DataHelper, UtilsService. If the class needs “Manager” in its name, its responsibility is probably unclear.
Files and directories
Follow the language’s convention. Most use kebab-case or snake_case for files.
user-repository.ts
order_processor.py
Name the file after its primary export, so the file is findable.
Casing conventions
| Style | Example | Common in |
|---|---|---|
| camelCase | userName | JavaScript, Java, TypeScript |
| PascalCase | UserName | Classes in most languages |
| snake_case | user_name | Python, Ruby, Rust |
| SCREAMING_SNAKE | MAX_SIZE | Constants in most languages |
| kebab-case | user-name | File names, CSS classes |
Follow the language’s convention rather than your preference. Consistency within a codebase matters more than which convention you pick.
Names to avoid
Abbreviations. usr, msg, btn, cfg save characters and cost clarity. Exceptions: id, url, http, api are universally understood.
Type in the name. userArray, nameString, countInt — the type is visible from the declaration, and the name will be wrong if the type changes.
Implementation detail. userHashMap becomes wrong if you switch to a tree. Name the concept, not the structure.
Noise words. data, info, manager, helper, util, handler add length without meaning. UserData and User say the same thing; the shorter one is better.
Numbers in names. user1, user2, temp3 indicate a collection that should be an array.
Misleading names. A function called getUser that also creates a user if missing is a bug waiting to happen. Name it getOrCreateUser.
Negatives in booleans. isNotReady produces double negatives: if (!isNotReady). Use isReady.
Renaming as a habit
Renaming is one of the cheapest refactorings and one of the highest value. Modern IDEs make it instant and safe.
Rename when:
- A name does not reveal intent.
- A name is misleading.
- You understand the code better than when it was named.
- A concept has been renamed in the domain.
// Before: what is "d"?
const d = order.createdAt.getTime() - Date.now();
// After
const ageInMilliseconds = Date.now() - order.createdAt.getTime();
The rename costs seconds and saves every future reader.
A worked example
// Before
function proc(a, b) {
let r = [];
for (let i = 0; i < a.length; i++) {
if (a[i].s === 1 && a[i].t > b) {
r.push(a[i]);
}
}
return r;
}
// After
function findRecentActiveOrders(orders: Order[], sinceTimestamp: number): Order[] {
return orders.filter(
(order) => order.status === OrderStatus.Active && order.createdAt > sinceTimestamp,
);
}
The second version needs no comment. Every name says what it is: orders, sinceTimestamp, order.status, OrderStatus.Active. The reader knows what the function does from the signature.
Names in tests
Test names deserve their own note, because they are read more often than almost any other code — a failing test name is the first thing you see when something breaks.
A test name should describe the behaviour and the condition, so a failure tells you what broke without opening the file.
// Bad: says nothing
test('test1', () => { });
test('works', () => { });
// Good: describes behaviour and condition
test('returns 0 when the cart is empty', () => { });
test('throws EmptyCartError when items is null', () => { });
test('applies the premium discount when the user is premium', () => { });
The pattern is: what it does + under what condition. returns 0 when the cart is empty reads as a sentence and tells you exactly what failed.
Avoid names that describe the implementation rather than the behaviour. calls repository.save once is about the implementation; persists the order is about the behaviour. The second survives a refactor; the first breaks when you change how persistence works.
Names in configuration and environment
Configuration keys are names too, and they are read by people who may not know the codebase.
# Bad: ambiguous
TIMEOUT=30
MAX=100
# Good: scoped and specific
DATABASE_CONNECTION_TIMEOUT_SECONDS=30
MAX_UPLOAD_SIZE_MB=100
Two habits help. Include the unit in the name, because TIMEOUT=30 does not say whether it is seconds or milliseconds. Include the scope, because MAX does not say what is being maximised.
The same applies to feature flags, cache keys, and metric names. A metric called errors is ambiguous; http_requests_failed_total says what it counts.
Practical guidance
- Reveal intent in every name.
- Use nouns for values, verbs for functions, predicates for booleans.
- Match name length to scope.
- Avoid abbreviations except universally understood ones.
- Do not encode type or implementation in names.
- Rename whenever a name misleads — it is cheap and high value.
- Follow the language’s casing convention.
- Read the call site — if
findRecentActiveOrders(orders, cutoff)reads well, the name is good.
For the related practices, see writing clean functions and when to write code comments. For the broader context, refactoring basics and art of naming code.
Quotable summary
A name should reveal intent, so a reader understands what the thing is or does without reading its implementation. Names should be pronounceable, searchable, and proportional in length to their scope. Use nouns for values and classes, verbs for functions, and predicates like is, has, and can for booleans. Avoid abbreviations, names that encode type or implementation detail, and noise words like data, manager, and helper. Renaming is one of the cheapest and highest-value refactorings, so do it whenever a name misleads — the cost is seconds and the benefit accrues to every future reader.