KeyValueX: Eliminate boilerplate code and make Android projects no longer KV explosion

background

From a late night monologue:

It is common to define dozens or hundreds of Key Values. Is there an easier way?

This is one of the few uncontrolled places in the project, with exponential expansion, and it is easy to bury hidden dangers of consistency.

Every time a new value is added, it is necessary to take into account key, get, put, init, 5 places...

public class Configs {
  
  ...
    
  private static int TEST_ID;
  
  public final static String KEY_TEST_ID = "KEY_TEST_ID";
  
  public static void setTestId(int id) {
    TEST_ID = id;
    SPUtils.getInstance().put(KEY_TEST_ID, id);
  }
  
  public static int getTestId() {
    if (IS_XXXX()) return TEST_ID;
    return UUID.ramdom().toString();
  }
  
  public static void initConfigs() {
    TEST_ID = SPUtils.getInstance().getInt(KEY_TEST_ID, 0);
  }
}

Afterwards, I received improvement suggestions one after another. Some friends mentioned "attribute agent" and recommended the DylanCai open source library MMKV-KTX .

At the same time, inspired by the "attribute proxy", I came up with a design that reduces the key, value, get, put, and init to a single design in Java.

implementation 'com.kunminx.arch:key-value:1.2.0-beta'

Use a 3-step song:

1. If you read and write POJOs, you need to implement the Serializable interface

public class User implements Serializable {
  public String title;
  public String content;
}

2. As usual, create project configuration management classes like Configs

//Configs 中不再定义一堆 KEY、VALUE 常量和 get、put、init 静态方法,
//只需一条条 KeyValue 静态变量:
​
public class Configs {
  public final static KeyValueString accountId = new KeyValueString("accountId");
  public final static KeyValueSerializable<User> user = new KeyValueSerializable<>("user");
}

3. Read and write KeyValue through the get( ) set( ) method on the page, etc.

public class MainActivity extends AppCompatActivity {
  ...
          
  //测试持久化写入
  Configs.user.set(u);
​
  //测试读取
  Log.d("---title", Configs.user.get().title);
  Log.d("---content", Configs.user.get().content);
}

KeyValueX uses SharedPreference to read and write by default, and can also inject MMKV and other implementations according to KeyValueTool (see the MainActivity example for details).

At present, the library is open source, and feedback is welcome:

Github:KeyValueX

Guess you like

Origin juejin.im/post/7121955840319291428