FindBugs死店警告 - 我应该重组代码还是忽略警告

时间:2013-03-13 16:57:06

标签: java findbugs

我在下面的 int i 上收到了 Findbugs 的DeadStore警告。由于可读性,我不想写单行。有没有更好的方法来写这个,以便没有DeadStore到,但是可读?

   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;
        }
    }

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:3)

您无需分配到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;
      }
   }