What anti-patterns exist in Go? What should not be done, what is considered bad tone?
sobes.tech AI
Answer from AI
In Go, there are several common anti-patterns to avoid:
-
Global variables and state. Using global variables complicates testing and leads to concurrency issues.
-
Ignoring errors. In Go, errors are returned explicitly, and ignoring them (
_ = err) is considered bad practice as it can lead to hidden bugs. -
Functions that are too long. It's better to break logic into small functions for improved readability and maintainability.
-
Using
panicfor normal errors.panicis intended for critical errors, not for flow control. -
Incorrect use of interfaces. Interfaces should describe behavior, not data; creating an interface with a single method unnecessarily is excessive.
-
Complex nested structures and excessive use of pointers. This complicates code and can lead to errors.
-
Using
initfor complex logic.initshould only be used for simple initialization. -
Lack of comments for exported functions and types. In Go, it's customary to document exported elements.
An example of bad practice is ignoring errors:
file, _ := os.Open("file.txt") // Error is ignored
Better:
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
Following these rules helps write clean, maintainable, and reliable Go code.