Live data from Hacker News

A Guide to Naming Variables

a-nickels-worth.blogspot.com

131–140 of 175 posts

Re: A Guide to Naming Variables

#131
post #56

Earlier quoted context omitted.

I have mixed feelings. For a return value, retval et al are completely appropriate. Same for count. Tmp/temp borrow meaning from whatever they are a temporary for. These are all fine. But "value" is horrible. You really don't know what it is? You might as well name it "variable". "Str" is in the same boat, unless it's short for "tmpstr".

If I'm iterating over a hash, it seems natural to use "k" and "v" or "key" and "value". Do other people use different names for these?

I typically keep it consistent, using either k,v or key,val (I like the symmetry of var letter length in a weird OCD kind of way).

Re: A Guide to Naming Variables

#132

Here's a tip along these lines: Use 'j' and 'k' for integral loop control variables, not 'i'. Both 'j' and 'k' are pretty high-value Scrabble letters and it's easier to search for their appearances in code. Apart from "break", they don't appear in the reserved words of common programming languages. (And never use 'l' as a variable name; but you knew that already.)

[deleted]

Re: A Guide to Naming Variables

#133

"rather than the elliptical vagueness of Romance languages like English" - what?

I had the same reaction too. After googling it to make sure, english was a germanic language like I always knew. Then I'm like, English might as well be romance because it's riddled with french words.

It's not (just) the vocabulary. Besides a the history it's primarily the inflection system that Romance languages have in common.

Compare for example English with Spanish, Italian and Portuguese:

    en                  es    it      pt
    I go		voy   vado    vou
    He/She goes	        va    va      vai
    We go		vamos andiamo vamos
    They go		van   vanno   vao
While the Romance Languages are very similar, English is completely different.

Re: A Guide to Naming Variables

#134
post #91
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…

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;

   bool emailSent;
These can be initialized or assigned at various points in the flow. Then later we can have:

   if (pricingUpdated && !deliverySucceeded && emailSent) ...

Re: A Guide to Naming Variables

#135

Earlier quoted context omitted.

it's obvious that computer scientists have COMPLETELY dropped the ball by not figuring out a way for anyone to write "it", "that", "which" and so on and have the IDE and language disambiguate it into what you were JUST talking about. This is stuff that my great-grandparents should have been suggesting some time after Ada Lovelace wrote about the analytical engine in 1842 or 1843. Not something I should be writing abo…

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

Re: A Guide to Naming Variables

#136

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…

You answered your own question: such abstract (not meaningless) variables make sense when the code is completely generic. Most code however is somewhere between generic and specific, literal values, and variable names should represent that semantically.

Also, I would even argue that x and y are not meaningless in this context. There's a reason you didn't write:

    function flip(gnarf) {
      return function(t, m) {
        return gnarf(m, t);
      };
    }

    function compose(bip, boop) {
      return function(blep) {
        return bip(boop(blep));
      };
    }
The sequences {a, b, c}, and {i, j, k}, {m, n}, {p, q}, {x, y, z} are all well-established "abstract" variable names that most of us remember from high school algebra, and all have different baggage and expectations:

- a, b, and c tend to be generic labels for things, not numbers

- i, j, and k are used for indices and tend to be natural numbers (or more rarely for complex numbers/quaternions, where they are floats)

- m and n are used in matrices and also are used for natural numbers

- in maths, p and q are often fractions

- x, y, and z tend to represent coordinate systems and/or floating numbers

We can combine this to create variable sequences, with subtly different meanings. For example: compare (x1, y1), (x2, y2) with (xa, ya), (xb, yb). To me, if I see foo(x1, y1, x2, y2) that implies either top left, bottom right in an axis aligned bounding box, or perhaps the first point and the second point of a line or vector, or some other situation where the two points are somehow connected in one object or shape. Using (xa,ya) and (xb, yb) however suggests I'm dealing with two distinct points.

Re: A Guide to Naming Variables

#137
post #11

when it's coding as fast as humanly possible, the last thing I want to do is slow down to think of good var names. I'll often just name something "foo" if I can't think of a good name and come back and rename it later. Sometimes it's a little better than foo but still not perfect but I'll leave that and move on to something else. I really don't like the idea that code must be perfect. Code is never perfect.

