【问题标题】:PMD rules: How to properly solve this DD-anomaly issuePMD 规则:如何正确解决这个 DD 异常问题
【发布时间】:2012-12-29 17:43:08
【问题描述】:

我有以下 Android 代码:

public final List<MyObj> getList()  {
    Cursor cursor = null;
    try {
        final String queryStr = GET_LIST_STATEMENT;
        cursor = db.rawQuery(queryStr, new String[] {});
        List<MyObj> list = null;
        //here I get the data from de cursor.
        return list ;
    } catch (SQLiteFullException ex) {
        //do something to treat the exception.
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

当我对此代码运行 PMD 分析时,出现以下问题:Found 'DD'-anomaly for variable 'cursor' (lines '182'-'185').

  • 第 182 行是:Cursor cursor = null;
  • 第 185 行是:cursor = db.rawQuery(queryStr, new String[] {});

所以,我知道问题在于我在第 182 行进行了过早初始化(我从未读取过第 182 行和第 185 行之间的变量),但如果我不这样做,我就不能让代码在 finally 块中关闭 cursor

在这种情况下该怎么办?忽略这个 PMD 问题?我可以将 PMD 配置为不引发这种特定类型的 DD 异常(不是所有 DD 异常)吗? PMD 是否应该足够聪明,不会引发这个问题?

另一个我认为不是真正问题的 DD 异常示例:

    Date distributeDate;
    try {
        distributeDate = mDf.parse(someStringDate);
    } catch (ParseException e) {
        Log.e("Problem", "Problem parsing the date of the education. Apply default date.");
        distributeDate = Calendar.getInstance().getTime();
    }

在这种情况下,distributeDate 变量发生异常。

【问题讨论】:

    标签: java code-analysis pmd dataflow static-code-analysis


    【解决方案1】:

    documentation 很容易理解:

    要么使用注释来抑制警告:

    // This will suppress UnusedLocalVariable warnings in this class
    @SuppressWarnings("PMD.UnusedLocalVariable")
    public class Bar {
     void bar() {
      int foo;
     }
    }
    

    或者你使用评论:

    public class Bar {
     // 'bar' is accessed by a native method, so we want to suppress warnings for it
     private int bar; //NOPMD
    }
    

    当涉及到您的特定代码时,我想说处理它的最简单方法是不使用 finally 块,即使这看起来是它的完美位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多