为什么我会收到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的错误,我可以忽略这些警告?
答案 0 :(得分:3)
您的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
}