0

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 !

Omar Aflak
  • 2,918
  • 21
  • 39
  • 1
    It isn't but you shouldn't pass Activity context to a static method. It would result in memory leak. You can use `getApplicationContext()` – rusted brain Aug 08 '17 at 13:25
  • 1
    Using dagger with singleton scope would be better, but there is nothing wrong with your implementation. I've been using this approach in many of my apps, never had one issue. In fact the same approach is used in many google products, for example firebase asks for init with context on app startup. – Andrej Jurkin Aug 08 '17 at 13:54

0 Answers0