PMD"发现' DD' -anomaly" vs"只有一个退货声明"

时间:2013-10-11 06:24:37

标签: java pmd

我尝试删除项目中的所有PMD警告并遇到一些困难。我有一个返回Container对象的方法。这是我原来的方法(简化):

try {
    return setResult();
} catch (Exception ex) {

}
return null;

PMD警告说有2个退货声明。所以我尝试了这个:

Container result = null;
try {
    result = setResult();
} catch (Exception ex) {

}
return result;

=> PMD警告用null初始化。所以我尝试了这个:

Container result;
try {
    result = setResult();
} catch (Exception ex) {

}
return result;

=> Eclipse没有编译它,建议使用“= null”变体。

我在这里缺少什么?如何在没有PMD警告的情况下编写此方法?

1 个答案:

答案 0 :(得分:1)

我会使用您展示的第二种方法:

Container result = null;
try {
    result = setResult();
} catch (Exception ex) {

}
return result;

因为,正如PMD指出的那样,为了降低复杂性,避免不必要的退货声明是很重要的。

PMD文档对NullAssignment rule as "controversial"进行分类。它的用处在很大程度上取决于上下文。以下是他们提供的示例代码:

public void bar() {
  Object x = null; // this is OK
  x = new Object();
   // big, complex piece of code here
  x = null; // this is not required
   // big, complex piece of code here
}

因此,除非您事先可以为Container变量赋予有意义的值,否则您应该忽略此规则片段的此规则。

如果要完全避免空分配,可以使用Guava's Optional。在这种情况下,它具有以下优点:

  1. 它强迫你考虑缺少价值
  2. 使代码更容易理解
  3. 让PMD开心