Open plastikfan opened 2 years ago
It is not practical to entirely remove all package scope varaibles. We can use const variables to minimise the potential of harm in multi-threaded context. The rationale for wanting to eliminate package globals is the problem of concurrent access to shared state. If this state is private and created as const, then this is ok. The user should be wary of creating non const state that can be modified by the client. If you do want package state, try to restrict this to read only entities and provide public getter method.
If a public var is used, it should not be the default behaviour to expose it as it implementation type. You want to minimise the exposed surface by the use of an interface, eg it would better to expose an variable as io.Reader instead of its implementation type.
Actually, exposing a getting function for an interal var is not good afterall, see Functional options for friendly APIs, for an alternative.
Inspiration for this issue came from these youtube videos:
GopherCon 2018: Kat Zien - How Do You Structure Your Go Apps
dotGo 2019 - Kat Zień - Achieving maintainability with hexagonal architecture
go-without-package-scoped-variables
[ ] minimine or remove global state
[ ] minimine or remove use of the init() function and replace with a client invocable bootstrap function
[ ] library code tends to go under a directory named pkg. Therefore, we should rename our lib directory to pkg and leave it as that (remember to update the readme)
You might also need to look at go-build-tmeplatate for more refactoring ideas and also using-domain-driven-design-ddd-in-golang
Also see: go-without-package-scoped-variables