28

Are short identifiers bad? How does identifier length correlate with code comprehension? What other factors (besides code comprehension) might be of consideration when it comes to naming identifiers?

Just to try to keep the quality of the answers up, please note that there is some research on the subject already!

Edit

Curious that everyone either doesn't think length is relevant or tend to prefer larger identifiers, when both links I provided indicate large identifiers are harmful!

Broken Link

The link below pointed to a research on the subject, but it's now broken, I don't seem to have a copy of the paper with me, and I don't recall what it was. I'm leaving it here in case someone else figure it out.

9
  • 5
    Data point. My favorite short identifier is :, as in :(){ :;:& };: -- I'd say most people think it's pretty bad. ;)
    – user2348
    Dec 6, 2010 at 18:30
  • @fennec: Fork bombs tend to be.
    – Josh K
    Dec 6, 2010 at 20:24
  • Check this question of stackoverflow there's a comment about Practice of Programming a book every programmer should read.
    – slu
    Dec 7, 2010 at 8:59
  • 1
    Just because longer names should be avoided doesn't mean you should make an extra effort to shorten them for shortness sake.
    – JeffO
    May 10, 2011 at 23:00
  • 1
    @cessor Funny that something that was intended to be about research was closed as opinion-based. Sadly, I agree, given the answers it received. Aug 20, 2018 at 0:16

15 Answers 15

70

The best "rule" I've heard is that name lengths should be proportional to the length of the scope of the variable. So an index i is fine if the body of the loop is a few lines long, but I like to use something a little more descriptive if it gets to be longer than 15ish lines.

7
  • 6
    I've never heard of such a thing, and I don't think this principle would improve the readability of code. Dec 6, 2010 at 12:06
  • 8
    @Nim: I agree. Even in a short for loop, I'd name the index, customerCounter or something. It takes minimal extra effort and makes your code so much better. Using short variables for a short scope sounds like an excuse to be lazy.
    – Nobody
    Dec 6, 2010 at 12:38
  • 2
    Hmm, its not a rule or a guideline to me but a way of making you think about length and in that context it makes some sense. I certainly don't think its an excuse for laziness (though I'll agree that some might take it as such). My identifiers are long more often than not (signs of being taught pascal early on) except now when I get to things like linq queries and lambda expressions where 1, 2, or 3 character identifiers (usually type initials) seem to make sense to me.
    – Murph
    Dec 6, 2010 at 13:43
  • 33
    +1 Honestly a "descriptive" name is just noise in a five line for loop; I think most people have a pretty good grasp on what you are doing with the "i". I have used descriptive names in nested loops, but those have a longer scope.
    – Jeremy
    Dec 6, 2010 at 15:28
  • 18
    +1 - Using i and j are common names that every developer should be able to understand IMO. Dec 6, 2010 at 15:38
49

Each variable should have a meaning, and its name is a part of that meaning. And a very important part, since it helps the reader to understand what it is for without digging deeper into algorithm. i, j are obvious to be used as indices, they are short, but very informative. bnt is ugly, close or closeButton are meaningful. So being short or long is not the most important criterion for the variable name, it should be meaningful. The meaningfulness strongly depends on the context. For example, you can give a very short name like n to the local string variable which is used in a small block of the code say 10 lines and refers to the name of a property (v for value is another example).

So variable names should be informative and it doesn't matter they short or long.

2
  • 2
    +1, and just to note, close and closeButton aren't synonymous either. Close is a verb, and thus, should be the name of a function or method. While closeButton is a noun, and should, obviously, be the name of the button that triggers the close function.
    – CaffGeek
    Dec 7, 2010 at 16:54
  • close is an adjective, e.g. close = true ;)
    – Armand
    Dec 8, 2010 at 1:36
13

I will use an identifier that describes the variable, irrespective of length.

The cases of i,j and k are in themselves so ubiquitous they are self describing, you automatically know they are loop indices. You could also say the same for :

foreach loop (Strings s : myString)

However, IDE's now provide code completion tools so the only negative side effect of very long and descriptive identifiers has been removed afaik.

I will happily add and extra word to an identifier, if its required to explain the purpose of the variable.

4
  • 3
    BTW, the use of i, j and k for loop indicies goes back 50+ years to FORTRAN. Variables that begin with the letters I thru N are by default of type INTEGER. Variables that begin with any other letter are by default REALs. This naturally led to using I, J, and K for for-loop indices. (The FORTRAN convention probably came about from the use of these variables used in math equations before that.)
    – tcrosley
    Dec 6, 2010 at 15:39
  • 2
    The second paper I linked has shown that very long descriptive identifiers decreases one's ability to understand the code, contradicting the "only negative side effect" remark. Dec 6, 2010 at 16:42
  • 3
    The real negative side effect of very long identifiers is in readability. It's hard to tell at a glance whether two very long identifiers are the same or different, and it can be hard to pick out all the elements of an expression with very long identifiers. Dec 6, 2010 at 16:49
  • tcrosley - I'd add that just because it comes from Fortran is no reason to continue such a practice. I strongly discourage the use of iterator / loop counters called "i", "j", "k", etc. It's plain intellectual laziness. Ubiquitous <> good. Jan 6, 2011 at 22:21
