Live data from Hacker News

A Guide to Naming Variables

a-nickels-worth.blogspot.com

141–150 of 175 posts

Re: A Guide to Naming Variables

#141
post #4

Most of this, even if it's not my preference, I would never bother arguing with. But I have a question about a practice that is tremendously widespread. I have real trouble with single-letter variable names like "c", for any function more than, say, 2-3 lines. I scan the code and it increases my mental load because I have to remind myself what it means. Obviously a lot of people don't have problems with this, but I d…

I agree. I prefer this

List hosts = hostService.fetchMatchingHosts(hostFilter);

Set versions = JVMServiceFactory.factory(region).getApprovedVersions(),

List zones = RegionFactory(region).getZones();

return hostUpdater.updateJVM(hosts, versions, zones);

to this

List hs = hostService.fetchMatchingHosts(hostFilter);

Set js = JVMServiceFactory.factory(region).getApprovedVersions(),

List zs = RegionFactory(region).getZones();

return hostUpdater.updateJVM(hs, js, zs);

The top version means I can read the return line by itself and get a feel for what it does without having to skip back up a few lines. And while there definitely is a tax on longer variable names, I usually don't feel that way with single words.

The brain chunks small common words, so hs probably takes just as much if not more working memory than hosts.

Footnote : Just while writing this I had to look up a couple of times to remember hs, js, and zs. But I never hard to look up to to remember hosts, versions, and zones.

Re: A Guide to Naming Variables

#142

A good guide, but I didn't like this part: Avoid Over-used Cliches In addition to not being Teutonic, the following variable names have been so horribly abused over the years that they should never be used, ever. val, value result, res, retval tmp, temp count str Cliches? If you are trying to communicate, these names are well known ways to do that. If there is something more specific to put in there, by all means, bu…

I will stop using these when smooth jazz stops punctuating turnarounds in bluesy minor grooves with a 7#9 chord.

Re: A Guide to Naming Variables

#143

Earlier quoted context omitted.

"Computer scientists" don't have an opinion much about a particular IDE; if you want that functionality in an IDE, it might be a shorter path to cause it to exist in the first place. I bet it's harder than you think. Also, IDEs are better than they used to be - I stopped using them because they caused problems in the late 20th Century. There was a proliferation of them until Eclipse got good enough to not cause probl…

That is fair. I don't have a specific suggestion on how to implement it, which layer (language, IDE, some connected service) or where to do it. I just know that current coding practice must be wrong.

If that's the worst thing you see, please consider being grateful :) It could always be worse.

Re: A Guide to Naming Variables

#144
post #4

Most of this, even if it's not my preference, I would never bother arguing with. But I have a question about a practice that is tremendously widespread. I have real trouble with single-letter variable names like "c", for any function more than, say, 2-3 lines. I scan the code and it increases my mental load because I have to remind myself what it means. Obviously a lot of people don't have problems with this, but I d…

The function is not very long and it's sort of pointless. Besides, what do you name it? collectionInts? That's in the declaration, right there. candidates? As obtuse (and useless) as c.

If you're grepping/ag'ing for c you've got another issue, because I can't think of the context that you would grep c in a function that fits on less than 2 24-row terminal screens. At worst, /c and a few presses of 'n' is all you need once you get to the function.

If you're outside the function grepping, it's because you saw printNFirstIntegers(4, someOtherVariableName). You'll hardly have named the variable (or collection literal) "c". So you'll be using ag printNFirstIntegers.

To me, your request is akin to the last time I had a code review for a rake task and someone complained about the 'f' in:

  FileList['deploy_assets/ebextensions/*'] do |f|
    @helper.process_template(f, ".ebextensions/#{File.basename(f)}")
  end
Calling it File is horribly obvious and annoying.

Edit: The function name probably should be run_erb_on or something like that. None of us are free of naming sins. Lol.

Re: A Guide to Naming Variables

#145
post #91

Earlier quoted context omitted.

bool productPricingUpdatedAfterDeliveryFailedButEmailSent = false; I've seen variables with names like the above. It would have been better explained in a comment and used a short variable name. Unless you like typing it forces you to use an editor with autocomplete (which you are crazy not to use one), and IMO pollutes the code. Variables should be easy to type and read. It's a trade off.

