There are many questions and answers on how to implement a global variable in Android/Java.
So it seems one can either implement a singleton or use a data class itself with static variables.
I am about to start a larger project and would like to start on the right foot.
I am just not sure which one to use.
Pro singleton/con Data Class
- supposedly "cleaner" way (but I really don't know why)
- ensures that there is really always just one representation
- creates a new instance should the old one be "cleaned away" (whenever this may happen?)
Con singleton/pro Data Class
- not recommendet by some (but did not find convincng reasons)
- ensures that there is only one representation by design
- very easy to access just by writing MyDataClass.x (vs accessing singleton requires getting access to it first somehow)
- no need to pass it as a parameter
So in summary I tend to use DataClass but I am unsure because I read that this is supposedly not good programming style.
I like to add
- the data this global object has to hold is quite big, more than 30k strings/keys. And this should not be cleaned at any stage so that when the app return it may crash because of that - as I read in other places eg Singletons vs. Application Context in Android? (the 3rd answer)
- it's not a web application, I use only one classloader
- it is multithread but only one thread is actually accessing this data
- one may certainly also use this approach How to declare global variables in Android?, but isn't an ObjectClass just easier to use and access in this case?
- And checking this http://developer.android.com/resources/faq/framework.html, esp under "Persistent Objects", implies that there is no real advantage for on or the other in those cases anyway.
Many thanks