News for hackers. Stuff that matters.
Re:Google’s Go Style Guide by adamgordonbell on Friday November 18, 2022 @08:20AM (#33654169)

    > 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.
Re:Google’s Go Style Guide by don_albrecht on Friday November 18, 2022 @08:25AM (#33654229)
This 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.
Re:Google’s Go Style Guide by thunky on Friday November 18, 2022 @09:01AM (#33654795)
For 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.

Re:Google’s Go Style Guide by philote on Friday November 18, 2022 @09:08AM (#33654897)
I agree. Plus, with IDEs and auto-completion, why not use longer names?
Re:Google’s Go Style Guide by vbezhenar on Friday November 18, 2022 @09:29AM (#33655211)
One 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.
Re:Google’s Go Style Guide by GuB-42 on Friday November 18, 2022 @10:07AM (#33655754)
- 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.

Re:Google’s Go Style Guide by mikepurvis on Friday November 18, 2022 @10:38AM (#33656260)
If you have to use that name a bunch of times close together, it bloats line lengths which also affects readability.
Re:Google’s Go Style Guide by madeofpalk on Friday November 18, 2022 @09:50AM (#33655524)
There'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.
Re:Google’s Go Style Guide by ErikCorry on Friday November 18, 2022 @09:52AM (#33655549)
If you are using a mouse for things like this you already lost though.
Re:Google’s Go Style Guide by shepherdjerred on Friday November 18, 2022 @02:49PM (#33661008)
Most developers use their mouse quite often.
Re:Google’s Go Style Guide by SnooSux on Friday November 18, 2022 @11:04AM (#33656698)
I 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.
Re:Google’s Go Style Guide by Xeoncross on Friday November 18, 2022 @09:51AM (#33655526)
The 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.

Re:Google’s Go Style Guide by jawzz on Friday November 18, 2022 @10:09AM (#33655774)
This makes me wonder: what if there was a language where variable names are determined according to the type, with the option of overriding with a custom name. So a variable of type http.Request would automatically be named “req”, the next one in scope would be “req2”, etc.

If you think about it, when you solve a physics problem, for instance, you call every mass “m1”, “m2”, etc. Maybe this would be another step in Go’s direction of conforming style to make code more standard and readable.

Re:Google’s Go Style Guide by notpushkin on Friday November 18, 2022 @10:35AM (#33656208)
Re:Google’s Go Style Guide by jawzz on Friday November 18, 2022 @05:57PM (#33663917)
Oh cool, thanks for that.
Re:Google’s Go Style Guide by leetrout on Friday November 18, 2022 @10:22AM (#33655990)
This is interesting.

The idea of having a standard library of types related to what are effectively program keywords... could be really good. Or hideous like global vars.

I wonder if any language has tried this?

Re:Google’s Go Style Guide by gbalduzzi on Friday November 18, 2022 @11:12AM (#33656811)
I agree that most types come with a natural variable name.

However, in many cases a more descriptive name is way appropriate. On top of my mind:

- Multiple variables of the same type. How are you supposed to distinguish between req and req2? Compare it to something like "apiReq" and "cdnReq"

- Primitive types, that does not inherently carry a domain value. An integer called "seconds" or "max_offset" has a lot more meaning that one named "num"

Forcing such a notation into the language would make impossibile to represent all these cases

Re:Google’s Go Style Guide by gogogogogogo on Friday November 18, 2022 @02:46PM (#33660958)
The real question from this example is: why are you creating two http requests in the same scope before using them?

I've been writing Go cloud stuff for the better part of a decade and "req" for a request has never been ambiguous because I go ahead and send the request and process the response before sending another one, at which point I can just reassign the variable and let the first one fall out of scope.

Re:Google’s Go Style Guide by gbalduzzi on Monday November 21, 2022 @06:42AM (#33691476)
The request type is just an example, of course, building up from the example in the comment I was replying to.
Re:Google’s Go Style Guide by jawzz on Friday November 18, 2022 @05:56PM (#33663902)
You’re right. Going back to my physics example, all the variables in a physics problem are actually of the same type, float. So you’d need more specific types, but that would be infeasible-the whole point of types in a general purpose language is that they’re general enough for any use case.

If you were just coding physics problems you could have types restricted to the physics domain, that is, physical units. Which it looks like MATLAB does now support: https://www.mathworks.com/help/symbolic/units-of-measurement...

Re:Google’s Go Style Guide by randomswede on Monday November 21, 2022 @04:03AM (#33690430)
Werrrrlllllll... It all depends on what yo umean by "type". In physics problems, I find taht quantities may be measured in "floats", but have the types "mass", "amperage", "distance per second per second" and the like.

In Go, I would probably model this as:

    type mass float64
    type speed float64
    type acceleration float64
That way, they'd all have float64 as the "storage type", but it would be harder to accidentally pass an acceleration when I wanted a mass.
Re:Google’s Go Style Guide by robertlagrant on Monday November 21, 2022 @09:11AM (#33692631)
> Going back to my physics example, all the variables in a physics problem are actually of the same type, float

This is why some people recommend a practice I've forgotten the name of, where they defined a new type that maps to language type. So type Mass could just be a float, but you know better how to treat it.

Re:Google’s Go Style Guide by vlunkr on Friday November 18, 2022 @01:29PM (#33659415)
What if I introduce a new http.Request between 1 and 2? Now all the references are broken.
Re:Google’s Go Style Guide by Too on Saturday November 19, 2022 @02:08AM (#33667807)
Terraform has an extreme approach to that, every time you reference a variable you have to spell out the complete TYPE.NAME.ATTRIBUTE, eg resource.aws_s3_bucket.my_bucket.website_endpoint. There is no way to access my_bucket without the whole prefix, even after assigning it to local variable you must prefix the reads as locals.my_bucket.

For sensitive infrastructure this makes sense, i surely wouldn't want to write other code like this.

Re:Google’s Go Style Guide by Ferret7446 on Saturday November 19, 2022 @04:38AM (#33668616)
That could be easily done by the editor in a statically typed language like Go, so there is no point bloating the language with it. Just turn on an overlay that displays the types of all names. I believe LSP adds this to many languages/editors already.
Re:Google’s Go Style Guide by bpicolo on Friday November 18, 2022 @10:01AM (#33655674)
I 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.

Re:Google’s Go Style Guide by kevmo314 on Friday November 18, 2022 @01:32PM (#33659507)
Sometimes you run into packages called reader which makes for a less fun time using variable names that are also words.
Re:Google’s Go Style Guide by rlabrecque on Friday November 18, 2022 @01:56PM (#33660062)
This 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.
Re:Google’s Go Style Guide by dimitrios1 on Friday November 18, 2022 @02:16PM (#33660460)
Sorry 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.
Re:Google’s Go Style Guide by shepherdjerred on Friday November 18, 2022 @02:47PM (#33660981)
I 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`?

Re:Google’s Go Style Guide by jrockway on Friday November 18, 2022 @03:02PM (#33661219)
Designing an API that "stutters" is a very common mistake that many programmers make. reader.Read() is pretty jarring.

There is also nothing wrong with naming variables after what they're for instead of what they are. Consider io.Copy(dst, src). That's nicer than io.Copy(reader1, reader2).

Re:Google’s Go Style Guide by pindab0ter on Friday November 18, 2022 @04:32PM (#33662584)
But not necessarily nicer than io.Copy(destination, source).
Re:Google’s Go Style Guide by shepherdjerred on Friday November 18, 2022 @07:17PM (#33664999)
Sure, so call your reader `file` or `network` or `stream`. Don't call it `r`. Nobody is charging you by the character.

It isn't a huge deal when the code is simple, e.g. you create a reader named `r` and in the next line you use it. That's easy to understand. The problem is that the pattern propagates. A few more lines of code are added, the reader is still named `r`. It's name `r` here, so we start putting it in a struct as `r`. Soon enough the codebase is littered with instances of `r`. Not great.

Re:Google’s Go Style Guide by david422 on Friday November 18, 2022 @11:22AM (#33656996)
Or 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()
Re:Google’s Go Style Guide by monocasa on Friday November 18, 2022 @12:48PM (#33658616)
Exactly.

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.

Re:Google’s Go Style Guide by SEJeff on Friday November 18, 2022 @12:37PM (#33658377)
Yeah i for for loops (in python) x for comprehensions, etc, make sense. But in general, single character variables make code really hard to read.
Re:Google’s Go Style Guide by ehsankia on Friday November 18, 2022 @01:09PM (#33659029)
Yep, 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.
Re:Google’s Go Style Guide by SEJeff on Friday November 18, 2022 @09:31PM (#33666154)
I 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.
Re:Google’s Go Style Guide by stevekemp on Friday November 18, 2022 @01:52PM (#33659970)
When 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.
Re:Google’s Go Style Guide by antod on Friday November 18, 2022 @03:19PM (#33661439)
And 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-spec...

The low cost and quirky masochism was mainly why we loved it.

Re:Google’s Go Style Guide by randomswede on Monday November 21, 2022 @04:11AM (#33690495)
Same 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.
Re:Google’s Go Style Guide by raverbashing on Friday November 18, 2022 @08:24AM (#33654214)
Good

Apple APIs are infamous for their long names. Not sure what they gain by it

Re:Google’s Go Style Guide by Cthulhu_ on Friday November 18, 2022 @08:36AM (#33654391)
I 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.
Re:Google’s Go Style Guide by wingerlang on Friday November 18, 2022 @09:15AM (#33654989)
Never 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)

Re:Google’s Go Style Guide by speedyapoc on Friday November 18, 2022 @09:44AM (#33655422)
Right? I have never understood the frustration around named parameters like this. It helps reduce cognitive load quite a bit.
Re:Google’s Go Style Guide by Jiro on Friday November 18, 2022 @10:39AM (#33656278)
It 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".
Re:Google’s Go Style Guide by masklinn on Friday November 18, 2022 @11:28AM (#33657094)
> 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.

Re:Google’s Go Style Guide by masklinn on Friday November 18, 2022 @11:21AM (#33656972)
> Apple APIs are infamous for their long names. Not sure what they gain by it

Clarity.

It's also a factor of Objective-C's compound methods (inherited from Smalltalk), as each parameter names appears in the method, and which leads to a very phrase-like style.

By osmosis, the C APIs use a similar style.

Re:Google’s Go Style Guide by hoosieree on Friday November 18, 2022 @09:27AM (#33655164)
The 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.

Re:Google’s Go Style Guide by everybodyknows on Friday November 18, 2022 @10:25AM (#33656028)
> 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.

Re:Google’s Go Style Guide by avianlyric on Friday November 18, 2022 @10:38AM (#33656262)
I 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
Re:Google’s Go Style Guide by everybodyknows on Friday November 18, 2022 @11:01AM (#33656666)
It 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.
Re:Google’s Go Style Guide by chrsig on Friday November 18, 2022 @12:38PM (#33658393)
You'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.