Script Valley
Writing Clean Code: Naming, Functions & Structure
Why Naming MattersLesson 1.1

How to name variables so your code explains itself

intention-revealing names, avoiding abbreviations, meaningful context, variable scope naming, boolean naming conventions

Intention-Revealing Variable Names

Intention-revealing variable names

A variable name should answer one question: what does this hold and why does it exist? If you need a comment to explain a variable, the name has already failed.

Compare these two blocks. They do identical things:

// Bad
int d = 7;
boolean f = true;
String u = "john";

// Good
int sessionTimeoutDays = 7;
boolean isEmailVerified = true;
String currentUsername = "john";

The second block communicates intent without a single comment. Anyone reading it knows exactly what each variable represents.

Rules for variable names:

Use full words, not abbreviations. cnt saves you two keystrokes and costs your teammates five seconds of confusion every time they see it. Use count.

For booleans, prefix with is, has, or can. isActive, hasPermission, canDelete all read like English sentences in an if-statement.

Match the scope to the name length. A loop variable in three lines can be i. A variable used across a 200-line function needs a full descriptive name.

// Loop variable โ€” short scope, short name is fine
for (int i = 0; i < users.length; i++) { ... }

// Wide scope โ€” needs a real name
int totalActiveSubscribersThisMonth = getActiveSubscribers();

Avoid noise words: data, info, value, temp. userData tells you nothing that user doesn't. Strip the noise and name the thing precisely.

Names are the cheapest form of documentation. Invest thirty seconds choosing a name well, and save hours of confusion later.

Up next

How to name functions clearly in any language

Sign in to track progress

How to name variables so your code explains itself โ€” Why Naming Matters โ€” Writing Clean Code: Naming, Functions & Structure โ€” Script Valley โ€” Script Valley