How to Name Variables and Functions: Clean Code Naming Tips with Python, JavaScript and PHP Examples

Ask any senior developer what makes code hard to work with, and you will hear the same answer again and again: bad names. A function called calc(), a variable called x, a column called flag2. The code runs, but nobody, including you three weeks later, can tell what it does without reading every line.

Naming is a skill you can learn, and it pays off right away: in capstone defenses, in code reviews, in job interviews where you share your screen, and when an AI assistant or a teammate has to understand your code. This guide gives you practical rules with before-and-after examples in Python, JavaScript and PHP. Each example was run, and the output is shown so you can see that the clean version does exactly the same job.

Why Good Names Matter More Than Comments

Comments explain code, but they go out of date the moment someone changes the code and forgets the comment. A good name travels with the code everywhere it is used. When you read compute_order_total(cart, is_senior_citizen=True) in another file, you already know what is happening. When you read calc(l, True), you have to open the function and decode it.

A useful test: if you need a comment to explain what a variable holds, rename the variable instead. Save comments for why something is done, not what it is.

Rule 1: Say What It Is, Not How Long It Is

Short names are not the goal. Clear names are. Here is a function you might find in a student POS project:

def calc(l, d):
    t = 0
    for x in l:
        if x[2] > 0:
            t += x[1] * x[2]
    if d:
        t = t - t * 0.2
    return t

print(calc([("Pencil", 12.0, 3), ("Notebook", 45.0, 0), ("Bond paper", 250.0, 1)], True))

Output:

228.8

It works, but l, d, t, x[1] and x[2] tell you nothing. Is 0.2 a tax or a discount? Here is the same logic with honest names:

from dataclasses import dataclass

SENIOR_CITIZEN_DISCOUNT = 0.20


@dataclass
class CartItem:
    name: str
    unit_price: float
    quantity: int


def compute_order_total(items: list[CartItem], is_senior_citizen: bool) -> float:
    subtotal = sum(item.unit_price * item.quantity for item in items if item.quantity > 0)
    if is_senior_citizen:
        subtotal -= subtotal * SENIOR_CITIZEN_DISCOUNT
    return subtotal


cart = [
    CartItem("Pencil", 12.0, 3),
    CartItem("Notebook", 45.0, 0),
    CartItem("Bond paper", 250.0, 1),
]
print(compute_order_total(cart, is_senior_citizen=True))

Output:

228.8

Same result, but now the code reads like a sentence. A few things changed:

  • calc became compute_order_total: a verb plus what it produces.
  • Tuple positions like x[1] became named fields: item.unit_price, item.quantity.
  • The mystery 0.2 became SENIOR_CITIZEN_DISCOUNT.
  • The keyword argument is_senior_citizen=True makes the call site self-explaining.

Short names are still fine in tiny scopes, like i in a three-line loop or x in a math formula. The bigger the scope and the longer the variable lives, the more descriptive its name should be.

Rule 2: Name Booleans as Yes/No Questions

A boolean should read naturally in an if statement. Prefixes like is, has, can and should do most of the work:

// Unclear: what does "status" mean here?
const user1 = { name: "Ana", status: true, flag: false };
if (user1.status && !user1.flag) console.log("Unclear: allowed?");

// Clear: a boolean name answers a yes/no question
const user2 = { name: "Ana", isActive: true, isBanned: false, hasPaidTuition: true };
const canEnroll = user2.isActive && !user2.isBanned && user2.hasPaidTuition;
console.log(`${user2.name} can enroll: ${canEnroll}`);

Output:

Unclear: allowed?
Ana can enroll: true

status and flag could mean anything. isActive, isBanned and hasPaidTuition leave no doubt, and the combined rule gets its own name, canEnroll. Also avoid negative names like isNotValid or disableLogin: if (!isNotValid) forces every reader to do a double negative in their head.

Rule 3: Replace Magic Numbers with Named Constants

A "magic number" is a literal value in your code whose meaning is not obvious. Library fines are a classic capstone example:

