Reputation: 5845
Are there any differences between the two approaches in terms of the lifecycle of these variables?
As I understand in both cases foo gets garbage collected when the app get's cleared from the memory at the very
end. (correct? or am I missing something?)
Option 1: Storing a static variable in the Application class:
public class App extends android.app.Application {
private static SomeClass foo;
public static init setSomeObject(SomeClass someValue){
foo = someValue;
}
public static SomeClass getSomeObject(){
return foo;
}
}
Option 2: String a static variable in any static class?
public class JustSomeClass {
private static SomeClass foo;
public static init setSomeObject(SomeClass someValue){
foo = someValue;
}
public static SomeClass getSomeObject(){
return foo;
}
}
I prefer the second, purely for better readability as I don't want my Application class to grow too big, but I need to know if there are any disadvantages with that.
Upvotes: 1
Views: 1034
Reputation: 625
I agree to GhostCat and Chetan. I too feel using static must be avoided to avoid excess of memory usage.
I'd prefer making a singleton class for each process, say, to handle flow of screens in my app or to write the helper methods for database operations or few common methods used by many activities/ fragments in my app.
This link has a good discussion on Application class vs. Singleton.
Upvotes: 2
Reputation: 140427
Conceptually, static is an abnormality in good OO design. So when you ask about best practices, start by thinking up designs that do not use static in the first place.
And beyond that: your classes should resemble a helpful model of the "thing" you intend to built. You don't put "stuff here ore there"; you put it ... where it belongs to from a conceptual point.
Upvotes: 2