Meaningful Variable

EditHint: RefactorByMerging with MeaningfulName.

Consider the example:

 for ( int i = 0; i < 10; i++ ) {
   printf( "%d ", i );
 }
Here, it's not too difficult to see what i does What if i were in the middle of a large chunk of code? Using a MeaningfulName for each variable will go a long way to enhancing the readability of code. The occasional MeaningfulComment is nice, too. And so is the avoidance of large chunks of code.


On the other hand, we're not indexing an array. It appears that we're printing the digits zero through nine: "0 1 2 3 4 5 6 7 8 9 " So would it be better to say...

 for ( int digit = 0; digit < 10; ++digit ) {
   printf( "%d ", digit );
 }

i is a meaningful variable name. It is the name of a loop index, probably because you are iterating over an array. When it is used that way, I never have any problems with it.

If you have a large chunk of code then you have other problems. You need a ComposedMethod. Loop bodies should never be more than a few lines long, and so a loop index should never be part of a large chunk of code.


There are a few single letter variable names with well understood meanings across a wide variety of programming languages. These are ...

Since these meanings are generic, one must be able to quickly find the variable's definition to understand to which index, coordinate, pointer or time the variable refers. They should only be used within small scopes, and within such scopes they are preferred over longer names.

Why are the short names preferred? Especially in a 3 dimensional array, I would prefer to see something like iTable, iRow, and iColumn rather than try to figure out the correlation to i, j, and k.

Long names can add noise and make things harder to read. For example, some find it much easier to read the i form of the loop at the top of the page than the digit form. It would be even worse if someone chose the name nextDigitToPrint or such. But it is true that if one has multiple variables within a scope, then descriptive names help to tell them apart.

Even these single letter names are rarely used in Smalltalk because most indices, coordinates, pointers and times are encapsulated within higher level abstractions.


There is also the argument from "egoless programming", which says that we should eschew possessive variable names like i in favor of the more inclusive we or us. --DaveSmith


See also
CategoryNaming CategoryCodingIssues
EditText of this page (last edited September 18, 2004)
FindPage by browsing or searching

This page mirrored in WikiPagesAboutRefactoring as of April 29, 2006