<?php
// Before: what do 3, 5 and 1.12 mean?
function fee($days) {
    return $days > 3 ? ($days - 3) * 5 * 1.12 : 0;
}

// After: names explain the rules
const FREE_BORROWING_DAYS = 3;
const FINE_PER_DAY = 5.00;
const VAT_RATE = 0.12;

function computeOverdueFine(int $daysBorrowed): float {
    $overdueDays = max(0, $daysBorrowed - FREE_BORROWING_DAYS);
    return $overdueDays * FINE_PER_DAY * (1 + VAT_RATE);
}

printf("before: %.2f\n", fee(7));
printf("after:  %.2f\n", computeOverdueFine(7));
printf("on time: %.2f\n", computeOverdueFine(2));

Output:

before: 22.40
after:  22.40
on time: 0.00

Both versions return the same fine, but only the second one tells the panel during your defense that the first 3 days are free, the fine is 5 pesos per day, and VAT is added. When the librarian says "make it 7 free days," you change one constant instead of hunting for every 3 in the project.

Rule 4: Use Verbs for Functions and Nouns for Data

  • Functions do things, so start with a verb: get_student(), saveInvoice(), sendReminderEmail(), validateForm(), calculateGwa().
  • Variables and classes hold things, so use nouns: student, invoice, overdueBooks, PaymentReceipt.
  • Use plurals for collections: students is a list, student is one item. Then for student in students reads perfectly.
  • Be specific with verbs. getUser() suggests a quick lookup; fetchUserFromApi() or loadUserProfile() warns the reader that it may be slow or can fail.

Rule 5: Follow the Language's Style

Every language has a convention, and following it makes your code look professional instantly:

LanguageVariables and functionsClassesConstants
Python (PEP 8)order_total, compute_total()CartItemMAX_RETRIES
JavaScript / TypeScriptorderTotal, computeTotal()CartItemMAX_RETRIES
JavaorderTotal, computeTotal()CartItemMAX_RETRIES
C#orderTotal (locals), ComputeTotal() (methods)CartItemMaxRetries
PHP (PSR-1/PSR-12)$orderTotal, computeTotal()CartItemMAX_RETRIES
SQL tables and columnsstudent_grades, created_at (snake_case is the most common choice)

Whatever your team picks, be consistent. A project that mixes student_id, studentID and StudID for the same thing is a project where bugs hide.

Rule 6: Avoid These Common Naming Traps

  • Meaningless words: data, info, temp, stuff, obj, result2. Everything is data. Say what kind.
  • Unclear abbreviations: stdnt, cstmr, amt_pd. Well-known ones like id, url, html and max are fine.
  • Type names in the name: strName, arrStudents, studentList when it is actually a dictionary. Types change; names should describe meaning.
  • Lying names: a function called getTotal() that also saves to the database, or isValid() that shows an alert. A name should never surprise the reader.
  • Units left out: timeout = 30. Seconds? Minutes? timeout_seconds = 30 or loanPeriodDays removes the guesswork.
  • Mixed languages: pick one language for names (usually English) and stick with it, so you do not end up with getPangalan() next to saveAddress().

How to Rename Safely

Do not rename things with find-and-replace across the whole project. Your editor can do it safely: in VS Code, put the cursor on a name and press F2 (Rename Symbol); in JetBrains IDEs such as PyCharm, IntelliJ and PhpStorm, use Shift+F6. These update every real reference and skip unrelated text. For database columns, rename in a migration or SQL script and update the queries in the same commit, then run your tests or click through the app once.

A Quick Naming Checklist

  • Can someone guess what it holds or does without reading the code around it?
  • Does a boolean read like a yes/no question?
  • Does every function start with a verb?
  • Are there unexplained numbers or strings that should be constants?
  • Does it follow the language's casing style, consistently?
  • Would the name still be true after the next small change?

Conclusion

Clean naming costs a few extra seconds while you type and saves hours when you, your teammates or your panelists read the code later. Start small: next time you write a function, give it a verb, give booleans an is or has, and turn the first magic number you see into a constant. After a week, it becomes a habit, and your code starts explaining itself.