Putting the SharedPrefs Editor Into the Utility Class?

Is it a good idea / practice to put the static general settings editor in the utility class so that I can call it when necessary? The method in the utility class will look like this:

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

and use it in different classes:

Utility.editor(mContext).putBoolean(categoryId, true);
Utility.editor(mContext).apply();
+4
source share
2 answers

At least I would say that this is a bad idea.

But here's an even better idea: distract the specific details of Android and create a clean, readable interface to access the repository that matches your domain .

eg:

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

and then execute it with SharedPreferences

 class SharedPreferencesUserSettings implements UserSettings {

   final SharedPreferences sharedPrefs;

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

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

   ...

 }

, / ! API SharedPreferences ( commit apply , , ), , .
: , SharedPreferences , , . a. SQLite Database ObjectBox. , .

, ( , ), .

+1

, . .
, , , , . , .

0

Source: https://habr.com/ru/post/1694286/


All Articles