At GopherCon earlier this month, Dave Cheney, a well-known Go contributor and evangelist, gave a talk called “The Zen of Go,” which he later shared on his blog. He wrote a shorter version because it was too long:
- The full version: dave.cheney.net/2020/02/23/…
- Concise version: the-zen-of-go.netlify.com
Here’s a quick translation of the concise version:
Ten engineering essentials for writing simple, readable, maintainable Go code.
Each package implements a single goal
A well-designed Go package provides a single idea, along with a set of related behaviors. A good Go package starts with choosing a good name, using the elevator rule (explain a solution to a client in 30 seconds), and using just one word to think about what your package offers.
Unambiguously handling errors
A robust program is actually made up of fragments that deal with failure cases and need to be handled before a failure occurs. Redundant if err! = nil {return err} is more valuable than having to deal with failures one by one. The same goes for Panic and Recover.
Return early and don’t get bogged down
Each indentation adds another prerequisite to the programmer’s stack, which takes up 7±2 fragments of their short-term memory. Avoid control flows that require deep indentation. Rather than go deep into nesting, use a guard clause to keep the success path to the left.
Concurrency is left to the caller
Let callers choose whether to run your library or function asynchronously, don’t force them to use asynchrony.
Before you start Goroutine, know when it will stop
Goroutines have resources, locks, variables, memory, etc. A reliable way to release these resources is to stop Goroutines.
Avoid package-level states
Instead of using package variables, you accomplish explicit and reduced coupling by providing the dependencies required by a type as fields on that type.
Simplicity is important
Simplicity is not a byword for sophistication. Simple doesn’t mean rough, it means readability and maintainability. If you have a choice, follow the simpler solution.
Write tests to confirm the behavior of the package API
A package’s API is a contract with the consumer that must be tested, no matter how early or late. Testing is the guarantee of the contract. Make sure that test users can observe and rely on behavior.
If you think it’s slow, verify it by benchmarking first
Many crimes against maintainability can be committed in the name of performance. Optimization breaks abstractions and exposes internals and tight coupling. If there is a price to pay, make sure there is a good reason to do so.
Temperance is a virtue
Use Goroutine, channels, locks, interfaces, and nesting sparingly.
The article is reprinted from OSCHINA community [http://www.oschina.net]
This paper addresses: www.oschina.net/news/113606…