Possible Duplicate:
What is the reason for these PMD rules?
为什么会收到DD / DU警告?
这是我的代码:
// DD warning from PMD
public Object foo() {
Object result = null;
if (condition) {
// code block, no accec to result
result = newResult;
}
return result;
}
// DU warning from PMD
List<Object> data = new ArrayList<Object>(anotherList);
anotherList.remove(1);
// some other modification of anotherList
if (condition) {
// some code. no access to data
for (Object o : data) {
// loop for original content of the list
}
}
我可能在这里出问题了吗?还是PMD的错误,我可以忽略这些警告?
最佳答案
实际上,您的DD异常可以写得更好,而出现错误的机会更少:
return condition? newResult : null;
或者,如果您对语法比较保守,
if (condition)
return newResult;
return null;
在第二个示例中,将无条件创建
data
,但仅有条件地使用它。改写为if (condition) {
List<Object> data = new ArrayList<>(anotherList);
// or maybe just use anotherList without copying
...
}
else {
anotherList.remove(1);
// some other modifications of anotherList
}