Summary “Recipes for reducing cognitive load” FOSDEM 04.02.2023 by Federico Paolinelli
Based on experience of reviewing PRs in metallb project.
The less cognitive load, the less you spend energy.
The simpler is solution, the less is load.
Line of sight
One line of happy path and next ident for exceptions. “Align to the left”
There are different ways to achieve this. Like return earlier, wrap to functions, etc.
https://medium.com/@matryer/line-of-sight-in-code-186dd7cdea88
Package size and name
Utils.copyNode is not that good as Node.copy
Package names — The Go Programming Language
Errors handling
Working with Errors in Go 1.13 — The Go Programming Language
Pure functions
- Easier to test
- No side effects
Environment variables
It’s very easy to use in modern containers world environment variables.
But it’s hard to track all the parameters read during execution.
That’s why env variables should be read once in the main and propagated to other parts.
Booleans
When functions uses multiple booleans as an input, you might end up in a call like dosmth(true, false, true, true). It’s impossible to understand what is what without function definition.
Use constant or structure to pass it to the function for clear understanding of parameters.
Function overload
No support in Golang. But functional options come to the rescue.
Methods should be functions if possible
Easier to test, easier to understand, easier to write and reuse.
Pointers
If functions don’t change object, pass it as value, otherwise pointer.
It’s could be more expensive to copy, but it will make code easier and less prone to unclear behavior.
Structure
Code should be read as newspaper.
- split package to file
- Put definitions on top of file
https://github.com/golang/go/wiki/CodeReviewComments
Asynchronous functions
Move business logic to synchronous functions and then call them in goroutines.
It’s easier to test synchronous functions.
Functions that lie
If function says for example, clearnode(), but then it don’t clean it in some cases, it will mislead others.
Conclusion
Pareto principle. Around 80% of outcome is achieved by 20% of efforts.
Simplicity is complicated, but clarity worth it.
Link to the talk where slides and video will be added later https://fosdem.org/2023/schedule/event/goreducecognitive/