LoginSignup
8
6

More than 5 years have passed since last update.

[小ネタ]Bundleに入れる時はキーにEnumを使う

Posted at

小ネタです

Androidアプリを開発しているとBundleへ値を格納する機会が頻繁にありますが
その際にキーの管理でのヒューマンエラーを減らそうという作戦です。

java
private static final String KEY_TITLE = "title";

private void hogehoge(String title){
    Bundle bundle = new Bundle();
    bundle.putString(KEY_TITLE, title);

    ...
}

上記のようにキーを定数で管理する人が多いと思いますが、キーを行のコピペで増やした時に中身を変え忘れて

java
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "title";

みたいなことになってほああああ!!!となるヒューマンエラーに襲われたので

java
private enum Key {
    TITLE,
    CONTENT,
}

private void hogehoge(String title, String content){
    Bundle bundle = new Bundle();
    bundle.putString(Key.TITLE.name(), title);
    bundle.putString(Key.CONTENT.name(), content);

    ...
}

のようにEnumを用いたほうが管理が楽でミスも減らすことが出来そうという小ネタでしたまる

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6