The most important thing to keep in mind when choosing names for your variables is who you’re naming them for. Many people have the misconception that the computer cares about the name of your variables, or that different variable names have some kind of performance impact. This is not true. Decades ago, when memory was incredibly scarce, programming was brand new, and every byte mattered, keeping your variable names short actually did have an impact. Thankfully, those days are now well behind us.
Another common fallacy is thinking that as long as your variable names make sense in the moment, you’re fine. Maybe you think you’ll never need to come back to this code in the future (chances are you will), or that you’ll be able to pick things back up quickly and easily. Nothing could be further from the truth.
When you’re writing code, you’re thinking about the entire program. You have some version of it running in your head. You have context. Naming a variable
aThing might make perfect sense in the moment, but you have to remember that your current coding mindset is temporary. If the names of your variables aren’t clear, it will be incredibly hard to remember what you were thinking in two weeks, let alone two months or two years from now.
You don’t name variables for the computer, and you don’t name them for the you of today. Your target audience when naming variables is Future You, and anyone else who might need to understand your code later.
The trick to naming variables correctly is twofold:
- Keep Future You, and other people, in mind.
- Walk the line between too short and too long.
One way to tell if your variable names are conveying what they need to convey is to try reading your code like a sentence. If you come up with something like, “This function takes A and add B and C to it and then returns the result,” that’s a bad sign. You want to aim for something like “This function takes a price and adds tax and shipping to it.”
On the other end of the spectrum, I’ve seen variable names like
postsAfterFilteringHTML. In some situations names like these might be warranted (when in doubt, Future You will appreciate more verbosity instead of less), but names like these usually point to bigger problems in the code, like a lack of clarity and context in the surrounding functions, comments, and/or methods.
If you find yourself being overly verbose with your variable names ask yourself why you feel the need for that level of detail. Has your code gotten away from you? Are you not adding in proper comments? Find and fix those underlying problems first, then try naming your variables again.
When all else fails, ask yourself this question: “If I look at this code six months from now, will the name of this variable sense?”