# Is there an excuse for short variable names?

This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent.

For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows:

double dR, dCV, dK, dDin, dDout, dRin, dRout
dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1));
dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1));
... and so on

Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant:

dCV = curvature
dK = conic constant
dDin = inner aperture
dDout = outer aperture

I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

-
It appears to me that in that specific case, those are variable names copied directly from a longhand math formula. – Dave Nay Nov 20 '12 at 20:36
If you find yourself unable to understand mathematical code because of short variable names, be aware that it may be because you don't understand the mathematics, not because the names are too short. Altering mathematical expressions you don't understand is not a high-reliability process. Once you understand the math, the length of the variable names is irrelevant. Do others a favor and leave a citation (in a comment) to some relevant description of the math, though, if you had to learn it! – Rex Kerr Nov 21 '12 at 17:02
Any identifier that is named after Donkey Kong is approved: dK = conic constant. – Thomas Eding Dec 14 '12 at 1:38
Conversely, one could ask if ignorance of the domain field justifies ignoring its conventions. In the end, it depends on the context. – Daniel C. Sobral Feb 2 '13 at 17:49

It appears that these variable names are based on the abbreviations you'd expect to find in a physics textbook working various optics problems. This is one of the situations where short variable names are often preferable to longer variable names. If you have physicists (or people that are accustomed to working the equations out by hand) that are accustomed to using common abbreviations like Rin, Rout, etc. the code will be much clearer with those abbreviations than it would be with longer variable names. It also makes it much easier to compare formulas from papers and textbooks with code to make sure that the code is actually doing the computations properly.

Anyone that is familiar with optics will immediately recognize something like Rin as the inner radius (in a physics paper, the in would be rendered as a subscript), Rout as the outer radius, etc. Although they would almost certainly be able to mentally translate something like innerRadius to the more familiar nomenclature, doing so would make the code less clear to that person. It would make it more difficult to spot cases where a familiar formula had been coded incorrectly and it would make it more difficult to translate equations in code to and from the equations they would find in a paper or a textbook.

If you are the only person that ever looks at this code, you never need to translate between the code and a standard optics equation, and it is unlikely that a physicist is ever going to need to look at the code in the future perhaps it does make sense to refactor because the benefit of the abbreviations no longer outweighs the cost. If this was new development, however, it would almost certainly make sense to use the same abbreviations in the code that you would find in the literature.

-
And if there are no physicists or mathematicians on staff? The code was essentially left to me. It's largely undocumented. Would it be more difficult to read the descriptive names? – KChaloux Nov 20 '12 at 20:40
+1 It's not unreasonable to expect a programmer to understand the domain he's working in. On the other hand, in mathematical works, the variables are usually defined in a convenient place. In code like this I would expect a prominent comment showing the long form. – Karl Bielefeldt Nov 20 '12 at 20:52
+1: What you're basically saying is that a programmer who understands the domain that they're working in will understand the variable names. This is going to be the same in many projects even with longer variable names. eg. a variable named column in a military strategy game very likely means something different than it would in charting software. – Steve Evers Nov 20 '12 at 20:57
In medical programming you'll often find terms that persist into the programming sphere. For example with ophthalmology you'll see OU, OD, and OS. These denote which eye, for example ouSphere may reference the 'sphere' component of a eyeglass prescription for the right eye. You'll be a better programmer if you understand the business domain you are programming for. – Bill Nov 20 '12 at 23:57
+1 for noting that short names that match those in equations & formulas from papers and texts. When I do that, I include the comments on where to find the original reference material . – Jay Elston Nov 21 '12 at 1:08

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 general rule of thumb it could be said that the shorter the variable scope the shorter the name should be. Loop counters are often only single letters, say i, j and k. Local variables are something like base or from and to. Global variables are then somewhat more elaborate, for example EntityTablePointer.

Perhaps a rule like this isn't being followed with the codebase you work with. It's a good reason for doing some refactoring though!

-
i, j and k for array indices represent a tradition going back at least to Fortran. Any self-respecting programmer will be familiar with this convention. – Dominic Cronin Nov 20 '12 at 21:24
I usually don't write i, j, k, I write something like personPos because then I won't forget what I'm iterating on and what the index represents. – Malcolm Nov 21 '12 at 4:56
-1, I do use long names for array index iterations, but I give them meaningful name instead of obvious and meaningless arrayCounter. Makes code easier to read and at very least saves you from stomping all over outer counter when you copy/paste another loop inside this one. – Oleg V. Volkov Nov 21 '12 at 11:10
counter is a noun or an adjective. Count is a noun or a verb. Of course, I still wouldn't call something arrayCounter, I'd use personIndex or row or whatever described what I'm looking at. – Wayne Werner Nov 21 '12 at 13:45
When I'm doing a single loop, I use i. But as soon as I transition to a nested loop, I drop the i nomenclature. The reason for this is because I really want to track which loop variable is being worked with, and i vs j can be quite deceiving in dense code. Making it more readable, and adding more whitespace, is inherently necessary to me. – jcolebrand Nov 21 '12 at 18:07

