by matthewmacleod · 11y ago · 0 comments
On one hand, it addresses many of the pain points I've experienced with other languages. It's easy to build and deploy, reasonably performant, and has a powerful and consistent standard library.
On the other… developing in it feels like a total slog. It manages to be simultaneously far too anal and overly forgiving about syntax. Visibility definition using upper/lowercase is a shite idea. Package names (and packaging generally) are a mess. Magical built-in globals are a huge design smell. The lack of generics, as cliché a complaint as it is, results in loads of duplicated or generated code when building anything more complex than the simplest app. And so on.
I find the whole experience of using it to be unpleasant (rather like using a blunt knife), and yet it fits a set of requirements that mean I keep developing new projects using it – particularly high-performance small services that do things like fling JSON around, for which the built-in HTTP libraries + Gin are brilliant.
I'm looking forward to the point that a (trans|com)piler which smooths over the bad parts is available.
We've got a limit-order-book market with a FIX API and an HTTPS/JSON API, a bunch of market makers, an AVR emulator, a dispatcher to handle thousands of AVRs concurrently, a C compiler, HTTPS/JSON APIs to implement debug stubs for all of that, and a bunch of other random stuff --- and we have one (1) custom data structure --- the red-black tree we use for the order books themselves.
I'm a recovering C++ programmer and do not doubt for a moment that if Go had generics, I'd have availed myself of them. I'm not sure my code would be better for it, though.
I could use a lock free ring buffer in dozens of places. I could use promise/futures in dozens of places. I could use anything but the big honking lock that is channels in dozens of places.
I could use proper variance rules in the generics Go does provide in dozens of places. I could use monadic style errors and options in dozens of places.
Now, I agree that I generally don't need to write my own generic code very often, but if the blessed generic writers on the go lang compiler team don't write these things for me, I don't have a fall back option in Go (other than code gen, which people are starting to fall back on). It just seems unsustainable to me.
I don't think Go is a great language, as I'm fond of saying, I just think it's a very useful tool.
But it being a good tool should not be a deterrent from it becoming a better tool.
[edit] Edited to sound lest strident.
This all may be the ramblings of someone basing their opinions on "code I've written that has worked" and not on some higher standard of design patterns, so feel free to ignore if that's not productive :)
This ties into other thoughts I have rattling around about treating languages as specialty tools with well prescribed patterns, vs the trend to implement some subset of common lisp as the saying goes, but not well formulated enough to expound on them here. Broadly; I'm not sure which paradigm I prefer. (Having a big toolbox of specialty tools is nice, but if one tool can easily eat the functionality of another tool, I tend to side on considering that option.)
I won't harp on about generics in Go, because I think it's far from the biggest issue – but the hardcoded magic generics show that such a feature is useful. I'd love a simple set implementation, for example – but I often find myself reduced to writing dumb, ugly, difficult-to-read code to work around the fact that it's not possible.
SICP famously says "programs must be written for people to read, and only incidentally for machines to execute." And I can't help but feel, whenever I'm writing Go, that I'm spending far too much time telling the computer what to do – and nowhere near enough telling future developers what I wanted to do.
A good example is errors being values — which is a great idea. But then you realize every single function needs to be littered 1-10 cases of
if err != nil {
return nil, err
}
It's an extremely common pattern. It's tiring to write, over and over. Tiring to refactor, too: If you change a signature (to add an error, or add another return value, for example), every error check has to be updated.Unfortunately, Go doesn't offer any abstractions that might allow you to avoid such boilerplate. Functions that return errors cannot ever be chained, for example: If you have "func bar() (MyStruct, error)", you cannot do "foo(bar())". You must always assign the result to an intermediate variable. You could embed the error in the MyStruct struct instead, but that goes against Go's grain.
I find myself wishing for some magic macro that is smart enough to extract a value and return the error for me. Something like:
try! value, err := bar()
...would expand to: value, err := bar()
if err != nil {
return
}
I'm with you on upper/lower-case names. It results in schizophrenic-looking programs. Unless I'm writing a library, I tend to just export anything that isn't obviously an internal implementation detail, for consistency.I'm also up in arms about ":=" assignment behaviour. I've run into several bugs caused by shadowing inside blocks. You have to be careful when refactoring so as not to cause shadowing issues; really, editors should have their syntax highlighting set to highlight ":=" in blinking bright yellow or something. It's so hard to miss.
It's also inconsistent with how you (or, at least, I) want it to behave. It will shadow existing variables by default if there is at least one new variable on the left-hand side, but that's the least conservative behaviour, and feels contrary to Go's strictness — a language, after all, that considers unused imports to be a compilation error. Recently I've started avoiding ":=" in favour of vars, just to avoid falling into that trap by accident.
To be fair, I love many aspects of Go: Compilation speed, relative performance, ease of concurrency, static strictness. But after working with Go for a while and being quite productive with it, I'm at the same time seriously pining for a better language to replace it.
I've come to believe that slicker error handling is a bit of a false economy, at least compared to other "informal" languages like Java, Ruby, and Python (all bets are off if you want to compare Go to Haskell; I concede everything in advance there).
I feel like a lot of Java and (especially) Python/Ruby code is easier to read... until it matures enough to handle errors properly, at which point its just as crudded up. It's much easier to start sketching out code in Ruby and wrapping everything in blanket try/rescue blocks. But that code always breaks and always gets trickier before it's ready to ship.
Lots of people I've talked to have had the same experience coming off C, Ruby, and Python as I have: when the Go compiler stops spitting out errors, your program tends to work --- usually not perfectly, but still far better than a first-run Ruby or C program does!
Also, when people think about Go error handling compared to Ruby and Python, they rarely factor in the density of unit tests required for the Ruby and Python code.
Go basically tells us that errors are as really important — they should be in your face and handled by the caller. And then it goes ahead and makes it a second-class citizen that is really awfully laborious to work with. Why not make error-handling a first-class construct?
Most code needs to just pass the error on to the caller, for example. Go would benefit from an easy way to just "bounce" the error off to the caller. Something like my naive, hypothetical macro in my previous comment.
Some sum-type-based solution like Rust's Result enum would also have made the whole problem pretty much moot.
Not only that, it's very easy to just dump errors on the floor, which is why Golang needs tools like errcheck.
For an easy example of this in practice (os.Setenv returns an error): https://github.com/search?l=go&q=os.Setenv&type=Code&utf8=%E...
Good point but exceptions or explicit handling (even with sum-type like in Rust) are not the only ways. There is also the crash-and restart way, Go has some with panic, Rust, Erlang is probably king here, can do it with OS processes as well. That of course, has to be handled well by the runtime, so either no shared memory so corruption doesn't spread arbitrarily throughout the application or provable compile time checking (like Rust).
Chaining does work, but obviously the function needs the same signature as the return values, which limits things since most APIs don't accept errors as input. But within your code you can structure it to get error values for things you know you will be chaining. Or create wrappers to make your types chainable.
It can't always be done. A generic wrapper only works for functions that return values. It would be nice to have a wrapper that can take any function, e.g. foo in:
package main
import "fmt"
func foo(a ...interface{})interface{}{
if len(a) == 0 {
return nil
} else if len(a) == 1 {
return a[0]
} else {
return a
}
}
func barbar() (a, b int) { return 1, 2 }
func bar() (a int) { return 1 }
func baz() { return }
func main() {
fmt.Println( foo(barbar()) ) // prints: [1, 2]
fmt.Println( foo(bar()) ) // prints: 1
fmt.Println( foo(baz()) ) // compile error: baz() used as value
}
Instead of the compile error, it would be nice if foo accepted baz() as a argument, which would read the array length as 0 and here return nil.Still, having to let every function take an error parameter isn't really an option, generally.
I'm usually stuck using:
reply, err := redis.Givemethevalue(key)
if err != nil {
return err
}
thing, err2 := postgres.getById(reply)
if err2 != nil {
return err2
} reply, err := redis.Givemethevalue(key)
if err != nil {
return err
}
thing, err := postgres.getById(reply)
if err != nil {
return err
}
Go allows you to assign with := if at least one of the left-hand-side variables is new. struct fooer {
x int
blah string
// ... more state
err error
}
func Foo(x int) (string, error) {
f := &fooer{x: x};
defer f.cleanup()
f.stepOne()
f.stepTwo()
f.stepThree()
return f.blah, f.err
}
func (f *fooer) stepOne() {
// ... do stuff and maybe set f.err
}
func (f *fooer) stepTwo() {
if f.err != nil {
return
}
// ... do stuff and maybe set f.err
}
func (f *fooer) stepThree() {
if f.err != nil {
return
}
// ... do stuff and maybe set f.err; set f.blah
}
func (f *fooer) cleanup() {
// ...
}
While this is initially a tad more verbose, it has some nice benefits. For one thing, you can easily fmt.Printf("%#v", f) to dump all the relevant state. However, it also tends to be more resilient to refactoring:- No method signatures to patch up.
- Easier to non-local jump via return if you have some unusual control flow, etc.
- You can easily find all references to `f.err` to verify your error handling.
- The method names and step list take on a self-documenting quality.
Another key insight I had when learning to tolerate Go: It's ok to do throw away work. You don't need to abort instantly on failure, you can just make sure code paths handle zero values or other invalid states more robustly. For example, I sometimes add a function like:
func (f *fooer) fail(err error) {
if f.err == nil {
f.err = err
}
}
And then just add sprinkle some f.fail() calls, make code handle nils, invalid states, etc, and make cleanup code idempotent. Seems to work out much more nicely than if err, return. var err error
at the beginning of the function if needed.BTW, if you really want to make sure you don't make mistakes, use the compiler tools, or, better yet, https://github.com/alecthomas/gometalinter .
In Pascal you would use := every time you wanted to assign a variable, and a single equals when testing, such as "if (x = 5) then...". It is slightly more like math than most languages, which I appreciated. But, golang only allows it on the first assignment, the reasoning perhaps that it is a declaration?
I don't feel that this third way of doing it with no advantage was a benefit, choosing one C of Pascal rules would have been better and less to think about.
value, err := bar(); err {
// there was an error
}
I like how that looks, personally. Obviously YMMV. if value, err := bar(); err != nil {
return err
}
Note that this syntax declares "value" in the "if" scope. You can only access it inside the "then" block or in an "else" block: if value, err := bar(); err != nil {
return err
} else {
log.Print(value) // this compiles
}
log.Print(value) // does not compile
So if you need it later, you have to do: var value MyType
var err error
if value, err = bar(); err != nil {
return err
}
Note that you cannot do this: var value MyType
if value, err := bar(); err != nil {
return err
}
This would, again, declare a new "value" that shadows the outer "value" inside the "if" scope. (Go would fail to compile it since it doesn't allow unused variables.)func checkErrPanic(err error) { if err != nil { panic(err) } }
func checkErrNonFatal(err error) { if err != nil { fmt.Println(err) return } }
:/ Their json system reflects and allocates like a mad-man. It's probably one of the slowest parts of the std library.
Java can be terribly verbose at times and the culture often makes it worse, but it often doesn't feel like a slog in practice because errors are reported as you type, with quick fixes. Editor plugins for Go will tell you some of the errors, some of the time.
The slog seems to be in the frequent feeling of 'why do I have to do this – surely the computer should be doing it for me?'. This is mostly around things like list comprehension, where it feels like using stone-age tools. It sucks, because the development story around e.g. goroutines and channels is so elegant in comparison.
A diagnostic indicator is whether you gravitate towards things like Martini or Gin, which aren't idiomatic Go and seem designed to ease the pain of using Go for those who don't actually care for it much.
I have enjoyed the gin API. In maybe 10 lines of code, I can build a fast HTTP service that can serve up a small single-page app. The same thing using e.g. Negroni feels like I'm writing more boilerplate for no apparent gain – and I'm a great opponent of writing boilerplate code.
I love martini (and lately gin) and definitely love and use go every day. What about these frameworks is not idiomatic go?
Is there another framework that is? Or you suggest just rolling your own using net/http by itself?
Cheers
tl;dr - Martini doesn't have a strict, type-safe API. Overuse of reflection leads to a small performance loss but a much larger, much more important cognitive tax.
"Slow" in the case of a router/mux is entirely relative though. There's been this strange focus on routing speed/allocations, when its the smallest slice of your total request-to-response performance. Martini's router won't make your application noticeably slower than any other.