Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I agree. I’ve seen more prominent figures argue against global state often. Using global state is certainly not idiomatic Go.


> Using global state is certainly not idiomatic Go.

Unfortunately it's not this simple (and probably multi-idiomatic).

Go definitely adopts more global state than other languages; I don't know any other language that offers a default-global HTTP client and server. Now, part of that is because Go's stdlib goes out of its way to make these appear stateless even though they are not - and this is good, even if you (often rightly) don't use the default ones.

But I think a lot of people saw those carefully engineered APIs and instead ran with "globals are OK in Go!" Lots of packages have global-level configuration properties - some of this is a hacky replacement for DI e.g. most logger injection. Well, OK, I can support/tolerate some of that because DI in these cases is usually a hacky replacement for real AOP language support. But some of it just shouldn't be global. e.g. Gin debug vs. release vs. test mode should be a setting on the Engine.

And then you get into really bad stuff - I don't know why but it is common to to have a global sql.DB, or sarama.AsyncProducer, or whatnot. A lot of novice Go developers - anecodotally predominately skewed towards previous PHP users, I think because they are not used to have really global variables - use a global for anything concurrency-safe. And this has ended up in a lot of low-quality tutorials/examples/SO questions so I don't see it going away any time soon.


In recent history I have worked a lot with Golang and also encountered the tendency towards globals being the recommended path.

Specifically, I encountered it with logging, frameworks( Gin ), and DBs. It is interesting to me that you called out these three things specifically having encountered them all myself.

I agree also that it is a result of having poor DI support from the language.

I also like your point about PHP users using Golang. The approach Golang uses towards serving web content is very similar to me to how initial PHP frameworks did it.

Go tends to make it easy to setup concurrent things occurring, and so I've found myself spending a fair amount of time speculating on what is thread safe and what isn't.

No matter how much I see it I still do a double take when I see globals in Go modules. Seems like a bad practice to me.


> globals in Go modules. Seems like a bad practice to me.

It is, and good packages don't have them.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: