Search code examples
databasedecouplingglobal-state

Why isn't a database considered a form of global state?


I have a general gut feeling about the difference but I'm unable to pinpoint exactly what makes a database different from global state.

With a naive definition of "global state", a database is generally at least application-global. You could conceivably have an app that changes databases mid-execution, but in the general case it is used globally.

As for state, I don't think I need to argue the case that a database contains state.

So what makes a database different from the "bad" kind of global state?

This question came up because I'm trying to avoid tight-coupling where an object needs to know about its parent.

For example, say you're playing a strategy game, and one of your units have an ability that says when it deals damage to an enemy unit, that unit's owner loses x gold where x is the amount of damage dealt.

Well, under normal circumstances, a unit shouldn't have to know who it's owner is. The owner is the one controlling the unit, so the owner just issues commands to the unit and it does its thing.

However because of external factors, there becomes a need to find out who the owner of a unit is. In this case, the attacking unit knows the unit it is attacking, that's fine. But now in addition to knowing the unit it's attacking it must further know it's owner in order to cause the owner to lose 5 gold.

I've already diverged more from the original question than I intended, but if the state of the game was stored in a relational database it would be trivial to query for the owner of the target without units needing to know directly who their owner was. If such a database were an object, I would call that database a god-object in the sense that it knows the entire state of everything, and additionally is mutable.

What then makes a database different from global state?


Solution

  • You could equally ask, "Why isn't an operating system considered a form of global state?" I guess depending on how you want to look at it, it is. But who cares? It's not the kind of global state that causes so many problems, namely global variables in library code. Both databases and operating systems are enabling technologies for a huge variety of programs--they've proven their worth. This is not to say either is without its problems: databases can make unit testing more difficult (hint: try mocks), and the wide variety of operating systems can make it difficult to make a program that everyone can use equally well.

    Another way to look at it: there are valid alternatives to global state in most code, whereas the alternative to using a database would often be to effectively implement a database in your own code (whether you call it a database or not).