Search code examples
javaoopshared-memorysolid-principles

Is there a SOLID way to use the heap in java?


So I read that static variables and methods break the open close principle.

Lets say you have a class that has a variable with a "lot of data" (10mb) that is final and shared across all instances E.G. a sprite map for an enemy in a game, lets say a zombie.

If I wasn't using SOLID I would make the variable private static so it's only stored in memory once. Having 100 zombies using 10mb of memory spent on a sprite map stored on the heap being much less than 1gb of memory if it was 1 per instance.

Question - Is there a SOLID way to use the heap to store one copy of the sprite map so it won't take up so much memory?


Solution

  • Your problem is that you cannot have the knowledge of the sprite map being shared between all instances built into your class.

    You then need to move it elsewhere. Have a sprite map factory method in another class that knows that the same reference should be returned always. (A singleton)

    You will find as you get more experience that much coding is about postponing decisions about what value should actually be used at a given location, typically because you don't know until runtime. This typically results in quite gnarly code in order to connect the inner moving parts with the outside world where the decision about what to do is.

    In my experience, the cleanest way so far to do this, is to move it out of your own code and use a Dependency Injection framework. Several exist for Java; I find the Dagger 2 approach about determining the configuration at compile time very refreshing.