Image generated with AI
I get wary whenever I see a Go package using an init function. Init functions can be helpful in certain situations, but most people misuse them.
In Go, the function init() is executed as part of package initialization right after variables are initialized and values are set.
This process happens if a package is imported regardless of what within the package is used.
I often see logic within the init functions that should never be there.
Creating instances of a struct
Populating data within a struct
Initialization of other dependencies
The problem is testing.
Testing the happy path might be easy enough, but what about error scenarios?
If you add logic within the init functions that could behave differently under different conditions, it becomes challenging to duplicate these scenarios.
Remember, the key to building reliable software is to write tests that run the same functions repeatedly with different inputs to validate different outcomes. It isn’t easy to do that with init functions, so people don’t write those tests.
Overusing the init function ultimately makes code harder to test and maintain and unreliable.
My recommendation is to avoid the init function altogether. Usually, using a constructor like a New() function is the way to go.
The above is the detailed content of Avoid the Go init function. For more information, please follow other related articles on the PHP Chinese website!