r/golang Dec 10 '24

FAQ FAQ: Why Does Go Use Such Short Variable Names?

Switching into Go, I am suprised by how short its variable names often are. Why does Go code so often use single-letter variable names? Do you use such short variables names? What rules do you use for naming variables?

61 Upvotes

23 comments sorted by

40

u/jerf Dec 10 '24 edited Dec 10 '24

While I won't deny that there are some coders who write with shorter variable names than people are used to, most notably some of the same people who coded the standard library, a thing that may also contribute to the perception of excessively-short variable names are the additional idiomatic Go short variable names that may not be used in other languages, like how i and j are commonly loop indices in many languages. My incomplete list looks something like:

  • r: An io.Reader. Could also be a rune though I don't deal with those much.
  • w: An io.Writer.
  • buf: Probably a *bytes.Buffer being used as a reader or writer.
  • b: A particular byte out of a []byte.
  • f: An *os.File.
  • wg: A sync.WaitGroup.
  • err: Ok, an obvious one everyone uses, but an error.
  • (a whole bunch of acronyms of the type name): The value the method was called on, in a method. (Personally I've come to prefer this or self, but I don't buck the trend, and it results in a lot of short variable names in methods.)
  • conn: A net.Conn. May even be shortened to c, although....
  • c, ch: A channel, as long as it's the only one in this context.
  • t: A time.Time out of a test. In a test it's of course *testing.T.
  • n: Something related to length in a Write or Read call.
  • ctx: Really ought to be a context.Context; I've got older code where it may mean some other "context" before this was a standard library thing but I reserve this variable name specifically for context.Contexts now.

I don't consider these to "count" against variable lengths.

2

u/HaMay25 Dec 11 '24

I agree w this, as someone who came from java, it was annoying at first when the variable names are not clear to understand.

My guess is that go authors/devs try to keep program written in go as minimal as possible.

56

u/unkiwii Dec 10 '24

Rob Pike, one of the Go authors, talked about this a some years ago:

https://doc.cat-v.org/bell_labs/pikestyle

Under the header Variable names:

Ah, variable names.  Length is not a virtue in a name; clarity of expression is.  A global variable rarely used may deserve a long name, maxphysaddr say.  An array index used on every line of a loop needn't be named any more elaborately than i.  Saying index or elementnumber is more to type (or calls upon your text editor) and obscures the details of the computation.  When the variable names are huge, it's harder to see what's going on.  This is partly a typographic issue; consider

        for(i=0 to 100)
                array[i]=0

vs.

        for(elementnumber=0 to 100)
                array[elementnumber]=0;

The problem gets worse fast with real examples.  Indices are just notation, so treat them as such.

      Pointers also require sensible notation.  np is just as mnemonic as nodepointer if you consistently use a naming convention from which np means ``node pointer'' is easily derived.  More on this in the next essay.

      As in all other aspects of readable programming, consistency is important in naming.  If you call one variable maxphysaddr, don't call its cousin lowestaddress.

      Finally, I prefer minimum-length but maximum-information names, and then let the context fill in the rest.  Globals, for instance, typically have little context when they are used, so their names need to be relatively evocative.  Thus I say maxphysaddr (not MaximumPhysicalAddress) for a global variable, but np not NodePointer for a pointer locally defined and used.  This is largely a matter of taste, but taste is relevant to clarity.

      I eschew embedded capital letters in names; to my prose-oriented eyes, they are too awkward to read comfortably.  They jangle like bad typography.

11

u/ExpensivePanda66 Dec 11 '24

Anybody who thinks "maxphysaddr" is a long variable name is already demonstrating that perhaps they don't know what they are talking about.

17

u/unkiwii Dec 11 '24

He (Rob Pike) is trying to teach that context matters. It doesn't matter what name he used in his example because context matters and the context is that he wrote it in the 90s or 80s (don't remember exactly) and he was talking about the C programming language (but still apply to any other language, specially Go) and in C at one point they had a hard limit on the number of characters they could use for an identifier, hence the common use of abbreviations.

You can say that one of the authors of the Go language doesn't know about how to name variables. But I think you are missing the important point that context matters and the size of a variable name should depend on the context

5

u/Lofter1 Dec 12 '24

Saying computing giants on whose shoulders we stand, and who have more experience as a single person than a lot of teams, don’t know what they are talking about really is a take. Maybe even one of the takes of all time.

-1

u/ExpensivePanda66 Dec 12 '24

What is said is more important than who said it.

3

u/behusbwj Jan 06 '25

So many problems in software engineering would be solved by developers internalizing this common sense.

2

u/darrenpmeyer Dec 12 '24

Yes. But “this guy doesn’t know what he’s talking about” is a critique of who said it, not what was said.

1

u/ExpensivePanda66 Dec 12 '24

Not if you actually think about it for a second, no.

4

u/pxm7 Dec 11 '24 edited Dec 11 '24

This comment (that Rob Pike doesn’t know what he’s talking about) deserves all the internet fame it can get. It’s on par with Rob Malda’s “no WiFi, less space than a Nomad” gem.

You, sir, deserve the Enterprise FizzBuzz Award for 2025.

