6 ms·
> The general rule of thumb is that the length of a name should be proportional to the size of its scope and inversely proportional to the number of times that
by adamgordonbell 4y ago
> The general rule of thumb is that the length of a name should be proportional to the size of its scope and inversely proportional to the number of times that it is used within that scope.
> A variable created at file scope may require multiple words, whereas a variable scoped to a single inner block may be a single word or even just a character or two, to keep the code clear and avoid extraneous information.
I love how it covers both short iterators and long descriptive names under a single principle.
- don_albrecht 4y agoThis advice should be universal in coding. When I first started programming, I had a manager that hated 1-2 character variables. But they make sense for loop iterators.
- thunky 4y agoFor loop iterations it's fine, but I think Go code often takes this too far. It often takes longer to read a single character than a word, because I have to mentally map the character to the word anyway. Reminds me of when people go nuts aliasing table names in SQL queries, which IMO makes it harder to read as well.
- philote 4y agoI agree. Plus, with IDEs and auto-completion, why not use longer names?
- vbezhenar 4y agoOne reason so use short names is to keep lines short and reduce line wrapping. This helps to read code, especially when you do 3-way merges.
- GuB-42 4y ago- Longer names mean longer lines, and lines that are longer than your viewport are terrible. Less of a problem with modern ultrawide screens, but passed ~100 characters, it starts becoming a problem in some cases (ex: diffing). Personally, I have a soft limit at 80, hard limit at 120, because that's what works best for me. - With such rules, variable length is a hint of its scope. For example, I tend to use "i" when the loop body is small, "idx" or "index" when it is a bit larger, and a more descriptive name when it exceeds one screen. This way, just by looking at a single line, I already have a hint about its context. - Just because a variable name is short doesn't mean it is meaningless. For example "i", "j", "k", are loop indices, "x", "y", "z" are point coordinates and "dx", "dy", and "dz" are differences, "a" and "b" are both sides of a comparison function, "t" can be a temporary variable or a time depending on context, etc... The corollary is to make sure you use your single letter variables consistently. If I see an "x" in a place where a coordinate can be used and it does not refer to a coordinate, or an "i" that is not a loop index, I will be confused.
- mikepurvis 4y agoIf you have to use that name a bunch of times close together, it bloats line lengths which also affects readability.
- madeofpalk 4y agoThere's also a bit of Fitt's Law in here as well - I find it a lot harder to select, or put my cursor in, a single letter variable. So if I want to rename `i` to something else, I must carefully select `i`, whereas with a longer variable I find it easier to put my cursor in the middle of `index` and hit F2.
- ErikCorry 4y agoIf you are using a mouse for things like this you already lost though.
- shepherdjerred 4y agoMost developers use their mouse quite often.
- SnooSux 4y agoI started using ii as my iterator variable name for similar reasons. Easier to highlight and Ctrl-F for. Also removing ambiguity when using i as the imaginary constant.
- Xeoncross 4y agoThe constancy in Go makes this better. I have come to expect `r` to be an io.Reader or http.Request depending on context. There are a few interfaces in Go that are used heavily and I don't mind that people often use a single character for them. It's the same thing as everyone using `i` for iterators.
- bpicolo 4y agoI just use reader//req. Code is instantly easier to read for me personally and no time has been wasted. It's all preference, of course.
- kevmo314 4y agoSometimes you run into packages called reader which makes for a less fun time using variable names that are also words.
- rlabrecque 4y agoThis is much nicer for other people coming into this. It's the same problem with spoken language and slang, slang is better if you know it, worse if you don't.
- dimitrios1 4y agoSorry to be pedantic (well, not really it's M.O. for a hacker news commentor after all, isn't it?) , but as someone who knows a few languages, slang is not an issue with spoken languages at all. You learn a language by full immersion with other speakers, who impart that knowledge unto you. Unless all you are doing is conversing with grammaticians and newscasters, you will pick up on regional and local differences, euphemisms, and slang.
- shepherdjerred 4y agoI don't believe so. Imagine you're new to Go and you haven't mentally mapped all of these abbreviations. What would you rather read, `r` or `reader`?
- david422 4y agoOr in languages that you can import a resource but give it a custom name. So whenever you are reading someone else's code you have to double check to understand what is going on. For instance, import DiskUtils as DU, and now all the code references DU.diskSpace()
- monocasa 4y agoExactly. I think a better heuristic rather than tying it to scope is to sort of semantically huffman encode. Using an iterator is probably the most used variable name that starts with an 'i', so it gets just plain 'i'. As a _concept_ gets more specific, then it gets a longer name.
- SEJeff 4y agoYeah i for for loops (in python) x for comprehensions, etc, make sense. But in general, single character variables make code really hard to read.
- ehsankia 4y agoYep, you should just use the best judgement, for example for distance, time in driving_metrics: speed = distance / time is a lot clearer than for d, t in driving_metrics: s = d / t even if it's used in a tiny scope once. But some things don't have a valuable meaning, or the meaning can trivially be inferred.
- SEJeff 4y agoI meant i as in the iterator variable for a counter like when using enumerate() or a c style for loop where you manually specify the list index.
- stevekemp 4y agoWhen I started coding I'd type 10 FOR F = 1 TO 10 20 PRINT F, F*F 30 NEXT F Because "FOR" and "F" shared the same key, on my ZX Spectrum keyboard.
- antod 4y agoAnd for those that don't know - entering Basic code on the Spectrum (well the original one at least) was ALL single/shifted key shortcuts for keywords rather than typing them out. eg https://www.old-computers.com/museum/photos/sinclair_zx-spectrum_keyboard-detail_hr.jpg https://www.old-computers.com/museum/photos/sinclair_zx-spec... The low cost and quirky masochism was mainly why we loved it.
- randomswede 4y agoSame thing for the ZX-80 and ZX-81. If you were careful with your text prompts, you could save several bytes by injecting a keyword instead of typing it out, but anything that was a "start of line only" could be tricky injecting into a string.
- raverbashing 4y agoGood Apple APIs are infamous for their long names. Not sure what they gain by it
- Cthulhu_ 4y agoI never minded it so much in Apple code; with the syntax for calling methods, it made method invocations sound like sentences, more like literal programming. Plus, intrinsic named parameters, so many languages - including Go IMO - would benefit from named parameters.
- wingerlang 4y agoNever having to figure out what a function actually does is nice. builder.makeThing("a", true, true, 46) [builder makeThingNamed:"a" isRound:YES isRed:YES size:46] or lately builder.makeThing(named: "a", isRound:true, isRed:true, size:46)
- speedyapoc 4y agoRight? I have never understood the frustration around named parameters like this. It helps reduce cognitive load quite a bit.
- Jiro 4y agoIt increases cognitive load when writing the function call, since you now need to remember what kind of true to use. It also increases cognitive load for people who either do already understand the parameters or who are doing something for which the parameters are not relevant; it's harder to ignore a long thing than to ignore a plain "true".
- masklinn 4y ago> It increases cognitive load when writing the function call, since you now need to remember what kind of true to use. There is no "kind of true". > It also increases cognitive load for people who either do already understand the parameters By letting them see what the parameter they remember is? There's no cognitive load to seeing what you expect. > or who are doing something for which the parameters are not relevant; If the language doesn't have optional parameters, all parameters are relevant. By making parameters named, you avoid having to count positional parameters as in MS APIs to ensure you didn't get one in the wrong slot. > it's harder to ignore a long thing than to ignore a plain "true". Which is very much valuable. It's much easier to notice mistakes than when you've got 11 positional parameters of which 2/3rds are usually set to 0/null.
- nebiros 4y ago
- hoosieree 4y agoThe more I think about this rule the more I like it. One thing I would add is if you're writing a library, think of the people using it. Are they going to curse you every time they have to write YourModule.ExtremelyVerboseMethodNameWhyOhWhyIsItSoLong, even if it only appears once in your module? As soon as you start sharing code, you can't know how many times a name will appear. So err on the side of brevity, for our sakes.
- everybodyknows 4y ago> A variable created at file scope How does one declare a variable to be of file scope in Go? An ordinary "var x int" has package scope, visible from any file in the directory (aside from the special cases around _test.go files). Scope of package import declarations is narrowed to a single .go file, but these of course are not variables.
- avianlyric 4y agoI think you’re reading this too literally. They likely just mean file scope from a purely usage perspective. I.E. you only use the variable in one file, it doesn’t matter how the language processes it into a computational scope
- everybodyknows 4y agoIt absolutely does matter. If I'm editing the file in which the package-scope variable (or type, or const) is declared (and also referenced) and decide on the fly to subtly change its semantics, forgetting that the same is also referenced from some other file within the package, I have likely just created a bug. Worse, the bug will likely manifest itself only at run time.
- chrsig 4y agoYou're still taking things too literally. A human typed in something less precise than you'd like in a style guide. Find a bug tracker to request a verbiage change. It's not that big of a deal. No one is asserting that variables are in fact file scoped.