课题修改PMD总结.docx

上传人:b****8 文档编号:9612450 上传时间:2023-02-05 格式:DOCX 页数:16 大小:140.12KB
下载 相关 举报
课题修改PMD总结.docx_第1页
第1页 / 共16页
课题修改PMD总结.docx_第2页
第2页 / 共16页
课题修改PMD总结.docx_第3页
第3页 / 共16页
课题修改PMD总结.docx_第4页
第4页 / 共16页
课题修改PMD总结.docx_第5页
第5页 / 共16页
点击查看更多>>
下载资源
资源描述

课题修改PMD总结.docx

《课题修改PMD总结.docx》由会员分享,可在线阅读,更多相关《课题修改PMD总结.docx(16页珍藏版)》请在冰豆网上搜索。

课题修改PMD总结.docx

课题修改PMD总结

修改PMD总结

1.AvoidunnecessaryComparisonsinBooleanexception.(Boolean类型重复判断)

错误例子:

if(null!

=a&&a.size>0)

正确if(null!

=a&&false==a.IsEmpay())

2.AvoidUsingimplementationtypeslike(ArrayListHashMap/LinkedHashMap),usetheinterfaceinstand.(用数组的接口类型)

错误例子:

ArrayListarraylist=newArrayList();

正确Listlist=newArrayList();

错误例子:

privatestaticHashMapmap=newHashMap();

正确privatestaticMapmap=newHashMap();

错误例子:

privatestaticLinkedHashMapmap=newLinkedHashMap();

正确privatestaticMapmap=newLinkedHashMap();

3.Methodnamesshouldnotstartwithcapitalletters(方法名不能以大写开头)。

错误例子:

publicclassStart()

正确publicclassstart()可以用快捷键Alt+shift+R全部替

4.varivablethatarefinalandstaticshouldbeinallcaps.(定义的参数必须大写)

错误例子:

publicstaticfinalStringroot

正确publicstaticfinalStringROOT

5.AvoidappendingcharcutarsasStringsinStringBufferappend(避免在StringBuffer里附加单个字符时附加成String类型)

错误例子:

buf.append(“)”)或者buf.append(“a”)

正确buf.append(')')或者buf.append('a')

6.useArrayListinstandedofvector(使用ArrayList替换vector后还是会报错,所以直接改成是以它的接口形式替换)

错误例子:

vectorkeys=newvector(ELE);

正确Listkeys=newArrayList(ELE);

7.Variablesthatarenotfinalshouldnotcontainunderscores(exceptforunderscoresinstandardprefix/suffix)(变量不是final类型的不能包含下划线)

错误例子:

privateintDEAULT_PORT=8001;

正确privateintDEAULTPORT=8001;(调用它的所有类都需要改动)

8.Variablesshouldstartwithalowercasecharacter(参数必须要以小写开始)

错误例子:

privatestaticintHANDLE_MAX=200;

正确privatestaticinthandleMax=200;

9.UsingequalsIgnoreCase()iscleanerthanusingtoUpperCase/toLowerCase().equals().

错误例子:

正确

10.Unnecessarywrapperobjectcreation

错误例子:

intCurPage=Integer.valueOf(curPage).intValue();

正确intCurPage=Integer.parseInt(curPage);

11.ThisisaninefficientuseofStringBuffer.toString;callStringBuffer.lengthinstead.错误If(newPartLen+smsMOCommondArr.toString().getBytes(DB_CHARSET).length>DB_VERCHAR_MAX_LEN+1){}

正确if(newPartLen+(smsMOCommondArr.toString().getBytes(DB_CHARSET)).length>DB_VERCHAR_MAX_LEN+1){}

12.Thisfinalfieldcouldbemadestatic

错误例子:

privatefinalStringurlPrefix="http:

//";

正确privatestaticfinalStringURL_PREFIX="http:

//";

13.Thefieldnameindicatesaconstantbutitsmodifiersdonot

错误例子:

privatestaticStringCONF_NAME="version";

正确privatestaticfinalStringCONF_NAME="version";

14.System.out.printisused

错误例子:

System.out.println("PartalOneAppender--message=["+message+"]");

正确//System.out.println("PartalOneAppender--message=["+message+"]");

15.Switchstatementsshouldhaveadefaultlabel

错误例子:

switch(Type)

{

caseUSER:

displayType="USER";

break;

caseADMIN:

displayType="ADMIN";

break;

}

正确switch(Type)

{

caseUSER:

displayType="USER";

break;

caseADMIN:

displayType="ADMIN";

break;

default:

}

