[go: up one dir, main page]

Skip to content

Consider removing `init` functions where possible

I would like to know people's opinion on using Go's init inbuilt function. I personally think that it's usually not a necessary step when importing/using a package. A package's functionality should be explicit when instantiating a struct typically when calling NewSomePakcage(explicitParams ...interface{}) (*SomePackage, error)

There's some resources out there in favour of not using init and even a linter gochecknoinits here

Init functions cause an import to have side effects, and side effects are hard to test, reduce readability and increase the complexity of code.

This article A theory of modern Go gives a great example of this.

Although there's some cases where init can help, there are some instances where it's not clear what/when something runs e.g. in internal/source/domains.go where gitlabsourceconfig.WatchForGitlabSourceConfigChange is called in a Go routine inside an init function in the source package. So we are initialising a different package gitlabsourceconfig as part of the source package 🤯