DI to Global Variables
Avoid Mutable Globals
Avoid mutating global variables, instead opting for dependency injection. This applies to function pointers as well as other kinds of values.
// BAD
// sign.go
var _timeNow = time.Now
func sign(msg string) string {
now := _timeNow()
return signWithTime(msg, now)
}// GOOD
// sign.go
type signer struct {
now func() time.Time
}
func newSigner() *signer {
return &signer{
now: time.Now,
}
}
func (s *signer) Sign(msg string) string {
now := s.now()
return signWithTime(msg, now)
}
Last updated
Was this helpful?