Firstly, there are noise words in there. If there is no other kind of pricing in that context beside product pricing, "product" is useless. If the order of operations is perfectly clear from the program flow, "After" is useless. "But" is a useless conjunction which doesn't add any information to "EmailSent". This kind of thing can be broken into multiple Booelan variables: bool pricingUpdated; bool deliverySucceeded;…

I totally agree, and this is a good example of how I would refactor that noise.

Re: A Guide to Naming Variables

#146

> iterating through a for loop using i is a well-established idiom that everyone instantly understands. Give that count was useless anyway, i is preferable since it saves 4 characters. "Where does this idiom come from?" you might ask. Well, if I recall it's mostly due to languages like Fortran which implicitly typed identifiers starting with I through N as integers.

exactly right. Some jokes about writing fortran in any language focus on the use of "I, J, and K" as indexes and counters. But in mathematics the common iterator in a summation is also i, j, and k so mathematicians sometimes claim ownership of the use of i as a count.

Fortran, like most early programming languages, was explicitly modelled on mathematical notation. There was debate whether allowing multi-letter variable names was worth the loss of implicit multiplication. But today's programmer can write COBOL in any language.

Re: A Guide to Naming Variables

#147
I'm all for tricks that make 'coding in the small' easier, but grain of salt on this -- reading a large codebase, esp one with external dependencies, is a separate problem. In my day to day life (and not everybody is me, I know) the large program reading problem is THE problem; comprehending functions is a nice bonus but not as hard.

In small functions, I wish variable names were automatic based on type. If a function has only one local of type T, it should automatically get name t or something.

Re: A Guide to Naming Variables

#148

Earlier quoted context omitted.

Yeah, the problem with outlawing "retval" in particular is that there's no good variable name in this situation: int sum(Collection c) { int retval = 0; for(int i = 0; i What the hell should I call retval? If I call it sum, that's redundant with the method name. Also, while it might work in Java, it would be more dangerous in a language like Ruby where the equivalent code: def sum(c) sum = 0 c.each do |e| retval += e…

Call it "result": - "val" in "retval" carries no meaning. Everything stored in a variable is a value. - "ret" is an annoying abbreviation for "return" that makes it harder read. - "return" focuses on an implementation detail—that the function produces its value using the language's "return" statement. It doesn't matter how the result is emitted, just that it is. If a function is simple enough that the variable storin…

"result" was also included in the list. I honestly don't see anything wrong with either.

Re: A Guide to Naming Variables

#149

A good guide, but I didn't like this part: Avoid Over-used Cliches In addition to not being Teutonic, the following variable names have been so horribly abused over the years that they should never be used, ever. val, value result, res, retval tmp, temp count str Cliches? If you are trying to communicate, these names are well known ways to do that. If there is something more specific to put in there, by all means, bu…

Agreed with you. Perhaps if you're using temp or tmp, something could be done better, but I see no harm in using the others. If you're counting things, a variable named "count" sound perfectly reasonable to me.

Even "temp" would be a standard name for the temporary variable used in a swap function.

https://en.wikipedia.org/wiki/Swap_(computer_science)#Using_...

Re: A Guide to Naming Variables

#150

Earlier quoted context omitted.

I agree. It's not a mental tax to read a word we recognize. It's not like we have to sound it out letter by letter, we recognize its form at a glance. It's more taxing to maintain a mapping for an inherently meaningless single character. Although there are some single characters that do have meaning due to long time convention such as 'i'.

What about variables which are inherently "meaningless", i.e. they're only given a name in order to distinguish them from each other? For example: function flip(func) { return function(x, y) { return func(y, x); }; } function compose(func1, func2) { return function(x) { return func1(func2(x)); }; } Code like this is completely generic; we know absolutely nothing about `x`, `y`, etc. other than they're distinct argume…

It irrationally bothers me that you didn't use `f` and `g` for your composition example, as that's the common mathematical representation.

    function compose(f, g) {
        return function (x) {
            return f(g(x));
        };
    }
Post reply on HN