When to use global state?


Usually, people struggle to learn design pattern,  but strangely enough, nobody has any problem implementing a singleton. For beginning developers it’s a natural process: if you need an instance of a class, make it static, if you need to access a variable, make it public then static. Obviously this is the recipe for disaster causing spaghetti code / unmanageable mess. So, when to use global state?

If you are living in the 60’s and you don’t know better, then I guess it’s OK. Also, if you want to piss of your colleagues or you are a masochist I think you should do it. Some might say that singletons are OK, if you don’t abuse them. I think that at the moment you write the static member declaration you’re already abusing them.  Offended yet that I bashed your precious singletons? Good! If you are a singleton lover I probably want to offend you.

Now, let’s get serious, most people, and especially library developers, should never use global state but, there are some good exceptions for this rule. Obviously global state is not useless and there is a reason you have it in all major languages. For example, a logger is usually implemented using the singleton pattern. Also if you work at OS level writing drivers, socket programming using WinAPI, threading libraries etc… , you will need some kind of global state, and this is fine. I remember that long time ago I implemented the mother of all singletons! A shared memory location between multiple processes. I can’t remember exactly why I did that, but I remember that it was actually needed and I had no better option at the moment. Sometimes you need it, sometimes it just make sense to have it in your app, but most of the time you shouldn’t rely on global state. By most of the time, I mean if you are not working on something “exotic” then don’t use global state!

P.S. Global state that never changes such as constant declarations are fine. If your application’s behavior can be altered by some random global variable during run-time, that’s bad!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s