Meaningful Name

Always, always, always use good, unabbreviated, correctly-spelled meaningful names.

Rationale

It's clearer, easier to read. You aren't forced to remember the exact spelling of a symbol because you always know it is spelt correctly and thus consistently. It's also easier to search for with an editor's search function - try searching or grepping for all occurrences of the variable "i" within a function, without also picking up every instance of "void", "int", "printf", etc. You can do it with RegularExpressions, but not all editors have regex searches. It's statistically shown that using longer names leads to shorter debugging times, according to 201 Principles of Software Design.

A MeaningfulName gives you the ability to understand code two years after it is written.

Unless you are using Fortran or an archaic C compiler and have to worry about the six-character limit on external symbols, there is no reason to use abbreviations.

Disambiguation: See also a paper by the same name at http://tottinge.blogsome.com/meaningfulnames/

Arguments

"This is a mere platitude"

The rule does not help me choose between reasonable alternatives, it only tells me not to write bad, abbreviated, incorrectly-spelled meaningless names. Apart from the abbreviated or not question, why would I choose to do the other?

"I don't like typing that much!"

Good editors help. Copy and paste if you have to. It's not really that much to do. Typically, in a narrow system, a given symbol won't be referenced more than 20 times anyway.

"It's difficult to come up with meaningful names!"

Agreed. However I find that if I'm struggling to name something (be it local variable, object, pattern, ...) it is a sure sign I don't really understand what's going on. I also tend to think that bad names help to highlight areas where the CodeSmells. NonMeaningfulNames? can also be a sign of OverAbstraction?, or the fact that you, the reader, aren't literate in the program's ProblemDomain.

Disagree. If you have a good understanding of the problem domain, producing meaningful names becomes easy.

"Our simple, meaningful names tend to collide with third parties."

Use namespaces, scoped names, name mangling, or a large club to beat them with.

"I speak not good English and nobody in the my team does good. So we call method like getChilds() and getConcreteHead()"

"Short names make it easier to see the overall pattern of what is going on!"

Long names LoseSignalInNoise?.

(Being discussed below.)

Exceptions Abbreviations that have been used so often they have become words themselves. Such as the common mathematical functions min, max, sin, cos, abs; (although mathematics is a horror story in itself).

This is just a special case of another rule: Use term from the domain where appropriate. If your customer understands what an ni_rim is, use that.

Examples

"Sch" does not mean "Schedule". It means someone was too lazy to type the extra five characters and that probably means the rest of the code is equally as lax.

It is contentious whether or not "i" is the same as "count". "count" is probably just as bad as "i". "iStringPosition" may be better, but symbols that long tend to decrease readability of string parsing algorithms and simple iterations.

On the other hand, functional programming (C++'s STL supports this, although STL isn't necessarily supported by your compiler yet), removes even this case.


I think obscure abbreviated variable names are hard to use if they are hard to remember, otherwise, almost everything above is bad programming practice. Variable names aren't comments. If you think the variable needs more than the name you call it, then put the extra description in a comment. Why is it that almost all Mathematical formulas just use a, b, c or x, y, and z as variable names? Because the point is the relationship between them rather than what they are. Sometimes a table is given to explain what each of the variables mean. Almost all variables are local to a function, a table or an object. In all those cases, you only have to have unique names within that scope which doesn't require more than a single word. The more typing you do, the more chance of spelling the variable wrong. Long variable names also detract from the readability of a program and the longer names, in general, don't add any more explicit meaning than smaller variable names. I think there is a place for 1 character variable names but I am mostly saying that variables should be 1 word in size. I don't believe for 1 second that large variable names make debugging code easier. It is just not true. Having a good data dictionary and reusing the same variable names in different contexts makes program code easier to work with and less error prone. Encoding the variable type as a postfix or prefix of the variable name is also bad. If you don't know what type of variable it is don't touch it. -- DavidClarkd


NomenEstOmen? is Latin for "the name says it all" or maybe "take the name as a sign"

For OO programming that means that a class "Manager" is likely to not doing something productive.

