Ask HN: I prefer single letter variables

17 points by techsin101 2 years ago | 50 comments
So it's almost universally accepted variable names should always be descriptive, consistent, etc... but I'm sure there are scenarios where single variable names are preferable. I can't quite formulate solid parameters of when that is, but here is a try:

- There are few variables in the whole code block < 5.

- Amount of lines is < 25.

- Code is very functional in nature. ie. no a.getObj()

Sometimes I appreciate good variable names and sometimes I hate descriptive variable names. Short var names might be better where extra effort required to parse long names is not worth in terms of utility gained.

One example: variables are not meant to be used for long term just exist for next two lines....

i.e. filteredData = arr.filter(...) , noDateFilteredData = filteredData.filter(...), noNameDateFiltered = noDateFilteredData.filter(..)....

this would be easier to read when it's written like this

a = arr.filter(...), b = a.filter(...), filteredData = b.filter(...)

another situation...

data = arr.filter(n => n.flag === true);

// it's completely obvious what's happening here, n is iterable. calling it obj|arr|users|etc... doesn't add much value for this piece of code as is. you probably already know we are getting users. It's like not using pronouns "he"/"she" and just keep using first name: Mike wanted to come in because Mike had said that Mike needed to talk to Aniqa, Aniqa knows about the insurance stuff. Aniqa has worked in insurance....

There is inverse correlation between length of a variable name and the speed of understanding logic of the code. But smaller the name the more you need to remember what it is, and the longer it's carried over the more difficult it's to continue remembering it. So in situations where it doesn't need to be carried for a long time I prefer smaller names.

I'm sure of it from my experiences. I prefer short names generally when is less data massaging and more algorithmic in nature, because sometimes it's hard to name a var in a way that captures vague concept in algo, without making it downright misleading. i.e. i call something a sliding_window but then later don't use it as one. Reader would be like um... wait what??

