How to avoid Global State with a world map?

by Aze   Last Updated May 17, 2018 21:05 PM - source

This is a conceptual problem I'm having general difficulty with, and I'd like to look at an example that can hopefully help clarify this: using a map to represent an alterable game world. For simplicity, this map can just be a two dimensional array of ints. I'm approaching this from C# within Unity, if that changes anything.

Global State being bad, or at least far from ideal, is addressed here: Why is Global State so Evil? I conceptually understand these issues it poses, but I do not see how the proposed alternatives actually solve this. The largest issue seems to be mutability, and changes creating instability in the code.

Looking at my map example, there are a number of systems that might need to access the map: rendering needs to look at the data and determine what sprites to draw, input needs to check the data to determine if certain inputs are valid, the data of the map may need to be changed if a tile is destroyed or built upon, etc. My most instinctual approach is to create the map as a singleton that can then be easily referenced from wherever it's needed. This, however, obviously creates Global State and thus becomes a problem.

Dependency injection seems to be the most commonly referenced way of preventing global state, but I do not see how this reduces or eliminates Global State. From my understanding, instead of getting a reference to my map by creating a singleton, I instead pass in the reference through the constructors. This seems functionally identical to me - in both cases, everything ends up with a reference to the same Global State, except DI has what seems to be a downside because it requires extra passing of parameters.

Is DI supposed to use only copied state? In which case are there not relatively significant performance/memory impacts in the duplication of so much data? Obviously since I'm learning, I can probably ignore performance unless it really becomes an issue, but this just seems incredibly clunky and inefficient to me.

So, what am I missing about DI that makes it a viable solution to this problem? What alternative solutions exist that actually address this problem?

Related Questions

Why is Global State so Evil?

Updated May 24, 2016 09:02 AM

How are globals any different from a database?

Updated May 25, 2016 08:02 AM

Is global state evil if it doesn't change behavior?

Updated March 13, 2017 02:05 AM