This is another example of how everything depends on the user. From this comment I can only assume that you code by/for yourself or with very few other people, with which you surely share a lot of time and space which makes communication in that kind of shorthand possible. And now, I want to highlight how difficult was for me to be an understanding and constructive member of society right now, and try to explain why…

Even if you're working on a project by yourself this is still terrible practice! I know when I've done this and had to come back to my code weeks later, I've absolutely loathed my past self for writing opaque code.

Re: A Guide to Naming Variables

#138
post #39

Earlier quoted context omitted.

Funnily enough for your example, depending on whether you are describing different types of fruit or multiples of one type of fruit, the plural of fruit may be "fruit". :) > It also goes with the "don't put the type in the name" point, which I agree with in most cases. Is that a problem in practice in Python? That's the whole reason Perl uses different sigils to denote different types of variables, which Python speci…

> Is that a problem in practice in Python? > I prefer being able to tell if something is a collection, and which core type of collection, at a glance (barring refs). Not really a problem, but if you're writing more than a one-off script, such as a module you plan on sharing, it may be common that you get a mixture of concrete types coming in depending on the app and platform. I think in practice, it's actually benefi…

> The only thing I do not like about this is that in Python strings are also iterables.

This touches on a big pet peeve of mine, and coincides with some ranting I was doing on the Scala Native post the other day. :)

Languages that support coercion should try to make sure they don't overload core operators for different types of operations for different core types. E.g. '+' for numerical addition and string concatenation (one is commutative, the other is not, and if you decide on which action to take depending the order of variables, that's confusing), or ==/!= for string equivalence and numerical equivalence (10.0 and 10 are numerically equivalent, but for strings we generally want an exact match).

Having an iterating operation work on a string without any preparation is one of those things that seems simple and useful, but likely causes a lot of confusion in dynamic languages in practice because you lose track of exactly what it's possible a variable can hold because it's often dependent on the return value of someone else's function. I imagine exposing a method on strings that returned an iterable interface, and requiring that be the method you iterate over a string, would reduce that confusion quite a bit.

> I ought to learn Perl, because that's pretty cool.

I think it's worth picking up the core concepts for anyone, because there's a few concepts (e.g. context) it implements as core parts of the language that are still rarely used elsewhere. Unfortunately, its hybrid beginnings mean that you can largely miss the importance of things like context early on because the code looks enough like what you are used to that you assume it works the exact same way, and 95% of the time that's true. The other 5% will leave you scratching your head and wonder why Perl seems so stupid or inconsistent, when really your mental model is wrong. List and scalar context and how they apply to the core types should be the first learning item on a new Perl programmer's list if they know another C-like language.

Re: A Guide to Naming Variables

#139

> Most names should be Teutonic, following the spirit of languages like Norwegian, rather than the elliptical vagueness of Romance languages like English. Norwegian has more words like tannlege (literally "tooth doctor") and sykehus (literally "sick house"), and fewer words like dentist and hospital (which don't break down into other English words, and are thus confusing unless you already know their meaning). Not on…

What he means, but phases poorly, is to use compounds.

On your other point, at least German is very specific with how compounds work grammatically, namely that they follow a head-right principle which defines genus and declination and which essentially relegates everything left of the head to the status of further defining the head. Additionally, none of your examples work in German for the term "Krankenhaus" (sick house/hospital) for that very reason: a sick house (a house in disrepair) would have to be a krankes Haus following general rules of declension, which would also be the grammatically correct (though completely non-idiomatic) version for a fallen noble house. And while there is a very specific way that defines how stems of a compound are related, German can mark grammatical units differently from English (and akin to Latin) by requiring the agreement of case/numerus/genus between say an adjective and a noun, specifically making it grammatically impossible for krankes Haus to be understood as hospital or Krankenhaus to be understood as a dilapidated house.

edit: the above holds true for Norwegian and Danish as well, by the way.

Re: A Guide to Naming Variables

#140

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…

If the variables have no meaning other than argument placeholders in a transformation between functions, then they must not be given descriptive names that falsely hint at some deeper meaning.
Post reply on HN