63 comments

[ 1.7 ms ] story [ 138 ms ] thread
My personal favorite was always $hold, and its cousins, $hold1, $hold2 ... $holdn
I sometimes use data, but normally that's for a specific purpose - when I have a function that takes a void* in order to fit to a generic function template, which I then cast to something in every function of that type.

e.g.

  typedef void (*function_t)( void* );

  void someFunction( void* data ) {
    myStruct_s* myStruct = data;
    
    // do something with myStruct
    
  }
I would write something like:

  void someFunction( void* pvMyStruct ) {
    myStruct_s* myStruct = pvMyStruct;
Please explain why this is better.
The name "pvMyStruct" implies intention and suggests to the reader that the function parameter is a MyStruct pointer disguised as a void pointer. The name "data" does not provide any hints.
In PHP, I sometimes giggle when I see $hit as a variable name, or when people catch exceptions as $ex.
It's all about comprehension. Can the code be easily comprehended? Here's an example from the jquery docs:

    $.ajax({
      url: 'ajax/test.html',
      success: function(data) {
        $('.result').html(data);
        alert('Load was performed.');
      }
    });
Looks pretty easy to comprehend to me. And as far as $data2 goes, is it easily comprehensible? It's perfectly normal in functional programming to append a modifier to your variable name like so: data -> data' . To indicate that the contents of the two are related.

Finding absolutes in programming is a tough business. Rather than worrying about exact best and worst practices I find it more productive to just make things easy and fast. If using data or data2 makes your code easy to comprehend then do it. If not dont.

Are older blogs being regurgitated? In the past days I've read articles that I'm sure are 90+% similar to ones I've read one or two years ago.

I'm on my phone currently so I can't really be bothered to find links to support my case. Mostly curious whether others have got the same feeling.

I had the same sense of deja vu, I've seen exactly this some years ago. (Though I seem to remember "tmp" being contested as either the second worst or third worst variable.)
Not only that, but that guy also linked back to the original and said it was a modification of the previous post.
That guy put the reference to the original far enough down that people who enjoyed the article the first time around may have had a strong enough feeling of deja vu that they stopped reading before reaching it.
You can't talk about sensible naming without also talking about scope.

When a variable is only in scope for five lines, it's perfectly reasonable to give it a really short name.

Nobody said anything against really short names.
You don't consider "data".length() == 4 to be short?
Nobody said anything against really short names, the article argues against non-descriptive variable names, whether short or long.
Indeed, provided you know the problem domain, the most descriptive name (xs, x_rms) is almost always far shorter than the literal alternative (horizontal_positions, quadratic_mean_of_horizontal_positions).
(comment deleted)
Why are you working under the assumption that that was his issue with the term data? Especially when he specifically described his problems with it.
I'm not. Rather, I'm supporting the notion that as the relevant scope decreases, the weight of his objections to the variable name 'data' vanish and become dominated by the value of its brevity.
The same argument applies to non-descriptive names, and the main complaint about short names is that they are often not descriptive.

I like to bring up the English language in this particular debate. "It", "he", and "she" are incredibly non-descriptive names, but each one of them is used many orders of magnitude more often than any "descriptive" name (other than maybe "I" or "you") and yet we don't hear rants about that.

The reason is exactly what the original commenter pointed out - scope. Sometimes the word "it" is descriptive enough all by itself. Other times it isn't. It's a more subtle matter than "worst variable names".

> Sometimes the word "it" is descriptive enough all by itself. Other times it isn't. It's a more subtle matter than "worst variable names".

I see what you did there.

Agreed, the best variable name is the shortest one that's still specific within its scope. A variable name of CustomerWhoHasPlacedTheMostOrdersOnThisDay is quite bad inside a three-line function, just as "public static customer" is terrible in a five thousand lines factory class that has no obvious relation with a specific customer.
the five thousand lines factory class is the real problem.
Mathematicians solve for x, not for $unknown_quantity.
OT, but I do believe one of the important reasons why many people considered math hard is one letter names.

Optimizing for writing is not optimizing for reading.

I have to fully agree with you: I hate when people use 'unknown_quantity' instead of a simple 'x' as a simple line become very long and hard to read with the important informations spread over a very large area.

Having to frequently parse very long name who doesn't give more informations is very painful, and generally make the real information harder to understand.

  $conn = mysql_connect(...);
  $res = mysql_query($conn);
  while($row = mysql_fetch_array($res)){...}
I think these are by far the three most common name conventions, at least for beginners in PHP.
Sorry, but my vote is for $foo and $bar, by far.
I think I've seen far worse. For example, I saw some code where the variables were a, b, c, d, e, f... z, a1, b1, c1...z1, etc.

Never underestimate the willingness of programmers to obfuscate in the name of (supposed) job security.

Even there, context matters. For example, lambdas in functional languages. In that case it's generally agreed that single-letter variable names are very much preferable to descriptive ones.

For one, in the cases where lambdas are normally used, verbose naming can actually make the code harder to understand by disrupting the formatting of the code in which the lambda is embedded. Also, it creates a nice built-in code smell: If the lambda statement is complicated enough that its purpose is hard to understand without descriptive variable names, that's an indication you should be using a named procedure instead.

maybe it was from some kind of code minimizer? like gwt renames variable names to reduce file size when pushing for production.
That would be a valid excuse. It was not the case.
"Metadata" can also be painful. One abstraction's metadata is another's "data data".

For example, there was a structured store where each entity was a byte array ("blob") with certain searchable, indexed "metadata". (The "data data" was the blob itself.) However, demands on the structure required certain additional fields regarding the content of that "metadata" that were allowed to break the contract of the original "metadata" and were therefore metadata on the metadata.

I fell out of my chair, hoping the "kick" would bring me up a level. It didn't. I wasn't dreaming.

I've seen one much worse: $stuff
For every rule an exception - data is a perfectly fine name for the scenario where we don't know what data the variable represents. For example in a logging framework that has to loop over the contents of a collection and dump it to the console then data or entry or something similarly vague would be a perfectly reasonable variable name.

Then data2 might be a reasonable name in a unit test that checks to see if a function can handle the traditional "1, 2, many" categories of failure.

Which is not to say that data and data2 are not, often, horrible names. But the circumstances dictate (or excuse) all.

You could name it after the source of the data. The point the author was making is it makes your code much more readable when you see the variable turn up and you don't need to go back and see where it comes from to determine what it is (ie you come accross a 'data.parameter < constant' condition or some such). Even calling it log-data would be an improvement, as its source is immediately obvious from the name.
Even the source is not always obvious. Cocoa has a class called NSData, which is a container for arbitrary binary data (e.g. it basically holds a char* , a length, and a bunch of methods for looking at this stuff). If I write a function that needs to operate on an NSData instance, then I'm perfectly justified in calling the variable 'data'. For example,

  NSData *calculateHash(NSData *data) {
      char result[CC_SHA1_DIGEST_LENGTH];
      CC_SHA1([data bytes], [data length], result);
      return [NSData dataWithBytes:result length:CC_SHA1_DIGEST_LENGTH];
  }
That's a good point. If in the scope of the variable, you're only concerned with calculating its hash (or some similar function that is qualitatively indifferent to it), and not testing or parsing it or making any specific use out of it, then 'data' makes sense (though I'm guessing 'file' is arguably a better descriptor of the data in this example, if indeed that's what you're hoping to find in NSData, I get your point, and 'foo' might do just as well). That has to be a fairly unusual case, though.
'datum' often is a more appropriate name. 'data' is ambiguous w.r.t singular/plural.

However, I prefer 'item' and 'items', as that completely evades any possible confusion. Especially useful when iterating over generic containers. Compare:

  Foreac
Oops, hit the "reply" button by accident when trying to dismiss a spelling correction on the iPad, and I do not know how to edit, due to my anti-procrastination setting. Intended was to compare:

  Foreach item in items
With

  Foreach datum in data
I also use itemss for a container of containers:

  Foreach items in itemss
    Foreach item in items
Of course, if the code is less generic, different names are more appropriate:

  Foreach row in matrix
    Foreach cell in row
For small scoped loops, I usually just abbreviate to the first letter. I'm not sure how others feel about this, but I think it's perfectly legible:

  for i in items:
    i += 1

  for r in rows:
    for c in columns:
      matrix[r][c] *= 2
char mander;

It intrigues me why this is not on the article

Personally the worst variable name I have seen was in the line:

boolean alanIsABastard = true;

Where I am the Alan in question and this was written by someone who worked for me. :-)

this is what source control is for, right?
Well, there is always the unpleasant possibility that the person writing that code had a legitimate reason to call you a bastard. Perhaps you were seen as inconsiderate, or he was having a bad day where everyone seemed like a bastard and you were the nearest target.
I am curious on the usage of this variable or was it never referenced afterwards?

Perhaps the author sets it to false later symbolizing some sort of transformation you went through or at least a change in his perception of you.

Perhaps it was in a "bipolar" loop:

   while (true):
      sleep(1000 * 60 * 24)
      alanIsABastard = !alanIsABastard
I must admit that I never considered this point in any great depth.

Perhaps it should have been a constant (and it was Java):

     public static final boolean ALAN_IS_A_BASTARD = true;
I think I agree with the general tone of the article, but his ordering is upside down: "data" is bad, but "data2" is worse, not better.
$data is fine for the name of the data variable of a generic container.

Again, using $data2 to represent the square of $data is fine too.

I understand your point, but there are definitely exceptions.

You can do much worse than "data" for a variable name. A name that gives no clue as to what the variable is isn't nearly as bad as one which gives a misleading impression.
I have boxes in the garage labeled junk, and that is exactly what it is. I agree a more meaningful name could be given, but its accurate. Same so with data or other such nonsense variable names. I could give a better name, but i'm busy trying to get my first prototype done!
Grep says the variable name "data" occurs about 80 times in the program I'm working on.

I used to prefer descriptiveVariableNames, but as my programs have gotten shorter, my variable names have gotten much shorter. I found that longVariableNames were starting to overwhelm everything else and obscure the shape of the code. They were still communicating theIntentOfTheVariable like they always did, but in a way that felt less helpful and more like lexical noise.

Code shape communicates meaning through a different channel than variable names do. As code gets less verbose, its shape emerges more and more, that channel becomes more and more informative, and one begins to use shorter names so as not to drown it out.

This is very different than verbose programs written in verbose languages. There, descriptiveVariableNames don't take up an unseemly amount of space relative to everything else. The shape of the code is less meaningful because you can't see the forest for the trees. And you're far more dependent on intentionClarifyingNames to orient yourself in that forest.

This is why programs written in concise languages look absurdly cryptic to people who haven't spent time in that language's world. The markers of meaning they're used to relying on are missing, and their eyes haven't adjusted to the meaning that is there. The program may have been crafted to maximize overall meaning across several channels, but one needs time and practice to get what those channels are. And the tradeoffs are probably different in each language.

    > Of course it’s data! That’s what variables contain! That’s all they ever contain. It’s like if you were packing up your belongings in moving boxes, and on the side you labeled the box “matter.”
Nope, if he goes with that analogy that data contains data, the box should be labeled with box, imho.
Huh, I've used nearly this example for years, except my two worst are "var" and "var3" - with no var2, leaving the reader to wonder what happened to it.
Negatively named bools bother me. e.g.:

  while notDone: { if condition() notDone = false; };