2016-03-07 10:23 GMT+01:00 Tom Scrace <
t.sc...@gmail.com>:
> To my mind, the latter is by far the most important. And - although I know
> this is not a popular view within the Go community - I think this is a
> tradeoff that exceptions solve quite nicely.
>
> Nonetheless I think there might be better ways to sove this. For example:
>
> func (g *Gopher) WriteTo(w io.Writer) (int64, error) {
> bw, bwErr := &binWriter{w: w}
> bw.Write(int32(len(g.Name)))
> bw.Write([]byte(g.Name))
> bw.Write(int64(g.AgeYears))
> return bw.size, bwErr
> }
Here bwErr would need to be a *error, which would need to be
dereferenced in the return statement. That would be a very unusual API
and somewhat spooky action at a distance. You might think you could
return an object that implements the error interface and just update
that object behind the scenes, but since the convention is to compare
the error to nil that wouldn't fly.
If you're worried about the error not being checked, the above API
implies that the error would happen during the *creation* of binWriter
(which would need a constructor to return the two arguments) so you'd
probably see someone do the error check immediately after construction
(and then not later) and that wouldn't look immediately wrong as it
follows a common pattern. Except for the pointer-to-error type, that
is.
So all in all, I think the previous variant is significantly cleaner. :)
//jb