The world's two worst variable names
by Andy Lester
Code Complete, due out in June. Bless his heart, he's got an entire chapter devoted
to good variable naming practices. He touches on, but doesn't fully
explore, two of the biggest sins in variable naming. Allow me to hop
up on my soapbox.
Bad variables are all over the place.
Usually it will be something like a short variable used for too long, like $n being used for the duration of an entire subroutine. The programmer might as well have been working in
TRS-80 BASIC, where only the first two characters of variable names were
significant, and we had to keep a handwritten lookup chart of names in
a spiral notebook next to the keyboard.
Sometimes you'll find variables where all vowels have been removed as a shortening technique, instead of simple truncation, so you have $cstmr instead of $cust. I sure hope you don't have to distinguish the customers from costumers!
There have also been intentionally bad variable names, where the writer
was more interested in being funny than useful. I've seen $crap
as a loop variable, and a colleague tells of overhauling
old code with a function called THE_LONE_RANGER_RIDES_AGAIN().
That's not the type of bad variable name I mean.
Variable naming conventions can often turn into a religious war, but
I'm entirely confident when I declare The World's Worst Variable Name to be:
$dataOf course it's data! That's what variables contain! That's all they
ever can contain. It's like you're packing up your belongings to move to
a new house, and on the side of the box you write, in big black marker,
"matter."
Even if it's a function pointer, it's data that tells the language what
function to run. Even if it's undef or NULL, that the variable
contains that value is significant in itself.
Variables should say what type of data they hold. Asking the question
"what kind" is an easy way to enhance your variable naming. I once saw
$data used when reading a record from a database table. The code
was something like:
$data = read_record();
print "ID = ", $data["CUSTOMER_ID"];
Asking the question "what kind of $data" turns up immediate ideas
for renaming. $record would be a good start. $customer_record
would be better still.
I promised the two worst variable names, and I feel no fear of
disagreement as I declare The World's Second Worst Variable Name to be:
$data2More generally, any variable that relies on a numeral to distinguish it from a similar
variable needs to be refactored, immediately. Usually, you'll see it like this:
$total = $price * $qty;
$total2 = $total - $discount;
$total2 += $total * $taxrate;
$total3 = $purchase_order_value + $available_credit;
if ( $total2 < $total3 ) {
print "You can't afford this order.";
}
You can see this as an archaeological dig through the code.
At one point, the code only figured out the total cost of the order,
$total. If that's all the code does, then $total is a fine name.
Unfortunately, someone came along later, added code for handling discounts
and tax rate, and took the lazy way out by putting it in $total2.
Finally, someone added some checking against the total that the user
can pay and named it $total3.
The real killer in this chunk of code is that if statement:
if ( $total2 < $total3 )
You can't read that without going back to figure out how it was
calculated. You have to look back up above to keep track of what's what.
If you're faced with naming something $total2, change the existing
name to something more specific. Spend the five minutes to name the
variables appropriately. This level of refactoring is one of the easiest,
cheapest and safest forms of refactoring you can have, especially if
the naming is confined to a single subroutine.
Let's do a simple search-and-replace on the coding horror above:
$order_total = $price * $qty;
$payable_total = $order_total - $discount;
$payable_total += $payable_total * $taxrate;
$available_funds = $purchase_order_value + $availble_credit;
if ( $payable_total < $available_funds ) {
print "You can't afford this order.";
}
The only thing that changed was the variable names, and already it's
much easier to read. Now there's no ambiguity as to what each of the
_total variables means. And look what we found: The comparison in
the if statement was reversed. Effective naming makes it obvious.
There is one exception to the rule that all variables ending with numerals are bad. If the entity itself is named with a number, then keep that as part of the name. A variable for the road running through town would be just fine as $route31. It would be silly to rename it as $route_thirty_one.
Finally, remember that all of these rules apply to subroutine and file naming as well. We often don't spend enough time considering file names, but that's a rant for another day.
What other naming sins drive you crazy?
33 Comments
| pudge 2004-03-06 23:03:52 |
Time The time it takes to think up better names is often better spent in other ways. If it is just a short snippet of code where you can see the entire context, why should I spend time thinking of better names, when it's clear what it is? I believe it is not a good use of my time. |
| wegrosso 2004-03-06 23:50:25 |
Time My initial reaction to this is: if you don't have a good name at hand, then you're not sure what it is.
|
| wegrosso 2004-03-06 23:51:04 |
Not event close The fabled TWENTY_EIGHT has you beat by a mile.
|
| rsschaut 2004-03-07 01:02:44 |
Antithesis Ed Fries once defined a data structure for a "Piece O Text". It led to such routine names as "CleanPots" and "FreePot," that still exist in Microsoft Excel to this day. |
| dsteinberg 2004-03-07 05:42:31 |
my nominee I once was given code by a student who used variable names one , two , three in order that the variables occurred to him. So one was a JButton and two was a JLabel with no rhyme or reason. He could keep it all straight in his head and didn't understand "what was so big about names anyway".
|
| andy-lester 2004-03-07 06:08:21 |
Not event close I disagree. TWENTY_EIGHT still tells you something about what it contains. That the variable exists is another issue.
|
| brian_d_foy 2004-03-07 07:57:57 |
Time You may indeed not be sure what something is, and that might not be a bad thing, and something that has a short lifespan in the code can have a generic name without affecting readability.
|
| naum 2004-03-07 10:28:07 |
test test |
| naum 2004-03-07 10:29:25 |
Here's one from the past One from a while back, written in COBOL, that I still remember having to ferret through...
|
| chirael 2004-03-07 16:20:19 |
What about foo? It strikes me that a variable whose name isn't even intelligible english must be inferior to $data, since at least data is understandable. And doesn't "data" at least tell you it's not "logic" or "executable code"?
|
| aristotle 2004-03-07 17:39:02 |
Refactoring (alone) shouldn't semantics. But in your case it did. The original reads $total = $price * $qty;while the refactored version reads $order_total = $price * $qty;Spot the difference. |
| aristotle 2004-03-07 17:40:51 |
Refactoring (alone) shouldn't change semantics. s/shouldn't/shouldn't change/ of course. Stupid that one can neither preview before posting nor edit afterwards.. |
| aristotle 2004-03-07 17:49:31 |
No hard and fast rules. Overall, I agree heartily with all of your points. But there are occasions where I'll intentionally use variable names such as good old i -- f.ex, in a two- or three-line loop, particularly when I use it as an index into an array. Sometimes, longer variable names only amount to more mental parsing work without really offering much in return.
|
| andy-lester 2004-03-07 18:01:37 |
No hard and fast rules. And I have no problem with i as a loop variable. in fact, I think that anything longer than that, unless there's a specific reason, is probably unnecessary.
|
| aristotle 2004-03-07 22:03:02 |
No hard and fast rules. And I expected you'd agree.
|
| paguilera 2004-03-08 08:34:42 |
Refactoring (alone) shouldn't semantics. The main difference I had seen was what I thought was a problem in your code, but going back to the original weblog, I see the same error there.
|
| andy-lester 2004-03-08 13:52:50 |
Naming rant "tell me something I don't know"
|
| tom_davies 2004-03-08 17:03:41 |
Vowel removal See James Thurber's 'The wonderful O'. |
| fizbin 2004-03-10 06:45:28 |
Refactoring (alone) shouldn't semantics. There's another problem with the refactored code, in the line below the ones you quoted: $available_funds = $purchase_order_value + $availble_credit; Can we say "vowel removal"? By the way, gratuitous vowel removal (or other misspellings) is becoming a bit of a pet peeve of mine (which reminds me - I need to go grumble at someone about a function named getAtributes), mostly because one of the pieces of legacy code I have to maintain is a load of Sybase stored procedures that refer to table names like VndrEntDataHst. (That table has a column named TrnsTypCd) Refactoring the production database and possibly breaking other reports isn't really an option.
|
| garyridgway 2004-03-10 12:52:46 |
If this article is not a parody... Then it's a good indication why programming jobs are going overseas. |
| gng 2004-03-12 06:06:05 |
Worst variable names I once worked at a place where a phb had written an MS Access module and had called his (boolean) variables true_ and false_ ! So, when debugging his code you were presented with the delightful
|
| mattocks 2004-03-14 00:06:24 |
Worst var names A call to a Fortran subroutine:
|
| enygma 2004-03-15 02:26:19 |
I've seen the worst Saw a guy once that always had trouble coming up with variable names. He decided to use the letters of his name when he needed a new one. So lets say his name was (for arguments sake) Brian. His code would look like this:
|
| jimoore 2004-03-15 04:06:46 |
The world's two worst variable names I once consulted for a company that had previously employed a programmer who used variables named x, _x, __x, ___x, etc., and these were the only variables that he used. You had to count underscores in order to begin to read the code. Surely these variable names were worse than data and data1. BTW, the programmer eventually lost his job. |
| aristotle 2004-03-15 17:12:32 |
Refactoring (alone) shouldn't semantics. Mine was indeed intentional. And yes, that was the problem: the refactored code was changed to correctly use $payable_total in the third line, while it would have been $order_total in the original. So using meaningful variable names led to the discovery of a bug that much was much harder to spot before.
|
| erikjanvens 2004-03-18 07:44:17 |
's more, 's more The worst project I ever picked up was from a guy who had already been fired and who had left no documentation. Obviously.
|
| bluecoat93 2004-03-18 09:24:27 |
My variable horror story I once was in charge of cleaning up a fairly large (10k+ LOC) Perl application. The original developer had 3 variables all named 'data': a scalar, an array, and a hash. So you'd get stuff like:
|
| autodmc 2004-03-23 07:22:08 |
Maybe it's bad habit.... Took a long time to straighten out that Foo/Bar/Hello World mess when I was starting programming...
|
| sceen1 2004-11-11 23:55:47 |
"i hate typing" So don't type them. Get a decent editor that will do autocompletion.
|
| sceen1 2004-11-15 15:18:38 |
Antithesis I think that's a great mnemonic. Using concrete metaphors helps people remember. |
| XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 2005-03-09 06:52:10 |
Exactly I recently had to go and update someone else's code... and was facing the this Perl code:
|
| Bhagavan 2005-09-30 05:43:53 |
Variables in German Language In my experience, I have seen code in COBOL where all the variables were in GERMAN !! Bloody Hell! |
| Dreamer 2006-03-04 22:43:36 |
Variables in German Language Is it not likely that the original developer was German, lol? Surely you'd be complaining if you only spoke German and the variables were English? ;)
|