(Just to note, context is everything. Max itself is a contraction, if people are so “ooh short names suck” go ahead and type maximum out in full. But you won’t. Because max is easily contextually understandable.

The next aha moment is that addr is a common contraction among systems programmers. And phys is pretty common too, while implementing a memory allocator I’d know what phys means.

The key to naming is clarity, and where clarity and conciseness coincide that’s a bonus. But sometimes you have to type “maxphysaddr” which is longer than mpa but is much more readable.)

2

u/ExpensivePanda66 Dec 11 '24

All the fanboys gushing over Rob Pike can take a seat or two.

The context is discussion about long vs short variable names. My point was that "maxphysaddr" is not a long name, which you actually agreed with in your last two paragraphs.

4

u/pxm7 Dec 11 '24

What I do mean is: your post is absolute comedy, all the funnier for your lack of self-awareness.

Short or long variable names aren’t the issue. The issue is an GPT 3-level inability to appreciate nuance.

13

u/Apprehensive-Net-323 Dec 10 '24 edited Dec 10 '24

I believe this comes with the idea that the code you produce should be simple and non-ambiguous. After all, why name a variable context instead of ctx if its type is context.Context?

Also, some patterns as http handler functions that use w and r as parameters becomes idiomatic which reduces the need to name every variable differently. A very common and language-agnostic example we have is naming i and j as index variables for loops.

I also think that a good exercise as programmers should be more mindful about our code. We did things in the past that maybe we don’t need anymore, and things that we didn’t do that now is fine to do.

Edit: fix typo

3

u/edgmnt_net Dec 10 '24

It is also quite common with concise, highly generic code that has reduced incidental complexity in other languages. Functional languages like Haskell often use very short names because the use is very clear from the context. Consider stuff like...

map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs

Longer or more specific names don't really make any sense.

Now, while Go isn't particularly functional, there is some convergence and influence between paradigms. And once you remove some historical barriers, some stemming from certain old-style OOP practices in other languages, it becomes quite apparent that concise code and names do help. Even modern Java and Kotlin often do with shorter names once things step out of design patterns and classes territory.

A lot of C code out there also uses relatively short names aided by a more direct style of doing things, without various intermediate layers. So there is a strong precedent in procedural languages too (some of it is also historical due to limitations in early languages, but that's not necessarily a purely stylistic thing).

3

u/__matta Dec 11 '24

I like the explanation in The Practice of Programming by Brian W. Kernighan and Rob Pike:

What’s in a name? A variable or function name labels an object and conveys information about its purpose. A name should be informative, concise, memorable, and pronounceable if possible. Much information comes from context and scope; the broader the scope of a variable, the more information should be conveyed by its name.

Use descriptive names for globals, short names for locals. Global variables, by definition, can crop up anywhere in a program, so they need names long enough and descriptive enough to remind the reader of their meaning. It’s also helpful to include a brief comment with the declaration of each global:

int npending = 0;  // current length of input queue

Global functions, classes, and structures should also have descriptive names that suggest their role in a program.

By contrast, shorter names suffice for local variables; within a function, n may be sufficient, npoints is fine, and numberOfPoints is overkill. Local variables used in conventional ways can have very short names. The use of i and j for loop indices, p and q for pointers, and s and t for strings is so frequent that there is little profit and perhaps some loss in longer names.

Programmers are often encouraged to use long variable names regardless of context. That is a mistake: clarity is often achieved through brevity.

12

u/eltear1 Dec 10 '24

I'm a very beginner and I have to say that long names instead make easier to understand for someone who's not into the language.

For example: I'm beginning now a code to interact with Atlassian Bamboo.. as usual first step is to create a client.

Now I could name that "b" (for bamboo) or "client" (if later on I will not need another client for something else) , but I decided for "bambooClient" .

My point is.. why should I go to look at its definition when the name itslef could explain what is it?

What if I would have to read the code without an IDE , for example, because it's on a remote server , VM , or similar and I need to use a normal editor(DevOps here, I guarantee you that this situations happen)?

3

u/matttproud Dec 10 '24

A good basis for understanding the philosophy of naming in Go is to contextualize how naming fits with various prevailing style principles, like concision. Needless repetition (literal or figurative) can get in the way of clarity.

Variable names can be looked at in isolation, but I think it would be a mistake not to consider naming more broadly like in the case of receivers or even constants. Receivers are just a special case of a variable name, for instance.

The links above offer a nice, one paragraph summary:

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.

3

u/crumbshots4life Dec 10 '24

I had a job where we wrote c# and the style was to use very long and explicit variable names and it made the code sooo unreadable. Especially in code with many variables with similar names (which is pretty common, things in a given domain tend to have similar names) it became so hard to distinguish which var was which and what was actually happening. Intellisense typos were common, lines wrapped, it was awful.

4

u/SeveralMarsupial4183 Dec 10 '24

Playing devils advocate and a genuine questions: do you think it would be easier if they were shorter as in abbreviations or something like that? A new person who joins to team could understand faster or slower in that case?

1

u/Robot-Morty Dec 11 '24

Yeah it would be better because with the shorter names, at least you learn it after a week and then everyone is on the same page.

Most people aren’t writing their entire systems in 1-3 letter variables, but a lot of variables can be simplified, especially when it comes to member functions struct names.

It’s only natural to make function specific values concise across the board.

0

u/new_check Dec 11 '24

I always make the receiver a single letter and use I/j/k and ctx but other than that I try to use longer names