r/ProgrammerTIL • u/englishm_ • Jan 05 '19
Other Language [Go] TIL a new Go proverb: "The happy path is left-aligned"
Today, while working through some exercises on exercism.io, a mentor shared with me a really great "Go proverb":
"The happy path is left-aligned"
I had never heard it phrased that way before, but it seems like a great guide for untangling badly nested conditionals that obscure the overall intent of a piece of code.
This post from /u/matryer has a lot more about how this makes for good "line of sight" in Go code: Code: Align the happy path to the left edge
56
Upvotes
18
u/[deleted] Jan 05 '19
This is pretty common, not only for go. I think of it as a common-sense thing since not doing it makes the code wander away towards the right margin.
The result when people don't take this to heart can be proper scary. I once had to refactor a go function with I think seven different error checks, all on the form
if err == nil{ do stuff }. The nesting still haunts me.6
u/atimholt Jan 06 '19 edited Jan 06 '19
Go proverbs?
(Seriously, I thought this was posted in r/baduk for a sec. I was confused because chirality in a symmetrical game is impossible.)
4
u/manthinking Jan 05 '19
nesting is a pretty good rule of thumb for complexity / code smells in general. I don't know how many times I've seen smoke just by scanning the amount of nesting in a PR.
I have a preference for early returns over an else clause in most scenarios in every language where that's a thing. I would say that golang's reliance on the "for" construct over higher-order functions for iteration make it especially vulnerable to wild nesting from cowboy coders, so it's good to emphasize best practices.
2
u/Blando-Cartesian Jan 16 '19
Good ideas get rediscovered over and over again.
There's an 80's Soviet program diagram called DRAKON that has the same idea in its heart. Happy path is down. Each step to the right means things are going more and more wrong.
0
u/[deleted] Jan 05 '19
[deleted] ā view deleted comment