Hacker News new | ask | show | jobs
by simon_o 3143 days ago
Exceptions are bad outside the "your computer just started burning" cases, but Go has replaced them with something even worse, "multiple return values".

So instead of some imagined return of "int or throw Exception" you now have "(int, error)", which basically means that the result of a function call can be any of these four options:

  - (   value, no error)
  - (no value,    error)
  - (   value,    error)
  - (no value, no error)
And due to the lack of Generics you can't abstract over your error handling.

And due to the lack of proper ADTs you can't even properly model "value OR error" manually.

3 comments

The last case is rarely seen in Go (at least not in the standard library).

Accepting for the moment that Go has no exceptions and and error returns are the way to go, the first two cases make sense.

The third case ( value, error) is actually useful in several scenarios. For instance, considering you're writing bytes to a stream that fail partway. The value is the number of bytes return so far and the error is the error that was encountered. In fact, this is the signature that the ubiquitous io.Writer's Write method uses.

If all you had was single return values (aka "int or throw Exception"), how would you model the io.Writer?

> If all you had was single return values (aka "int or throw Exception"), how would you model the io.Writer?

This is not an problem, because a single return value is _not_ everything one has.

The last two options are not idiomatic Go. (zero, err) and (nonZero, nil) are. So the error check is almost always a simple `if err != nil {return err}`.
> The last two options are not idiomatic Go.

Who are the authors of https://golang.org/pkg/io again?

Yeah, 90% of Go devs agree with you.

10% think it is a really great idea.

So you can never be sure without reading the documentation.

Feels like Javascript callback error handling. Which was not much fun.
Just without the callbacks. At least you could abstract over error handling with callbacks...