【问题标题】:DD/DU warnings from PMD [duplicate]来自 PMD 的 DD/DU 警告 [重复]
【发布时间】:2013-01-01 23:56:14
【问题描述】:

可能重复:
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错误?我可以忽略这些警告吗?

【问题讨论】:

    标签: java pmd dataflow


    【解决方案1】:

    您的 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
    }
    

    【讨论】:

    • 无法实现 DD 异常的第一个提案,因为 newResult 是在块中计算的。第二 - 引发另一个 PMD 规则破坏(从方法中多次退出)。 DU 提案导致代码重复。
    • 我相信你的话;这不是你问题的一部分。无论如何,这回答了您的问题:这不是 PMD 的错误。
    猜你喜欢
    • 2020-10-08
    • 2013-05-19
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 2016-05-16
    • 2011-07-28
    • 2011-12-28
    相关资源
    最近更新 更多