Using The Static Keyword To Preserve The State Of A Tic-tac-toe Board In Android
Solution 1:
is there something wrong with using this method?
First, generally speaking, static
data members should be used carefully, as they represent intentional memory leaks. Whatever is in this TicTacToe
object cannot be garbage collected, and anything that can be indirectly reached by this TicTacToe
object cannot be garbage collected. In classic Java development, static
data members are considered to be poor form as a result. In Android, they tend to be used somewhat more, but ideally only by experienced developers.
Related to this is choosing the right tool for the job. We could cure cancer by beheading the patient, as the tumor will stop growing. However, this epitomizes "the cure is worse than the disease". In this case, there are better solutions for specific problems, such as handling configuration changes (e.g., screen rotations) that should be considered in lieu of static
data members.
Second, static
data members do not live forever. They go away when your process does. Your process can go away at any point once you are no longer in the foreground, and when your process is terminated, your TicTacToe
object goes poof. And, since your process can be terminated within seconds of moving into the background (depending on what else is going on with the device), your data model is at risk.
This gets back to user expectations.
If the user would expect that the "Continue" option should be available at any point, then while you could use TicTacToe
as some sort of in-process cache, the real data model needs to be a persistent data store: SharedPreferences
, database, or an arbitrary file.
On the far other end of the spectrum, if you don't care that the user's game may be lost when, say, they take a phone call and you move into the background, then saying that your data model is purely in memory is certainly an option.
And there are "middle ground" approaches (e.g., saved instance state) as well.
The solutions from your other question that focus on startActivityForResult()
are inappropriate IMHO.
Solution 2:
Static data is not persistent, and will be cleared as soon as the class is unloaded (at some point after your app is in the background and Android kills the process to reclaim memory).
Static data is not a place to store persistent data -- you should use either SharedPreferences (easiest route) or a SQLite database (more difficult but probably best route, long-term), or even just serializing your state to a file somewhere.
Post a Comment for "Using The Static Keyword To Preserve The State Of A Tic-tac-toe Board In Android"