Good Variable Names

Learn to Program, Third Edition — by Chris Pine (28 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Cleaning Up User Input | TOC | Progress Checkpoint 👉

When writing a program, always try to have a good feel for what each variable is pointing to: a number, a string, or whatever. As in the favorite number program, at some point you’ll have the person’s favorite number as a string, and at another point you’ll have it as an integer. It’s important to keep track of which is which, and you can do this by keeping them in different variables.

Name the variables so that it’s easy to tell what they are at a glance. For example, if you had a variable for someone’s name, you might call it name and assume it was a string. If you had someone’s age in a variable, you might call it age and assume it was an integer. So, if you needed to have a string version of someone’s age, try to make that obvious by calling it something like age_string or age_as_string.

Most of all, try not to use bad variable names: no vague, meaningless names like stuff and things. In nearly all cases, avoid variables with a single letter. (The few exceptions are in abstract, math-heavy code, or in graphics programming, where x and y have concrete meanings.) And while you might often see example code in tutorials using foo and bar, never use these in your code. These are almost like meta-variables, meaning “replace these in your code with variables that actually make sense.”

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.