TLDR: I guess correct name matters more and more, the farther you are from its declaration.

  • orzig 2 years ago
    I am with you on this, though I am in a minority at work. An underappreciated benefit is that you are signaling to the reader, when they first see the variable, that it will only be used briefly. That helps them ration their attention.

    The strongest counter argument is that developers cannot be trusted to avoid building a house of cards if you let them use, even a single shortcut. And there is plenty of evidence, including my own experience, to back that up. But if you can prove you will re-factor when the time is right, it becomes a lot easier to make your case for brevity.

    • cirrus3 2 years ago
      > though I am in a minority at work

      This should tell you something. Taking the time to name it nicely now costs almost nothing vs wasting your time trying to prove it can be refactored later and then doing that refactor later. Why? What are you getting out this? Taking 1 second to name it nicely vs the time it costs for everyone to listen to you "make a case for brevity", just please don't be that person. No one likes or respects that person more even when you are right.

      • saeranv 2 years ago
        The main argument I see for short variable names is that it's easier to read, and interpret (yes, ironically the exact same case the other side makes). In certain contexts (for small functions, math) code is a lot easier to read when using simple, or single variable names. Every now and then I see someone writing out math formulas with long names, and it's so difficult to grok the equation. Just use single variable names so we can grasp the whole thing in a single glance!
        • drpyser22 2 years ago
          I disagree that naming something correctly always takes no time. Sometimes a useful and correct name is non-obvious, or repetitive, or you're trying to name something abstract or generic.
        • techsin101 2 years ago
          Yea, often vars are placeholders and making them descripting just makes them misleading and harder to get to the point. But yea at least I trust myself to refactor code and make the var name more descriptive if I see it's no longer just temporary placeholder... but would be a challenge to have others follow the same principle. One using is short name because it only helps, another to use it because you are just lazy.
        • lucb1e 2 years ago
          Exceptions exist, sure. The title is that you prefer single letters generally but the submission text is more about exception situations for throwaway variables, so it doesn't quite sound consistent. The title and submission text also contain no concrete question, so I'm not really sure what you're looking for here.

          Even in your example cases, though, compare these two lines:

             a = arr.filter(n => n.flag === true);
             a = arr.filter(user => user.flag === true);
          
          Which one is more clear here?

          I hate ${JavaStyleVariableName}s that are so long that it takes extra mental effort to parse the names, so I'm fully with you if you argue for appropriate variable name lengths, but having any name at all (one character is typically not a name) can give some indication of what it is, even if abbreviated or otherwise terse. The variable 'n' sounds like a number, rather than an object that would have a .flag property. While not very confusing, it's also not the most intuitive thing to call it. I wouldn't flag this as "please fix" in a code review, but it's also not better than using any name at all.

          • cirrus3 2 years ago
            Using "n" here instead of "user" just screams lazy... I wouldn't flag it either, and it will probably never be a problem is this case, but I would momentarily think of the dev that wrote "n" as lazy and worry a tiny bit more about what other code they are writing lazily as well. Don't be that person.
            • sublinear 2 years ago
              I completely agree.

              One letter names are a code smell I associate with the nastiest bugs I've experienced especially when the git blame shows multiple authors on it.

            • AndrewDucker 2 years ago
              At the very least make "n" "u", so that it's easier to remember it's a user!
              • techsin101 2 years ago
                Sure, in this example user looks better. But as I said this code is not going to be existing on its own. There's going to be code preceded by this. Which is going to give a pretty good idea of what is being filtered on and you can always have comments before the code that can explain the general idea of what you're trying to achieve instead of burdening short-lived variables with a role of needing to give hints of what's going on at the expense of readability and speed of parsing mentally
              • moloch-hai 2 years ago
                This is a ridiculous thing to have to discuss. Probably it is a product of software development's version of the "Homeowner's Association", Code Review, where petty rule enforcement is allowed to overrule good sense.

                The essence of a name is twofold: it identifies a thing, and distinguishes it from every other thing. Anything that achieves these two ends is a good name.

                Where there is only one thing, its name doesn't matter: only language syntax demands it have a name at all. Shortest is best. In some languages, "_" is that name.

                Where there are only two, you need two names visibly distinct. The easiest and cleanest way is two one-letter names.

                Using longer names lets you provide documentation without adding a comment which could later become incorrect. That is the only value in a longer name. A longer name has a cost that has nothing to do with how long it takes to type: the reader has to read it to determine it is this thing and not that. It squanders readers' attention. It is worst if it is similar to another name.

                If you want to use talking about names in code review to make code better, pay more attention to names that are too similar than to short names.

                • techsin101 2 years ago
                  At first I thought you were arguing against the point I made, but after reading this fully I totally agree. The worst offenders that are hell bent on naming variables as sentences are java developers. For some reason the boiler plate required by Java is no long enough for them. Lol. Joking aside, I think anywhere where the code is an API for external functions or anything like that. Having a very descriptive name and consistent convention is good, also if the variable is being carried over in a nested code or is being passed around or is being used 50 lines down somewhere then it is useful to name it in a way that is recognizable

                  Ultimately, I think even the choice of naming something and using a single letter communicates your intentions. If you make something a single letter then you're telling the reader that do not even worry about this variable it is just passing through, but if you need something your communicating your intentions of using this variable in the future it is more permanent in a sense

                  • moloch-hai 2 years ago
                    Right! Anywhere you are offered a choice about what to write, you can use that choice to communicate something. Best is when the message comes through without need to read text.

                    Whitespace is such a choice. Used judiciously, whitespace and its absence can call attention to organizational choices. Used injudiciously, it loses all useful meaning. People who splatter whitespace everywhere -- a blank line above and below every line of code, every parenthesis with a space before and after -- communicate only their contempt for the reader.

                  • sublinear 2 years ago
                    > ... pay more attention to names that are too similar than to short names.

                    Ah this is exactly why people dislike the short names.

                    If you ever have more than a few of them and they aren't even real words, common abbreviations, or hijack well known unreserved names I would immediately reject that during code review.

                    I think most people are fine with plain English 1 to 3 word names concatenated in whatever style of the language or other conventions.

                    i.e. "result" instead of "r", "re", or "res"

                    Why? Because "r" is familiar as a read permission, "re" is familiar as a regular expression, and "res" is familiar as a response object.

                    This is the bad kind of familiarity that drives people up a wall and wastes a ton of time.

                    • moloch-hai 2 years ago
                      Keep control of syllables. Each counts against your cognitive limit of "seven plus or minus two" items that fit in registers.
                  • mudrockbestgirl 2 years ago
                    I generally agree with you, but it depends on how obvious the semantics of the code are.

                    In your example, noNameDateFiltered is most likely superfluous. If the filter function is short it's self-descriptive what it does. Adding long variables names makes the code harder to read and adds cognitive overhead. In this case, I would strongly prefer just re-using arr or a.

                    On the other hand, I have seen long complex function that use single-letter variable names and end up with 20 variables that mean different things. Keeping track of what's what in such a case becomes difficult, and you want something more descriptive.

                    Taking a step back, the goal of variable names is to make the code easily comprehensible by someone else or you at a later time. You have a few choices to do this, in order of preference:

                    - The code is self-explanatory, like a simpler filter function - use a short simple variable names. This is always the preferred method. Why make it harder than it needs to be? Reading over-the-top verbose code is just as bad as the opposite.

                    - The code expression may cause confusion - use a more descriptive variable name, but don't go overboard

                    - It's difficult to describe the result succinctly even with a variable name - use comments

                    • cirrus3 2 years ago
                      > The code is self-explanatory

                      Never overestimate this, there is no upside to the one time it isn't.

                      > Reading over-the-top verbose code is just as bad as the opposite

                      No it isn't, it is just as easy, and when can help it pays off, there is no downside.

                      > It's difficult to describe the result succinctly even with a variable name - use comments

                      This isn't an either or, if it deserves a comment by all means use one, but that doesn't negate the benefits of thoughtfully named vars.

                    • pjdkoch 2 years ago
                      You're not alone. 3 to 5 letters works best for me.

                      Obligatory reference, given the aesthetic: https://archive.vn/mIwG0

                      My rule of thumb is to avoid variable names that are only used once. Instead, use something like pipeline operators, flow(), etc.

                      Another preference I have is to use initialisms. Might feel dumb at first, but eventually you realize (or I did, at least) that it matters more how things are "braided together" than having perfect names, and your editor prolly highlights all the uses of the variable where you have your cursor.

                      But, as always, prefer consistency with the rest of the team, even if you feel the rule is dumb. Don't proselytize. If the style really gets in your way to understanding the code, rewrite it and throw it away. There's something elucidating (and satisfying) in seeing a non-obvious piece of code in your native style.

                      • lucb1e 2 years ago
                        OP: "I prefer single letter variables"

                        Reply: "You're not alone. 3 to 5 letters works best for me."

                        I mostly agree with your comment, also the "prefer consistency with the rest of the team" part, but you are not proposing the same as what OP described.

                        • kmoser 2 years ago
                          Apparently they're not a fan of consistency, either :)
                          • pjdkoch 2 years ago
                            No, it's more than I'm just dumb.
                        • cirrus3 2 years ago
                          > There's something elucidating (and satisfying) in seeing a non-obvious piece of code in your native style.

                          Not 5 years later, and when it is someone else's code. Just don't. Initialisms are no better than single char var names. No one later is going to know you started naming "SmartFooProcessingThing" as "sfpt" and when they search for it in millions of lines of the codebase, they are gonna come up empty and waste time.

                          There is nothing you should be finding "satisfying" in a non-obvious piece of code. And if you are working on team, there should be nothing "in your native style". Don't be that person.

                          • pjdkoch 2 years ago
                            I don't think we're talking about the same things.

                            > Not 5 years later, and when it is someone else's code. Just don't.

                            That's precisely when you rewrite more: when the initial context is gone.

                            > Initialisms are no better than single char var names.

                            Correct.

                            > No one later is going to know you started naming "SmartFooProcessingThing" as "sfpt" and when they search for it in millions of lines of the codebase, they are gonna come up empty and waste time.

                            They're not meant to be grepped for. They're meant to be local, fleeting, names for something.

                            > There is nothing you should be finding "satisfying" in a non-obvious piece of code.

                            There is. When you understand it, it's satisfying. Or so has been my experience. There's also the frustration of "why was this left like this in the first place", but sometimes it's merely a matter of preference.

                            Please note that I'm advocating for rewriting and throwing away things you don't understand, not for leaving puzzles for others to relish on.

                            > And if you are working on team, there should be nothing "in your native style". Don't be that person.

                            Indeed.

                        • readthenotes1 2 years ago
                          Clean Code advocates that the length of a variable name should be proportional to it's scope.

                          That's worked well for me on a qualitative level

                          • akerl_ 2 years ago
                            Do you type your variable names using vim or emacs?

                            “When should you use single letter var names” feels like one of those style/preference calls that doesn’t ever have solid rules, other than “if you’re working on a collaborative project, pick a rule and enforce it, even if it’s not perfect”

                            • lucb1e 2 years ago
                              I use vim exclusively but my names are still descriptive. To give an example from a file I have open right now:

                                  list($maxTrophies, $positions, $winStreak, $lossStreak, $lastfetch) = $result->fetch_row();
                              
                              (This is my own hobby code on a solo project; not for an employer where I would be more careful to make it clear for others.)

                              Some are context-specific, like $positions being an array of how often you finished in which position (e.g.: [1,2,3]=[1 finish in 1st position, 2 finishes in 2nd position, 3 finishes as DNF]). Not all names will make sense if you're not familiar with the context, but given how often it's used, I think that's better than having to use onlineRaceFinishPositionArray. Maybe I could have used finishPositions, though. Not sure, it wasn't a choice I thought about very long, but I definitely am not using "p" as a "name".

                              For long names there is Ctrl+n, for example maxtr<Ctrl+n> will autocomplete to maxTrophies. Or for another example, "goldTime_ms": there isn't anything else starting with 'gold' than the gold medal time, and the underscore is annoying to type so this is nice to autocomplete.

                            • borplk 2 years ago
                              I agree with you and let me make another argument for it.

                              Consider the fact that a sensible longer variable name can not be THAT MUCH longer.

                              This creates a problem where you have to manufacture a 10-20-30 character name that somewhat describes what the variable is.

                              Inevitably you end up creating a somewhat misleading name that badly describes what that variable is supposed to be. Probably leaving something out to avoid the name getting too long. You can't write an essay as the variable name.

                              If you accept the short single letter variable name instead you avoid this losing battle to manufacture a name for an abstract thing.

                              Instead you will have the ability to maybe describe what "a" is in a more elaborate code comment.

                              • techsin101 2 years ago
                                yes this as well... wrong info is worse than no info. Short var almost is like writing _list "_" indicates it's an internal property ignore it
                              • saeranv 2 years ago
                                Yeap, me too. Especially when dealing with math/physics. Full named variables for math and physics is incredibly difficult to grok, once you're used to reading it in traditional math form.
                                • pestatije 2 years ago
                                  filteredData, noDateFilteredData, etc. gives me more info than a, b, etc.

                                  Let's say you have 2 lines of code where the variable a is used: a = expr, b = a.filter(...)

                                  Now I have to do the mental effort to see what expr is doing, instead of going directly to the second line and see filteredDateData = filteredData.filter(...)

                                  • techsin101 2 years ago
                                    I'd prefer it like this...

                                    // get users older than 90

                                    a = data.results;

                                    b = a.filter(u => u.dob > 123456)

                                    seniorUsers = b.map(x => {name: x.name, age: x.age})

                                    // self contained

                                    // comes out with one final var that is named to be used later on

                                    // other vars are obviously meant to be ignored and just placeholders

                                    // comment explains what is happening so each var doesn't need sacrifice comprehension speed

                                    • sli 2 years ago
                                      Gonna need parens around that object constructor. ;)
                                • cirrus3 2 years ago
                                  If nothing else, do it for the increased search scope... you can never predict when someone later is going to be desperately searching any reference to something and when digging into an issue with "foo" then the var name of "fooOutputDirectory" is going to save time vs if you named it "out" or "o".

                                  There is no excuse about "well maybe the controller/service/repository/whatever should have been named foo* in that case, I was just holding this temp var for 2 lines of code in helper function and it shouldn't matter".... just don't. Don't be that person. No one thinks you are smarter or cooler for that.

                                  Also consider that if you are really using tiny-scoped vars so often, maybe you are doing something else wrong.

                                  If you have "data = arr.filter(n => n.flag === true);" and it is so tightly scoped, why do you even need "data"? Maybe just return it... if you need to do some other operation on "data", maybe chain the call? If you need to do literally anything else (even just logging it), name it it something useful.

                                  "n" is fine here. "arr" is not... wtf is contained in "arr", what are these types that have "flag"?

                                  Sounds like you got slammed in a code review by someone who has had to debug this type of stuff more than you and you are looking for validation. Just stop being this way sooner than later.

                                  • techsin101 2 years ago
                                    If there is every time there a single variable is being searched then it means that it was not limited to that scope and by let's go. I mean in few lines front and back and if it wasn't then it should have never been a single letter variable. I see single letter variables as placeholders that are meant to live very temporarily. Few lines at best
                                  • 2 years ago
                                    • Gualdrapo 2 years ago
                                      The only thing I can say is that I remember having quite a hard time when my buddy used all single letter variables and reading his code, back when we were learning C at uni. Not sure if after a while one can get used to it and have some "buffer memory" (sort of speak) in the brain for allocating single letter variables while reading or working with code (and if I ever had such thing for the time being), but I do remember writing in paper which variable was which when I got lost after 50 lines or so while reading - and helped me to "debug" because, a couple of times, things didn't work as expected because it seemed it was he who mixed vars when writing the code
                                      • igtztorrero 2 years ago
                                        In GoLang we use single letter variables names in selectors and local variables in small functions
                                        • justsomeuser 2 years ago
                                          I agree. For public interfaces/types or global variables descriptive names are important.

                                          But for temp vars in short functions or closures, I also use single letter vars because I want to see what is being done to the variables rather than the description. If a description is needed I'll use a comment.

                                          Another pattern I find myself using is trying not to use `else`, instead using a function return (either returning early with an if, or a default return at the bottom of the function).

                                          • D-Coder 2 years ago
                                            For me, at least, typing is a lot easier than thinking.
                                            • sublinear 2 years ago
                                              I can only think of a few scenarios: math functions, string formatting, iterators, and generic code where there is no meaningful name.
                                              • AlphaWeaver 2 years ago
                                                I've encountered this in Erlang, but when using Elixir, pipes solve this problem quite nicely.
                                                • bityard 2 years ago
                                                  Single-letter variable names are fine for very short loops in some cases and that's about it. Nearly all other uses unnecessarily obfuscate the code for those who have to maintain it later. (Including Future You.)
                                                  • heavyset_go 2 years ago
                                                    The only time I feel comfortable using them is in short anonymous functions.
                                                    • KptMarchewa 2 years ago
                                                      In lambdas, sure, but in longer functions there's usually better way.
                                                      • decremental 2 years ago
                                                        I prefer variables of the same length so that code is symmetrical. I'll sometimes use synonyms to achieve this.
                                                        • kmoser 2 years ago
                                                          On a similar note, I like variable names that are in the same style, e.g. fooBar or bazBat. That means if I ever see a variable named simply foo or bar, there's likely to be a problem.
                                                        • sys_64738 2 years ago
                                                          Single char bars are terrible when you’re trying to maintain code. Searching becomes really hard with cscope.
                                                          • Tagbert 2 years ago
                                                            conversely, what is the case for single letter names, even in the situations you bring up? Why would someone chose to use single letter names?
                                                            • sokoloff 2 years ago
                                                              There are many cases where a single letter variable name is clearest and easiest to read.

                                                              My loop iterators are mostly single letter. A coordinate is likely to be an x, y, or z. A unit vector aligned to an axis will be i, j, or k. A point is likely to be p. A vector data structure v. The first transformation of a variable x is likely to be x’, the second x’’, etc.

                                                              • fortituded0002 2 years ago
                                                                All these are all math terms and standards which are defined outside of code.

                                                                I think there's something to that - if it's a common enough convention they use it. But if not, don't make it up.