DEV Community

PHPControls
PHPControls

Posted on

Why Naming Variables Can Distinguish a Good Programmer from a Bad One

While analyzing some old code from a previous project, I stumbled upon variable names that left me scratching my head. Here’s a snippet of what I found:

var type = 0;
...
var wfStart = "Server Workflow Start";
var num = 100000;
...
var yesOrNo = "Yes";
Enter fullscreen mode Exit fullscreen mode

At first glance, these names seemed cryptic at best. After 25 minutes of piecing together the context (aided by poorly written comments), I finally understood what they meant.

What’s wrong here? To me, it seems the original developer rushed through the implementation, disregarding the importance of meaningful variable names. Instead, they left behind a confusing mess for anyone working on the code later.

Imagine the difference if the variables were given descriptive, self-explanatory names. Here’s an improved version:

var typeCode = 0;
const SERVER_WORKFLOW_START = "Server Workflow Start";
var maxLimit = 100000;
var isConfirmed = true;
Enter fullscreen mode Exit fullscreen mode

These changes transform the code into something far more understandable. It reflects a clear understanding of the task at hand, good communication of intent.

The Importance of Clarity and Communication

Great variable names make it possible to read code almost like a narrative, reducing the need for excessive comments and helping others - and your future self - understand what's going on. Poorly named variables, however, add unnecessary confusion.

Consider this example:

int acctWithdrawn; // number of customers with withdrawn accounts
string ln; // last name of the current customer
Enter fullscreen mode Exit fullscreen mode

These names require a reader to remember the comments or consult documentation to understand what's going on. With clearer names, this confusion disappears:

int  customerWidthdrawnAccount;
string customerLastName;
Enter fullscreen mode Exit fullscreen mode

These improved names reveal the variables' purposes directly. Code, like any text, should be intuitive and readable.

If You Can't Name It, You Don't Understand It

If you struggle to name something, it's likely because you don't fully understand it yet. Naming variables often requires crystal-clear thinking about what the code is trying to accomplish, so unclear names often signal unclear ideas. If you find yourself reaching for vague terms, try asking, "What exactly is this variable representing?" This exercise helps you clarify your logic, which is beneficial not only for naming but for the overall structure of your code.

To help with this, try using a "descriptive placeholder" name, even if it's excessively long. For instance, instead of trying to name a counter vaguely, use something like numberOfActiveUsersWhereXisTrue. This will both clarify the variable's purpose for now and signal for future refactoring to find a concise, precise name as the code becomes more defined.

Here are two JavaScript code examples that demonstrate how to improve variable names for better readability and maintainability:

Example 1: Poor Variable Names

In this example, we have ambiguous and non-descriptive names, making it hard to follow the code's intent.

// Poor variable names
function calc(p, r) {
    let res = 0;
    for (let i = 0; i < r.length; i++) {
        res += r[i];
    }
    return res * (p/100);
}

let price = calc(100, [5, 10, 15]);
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • calc does not indicate what this function actually calculates.
  • p and r are not descriptive and don’t explain what values they represent.
  • res is unclear and doesn’t indicate that it’s the result of the sum of the array.

Improved Example: Good Variable Names

Let’s rename the variables for clarity so that anyone reading the code can understand its purpose at a glance.

// Improved variable names
function calculateTotalPrice(basePrice, discounts) {
    let totalDiscount = 0;
    for (let discount of discounts) {
        totalDiscount += discount;
    }
    return basePrice * (totalDiscount/100);
}

let totalPrice = calculateTotalPrice(100, [5, 10, 15]);
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • calculateTotalPrice clearly describes the purpose of the function.
  • basePrice and discounts specify what values are being passed in.
  • totalDiscount makes it clear that it’s the total sum of discounts from the array.

Example 2: Using Contextual Variable Names

Let’s look at a second example where the purpose of variables is unclear due to non-descriptive names.

// Poor variable names
function prsnData(d, a) {
    for (let v of a) {
        console.log(`${d}: ${v}`);
    }
}

let name = "Name";
let attributes = ["smart", "kind", "hardworking"];
prsnData(name, attributes);
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • prsnData is unclear—does it mean person data or print data?
  • d and a don’t describe the values they hold, making the function difficult to follow.

Improved Version:

// Improved variable names
function displayPersonAttributes(personName, attributes) {
    for (let attribute of attributes) {
        console.log(`${personName}: ${attribute}`);
    }
}

// Usage
let personName = "Name";
let attributes = ["smart", "kind", "hardworking"];
displayPersonAttributes(personName, attributes);
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • displayPersonAttributes is clear and communicates the function’s purpose.
  • personName and attributes indicate what each parameter represents, making the code easier to understand at a glance.

Using meaningful names greatly enhances readability and shows a careful, thoughtful approach to programming.

Characteristics of Good Variable Names

While good names vary by context, here are some principles to help make your naming conventions solid:

  1. Be Descriptive but Concise: Names should convey purpose. For instance, instead of x, userAge is much clearer. At the same time, avoid overly long names that may become cumbersome. Strive for a balance where a variable name is as short as possible while still conveying its purpose. If you have trouble find a good variable name, use aforementioned "descriptive placeholder", and come back to it later.  
  2. Use Context: Variable names should fit the function or class they're in. For instance, a variable in a function handling order data might use orderTotal or customerID rather than something generic like data or num.

  3. Follow Naming Conventions: Many languages have specific naming conventions (like camelCase in JavaScript and snake_case in Python). These conventions keep code style consistent and make it easier to read across different projects.

  4. Avoid Cryptic Abbreviations: Shortening words can lead to confusion, especially if the abbreviation isn't universally recognized. A name like num may be clear enough, but cnt could confuse readers who don't know whether it stands for "count," "content," or something else.

  5. Meaningful Prefixes and Suffixes: For certain data types or structures, adding a prefix can improve clarity. For example, use listOfUsers to indicate an array or list, or isEnabled to show that a variable is a boolean. These prefixes serve as quick cues about the variable's function and type.

Refactoring and Renaming When Necessary

As code evolves, so should variable names. It's common to start with one name and later realize it no longer reflects the variable's purpose accurately. If your variable's name no longer aligns with its function, take the time to rename it. Many modern IDEs such as VSCode support refactor->rename features, which make renaming painless across large codebases.

Naming as a Skill to Build Over Time

Variable naming is a skill that improves with practice and attention. Here are a few strategies to strengthen your naming skills:

  • Practice Mindfulness: When choosing a name, take a moment to consider how it reflects the variable's role in the code.

  • Review and Refine: As you revisit old code, critique your own variable names and improve them.

  • Ask for Feedback: Code reviews are invaluable for learning from other perspectives. Peers can offer insights into alternative names that may be clearer.

Naming variables may sound trivial, but it's one of the most telling signs of a programmer's skill and thoughtfulness. A programmer who takes time to name variables thoughtfully is often the one who approaches problems methodically, communicates clearly, and cares about long-term maintainability.

About the Author

The author is a veteran web developer who created the popular PHP datagrid tool (phpgrid.com), harnessing the power of CRUD to make the world a better place — at least for developers looking to simplify their lives!

Top comments (0)