Why I still consider if/else idiomatic Go

September 4, 2016

Continuation of Why I consider if/else idiomatic Go

Please adhere to the Gopher values. I’m not writing this to criticize anyone nor claim right and wrong. This is simply my statement for why I don’t adhere to one particular Go idiom.


This is considered idiomatic Go:

if err != nil {
  // error handling
  return // or continue, etc.
// normal code?

That’s generally great. Fail early. One problem is, logically, it literally means:

if err != nil {
  // error handling
// depending on the error handling, possibly execute this

Also, not really horrible. I’m working on an update to go vet that’ll catch possibly unintentional error-handling fall-throughs.


In Other languages

I’ve discovered that I like that style quite a lot. I use it when programming in all other languages, mostly: Java, Python, JavaScript, and C. (I use Scala much more than Java but this style doesn’t really pertain to Scala.)

So I wondered, what is it about Go that makes me not want to use that style?

It’s Scope

I have long cared about scope quite a lot. It’s very high on my list of design decisions while I’m coding. So much so that I often write C and Java in blocks:

// define x
  // do something to compute x
// use x

Essentially, I try not to allow a variable to live beyond its use while living close to its use.

The reason: keeping variables minimally scoped reduces complexity. We all inherently know this from Avoid Globals 101.

Scope in Go

So when I read Go’s early spec and learned that initialization statements scoped the variables to the block, I thought it was interesting. Around Go 1.2 when I was using Go heavily, I was in love with them.

The problem, with respect to idiomatic Go: they scope the variables, requiring the use of else.

if x, err := f(); err != nil {
  // error handling
} else {
  // use x

Not A Problem

To me, I’m perfectly fine typing an else since it gives me the scoping rules I prefer. If you don’t like looking at my code, don’t read my code or change your editor’s code-style to disable the color for else and it’ll look a lot like idiomatic Go.

I believe if init/else is logically-superior code, more consistently applicable, and less complex on average. I’ll stick with it and I’m completely fine that you ridicule me and whine about how wrong you think I am.

Discussion, links, and tweets

comments powered by Disqus