16.Substitutecallstosize()==0(orsize()!

=0)withcallstoisEmpty()

错误例子:

if(null==Handlers||0==Handlers.size())

正确if(null==Handlers||Handlers.isEmpty())

17.Returnanemptyarrayratherthannull.

错误例子:

if(null!

=g&&g.length>0)

{

String[]cloneGroups=newString[g.length];

System.arraycopy(g,0,cloneGroups,0,g.length);

returncloneGroups;

}

returnnull;

}

正确if(null!

=g&&g.length>0)

{

String[]cloneGroups=newString[g.length];

System.arraycopy(g,0,cloneGroups,0,g.length);

returncloneGroups;

}

returnnewString[0];

18.Deeplynestedif..thenstatementsarehardtoread

原因:

深嵌套的if循环很难读懂。

报错例子

if(null!

=portalScriptionInfo&&null!

=portalScriptionInfo.getChargeInfo()){

if(productId.equals(portalScriptionInfo.getChargeInfo().getSourceChargeId()))

{//构造orderInfo对象

portalOrderInfo.setProductId(productId);

productName=chargeInfo.getProductName();

break;

}

}

修改后的例子

if(null!

=portalScriptionInfo&&null!

=portalScriptionInfo.getChargeInfo()&&(productId.equals(portalScriptionInfo.getChargeInfo()

.getSourceChargeId())))

{

portalOrderInfo.setProductId(productId);

productName=chargeInfo.getProductName();

break;

}

19.Caughtexceptionisrethrown,originalstacktracemaybelost

原因:

捕捉一个异常后,再从新把异常扔出去,会把以前的异常信息丢掉。

修改:

可以把在此扔出的异常信息以Log日志的形式打印出来。

例如:

(错误)catch(IOExceptionioe)

{

Stringmsg="Can'topenconfigfile:

"+xmlFile+"dueto:

"

+ioe;

thrownewIOException(msg);

}

改正后:

catch(IOExceptionioe)

{

Stringmsg="Can'topenconfigfile:

"+xmlFile+"dueto:

"

+ioe;

LogFactory.getInstance().logAction(msg);}

20.AvoidthrowingrawExceptiontypes(避免抛出一个生疏的异常类型)

错误例子:

catch(IOExceptionioe)

{

ioe.printStackTrace();

Stringmsg="Can'topenconfigfile:

"+xmlFile.getAbsolutePath()+"dueto:

"+ioe;

thrownewException(msg);}

正确catch(IOExceptionioe)

{

ioe.printStackTrace();

Stringmsg="Can'topenconfigfile:

"+xmlFile.getAbsolutePath()+"dueto:

"+ioe;

LogFactory.getInstance().logAction(msg);}

21.Methodcallonobjectwhichmaybenull

错误例子:

if(GroupList==null&&GroupList.size()<1)

正确if(GroupList.isEmpty())

22.Itissomewhatconfusingtohaveafieldnamewiththesamenameasamethod.

原因:

A'getX()'methodwhichreturnsabooleanshouldbenamed'isX()'属性名与方法名称相似。

修改:

错误privatebooleanstopServer;

publicvoidstopServer(){

this.stopServer=true;

}

正确可以把方法名称该换一个名字!

23.Donotuseifstatementsthatarealwaystrueoralwaysfalse

原因:

不要总使用If循环条件是true或者是false。

修改:

(错误的)

StringNameKey=request.getParameter("NameKey");