See: DoesWhatItSaysOnTheTin, RonsealPattern


But

Abbreviations are bad, but much better than omitting information totally. So a function "copy" (unabbreviated word) is unacceptable compared to "FileCpyUrl" (abbreviated words). Omitting a word should be considered identical to abbreviating it to length zero.

See also: LanguageOrientedProgramming, ThelopLanguage, ThelopDictionary

-- HelmutLeitner

"FileCpyUrl" is still a terrible name, hardly better than "copy" at all. Does it copy data from a file to a URL, or copy data from a URL into a local file? And why "Cpy" not "Copy". Is one character going to make that much difference?


Examples of MeaningfulNames are:

Some not so meaningful names for the above would be: --Kris Wenzel


In practice I have found that FullySpellingOutAllWordsInCompoundVariableNames? can easily lead to excessively long names, such that even simple expressions, like "x = y + 1" won't fit in an 80-character line (after a few 4-character indents). Yes, refactoring things into micro-modules helps, but (to some extent) it trades one form of complexity for another. -- JeffGrigg

Excessively long lines are a CodeSmell. Assign state to variables in such a way that the contents of each variable may be described more succinctly.

The principle here should be that the length of a name must vary proportionately to its scope. I don't think that "i" is so bad in a list comp, or a loop counter inside a small method, but it is entirely wrong for a parameter name of a public function (or a private one, for that matter). Perhaps this is a matter of "dealing with a matter where the matter matters". I tend to use better variable names outside of list comps, where they can be seen, but in an anonymous or inner-nested function it is sometimes of little consequence.

That being said, long lines are a code smell as are confusing names. --TimOttinger


Meaningful to whom?

activateModem, initializeModem, makeModemReadyForUse, prepareModem, modemPrep, setupModem, setInitialModemState, executeModemPreparationSequence, ad nauseum ... none of these says more to me than modemInit.

The programmer making up the names may see things through very different eyes from those of the later programmers. Passive voice as opposed to active voice. Odd choices of adjectives.

