Go for short variable names

2014-03-06Comments

Recently Brad Fitzpatrick promoted the Go style guide on twitter, which prompted Tim Penhey to take issue with its advice on variable naming.

A brief and inconclusive exchange followed. Twitter’s fine for opinions and one-liners but flawed for discussions — even when the subject happens to be brevity.

I’m not going to tweet about it, but I like Go and I like its style. I’d rather read code which uses short variable names. Long descriptive names, which may appear to provide more information, often obscure the structure and flow of the code. The narrower the scope, the shorter names can be; so the style guide implicitly sanctions short functions and shuns globals. All good.

How short is short?

Those variables are certainly short rather than descriptive but they aren’t scary: c could be a character; ch for channel, maybe, or another character; d for data, difference or distance; m, midpoint; s string; st state. All guesses, of course, but in context I’d expect to see — in the space of just a few lines of code — where each variable lives and how it’s used, a more clear and correct indication of what it means than a lengthy name could ever be.

Single character variables are just fine, says the style guide:

Prefer c to lineCount. Prefer i to sliceIndex.

Some languages allow you to go further. Omit a variable in Perl and it defaults to being what you’d like it to be. Usually.

A single character variable name is an extreme form of abbreviation. It works nicely for small things, like pixels and characters.

Pixel pixel, pel, px, p;
Character character, char, ch, c;

Some less terse abbreviations hurt my ear: mngr, svr, cnt.

The style guide is, after all, a guide, and common sense applies. Some abbreviations are ugly and others save so little space they aren’t worth it.

Go’s advice on naming tips a hat to the language’s C heritage and to C’s great application, UNIX, which is unsurprising when you realise one of Go’s prominent contributors, Ken Thompson, had a hand in both. When Thompson was asked what he would do differently if he were redesigning UNIX he replied:

I’d spell creat with an “e”.

So, working on Go, he did.