Short Variable Names in Go

In a recent code review my colleague took issue with the following code.

func Enqueue(properties Properties) (err error) {
	logger := logging.GetLogger(ctx)
	bs, err := json.Marshal(properties)
	if err != nil {
		logger = logger.With().Err(err).Logger()
	} else {
		logger = logger.With().RawJSON("properties", bs).Logger()
        … go on to log some stuff and enqueue the supplied event with the supplied properties …

Specifically the question was around whether `bs` was a reasonable name for the variable holding the JSON version of the properties. My counterargument was that short names are better than long names when well understood and/or short in scope. And that Go has a C influence and favors short variable names which you can see in both the standard library and its examples. The Go encoding/json library calls []byte variously src and data (code), b, j and text (examples) –

My colleague said it took them longer 0s to understand the var so they called it out as a nit (not a blocker) and that they care more about knowing what is contained within than if it is `[]byte` or not.

I ended up renaming it `propertiesJSON`. It did start a discussion about short variable names in general and in Go in particular. I’m still not sure how I feel about it. I did find some reading that seemed relevant though.

Notes on Programming in C (Variable names)

Variable names in Go should be short rather than long. This is especially true for local variables with limited scope. Prefer c to lineCount. Prefer i to sliceIndex.

Go Code Review Comments (Variable Names)

Local variables. Keep them short; long names obscure what the code does … Prefer b to buffer.

What’s In a Name? (Local Variables)

4 Replies to “Short Variable Names in Go”

  1. I tried to summarize the common naming rules in Go as well as when and to which extent we can apply them. I also explained the main idea behind shorter naming in Go, which is to find a balance between being concise and descriptive.

  2. I think my comment spam fighter ate your URL but I found it via Google – That’s a good summary. I suppose the key question for my code is: “is `bs` an easily understood abbreviation for some-bytes-containing-json?” and, if not, “what is the shortest name that conveys the meaning of this variable?” From the review comment I guess `bs` is not sufficiently explicable. `json`? `jsonBytes`? `b`? `logJSON`, `eventJSON`, `propsJSON`? I think at the very least the `properties` param wants to become `props` by the rules of shortest-wins-if-still-clear.

Leave a Reply

Your email address will not be published.