And when one of the guys is from Thailand and creates function names like settingAllModemInsideRegisterForBeginValue and variables like wasStatusForToDialFinal (and, really, I'm not doing him justice -- some of his names were truly breathtaking) you can become a poster child for asprin.

Wait, wait, it gets better ... how about module name prefixing: customerModuleRetrieveFirstFitSpaceRecordSet among a set of functions that all begin with customerModuleRetrieve ... oh, man. You know, I was okay until I started to recall that nightmare. Andy, wherever you are, I hope you've opened a restaurant or something.

Keep names short. Code to a convention. Yes, make them meaningful. No, dontTryToWriteWholeSentencesWithYourStinkingFunctionName!

Let's make an exception to that rule for testing. TestThatTheParserDealsWithExtraneousLeadingWhitespace?() is not a problem. It's a solution. -- TimOttinger

I wonder if the tendency for South Asian cultures to have long names (both in individual parts and number of parts) was part of this Thai programmers motivation? Probably. CulturalAssumptions have a huge effect on name choices. Grammar probably also plays a large part; Thai does not have a rich, specific vocabulary for technical concepts. As a result, it tends (like German) to use a lot of highly verbose language to describe fairly commonplace technical things. Since culture plays such a huge part in such tendencies, it can be extremely difficult for programmers to conform to a Western/American methodology.


3 Choose a name that describes WHAT the object does, not how it does it.

-- TomStambaugh


I find that if I'm struggling to name something (be it local variable, object, pattern, ...) it is a sure sign I don't really understand what's going on. I also tend to think that bad names help to highlight areas where the CodeSmells. NonMeaningfulNames? can also be a sign of OverAbstraction?, or the fact that you, the reader, aren't literate in the program's ProblemDomain. I would add checking a prospective employee's naming conventions to the GuerrillaGuideToInterviewing as an easy way to immediately flag someone as a NoHire.

-- DanGreen


I added "but short names make it easier to see the pattern of what is going on." I have a general rule: The more frequently a name is used, the shorter it should be. Codified in CodeComplete, by the way -- JeffBay "index" is so common, and frequently so semantically unimportant, it can be abbreviated to "i" and make code easier to read.

 for(int i=0;i<SOME_LIMIT;i++)
   doSomethingImportant(withThis[i]);

Notice that the focus of this expression is on SOME_LIMIT, do_something_important, and with_this.

By increasing the length of "i", it starts to occupy much more cognitive space:

 for(int index=0;index<SOME_LIMIT;index++)
   doSomethingImportant(withThis[index]);

SOME_LIMIT is almost invisible. I don't want to think about indexes; I want to think about SOME_LIMIT, and doSomethingImportant, and withThis. Frequently, I'll make a pointer to something with a very long name, because I'm using it a lot in a block of code. That's the right thing to do, in that situation.

-- LionKimbro

I'd argue that typing anything short of index is wrong. For one, index is important, it tells you it's not count, i.e. it starts at 0 rather than 1 and this prevents common fencepost errors. It also reads better; read it out loud and you'll see; words are better than letters. The world isn't running out of words, don't abbreviate, it only adds to the confusion. -- RamonLeon

Of course it's not a count. If it was a count, it would be "n", not "i". My naming convention for short temporary names:

-- StefanVorkoetter.

It reads much better with i than index. i=0 gives a pretty clear indication that it starts at 0.

Hardly, "i" could mean anything, depending on context, "index" means "index", look at that, the power of language. Use words, not abbreviations. Abbreviations are bad form, and always make things difficult for the maintenance programmer later.

The operational phrase here is "depending on context". In the context of a loop, i means index.

[Using "i" for a simple loop index in C/C++ and several other languages is an extremely common language idiom, and as such is well-established to be actually preferred over e.g. "index", even though longer names are indeed generally preferable. Learn and use the idioms of the language at hand; departure from the common idioms often flags a mistake, and at best, distracts maintainers of the code.]

If the maintenance programmer has difficulty with that "i" in there later on, there's something seriously f**ked up with that maintenance programmer. They should not be maintaining programs.

If that "i" confuses you, and you are a programmer, then I am amazed.


One module I had to call into had a function that returned the raw, unprocessed count from an analog-to-digital converter. The function was named rawanal.


When Ken Thompson and Dennis Ritchie received the 1983 Turing Award, after their respective acceptance speeches, someone in the audience asked Ken what he would do differently with Unix if he were to do it all over again. He said, "I'd spell 'creat' with an 'e'."

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.
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 EgolessProgramming, which says that we should eschew possessive variable names like i in favor of the more inclusive we or us. --DaveSmith

Because I don't have LispLanguage I use a variable named "me" to uniquely identify an instance of a process - it is useful with recursion control.

Sorry, I don't have the time to read all this now... A presentation should be structured towards the intended audience, but this is sometimes underestimated. Language, vocabulary, jargon, definitions, abbreviations and symbols depend on the topic discussed. --GeraldLindsly


I like a MeaningfulName on my methods and classes, but within the scope of a ShortMethod? dealing purely with implementation, the single letters are better. If I find I'm confused by what the variables represent, then it tells me there is something wrong with the method.


--AlekseyPavlichenko


Remember that everybody's WetWare is different. What bothers/slows your mind may not another's and vice versa. Learn what works best for typical developers of your shop and/or in general. Ask around. You are not the world and should not be the primary target audience of your code. In my observation, a MeaningfulName is a compromise between lots of factors. --top


See SystemOfNames, BadVariableNames, RoleSuggestingVariable, ComplementaryNames, UnderscoreVersusCapitalAndLowerCaseVariableNaming, GoodVariableNames, UsingGoodNamingToDetectBadCode, RonsealPattern, MethodsWithNounNames, SelfDocumentingCode, AreLongAndDescriptiveRelated, AbbreviationsAreEvil.


CategoryCodingIssues CategoryNaming


EditText of this page (last edited December 8, 2014) or FindPage with title or text search