Lets say I write a small wrapper for Android SharedPreferences
:
public class ObjectSaver {
private SharedPreferences sharedPreferences;
private Gson gson;
public ObjectSaver(Context context){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
gson = new Gson();
}
public void put(String key, Object o){
sharedPreferences.edit()
.putString(key, gson.toJson(o))
.apply();
}
public <T> T get(String key, Class<T> type){
return gson.fromJson(sharedPreferences.getString(key, null), type);
}
}
I would use it like this :
ObjectSaver saver = new ObjectSaver(this);
saver.put("user", new User("Me"));
User me = saver.get("user", User.class);
Which is not bad, but I would need to initialize the class every time. (I know I can use Dagger but anyway)
To overcome this problem, I could set every method to be static :
public class ObjectSaver {
private static SharedPreferences sharedPreferences;
private static Gson gson;
public static void init(Context context) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
gson = new Gson();
}
public static void put(String key, Object o){
sharedPreferences.edit()
.putString(key, gson.toJson(o))
.apply();
}
public static <T> T get(String key, Class<T> type){
return gson.fromJson(sharedPreferences.getString(key, null), type);
}
}
In that case I can initialize only one time :
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ObjectSaver.init(this);
}
}
And then use it everywhere else like this :
ObjectSaver.put("user", new User("Me"));
User me = ObjectSaver.get("user", User.class);
This option seems actually pretty clean to me. My question is : is it a bad practice ? And Why ? (cause' I don't see this very often)
Thanks !