July 7, 1994
Although meaningful variable names can make reading code easier, they sometimes lead to mistakes and can make debugging difficult. Consider three experiences I had:
In my first job interview at Microsoft, the programmer who later became my supervisor asked me to write a function to trim spaces from the ends of a string. I had written similar routines many times and quicky wrote down a function. I usually keep a variable called length to keep track of the length of the string so I don’t have to recalculate it all the time. Because of the particular requirements of this function, though, it was more convenient to keep the length variable pointing to the last character in the string, one less than the length. Of course, the name of variable misled me and I had several bugs as a result.
A few weeks before writing this essay, I found a bug in a co-worker’s code here at UNC. He had a C++ class that kept track of identifiers in an array with an associated variable called NumElements. Again, he was using that variable to point to the last element in the list instead of the number of elements. One searching loop was written as “for (i = 0; i < NumElements; i++)”, missing the last element.
A few summers ago I had to modify a 500-line assembly language routine that was doing some fancy memory allocation and hardware initialization. I was forced to step through the whole code and keep track of each register’s contents. The meaninglessness of the register’s names made this task more difficult, but they insured that the code was actually doing what was intended and not what was implied by the variable names.
In the first two cases, had the variables been called x, the programmers would not have been misled. Of course, the correct solution to both is to either rename the variable or use it to hold the length. However, even if the variables are named correctly, the programmer immediately assumes that its name reflects its contents without checking. Meaningless variable names force the programmer to ask, “What’s in this x variable being used as a loop bound?”
It would be nice to have an editor that could switch into “meaningless” mode for debugging purposes, replacing all identifiers with random letters.