9

They are not as bad as the misleading identifiers. I don't mind debugging code in which the identifiers are only one letter, but the moment different naming conventions come into the picture it becomes annoying. E.g., if somewhere you see strPersonID, and then somewhere else you see s_EmployeeID, then it's confusing to tell if are these both strings and whether there is any difference. Also if the variables are copy-pasted (pmapIntString = new std::map<int,int>) and are totally wrong, I will worry.

When it comes to me, I add comments in the code for the important variables used and try to maintain the standard given in development guideline. If there is no standard then I try to maintain the same naming convention throughout the code.

4

I struggle...

I use to always use descriptive names as identifiers, but of late I've used very short identifiers.

I think, it depends on the context of the code:

  • If your writing complex functions (algorithms), then ALWAYS use short identifiers (single characters are best)
  • When writing Parameter values for functions use descriptive names.

I guess it depends on also how dense the code is. Sometimes having names actually makes it more difficult to read.

Sometimes without names its totally cryptic!

6
  • 1
    If you're writing complex algorithms, though, wouldn't you want the identifiers to be more descriptive for people looking at your code for the first time?
    – Maxpm
    Dec 6, 2010 at 16:49
  • When is a single character identifier ever appropriate? Dec 6, 2010 at 17:55
  • 1
    I use to also think that, but I've actually found this is not the case, try for yourself. Take a complex algorithm and try with descriptive names vs single letter variables.
    – Darknight
    Dec 6, 2010 at 18:36
  • 1
    I agree but only for a longer complex formulas, because they tend to get too long, and even then you could use functions (function names) to describe what parts of that formula are. Dec 6, 2010 at 21:38
  • 1
    If it's that complex, and has patterns, those patterns should be broken out into functions
    – CaffGeek
    Dec 7, 2010 at 16:59
3

My thinking is that they are not bad in themselves but they are uninformative unless they are very standard.

So loop variables being i, j and k is so standard that there is no reason not to use them if you are creating an indexed loop.

The other place I will use a very short identifier is when I'm declaring a temporary variable that will go out of scope in a few lines time- the temporary variable from a foreach loop, for example. If it's not going to be referred to anywhere else then it's easy for anyone reading the code to see the declaration and follow what it is being used for. If it's going to be used for more than five or six lines, though, I'll be looking to give it a clearer name.

Beyond that I try to use informative length identifiers- particularly at a class level I want an identifier that you can read and get an idea of what the variable is for. If they are getting too long ( and I do see code sometimes with four or five words strung together for an identifier ) I tend to regard that as a code smell - if I need that much text to distinguish my variables are they actually a group that could be better stored in a hashmap or list? Could I be creating some kind of object to model this data more accurately? Sometimes you can't but a very long identifier is an indicator that there is something worth looking at here.

3

I agree very much with the other answers here, but would like to point out one other factor that I think is often overlooked. A good name is often one that is idiomatic to the code. This can be on a language level, algorithm level or some internal idioms for the codebase at hand. The point is that while the name may mean nothing to someone that does not know the domain of the code, it may still be the best name in the given context.

3

Naming a variable is always an exercise in balancing uniqueness and comprehensibility. The length of the name is related to both, in different ways. Longer names are easier to make unique; medium length names tend to be more comprehensible than names that are too short or too long.

A very short variable name is useful only if it has a history that makes it comprehensible (e.g., i, j, & k for indices; dx for a distance along an axis) or a scope that is small enough for all references to be visible at once (e.g., temp). The worst variable names in the world are things like t47. ("What does that mean and why is it different from t46?") Thank goodness that style of naming mostly went out with FORTRAN, but this is where the desire for longer variable names is rooted.

As your original paper showed, too-long names are also hard to read, as subtle internal differences can be missed when glancing at code. (The difference between DistanceBetweenXAxisAbscissae & DistanceBetweenYAxisAbscissae is really hard to pick up quickly.)

As NoteToSelf pointed out earlier, the requirements for uniqueness of a name depend primarily on the scope the name has to be unique over. The index of a 5-line loop can be i; an index of an active record that gets passed from function to function had better have a much more descriptive name.

A variable local to a function can have a small descriptive name like deltaX without problem. A static delta X variable in a module must have a name that distinguishes this deltaX from other deltaX's in the same module, making it longer. And a global delta X variable must be made unique across all modules and all possible other modules that may be created, probably by concatenating the module name to the other descriptive name. This is one of the many problems with globals; to be usefully unique the names must be long enough to make them difficult to read.

2

