Class as container of static variables

I'm doing a app in android with Rest and observer design pattern, when I do a Rest request I cache the response but some of this response object I want to let the objects in memory permanently until the application is destroyed.

So I have been thinking in create a class with just public static variables (some projects use this kind of class to declare constants Strings) to set them and then I could use it in memory. Something like this:

public class Memory {

    public static HashMap<String, PersonDto> people;
    // This object could have another complex object as ArrayList or HashMap...
    public static LocationsDto locations;
    ...
}

All I want to know if this could be a bad practice to do what I am trying to solve.

Upvotes: 0

Views: 1245

Answers (2)

valentyn.vak
valentyn.vak

Reputation: 31

While its not definitively a bad practice, it is usually considered as a design flaw to have global mutable state. You can find a lot of information about why it is so. To me the most important disadvantages are problems with testability and unpredictable program state. If you are still going to use it, you would also want to synchronise access to the static fields.

Upvotes: 1

Sel&#231;uk Cihan
Sel&#231;uk Cihan

Reputation: 2034

It depends on the usage of these objects. The most important aspect being: is there a possibility of concurrent modification/access? If so, then you should implement some kind of synchronization.

If these objects are guaranteed to be constructed before any access to them and they will not change their state afterwards, then your approach would be fine in terms of synchronization issues.

For instance, if your Dto objects are immutable and the hashmap will not be modified concurrently, than you are safe. If the hashmap needs to support concurrent access/modification, then take a look at the ConcurrentHashMap.

Upvotes: 1

Related Questions