Best Practices for Naming Variables in Your Source Code

Have you ever struggled to understand your code or someone else’s because of poorly named variables? Correctly naming variables is crucial to writing clean and maintainable code. This article will discuss some best practices for naming variables that make your code more readable, effortless, and less prone to errors.

Here are some best practices for naming variables in your source code:

  1. Use descriptive names: Choose names that indicate the purpose of the variable. For example, instead of using a variable named “x,” use a more descriptive name like “num_items” or “total_sales.”

  2. Use consistent naming conventions: Adopt a consistent naming convention for all the variables in your codebase. This will help you and others quickly understand a variable’s purpose. Some popular naming conventions are camel-case, snake-case, and kebab-case. Picking the correct one of these can be a preference or a standard in your language.

    Python typically uses camel-case for classes and snake-case for methods, for example. Golang uses camel-case. Whether to capitalize the first letter is another detail you may make by preference or according to requirements from your language or group. See Golang, for example, and its rules about capitalizing the first letter of variables. You might hear pascal-case and camel-case used to denote the difference, but I usually hear camel-case used to describe both. Pascal-case is “PascalCase,” and camel-case is “camelCase.”

    Conventions extend further than capitalization and spacing. Try not to use “numBoxes” in one place and “rectangleCount” in another, for example. Instead, use “numBoxes” and “numRectangles” or “boxCount” and “rectangleCount.” If you use a combination of verbs and nouns, maintain the same order throughout your code. Use “flyingFish” and “runningCats,” for example, and not “flyingFish” and “catsRunning” in the same body of code. Finally, standardize using singular and plural words to keep similar groups of terms consistent.

  3. Avoid single-letter variable names: While single-letter variable names like “i” or “j” may be common in loops or mathematical equations, they can make your code hard to read and understand. Instead, use descriptive names that convey the purpose of the variable.

    You might think what “i” means in a small for-loop is obvious. The function it’s in might be concise. However, you can make your code quicker to read if you include more detail. And the extra effort will pay increasing dividends as others modify or extend it.

  4. Avoid using reserved keywords: Avoid using names already reserved in the programming language you’re using. Using reserved keywords can cause errors or unexpected behavior in your code.

    I used to prefix some of my C/C++ variables with underscores or “dunders” (double underscores) until I realized this convention was reserved. Technically, following an underscore with an uppercase or another underscore is reserved in C and C++. So stay away from those unless you’re writing a compiler or standard header.

  5. Be concise but not too brief. Be verbose but not too wordy. A variable named “qty” may be concise but is not as straightforward as “quantity,” for example. Watch for abbreviations that are only a few characters shorter than the word. Saving 3 or 4 keystrokes is not worth the mixups an abbreviation might cause. Use code completion in your editor to minimize typing instead of writing cryptic code.

    I’ve gone through a few phases in my career. I started out writing short and sometimes cryptic variable names. Then, after reading books like Code Complete, I wrote very descriptive code. It never occurred to me I was being too verbose. At some point in my career, a coworker complained about it, and I realized they were right. It takes a lot of work to parse through code full of long variable names. It decreases code density and wears readers down. Sometimes, you might have to think hard about variable names; this is normal.

    ‘number_of_jiffies_between_interrupt_assertions’ is too long. It is okay if you need something this specific in a spot or two for particular reasons, but use something shorter, or readers will want to rewrite instead of read your code. ‘num_intra_int_jiffies’ is more succinct and retains enough information. On the other hand, ‘no_jiffies’ might confuse readers.

  6. Avoid using abbreviations: While abbreviations can save typing time, they can make the code harder to understand. Again, use your editor to help minimize typing. People have advised me to use a lookup table for abbreviations and acronyms. While I agree with this, it’s better not to use them in the first place. Lookup tables are only effective if people notice them and keep them up to date. I am still waiting to see them be successful in my projects.

    A coworker once suggested I use two-letter prefixes for all my C variables. In addition, he suggested every module in our million-lines-of-code project should have its two-letter combination. Good conventions are helpful, but bad ones result in consistently poor code. We had quite a bit of code like this, and most developers needed to learn what the prefixes meant. Unfortunately, we kept no lookup table. While this prefix was only two characters, it merely lengthened each name without adding value.

    One of my least favorite abbreviations is “no” for “number.” Unfortunately, “no” is the non-ligature form of “number” in English and isn’t so common in North America. It’s only intuitive for a portion of programmers. Please spend the effort to type one more letter to spell “num” or press four more keys to use “number.” “noBoxes” and “numBoxes” can understandably mean completely different things, for example.

  7. Use meaningful prefixes and suffixes: If you have variables that are related or have similar names, consider using meaningful prefixes or suffixes to differentiate them. For example, you could use “total_sales_monthly” and “total_sales_weekly” to clarify variables with similar but different purposes.

  8. If you need a comment beside a variable to explain it, look at the comment long enough that you can come up with a better name and delete the comment. An excellent variable name keeps its intent more evident everywhere. One alternative is consistently adding a comment each time you use a variable. Or do you expect readers to find the variable’s declaration every time they forget its purpose so they can read the comment? I hope not.

    Programmers often fail to synchronize code and comments when they write or modify it, which confuses readers. In addition, it requires work and takes time to write, modify, and read comments. Therefore, minimize comments by making the code as straightforward and meaningful as possible.

  9. Keep your variable names DRY. DRY means “Don’t Repeat Yourself” and is a great principle to apply to many aspects of writing software. “numBoxesCount” is an obvious example of inefficiency. Avoid names that result in redundancy, like “packet.packetCount,” and prefer “packet.count” instead. These can be difficult to spot at first. However, you’ll find them with careful review and good craftsmanship.

Summary

In conclusion, correctly naming variables in source code is essential to writing clean, readable, and maintainable code. Following the best practices outlined above can make your code more understandable and reduce the risk of introducing bugs and errors. Those who read your code will be more efficient and less frustrated. They will be more willing to read your code instead of rewrite it.