if(true){

request.setAttribute("NameKey",nameKey);

ReleaseContentreleaseContent=newReleaseContent();

releaseContent.setCatalogId(catalogId);

Useruser=super.getUser(request);

intuserType=userInfo.getUserType();

…………………

(正确的)ift条件是真的就可以去掉if(true)

StringNameKey=request.getParameter("NameKey");

//if(true){

request.setAttribute("NameKey",nameKey);

ReleaseContentreleaseContent=newReleaseContent();

releaseContent.setCatalogId(catalogId);

Useruser=super.getUser(request);

intuserType=userInfo.getUserType();

…………………

24.System.arraycopyismoreefficient

报错的例子:

for(inti1=0;i1

{

tmpabcde[i1]=digestInt[i1];

}

修改成for(inti1=0;i1

{//tmpabcde[i1]=digestInt[i1];

System.arraycopy(digestInt,i1,tmpabcde,i1,1);

}

**arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

          从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。

参数:

src-源数组。

srcPos-源数组中的起始位置。

dest-目标数组。

destPos-目标数据中的起始位置。

length-要复制的数组元素的数量。

25.useaslistinstendedoftightloops()

原因for(inti=0;i

List.add(type[i]);}

修改:

List=Arrays.asList(type);

**提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素:

Listlist=Arrays.asList("Larry","Moe","Curly");

参数:

Larry:

存放的类型Moe:

有效性curly:

26.Avoidemptyifstatements()

原因:

在if循环中没有大括号。

做法:

错误例子:

if(mlang==null)

mlang=LanguageUtil.getDefaultLanguage();

return"_"+mlang.getLanguage().toUpperCase()+"_"

+mlang.getCountry().toUpperCase();

正确if(mlang==null)

{

mlang=LanguageUtil.getDefaultLanguage();

}

return"_"+mlang.getLanguage().toUpperCase()+"_"

+mlang.getCountry().toUpperCase();

27.Avoidusing(if...else/if/for/while)statementswithoutcurlybraces

原因:

避免使用(if...else/if/for/while)循环时没有波形括号(基本的语法错误)

修改:

应该加括号的地方加上括号。

28.Avoidusingexceptionsasflowcontrol.

原因:

避免使用异常来控制流程

修改:

报出的异常信息基本上都是在try。

catch。

的catch语句块中,可以

把在catch语句块中抛出的异常信息,用log日志来代替输出信息。

29.Avoidunnecessaryif..then..elsestatementswhenreturningaBoolean

原因:

在返回值是Boolean类型时,避免不必要的使用if..then..else

修改:

错误的:

if(UserConstant.TYPE_SP==getUser(request).getUserType())

{

returntrue;

}

else

{

returnfalse;

}

正确的:

if(UserConstant.TYPE_SP==getUser(request).getUserType())

{

returntrue;

}

returnfalse;

30.Avoidunnecessaryconstructors-thecompilerwillgeneratetheseforyou.

原因:

产生了一个多余的构造器,编辑器将为你产生它们。

做法:

一个公有的抽象类,不需要自己在写一个构造器,因为它本身自己就可以

提供构造方法。

删除多余的私有构造方法。

31.AvoidinstantiatingBooleanobjects;referenceBoolean.TRUEorBoolean.FALSEorcallBoolean.valueOf()instead.

错误例子:

request.setAttribute("productNotFound",Boolean.valueOf("true"));

正确request.setAttribute("productNotFound",Boolean.TRUE);

**Boolean类型的值不需要值类型转换,直接可以赋以true或者是false;

32.AvoidcatchingNullPointerException;considerremovingthecauseoftheNPE.

原因:

避免捕捉产生的空指针(排除由它造成的NPE原因)

做法:

删除语句块中抛出的异常信息,由Log日志来带它打印信息

33.AvoidcallingtoString()onStringobjects;thisisunnecessary.

错误例子:

Stringresult="";

returnresult.toString();

正确returnresult;

**本来就是String类型不需要再toString()转换;

34.Anemptystatement(semicolon)notpartofaloop.

原因:

if(is!

=null){

try{

is.close();

}

catch(Throwableu){

;

}

正确如果该方法没有任何的代码,你就可以使用日志来记录它的异常信息。

35.Athrowstatementinafinallyblockmakesthecontrolflowhardtounderstand.

原因:

不要在finally语句块中抛出异常,会造成一个很难理解的控制流。

做法:

可以把抛出的异常信息,用log日志的形式来替换。

36.Avoidreally(long/short)parameterlists.

原因:

方法参数名太长。

做法:

37.Noneedtoimportatypethatlivesinthesamepackage

原因:

不需要导入类型相识的架包。

做法:

使出这个多余的架包。

38.NoneedtocallString.valueOftoappendtoastring.

原因:

它把String类型的值再一次转化为String类型的值,是多余的。

做法:

不用转化它的值类型,因为它本身就是String类型的值。

39.Amethod/constructorshouldn'texplicitlythrowjava.lang.Exception

原因:

方法不能扔出一个不具体的异常信息。

做法:

根据具体的代码,抛出具体的异常信息。

40.Avoidusingimplementationtypelike('TreeMap'/'java.util.HashSet'/'java.util.HashSet')

usetheinterfaceinstead

错误例子:

TreeMapmap=NEWTreeMap();

正确Mapmap=NEWTreeMap();

41.Avoidunusedimportssuchas'org.apache.struts.action.ActionMessages'

原因:

导入了多余的架包,例如:

org.apache.struts.action.ActionMessages

做法:

删除掉。

同时也可以用快捷键先ctrl+A,再ctrl+shift+o就可以了。

42.Avoidreturningfromafinallyblock

原因:

返回信息在fina

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 外语学习 > 其它语言学习

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1