The problem with the code is not the short names, but rather the lack of a comment which would explain the abbreviations, or point to some helpful materials about the formulas from which the variables are derived.

The code simply assumes the problem-domain familiarity.

That is fine, since problem-domain familiarity is probably required to understand and maintain the code, especially in the role of someone who "owns" it, so it behooves you to acquire the familiarity rather than to go around lengthening names.

But it would be nice if the code provided some hints to serve as springboards. Even a domain expert could forget that dK is a conic constant. Adding a little "cheat sheet" in a comment block wouldn't hurt.

-
This is wrong. There is no reason to make your code hard to read in order to force people to spend more time "learning" it. You're not teaching, you're just slowing people down. Also, there is virtually never a single owner of code forever. You're being short sighted and selfish. – xaxxon Feb 3 '13 at 3:57
It is your interpretation that is wrong, not the answer. The code implements some math which exists outside of that code and independently of it, and which came before the code. Keeping the same naming is helpful. Someone who maintains the code will probably have to study that outside math, and not having to map between two naming schemes will help that person. – Kaz Feb 3 '13 at 4:09

For certain variables which are well-known in the problem domain -- like the case you have here -- terse variable names are reasonable. If I'm working on a game, I want my game entities to have position variables x and y, not horizontalPosition and verticalPosition. Likewise loop counters that don't have any semantics beyond indexing, I expect to see i, j, k.

-
And x and y, while common, don't carry implicit important aspects like where the origin in. – Ross Patterson Nov 21 '12 at 2:28
@RossPatterson: however, there are many contexts where that simply is not important. For example, consider a loop such as for (x,y) in list_of_coordinates: print x,y: The origin doesn't particularly matter when trying to understand the code. – Bryan Oakley Nov 21 '12 at 15:00

Acording to "Clean Code":

Variable names should:

• Be intention revealing
• Avoid disinformation
• Make meaningful distinctions
• Be pronounceable
• Be searchable

Exceptions are the proverbial i,j,k,m,n used in for loops.

The variable names you, rightfully, complain about do nothing of the above. Those names are bad names.

Also, as every method must be short, using prefixes to indicate either scope or type is no longer in use.

This names are better:

curvature
conicConstant
innerAperture
outerAperture

A commenter says that this would be too complex with long variable names:

Short variable names don't make it simple either:

fnZR = (r^2/fnR(1+Math.sqrt((1+k) * (r^2/R^2)))) + a[1]*r^2 + a[1]*r^4 + a[1]*r^6 ...;

The answer is long names and intermediate results until you get this at the end:

thisNiceThing =  ( thisOKThing / thisGreatThing ) + thisAwsomeThing;
-
These variables are probably used in mathematical formulae in the code. Mathematical formulae are much easier to read with short variable names. I use long variable names in most of my code, but maths is better with short variable names. Random example: consider how long this would be with long variable names. – MarkJ Nov 21 '12 at 16:19
It's not that tough if that's your bread and butter. – Radu Feb 2 '13 at 18:30

There are two good reasons not to rename variables in legacy code.

(1) unless you're using an automated refactoring tool, the possibility of introducing bugs is high. Hence, "if it's not broken, don't fix it"

(2) you will make comparing current versions with past versions, in order to see what changed, impossible. This will make future maintenance of the code more difficult.

-
Absolutely correct, but the risk of lack of understanding is much greater. – Ross Patterson Nov 21 '12 at 2:27

Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

The reason to use smaller names is if the original programmer finds them easier to work with. Presumably they have the right to find that to be the case, and the right not to have the same personal preferences that you have. Personally, I'd find...

dDin better than dDinnerAperture
dDout better than dDouterAperture

...if I was using them in long, complex calculations. The smaller the math expression, often the easier it is to see the whole thing at once. Though if that was the case, they might be better as dIn and dOut, so there wasnt a repetitive D that could lead to an easy typo.

On the other hand, if you find it harder to work with, then knock yourself out and rename then to their longer form. Especially if you are responsible for that code.

