140
votes

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:

dR = radius
dCV = curvature
dK = conic constant
dDin = inner aperture
dDout = outer aperture
dRin = inner radius
dRout = outer radius

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?

12
  • 98
    It appears to me that in that specific case, those are variable names copied directly from a longhand math formula.
    – Dave Nay
    Nov 20, 2012 at 20:36
  • 1
    the only excuse I would accept would be "My peer told it's OK after reviewing the code"
    – gnat
    Nov 21, 2012 at 15:37
  • 35
    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, 2012 at 17:02
  • 3
    Any identifier that is named after Donkey Kong is approved: dK = conic constant. Dec 14, 2012 at 1:38
  • 8
    Conversely, one could ask if ignorance of the domain field justifies ignoring its conventions. In the end, it depends on the context. Feb 2, 2013 at 17:49

18 Answers 18

234
votes

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.

18
  • 17
    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, 2012 at 20:40
  • 127
    +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. Nov 20, 2012 at 20:52
  • 15
    +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. Nov 20, 2012 at 20:57
  • 23
    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, 2012 at 23:57
  • 11
    +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, 2012 at 1:08
89
votes

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!

15
  • 14
    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. Nov 20, 2012 at 21:24
  • 7
    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, 2012 at 4:56
  • 18
    -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. Nov 21, 2012 at 11:10
  • 3
    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. Nov 21, 2012 at 13:45
  • 6
    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, 2012 at 18:07
48
votes

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.

3
  • Ultimately ended up going with something like this.
    – KChaloux
    Nov 21, 2012 at 13:42
  • 5
    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, 2013 at 3:57
  • 7
    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, 2013 at 4:09
19
votes

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.

3
  • I'd argue that cv, din, and dout aren't immediately obvious (though apparently they are established in specific fields). I wouldn't argue about x and y, seeing as Cartesian coordinates are applicable for any number of fields, and are taught to everyone in middle and high school.
    – KChaloux
    Nov 21, 2012 at 1:01
  • 1
    And x and y, while common, don't carry implicit important aspects like where the origin in. Nov 21, 2012 at 2:28
  • 3
    @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. Nov 21, 2012 at 15:00
16
votes

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:

radius
curvature
conicConstant
innerAperture
outerAperture
innerRadius
outerRadius

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

enter image description here

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;
5
  • 26
    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, 2012 at 16:19
  • @MarkJ You are right. Nov 21, 2012 at 20:58
  • 1
    Intermediate results have the added benefit of reducing and isolating programming errors. Our brains can only process so many pieces of information at a time, and it's tough to spot the error in something like 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 ...; Feb 2, 2013 at 17:55
  • 1
    It's not that tough if that's your bread and butter.
    – Radu
    Feb 2, 2013 at 18:30
  • 1
    The point is not to write a one-liner. But the problem is that if you need to change something and use another formula now you have a problem where it takes a long time to figure out which long_name the R in the textbook refers to. Use intermediate results, but keep your complex maths as close as possible to the problem domain so that you can actually maintain it if you need to add a feature.
    – slebetman
    Sep 17, 2014 at 6:25
8
votes

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.

3
  • 7
    Absolutely correct, but the risk of lack of understanding is much greater. Nov 21, 2012 at 2:27
  • 2
    You have way bigger problems if your tools can't handle simple problems like the ones you mentioned. Nov 22, 2012 at 16:17
  • Answers (1) Reasonable automated test coverage and sane encapsulation, (2) Proficiency with version control.
    – Adamantish
    Mar 9, 2018 at 11:34
5
votes

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.

6
  • 7
    At the very least I'm certainly getting rid of the Systems Hungarian notation...
    – KChaloux
    Nov 20, 2012 at 21:03
  • 4
    The leading d is Hungarian? I thought it was calculus as in in dx^2/dx = 2x. Nov 20, 2012 at 23:20
  • 7
    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. Nov 21, 2012 at 3:35
  • 2
    +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, 2012 at 16:20
  • 1
    @ShannonSeverance I agree with you. Coming from an engineering background, d should definitely be reserved for calculus when using variable names in the mathematical sense (as it is often mentioned here).
    – CodeMonkey
    Mar 1, 2017 at 9:28
4
votes

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.

1
vote

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.

0
votes

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.

1
  • Right, that element was going away regardless of what people ended up saying. There's a sort of half-Hungarian half-not schizophrenia going on in the codebase that I'm updating as I find it.
    – KChaloux
    Nov 21, 2012 at 20:20
0
votes

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.

1
  • 1
    We don't read words as a set of characters, we read them as shapes and resolve details conditionally when at-a-glance comprehension fails. The length a word must be to take longer to read is far greater than 4 characters, and we're able to mentally process camelCase and other means of breaking up variable name words as word boundaries. I doubt a reading test would bear out a claim that shorter names improve reading comprehension speed; instead, by removing recognizable words, there will be a speed decrease until the new words are assimilated (which you yourself point out). Feb 2, 2013 at 18:07
0
votes

To frame what @zxcdw said in a slightly different way, and elaborate on it in terms of approach:

Functions should be pure, brief and a perfect encapsulation of some functionality: Black box logic, regardless of whether it has been sitting untouched for 40 years, it will continue to do the job it was designed for, because its interface (in and out) is sound, even as you know nothing of its internals.

This is the kind of code you want to write: this is code that lasts, and is simple to port.

Where necessary, compose functions out of other (inline) function calls, to keep code fine-grained.

Now, with a suitably descriptive function name (verbose if necessary!), we minimise any chance of misinterpretation of those shortened variable names, since the scope is so small.

-1
votes

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.

3
  • 6
    Note that int dummy_variable_for_for_loops; is as descriptive as possible.
    – Kaz
    Nov 20, 2012 at 23:50
  • 4
    -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. Nov 21, 2012 at 0:50
  • I'd change that to read "as descriptive as necessary". If a short name conveys the variable's purpose, then it's OK to use a short name. Nov 22, 2012 at 9:02
-1
votes

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.

-1
votes

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).

-1
votes

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.)

1
  • 1
    Your example is still not very realistic.
    – Radu
    Feb 2, 2013 at 18:33
-1
votes

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

3
  • 1
    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, 2014 at 11:46
  • @MSalters That's pretty cool; a template/macro approach hadn't occurred to me. Still, in a "language-agnostic" question like this I'd group all compile-time unit checks under the "stronger types" umbrella, regardless of whether the language calls them "types" or not ;)
    – Warbo
    Sep 17, 2014 at 16:01
  • Template, necessarily. You can't do the necessary type calculus in macro's.
    – MSalters
    Sep 18, 2014 at 15:20
-2
votes

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.

7
  • 9
    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
    – Andy Hunt
    Nov 20, 2012 at 20:38
  • 2
    @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, 2012 at 20:44
  • 8
    @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. Nov 20, 2012 at 21:07
  • 2
    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? Nov 21, 2012 at 0:51
  • 4
    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, 2012 at 16:22

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