3

I am getting a DeadStore warning with Findbugs on int i below. I prefer not to write one-liners due to readability. Is there a better way to write this so that there is not DeadStore to i, but as readable?

   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 call the method and ignore the result, ideally with a comment to explain why:

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

It's not clear why you're trimming the version you haven't validated rather than the version you have, mind you. I'd prefer:

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

You don't have to assign to i. You could just call parseInt() and ignore the result:

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

That said, I would create a helper function:

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

and rewrite your snippet like so:

   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 回答