Simple question. Reviewing my code, I’ve noticed that I’ve got a lot of variables declared multiple times in my classes or methods…for example:
public Long dbInsertCheckin(final String Class) {
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
...
}
And
public class SmashDataSource {
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
final SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
...
}
this got me thinking that instead of declaring “dateformat”, “sdf”, or “timeformat” or others i use in multiple places, would it not make more sense for me to declare these globally in my application class, then refer to them wherever I wanted like
public class MyApp extends Application {
public final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public final SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
public final SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
and refer to them later in other classes as such:
MyApp.dateformat
Myapp.sdf
Would this be better from a performance/memory usage point of view? Is there any reason not to do this? To me, it would seem that having declared them multiple times would consume more memory, vs. a final declaration once…. but I don’t know how the compiler does it’s optimizations.
There is nothing wrong with using global variables. Generally they are avoided to keep things flexible and encapsulated. But some design patterns like the Factory Pattern go well with static/global classes. It also avoids code duplication.
(However I might avoid using my
Applicationclass so my global fields are only used when needed, but that’s an implementation detail.)I would do something like this probably. It keeps things flexible while also putting things in one place so they are consistent across your app.
Then you can use this in other classes:
====
Here’s some info from the dev docs about it:
http://developer.android.com/guide/faq/framework.html#3