avoid-global-state-and-init
Installation
SKILL.md
Summary
Avoid using package-level variables (Globals) for application state (like Database connections, Configs, Loggers) and avoid init() functions for side-effects. Instead, use Dependency Injection: pass dependencies explicitly to your structs or functions (controllers/handlers).
Rationale
- Traceability: It is clear what a component depends on by looking at its constructor or fields.
- Testability: Globals make parallel testing impossible (race conditions) and mocking difficult. You cannot run two tests with different configurations if they share a global config variable.
- Order of Initialization:
init()execution order can be subtle and hard to debug. Explicit wiring (main.go) is predictable.
Guidance
- No
var db *sql.DBat package level. - No
func init() { config.Load() }. - Pattern:
- Define a struct that holds dependencies.
- Create a "Constructor" (Factory) function.
- Wire everything in
main.go.