On the contrary, I think long identifiers are worse than short identifiers (unless you're dealing with constants). Using TheVariableThatHoldsTheCapacityOfMyContainerClass makes your code a lot more prone to errors than using Capacity.

11
  • 1
    You'd be happy to know that one of the researches I linked support your reasoning, if not for the same reasons, then. ;-) Dec 6, 2010 at 16:44
  • 1
    It's also real easy to misread very long identifiers, possibly confusing them or possibly failing to realize that two of them are the same. Dec 6, 2010 at 16:47
  • 2
    TheVariableThatHoldsTheCapacityOfMyContainerClass is bigger than I would regard as "long" - ten words is too long for CamelCase to help; you need spaces to make that readable. Dec 6, 2010 at 17:32
  • 1
    Sure, but this is a straw man. Your example of a long name adds verbiage but no information. Consider the case where you have multiple variables relating to various forms of capacity. Then you really might want names that distinguish the purposes, like initalCapacity, or finalCapacity. Dec 6, 2010 at 19:56
  • 2
    @Maxpm, var total = Capacity + Capacity2; What does Capacity contain, and what does Capacity2 contain? What will they be used for? Having to look for context clues wastes time. Whereas if it's written as var totalStorageCapacity = truckCapacity + trailerCapacity; I know what we're talking about.
    – CaffGeek
    Dec 7, 2010 at 17:52
1

The first paper you link to looks interesting, but its conclusion is that they found no significant evidence for or against the hypothesis that "grounding hints", including meaningful variable names, help in code comprehension. The used gaze dwell time as a proxy for code comprehension which is interesting, but not a slam dunk.

I'm afraid I found the second paper just silly. The first problem is that the examples of long names they provide are gratuitously long, providing no extra information. I think we can all agree that making a variable name longer just to make it longer is stupid. Their example of naming a variable distance_between_abscissae rather than dx is a straw man.

More importantly, their experiment is a test of simple memorization rather than comprehension. It tests the ability of subjects to fill in missing pieces of a variable name when presented in a list with no context. Yes, longer names are harder to memorize, but when I'm coding I don't memorize variable names, I use them to provide context. I suppose you could argue that the difficulty of remembering long variable makes code harder to write, but code is read far more often than it is written, so which activity should be optimized?

1
  • Note that the second paper states clearly that "The eight names used in the eight questions were extracted from production code." Also, they do not test for memorization alone, but for correctness as well. Dec 7, 2010 at 10:57
1

In, and of themselves, short identifiers are not bad. The purpose of choosing good names (short or long) is in service to code clarity. Choosing identifiers in the service of code clarity is more important than meeting some minimum length requirement. In general what this means is writing slightly longer meaningful names.

1
  • +1 you've said it very very well, I couldn't find my words when I've wrote the answer :-)
    – user8747
    Dec 14, 2010 at 5:17
1

One of my main metrics for determining whether a line of code is readable or not is how much other context from other lines must be read to really be sure that you understand what the line is doing.

It's easy to say that "anyone should be able to understand that i, j and k are loop variables". And most of the times it is really obvious. But I still try to stay humble and professional about this and assume that it's easy to make mistakes when programming. So if I am looping through an array of Grobbles I will name the loop variable grobbleIndex. I could also accept i as an abbreviation of index. When you are using i j and k it's harder to spot error like using the wrong index with the wrong array and so on. And it gets even worse when you have an inner loop.

PS. At the time I wrote this answer I was coding some javascript on a 10" mini laptop with a vertically split screen in vim and I still took the time to name my loop variables rowIndex and columnIndex.

0
0

An observation that I have had over the years and it's less so today than it was 10 or 15 years ago. Programmers that can't type are the one that will fight you tooth and nail over variable naming. They are the ones with all the 1-3 letter variable names.

So my advice is use a meaningful name as many commenters have said and then learn to type. I have been considering adding a typing test to interviews, just to see where people are, but I am starting to see a lot less of the non-typers as computers become a bigger part of society.

2
  • 2
    I have seen no such correlation, actually. If anything it seems people from OO languages go for long identifiers, and people from functional language go for short ones. It does put in question the allegation that OO helps with modelling. :-) Dec 6, 2010 at 16:44
  • Don't forget that the names need not only be typed but also read. Using too long identifiers may actually decrease the readability a lot. Using anything but i in a loop like for (int i=0; i<dst.size(); ++i) dst[i] += src[i] should be prohibited by law.
    – maaartinus
    May 10, 2011 at 22:14
0

In some applications a short variable simply cannot explain the data in the variable. Short or long is irrelevant. Using a longer variable does not make your code slower. Sure it is more effort typing out a long variable name but atleast the person who reads the code 6 months later (which may be you) will be able to make out what is happening without needing to put traces assuming that is even possible.

0

I think the ideal is that names should be descriptive unless...

The idea that names can (maybe should) be shorter - and thus by implication less descriptive - if they have limited scope is only one reason to deviate from the ideal.

Personally I frequently use short names for a small number of repeatedly-referenced entities. Frequently-called app-specific subroutines, for example.

Not the answer you're looking for? Browse other questions tagged or ask your own question.