[英]FindBugs Dead Store Warning - Should I restructure code or Ignore Warning
我在下面的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;
}
}
只需调用方法并忽略结果,理想情况下使用注释来解释原因:
// 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;
}
}
你不必分配给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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.