Jabbering Giraffe

Return errors or useful values, not both

One of the nice features of Go is returning multiple values natively. e.g.

type Foo struct{…}

func New() (*Foo, error) {
  if err := initSomething(); err != nil {
    return nil, err
  }
  return &Foo{…}, nil
}

What’s interesting is that either the error is nil (and you have a useful value) or the useful value is nil if you have an error. You don’t have to deal with the case of a useful value and an error. In general, this seems to be a good pattern.

Is it ever useful to return both? Possibly. But I’d argue that if you want to do this, it’s better to embed the error into the value. e.g.

type Foo struct {
  Err error
  // …
}

func New() *Foo {
  if err := initSomething(); err != nil {
    return &Foo{Err: err}
  }
  return &Foo{…}
}

Then it’s clear that the value returned may have other useful properties.