如何为任何已知的工具静态代码审查创建自定义错误检测器?

时间:2015-12-29 09:49:48

标签: checkstyle findbugs pmd static-code-analysis

我有以下课程。我可以通过重新设计来解决这个问题,但这是遗留代码所以我无法改变它。

现在,我无法审查所有初级开发人员编写的代码,但我想为任何静态代码审查工具(Checkstyle,PMD或Findbugs)创建一个自定义错误检测器,它将检测我们的这类错误。詹金斯。

我有这个界面 DataService

public interface DataService {
    public void discard();
}

MyDataService classe实现此接口。

public class MyDataService implements DataService {

    public void discard() {
          //Some code here
    }
}

测试课。

public class Test {
    Service service
    public Test(Service service) {
         this.service = service;
    }
    public static void main(String[] args) {
        DataService internalDataService = service.getInternalDataService();
        DataService threadLocalDataService = service.getThreadLocalDataService();


        // Developer must invoke this method before leaving this block.
        // If he forgets then it should be reported as bug like 'resource leaking or something'. 
        internalDataService.discard();

        // This should be reported as bug because programmer shouldn't
        //invoke discard method of DataService when it is threadlocal.
        threadLocalDataService.discard();
    }

}

1 个答案:

答案 0 :(得分:2)

您可以使用Close Resource规则使用PMD解决第一部分(报告忘记丢弃呼叫)。可以使用以下自定义规则集调整此规则以验证DataServicediscard

<?xml version="1.0"?>
<ruleset name="ExampleRuleset"
         xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">

    <description>
        discard as close resource target
    </description>

    <rule ref="rulesets/java/design.xml/CloseResource">
        <properties>
            <property name="types" value="DataService"/>
            <property name="closeTargets" value="discard"/>
        </properties>
    </rule>
</ruleset>

有关如何创建自定义规则集的详细信息:How to make a custom ruleset

将此规则集另存为文件,例如custom-ruleset.xml并在执行PMD时使用它:

bin/run.sh pmd -d sourceDirectory -f text -R custom-ruleset.xml

如果您取消注释&#34; discard&#34>,您应该会看到违规行为。电话,例如

src/Test.java:8:   Ensure that resources like this DataService object are closed after use

然而,如果服务是本地线程的话,那么不会检测到丢弃 ...