PMD规则:如何正确解决这个DD异常问题

问题描述 投票:3回答:1

我有以下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变量发生异常。

android code-analysis pmd
1个回答
2
投票

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块,即使这看起来像是一个完美的地方。

© www.soinside.com 2019 - 2024. All rights reserved.