我收到了一个DeadStore警告,下面是Findbug on int i。由于可读性,我不喜欢写一行.是否有更好的方法来编写这个,这样就不会有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;
}
}发布于 2013-03-13 16:59:23
您不必分配给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-13 16:59:10
只需调用该方法并忽略结果,最好用注释来解释原因:
// 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;
}
}https://stackoverflow.com/questions/15391654
复制相似问题