-
At the very least I'm certainly getting rid of the Systems Hungarian notation... – KChaloux Nov 20 '12 at 21:03
The leading d is Hungarian? I thought it was calculus as in in dx^2/dx = 2x. – Shannon Severance Nov 20 '12 at 23:20
If I saw dDinnerAperture by itself, I'd read it as "Dinner Aperture", and wonder if it's just a funny way of saying "your mouth". Never been a fan of the "capital letter followed by lower-case word) style. Very confusing sometimes. – Darrel Hoffman Nov 21 '12 at 3:35
+1 this is the answer. Long maths formulae are much easier to read with short variable names. These variables are probably used in mathematical formulae in the code. Mathematical formulae are much easier to read with short variable names. I use long variable names in most of my code, but maths is better with short variable names. Random example: consider how long this would be with long variable names. – MarkJ Nov 21 '12 at 16:20

Generally, I believe that the rule for this, should be that you can use extremely short variable names where you know that people who are "skilled in the art" of your particular code will immediately understand the reference of that variable name. (You always have comments for the exception of this case anyway), and that the localized usage of the variables can easily be discerned based on the context of how they are used.

To expand on this, it means that you shouldn't go out of your way to obfuscate your variable names, but, you can use abbreviations for your variables names, where you know that only people who understand the underlying concept of your code are likely to read it anyway.

To use a real world example, recently, I was creating a Javascript class that would take a latitude, and tell you the amount of sunlight that you would expect on a given date.

To create this Sundial class, I referred to perhaps half a dozen resources, the Astronomy Almanac, and snippets from other languages, (PHP, Java, C etc).

In almost all of these, they used similar identical abbreviations, which upon the face of it mean absolute nothing.

K, T, EPS, deltaPsi, eot, LM, RA

However, if you have knowledge of physics you can understand what they were. I wouldn't expect anyone else to be touching this code, so why use verbose variable names?

julianTime, nutationOfEclipticalLongitudeExpressedInDegrees, equationOfTime, longitudeMean, rightAscension.

Additionally, a lot of the time, when variable names are transitory, that is to say, they are only used to temporarily allocate some value, then it frequently doesn't make sense to use a verbose version, especially when the context of the variable explains it's purpose.

-

I can think of a reason for variable names to be reasonably short.

The short names are easy to read using shorter eye-span, hence a short attention span.

For example, once I get used to the fact that svdb means "save to the database", the rate of scanning the source code gets better as I only have to quickly scan 4 characters instead of when reading SaveToDatabase (14 characters, things get worse for more complex operation names). I say "scanning" not "reading", because that takes a major part of analyzing source code.

When scanning through large amount of source code, this can provide good performance gains.

Also, it just helps the lazy programmer to type out these short names when writing code.

Of course, all these "shorthands" is expected to be listed in some standard location in the source code.

-

Variable names should be as descriptive as possible to help the readability of the program. You experienced it yourself: you had a lot of trouble identifying what the program did because of the poor naming.

There is no good reason not to use descriptive name. It will help you, and everyone else that works/will work on the project. Well actually there is a single valid use for short names: loop counters.

-
Note that int dummy_variable_for_for_loops; is as descriptive as possible. – Kaz Nov 20 '12 at 23:50
-1 because this answer is confusing. First it says there are no good reasons, then finishes by saying that actually, there are. The answer would be better if it was rephrased not to contradict itself. – Bryan Oakley Nov 21 '12 at 0:50

For interfaces (e.g., method signatures, function signatures) I tend to solve this by annotating the parameter declarations. For C/C++ this decorates the .h file as well as the code of the implementation.

