Ok, so I’ll try to make that question a little more simple.
The core of this question is more about when to use static methods but after going through the bullet point theoretical concepts of what are static methods Vs Instance methods I would like a more practical/implementation suggestion using a real world problem as mentioned below.
- I have an andoid class(MyPreferences) that deals with setting and getting shared preferences.
- I have a custom listener registered in the constructor of MyPreferences that displays what preference changed everytime they change.
- The contructor also has the common stuff :
settings = ctx.getSharedPreferences(MyConfig.NAME_SHARED_PREFERENCES, 0);
editor = settings.edit();
settings.registerOnSharedPreferenceChangeListener(listener);
Now as I mentioned earlier, MyPreference has 10 functions which get/update the shared preferences keys…
public static void setPrefsIsAppEnabled(Boolean boolValue) {
editor.putBoolean(MyConfig.PREFS_IS_APP_ENABLED, boolValue);
editor.commit();
}
public static boolean getPrefsIsAppEnabled()
{
return settings.getBoolean(MyConfig.PREFS_IS_APP_ENABLED, false);
}
Now I am using these getters and setters from other classes in my project using static way(i.e MyPreferences.getPrefsIsAppEnabled()
Well, this obviously will throw an error because the constructor is not called which has the initialization of the shared preference objects.
My question : would it be a better logic to make all these 10 methods non static and instantiate MyPreference all over my project before accessing the getter and setter methods or should I move the code present in the constructor into all the setter/getter functions and repeat it everywhere its required before calling the methods of MyPreferences class. Please help me understand more clearly by stating why you are suggesting that solution.
I know its a very n00b question. Please forgive me for that. I am very new to Java so just building my concepts.
Your methods are clearly stateful (as they require access to the editor field) so it isn’t a good idea to implement them as static methods. Instead, you should use a class instance. (static methods are usually utility functions that are stateless, i.e. their outcome is always the same when the input is the same).
You can instantiate a new object every time or implement the Singleton pattern. A Singleton class can only be instantiated once. A static method (getInstance) is provided in order to get access to it.