代码检查工具PMD/CPD

一.PMD/CPD介绍

PMD是一个源代码分析器。它寻找常见的编程缺陷,例如未使用的变量、空的catch块、多余的对象创建等等。支持Java、JavaScript、Salesforce.com Apex、PLSQL、Apache Velocity、XML、XSL。

另外,它包含CPD(copy-paste-detector),一个复制粘贴检测器。CPD寻找重复的代码,支持Java、C、C++、C#、Groovy、PHP、Ruby、Fortran、JavaScript、PLSQL、Apache Velocity、Scala、Objective C,Matlab,Python,Go,Swift和Salesforce.com Apex。

二.下载工具

1. 公网可以下载pmd-bin-6.39.0.zip,解压缩后进入bin目录

pmd-bin-6.39.0.zip的bin目录结构展示

三 CPD功能

1.使用cpd的命令

./run.sh cpd --minimum-tokens 100 --files /vmdata/cloudci/XR_Server_BigSpace_New/XR_Server_BigSpace_New_DailyCI/1/xr-bigspace/ --format text --language java 

2.使用cpd生成的报告

Found a 26 line (141 tokens) duplication in the following files:
Starting at line 128 of /vmdata/cloudci/XR_Server_BigSpace_New/XR_Server_BigSpace_New_DailyCI/1/xr-bigspace/src/main/java/com/zte/bigspace/modules/centralControl/service/impl/CentralControlInfoImpl.java
Starting at line 172 of /vmdata/cloudci/XR_Server_BigSpace_New/XR_Server_BigSpace_New_DailyCI/1/xr-bigspace/src/main/java/com/zte/bigspace/modules/centralControl/service/impl/CentralControlInfoImpl.java

        String codec = centerDictionaryDao.getML();
        for (ClientLoginState clientLoginState : onlineUsers) {
            if (clientLoginState == null || clientLoginState.getState() == 0) {
                continue;
            }
            res.add(ThreadPoolUtil.submit(() -> startRender(contentInfo, clientLoginState, codec, rateAdaptive)));
        }

        int failed = 0;
        CommonResult<ClientLoginState> failedResult = null;
        // 处理结果
        for (Future<CommonResult<ClientLoginState>> resultFuture : res) {
            try {
                CommonResult<ClientLoginState> result = resultFuture.get();
                if (result.isSuccess()) {
                    clientDao.updateById(result.getData());
                } else {
                    failedResult = result;
                    failed ++;
                }
            } catch (Throwable e) {
                failed ++;
            }
        }
        int success = res.size() - failed;
        if (success == 0){
=====================================================================
Found a 35 line (128 tokens) duplication in the following files:
Starting at line 136 of /vmdata/cloudci/XR_Server_BigSpace_New/XR_Server_BigSpace_New_DailyCI/1/xr-bigspace/src/main/java/com/zte/bigspace/modules/client/service/impl/ClientDelayRecordServiceImpl.java
Starting at line 103 of /vmdata/cloudci/XR_Server_BigSpace_New/XR_Server_BigSpace_New_DailyCI/1/xr-bigspace/src/main/java/com/zte/bigspace/modules/client/service/impl/ClientMetricsRecordServiceImpl.java

            response.setHeader("Content-disposition", "attachment; filename=" + File.separator + "excel" + File.separator + PROBEDATE);
            response.setContentType("application/vnd.ms-excel");
            out = response.getOutputStream();
//            out = new FileOutputStream("D:/probe-date.xlsx");
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

            if (null != wb) {
                try {
                    wb.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

            if (null != in) {
                try {
                    in.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return CommonResult.success();
    }
}

3.cpd的报告解析

用=======隔开的是两处代码重复的地方,

第一个表示同一个类自身的代码重复CentralControlInfoImpl.java自身的代码有重复,该类的128-153(26行)和172-197(26行)行的代码完全重复,重复的代码可以抽出来,写成一个公用方法

第二个表示两个不同的类代码重复ClientDelayRecordServiceImpl.java的136-263(128行)ClientMetricsRecordServiceImpl.java的103-230(128行)的代码重复,提示重复的代码可以抽出来,写一个工具类

4.官网上的解决思路总结

Refactoring duplicates

Once you have located some duplicates, several refactoring strategies may apply depending of the scope and extent of the duplication. Here’s a quick summary:

  • If the duplication is local to a method or single class:

Extract a local variable if the duplicated logic is not prohibitively long

Extract the duplicated logic into a private method

  • If the duplication occurs in siblings within a class hierarchy:

Extract a method and pull it up in the class hierarchy, along with common fields

Use the Template Method design pattern

  • If the duplication occurs consistently in unrelated hierarchies:

Introduce a common ancestor to those class hierarchies

重构重复的代码:

一旦您找到了一些重复代码,可能会根据重复代码的范围和程度应用多种重构策略。以下是快速总结:

  • 如果重复代码属于方法或单个类:

    如果重复代码逻辑不长,提取局部变量
    将重复代码逻辑提取为一种私有方法

  • 如果重复代码发生在类层次结构中的同级中:

    提取方法并在类层次结构中将其与常见字段一起上拉
    使用模板方法设计模式

  • 如果重复代码在无关的组织存档中一致发生:

    将共同祖先介绍到这些类的层次结构中
    新手和高级读者可能想要在“重构大师”上阅读更深入的策略、用例和解释。

三 PMD的功能

1.使用pmd的命令

./run.sh pmd -dir /home/src/ -format html -reportfile /home/error.html -rulesets rulesets/java/quickstart.xml,category/java/codestyle.xml

2.使用pmd生成的报告

在这里插入图片描述
点蓝色的那几行,可以进入官网,了解代码的需要修改的提示,非常友好

3.官网的修复提示

官网的修复提示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值