3

以下のint iのFindbugsでDeadStore 警告が表示されます。読みやすさのために、ワンライナーを書くことは好みません。DeadStore がiになく、読みやすいようにこれを記述するより良い方法はありますか?

   if (aqForm.getId() != null) {
        try {
            int i = Integer.parseInt(aqForm.getId());
            aqForm.setId(aqForm.getId().trim());
        } catch (NumberFormatException nfe) {
            result.rejectValue("id", "error.id", "Please enter an integer.");
            foundError = true;
        }
    }
4

2 に答える 2

5

メソッドを呼び出して結果を無視するだけです。理想的には理由を説明するコメントを付けます。

// Just validate
Integer.parseInt(aqForm.getId());

持っているバージョンではなく、検証していないバージョンをトリミングしている理由は明らかではありません。私は好むだろう:

String id = aqForm.getId();
if (id != null) {
    try {
        id = id.trim();
        // Validate the ID
        Integer.parseInt(id);
        // Store the "known good" value, post-trimming
        aqForm.setId(id);
    } catch (NumberFormatException nfe) {
        result.rejectValue("id", "error.id", "Please enter an integer.");
        foundError = true;
    }
}
于 2013-03-13T16:59:10.673 に答える
4

に割り当てる必要はありませんi。結果を呼び出しparseInt()て無視することができます:

   if (aqForm.getId() != null) {
        try {
            Integer.parseInt(aqForm.getId()); // validate by trying to parse
            aqForm.setId(aqForm.getId().trim());
        } catch (NumberFormatException nfe) {
            result.rejectValue("id", "error.id", "Please enter an integer.");
            foundError = true;
        }
    }

つまり、ヘルパー関数を作成します。

   public static boolean isValidInteger(String str) {
      ...
   }

スニペットを次のように書き換えます。

   String id = aqForm.getId();
   if (id != null) {
      if (isValidInteger(id)) {
         aqForm.setId(id.trim());
      } else {
         result.rejectValue("id", "error.id", "Please enter an integer.");
         foundError = true;
      }
   }
于 2013-03-13T16:59:23.473 に答える