I do the same for variable declarations where knowing the usage of the variable is not obvious in context and in the naming. (This applies in languages that don't have strong typing also.)

There are many things that we don't want to clog the variable name. Is the angle in radians or degrees, is there some tolerance on precision or range, etc. The information can provide valuable assertions about characteristics that must be dealt with correctly.

I am not religious about it. I am simply interested in clarity and in making sure that I now what it is the next time my forgetful self visits the code. And anyone looking over my shoulder has what they need to know to see where something is off, what is essential (the last critical for proper maintenance).

-

Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

Usually, complex algorithms are implemented in matlab (or similar language). What I have seen is people just taking over the variables name. That way, it is simple to compare implementations.

All other answer are almost correct. These abbreviations can be found in math and physics, except they do not begin with d (as in your example). Variables beginning with d are usually named to represent differentiation.

All normal coding guides are telling not to name variables with the first letter representing type (as in your case), because it is so easy to browse the code in all modern IDEs.

-

There absolutely is; often times a short variable name is all that is necessary.

In my case, I am doing waypoint navigation in my senior Robotics class, and we program our robots in KISS-C. We need variables for current and destination (x, y) co-ordinates, (x, y) distances, current and destination headings, as well as turn angles.

Especially in the case of x and y co-ordinates, a long variable name is completely unnecessary, and names such as xC (current x), yD (destination y), and pD (destination phi), suffice and are the easiest to understand in this case.

You might argue that these aren't 'descriptive variable names' as programmer protocol would dictate, but since the names are based on a simple code (d = destination, c = current), a very simple comment at the outset is all the description they require.

-

Is there an excuse for excessively short variable names?

First: Naming a variable for energy e while calculating formulas such as E=MC2 is NOT excessively short naming. Using symbols as an argument for short names is not valid

This question was rather interesting to me, and I can only think of one excuse and that is money.

Say for instance you're wiring javascript for a client which knows that the file is to be downloaded many times a second. It would be cheaper and make the experience of the users better if the file (in number of bytes) is as small as possible.

(Just to keep the example 'realistic', you were not allowed to use a minifier tool, why? Security issues, no external tools allowed to touch the code base.)

-

I notice that the other answers don't mention the use of Hungarian Notation. This is orthogonal to the length debate, but relevant to naming schemes in general.

double dR, dCV, dK, dDin, dDout, dRin, dRout

The "d" at the beginning of all these variables is meant to indicate that they're doubles; but the language is enforcing this anyway. Despite the terseness of these names, they're up to 50% redundant!

If we're going to use a naming convention to reduce errors, we're much better off encoding information which isn't being checked by the language. For example, no language will complain about dK + dR in the above code, even though it's meaningless to adding a dimensionless number to a length.

A good way to prevent such errors is to use stronger types; however, if we're going to use doubles then a more appropriate naming scheme might be:

// Dimensions:
// l  = length
// rl = reciprocal length
double lR, rlCV, K, lDin, lDout, lRin, lRout

The language will still allow us to write K + lR, but now the names give us a hint that this might be incorrect.

This is the difference between Systems Hungarian (generally bad) and Apps Hungarian (possibly good)

http://en.wikipedia.org/wiki/Hungarian_notation

-
Actually, C++ can complain about K + lR if you properly declare your units. With SI units it can do dimensionality checks and unit conversion. Adding 3_feet + 2_meter should be no problem, while 2_meter+1_second should be a compile-time error. – MSalters Sep 17 '14 at 11:46

Surely this is what // comments are for?

If the assignments have comments which are descriptive you get the best of both worlds: a description of the variable and any equations are easily comparable with their text book counterpart.

-

The only case where illegibly short variable names are acceptable in modern software engineering is when they exist in a script and the throughput of that script (over a network generally) is important. Even then, keep the script with long names in source control, and minify the script in production.

-
What about when performing mathematical operations where the terms are considered common knowledge in the domain? Example: using M instead of "mass" in e=mc^2 – AndyBursh Nov 20 '12 at 20:38
@andyBursh - I'd be careful there. Programmers are not often experts (or even competent) in their problem domain. That said, this sort of thing can be okay, especially if there's the appropriate comment link to the formula in question; I had forgotten about this scenario. – Telastyn Nov 20 '12 at 20:44
@Telastyn - If you assume that the programmer is not an expert, though, that often leads to taking abbreviations that have a very well defined meaning and turning them into longer names that are at least somewhat ambiguous (i.e. someone decides to name a local variable radius when it stores the inner radius not understanding that is much more ambiguous than Rin). And then the non-expert developer has to translate between his unique nomenclature and the nomenclature that the business understands every time there is a discussion involving equations. – Justin Cave Nov 20 '12 at 21:07
What about "i" for a loop counter? Or "x" and "y" when dealing with a coordinate? Or a variable whose scope is only two lines of code? – Bryan Oakley Nov 21 '12 at 0:51
Disagree with this answer. A programmer working on a program containing complex mathematical expressions had better be able to at least read the formulae in the spec, otherwise they're not competent. That's not problem domain knowledge, that's an essential skill - some basic maths competency before working on a mathematical program. If the programmer doesn't have access to the spec formulae, that's another problem - and it can't be solved by comments alone. – MarkJ Nov 21 '12 at 16:22

## protected by maple_shaft♦Aug 30 '15 at 13:49

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site.