Variable naming rule of thumb

February 4, 2013

Ars Technica recently highlighted a very interesting and somewhat provocative Stack Overflow question "Is there an excuse for short variable names?". The question is from a developer who is clearly frustrated with having taken over a code base littered with those one and two character variable names, and took to going in the completely opposite direction of renaming variables to very verbosely express their contents.

I was in the same camp as the question's author for a long time; I despised ultra-short variable names and all they stood for. It probably has its origins in my forays into kernel and low level programming where no one cares to use proper variable names let alone document anything. But, about a year ago, I got lazy, and realised that I didn't always need to use 10 characters to describe what I was doing in a two-three line segment. While there were roughly as many different answers as there are opinions on programming style, zxcdw expresses a point that reflects exactly my approach — an approach that I've been very happy with:

Variables with short lifetimes should be named shortly. As an example, you don't write for(int arrayCounter = 0; arrayCounter < 10; arrayCounter++) { ... Instead, you use for(int i ...

In other words, the naming complexity of a variable should be proportional to the lifetime and scope of the variable. No one is going to be confused about what i is in a three line loop.