5 ms·
As a heavy daytime user of Go, I kind of get what you're getting at. You gave as examples two of the most typical cases of Go boilerplatitis: Error handling and
by unscaled 9y ago
As a heavy daytime user of Go, I kind of get what you're getting at. You gave as examples two of the most typical cases of Go boilerplatitis: Error handling and for loops. Of that, error handling definitely gets refactored to set states, wrap errors, do cleanup (though less often, since go has defer) etc.
I find myself refactoring Go code a lot in patterns just like you describe (internal functions for error handling), but for me it feels like a throwback to my imperative programming era of the 90s, using Pascal and C. I'm still old enough that it automatically clicks in my mind as clean code, but I also know it's hopelessly verbose.
Error handling doesn't have to be this verbose. In other static languages that eschew exceptions you could do something like this to achieve the same result:
let result = try!(DoSomething());
This form is clearly more readable once you understand what try! does (which doesn't have a steeper learning curve than the weird if syntax in Go).
Now, can you refactor it without throwing away all that nice terseness? Sure. Let's say we need to wrap the error value:
let result = try!(DoSomething().map_err(|e| MyError.wrap(e)));
It takes time to get used to, but you state what you're doing instead of how you're doing it.
Go's verbosity is even more cringing with the loops, and this is actually a place where I rarely need any refactoring in my experience. Is your experience any different? Can you give an example of you ended up refactoring loops?