Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting SharedPrefs Editor in Utility Class?

Is it a good idea/practice to put static shared preferences editor in a utility class so I can call it whenever needed? The method in the utility class would look like this:

public static SharedPreferences.Editor editor (Context context){
    final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    return sharedPrefs.edit();
}

and use it like this in different classes:

Utility.editor(mContext).putBoolean(categoryId, true);
Utility.editor(mContext).apply();
like image 997
fullmoon Avatar asked Mar 01 '18 10:03

fullmoon


1 Answers

At least I would't say it's a bad idea.

But here is an even better idea: abstract away the Android specific details and create a clean, readable interface for storage access that fits your domain.

e.g:

   interface UserSettings {
      void setAutoReloadEnabled(boolean enabled);
      boolean isAutoReloadEnabled();
     ...
   }

and then implement it using SharedPreferences

 class SharedPreferencesUserSettings implements UserSettings {

   final SharedPreferences sharedPrefs;

   public SharedPreferencesUserSettings(Context ctx) {
      sharedPrefs = ...;
   }

   @Override void setAutoReloadEnabled(boolean enabled) {
        sharedPrefs.editor().putBoolean("...", enabled).commit();
   }

   ...

 }

This gives you more readable code and you can actually provide a stub/mock implementation in your tests! If the API of SharedPreferences should change (or when you want to move from using commit to apply or vice-versa, or changing the Tags you used for the preferences) you only have to change it in one File, not everywhere in your code.
But there is more: if you should later decide that SharedPreferences were actually a bad choice, you can switch the implementation to use e.g. a . SQLite Database or ObjectBox instead. Again, without changing the rest of the code.

Needless to say that this might be overkill (aka over-engineering) in certain situations, but in bigger projects this pays out pretty fast.

like image 200
Lovis Avatar answered Sep 19 '22 04:09

Lovis