版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
JavaPMDBasicRules:TheBasicRulesetcontainsacollectionofgoodpracticeswhicheveryoneshouldfollow.BracesRules:TheBracesRulesetcontainsacollectionofbracesCloneImplementationRules:TheCloneImplementationrulesetcontainsacollectionofrulesthatfindquestionableusagesoftheclone()method.CodeSizeRules:TheCodeSizeRulesetcontainsacollectionofrulesthatfindcodesizerelatedproblems.ControversialRules:TheControversialRulesetcontainsrulesthat,forwhateverreason,areconsideredcontroversial.Theyareseparatedoutheretoallowpeopletoincludeastheyseefitviacustomrulesets.ThisrulesetwasinitiallycreatedinresponsetodiscussionsoverUnnecessaryConstructorRulewhichTomlikesbutmostpeoplereallydislike:-)CouplingRules:Theseareruleswhichfindinstancesofhighorinappropriatecouplingbetweenobjectsandpackages.DesignRules:TheDesignRulesetcontainsacollectionofrulesthatfindquestionabledesigns.FinalizerRules:Theserulesdealwithdifferentproblemsthatcanoccurwithfinalizers.ImportStatementRules:Theserulesdealwithdifferentproblemsthatcanoccurwithaclass'importstatements.J2EERules:ThesearerulesforJavaBeanRules:TheJavaBeansRulesetcatchesinstancesofbeanrulesnotbeingfollowed.JUnitRules:TheserulesdealwithdifferentproblemsthatcanoccurwithJUnittests.JakartaCommonsLoggingRules:TheJakartaCommonsLoggingrulesetcontainsacollectionofrulesthatfindquestionableusagesofthatJavaLoggingRules:TheJavaLoggingrulesetcontainsacollectionofrulesthatfindquestionableusagesofthelogger.MigrationRules:ContainsrulesaboutmigratingfromoneJDKversiontoanother.Don'tusetheserulesdirectly,rather,useawrapperrulesetsuchasmigrating_to_13.xml.NamingRules:TheNamingRulesetcontainsacollectionofrulesaboutnames-toolong,tooshort,andsoforth.OptimizationRules:Theserulesdealwithdifferentoptimizationsthatgenerallyapplytoperformancebestpractices.StrictExceptionRules:Theserulesprovidesomestrictguidelinesaboutthrowingandcatchingexceptions.StringandStringBufferRules:TheserulesdealwithdifferentproblemsthatcanoccurwithmanipulationoftheclassStringorStringBuffer.SecurityCodeGuidelines:TheserulescheckthesecurityguidelinesfromSun,publishedat TypeResolutionRules:TheseareruleswhichresolvejavaClassfilesforcomparisson,asopposedtoaStringUnusedCodeRules:TheUnusedCodeRulesetcontainsacollectionofrulesthatfindunusedcode.PMDBasicEmptyCatchBlock:EmptyCatchBlockfindsinstanceswhereanexceptioniscaught,butnothingisdone.Inmostcircumstances,thisswallowsanexceptionwhichshouldeitherbeactedonorreported.解决方案空的catchcatch块没做任何异常处理的事,在大多数情形EmptyIfStmt:EmptyIfStatementfindsinstanceswhereaconditionischeckedbutnothingisdoneaboutit.解决方 空的if表达式:发现使用if进行了条件判断,但是判断之后没做任何处EmptyWhileStmt:EmptyWhileStatementfindsallinstanceswhereawhilestatementdoesnothing.Ifitisatimingloop,thenyoushoulduseThread.sleep()forit;ifit'sawhileloopthatdoesalotintheexitexpression,rewriteittomakeitclearer.解决方案空的while表达式:发现空的while表达式,如果是一个定时的循环,你应该在循环体内使用Thread.sleep();如果是对于退出处理做的一个处理大量事情的while循环,重写代码使它更清晰EmptyTryBlock:Avoidemptytryblocks-what'sthe解决方案空的try块:避免空的tryEmptyFinallyBlock:Avoidemptyfinallyblocks-thesecanbe解决方案空的finally块:避免空的finally块-EmptySwitchStatements:Avoidemptyswitch解决方案空的switch表达式:避免空的switchJumbledIncrementer:Avoidjumbledloopincrementers-it'susuallyamistake,andit'sconfusingevenifit'swhat'sintended.解决方案避免的循环增量-它常常是一个错误,而且容易让人迷publicclassJumbledIncrementerRule1{publicvoidfoo(){for(inti=0;i<10;i++){for(intk=0;k<20;i++){}}}}ForLoopShouldBeWhileLoop:Someforloopscanbesimplifiedtowhileloops-thismakesthemmoreconcise.解决方案有些for循环可以简化为while循环-这样可以更加简明publicclassFoo{voidbar(){fortruetrue;//没有初始化块和变化块,相当于while}}UnnecessaryConversionTemporary:AvoidunnecessarytemporarieswhenconvertingprimitivestoStrings publicStringconvert(intx)//Stringfoo=new//return}OverrideBothEqualsAndHashcode:OverridebothpublicbooleanObject.equals(Objectother),andpublicintObject.hashCode(),oroverrideneither.EvenifyouareinheritingahashCode()fromaparentclass,considerimplementinghashCodeandexplicitlydelegatingtoyoursuperclass. 同时重写equals()和hashCode()方法:要么全部重写这两个方法,要DoubleCheckedLocking:PartiallycreatedobjectscanbereturnedbytheDoubleCheckedLockingpatternwhenusedinJava.AnoptimizingJREmayassignareferencetothebazvariablebeforeitcreatestheobjectthereferenceisintendedtopointto.Formoredetailssee /javaworld/jw-02-2001/jw-0209- 双重检查锁机制在JAVA中有时候创建的对象是通过双重检查机制获取的,一个优化的JRE可能在真正创建对象之前先将指向这个对象的赋给一个变量,如baz,需要细节参考: publicclassFoo{Objectbaz;Objectbar(){/**这里当对象没创建完时也可能判断不为空,那么在多线程环境下,就可能导致某些线程使用bar()方法后直接返回一个未指向完整对象的baz,从而发生错误,.aspx if(baz==null){if(baz==baz=new}}}return}}ReturnFromFinallyBlock:Avoidreturningfromafinallyblock-thiscandiscardexceptions. 从finally块中返避免从finally块中返回-这会导致异常捕获后又被抛弃.publicclassBar{publicStringfoo(){try{thrownewException("MyException"}catch(Exceptione){throwe;}finallyreturnAOK.";//.这句导致catchA.O.K}}}EmptySynchronizedBlock:Avoidemptysynchronizedblocks-they're解决方 空的Synchronized块:避免空的synchronized块-它们是无用UnnecessaryReturn:Avoidunnecessaryreturn 不必要的Return:避免不必要的return语句publicclassFoo{publicvoidbar(){intx=42;}}EmptyStaticInitializer:Anemptystaticinitializerwas publicclassFoo{static{//}}UnconditionalIfStatement:Donotuse"if"statementsthatarealwaystrueoralwaysfalse. 非条件化的if表达式:当表达式总是为真或总为假时,不要用ifpublicclassFoo{publicvoidclose(){if(true){//}}}EmptyStatementNotInLoop:Anemptystatement(akaasemicolonbyitself)thatisnotusedasthesolebodyofaforlooporwhileloopisprobablyabug.Itcouldalsobeadoublesemicolon,whichisuselessandshouldbe解决方案非循环中不要有空的表达式:在一个非for循环或非while循环体中使用的一个空的表达式(或者称为一个分号)bug。也可能是一对分号,这是无publicclassMyClass{publicvoidt(){//;//System.out.println("lookattheextra}}BooleanInstantiation:AvoidinstantiatingBooleanobjects;youcanreferenceBoolean.TRUE,Boolean.FALSE,orcallBoolean.valueOf()instead.解决方 Boolean.TRUE,Boolean.FALSE或Boolean.valueOf()的代UnnecessaryFinalModifier:Whenaclasshasthefinalmodifier,allthemethodsareautomaticallyfinal. 非必要的final修饰符:注意当一个类被fianl修饰时,所有这个类的方法就自动变为final类型了CollapsibleIfStatements:Sometimestwo'if'statementscanbeconsolidatedbyseparatingtheirconditionswithabooleanshort-circuit 分解的if表达式:有时候两个if语句可以通过布尔短路操作符分隔条件表UselessOverridingMethod:Theoverridingmethodmerelycallsthesamemethoddefinedinasuperclass解决方 ClassCastExceptionWithToArray:ifyouneedtogetanarrayofaclassfromyourCollection,youshouldpassanarrayofthedesideredclassastheparameterofthetoArraymethod.Otherwiseyouwillgeta toArray时类型转换异常:如果你想从一个枚举类型中得到某个类型的数组,你应该传给toArray()方法一个目的类型的数组作为参数,否则你可能得到一个类型转AvoidDecimalLiteralsInBigDecimalConstructor:Onemightassumethat"newBigDecimal(.1)"isexactlyequalto.1,butitisactuallyequalto Thisissobecause.1cannotberepresentedexactlyasadouble(or,forthatmatter,asabinaryfractionofanyfinitelength).Thus,thelongvaluethatisbeingpassedintotheconstructorisnotexactlyequalto.1,appearancesnotwithstanding.The(String)constructor,ontheotherhand,isperfectlypredictable:'newBigDecimal(".1")'isexactlyequalto.1,asonewouldexpect.Therefore,itisgenerally mendedthatthe(String)constructorbeusedinpreferencetothisone. 避免在BigDecimal类型的构造方法中用小数类型的字面量:人们常常以为”newBigDecimal(0.1)”能精确等于0.1,其实不然,它等于“0.5”,这0.1long类型不等0.1,而传入String类型的构造器newBigDecimal(“0.1”)可以精确等于0.1,故推荐这种情形时用String类型的构造器UselessOperationOnImmutable:AnoperationonanImmutableobject(String,BigDecimalorBigInteger)won'tchangetheobjectitself.Theresultoftheoperationisanewobject.Therefore,ignoringtheoperationresultisan 对于不变类型的无用操作:对于不变类型对象(String,BigDecimal或BigInteger)的操作不会改变对象本身,但操作结果是产生新的对象,所以,忽略操作importjava.math.*;classTest{voidmethod1()BigDecimalbd=newBigDecimal(10);bd.add(newBigDecimal(5这里违背了规则}voidmethod2()BigDecimalbd=newbdbd.add(newBigDecimal(5));//}}MisplacedNullCheck:Thenullcheckhereismisplaced.ifthevariableisnullyou'llgetaNullPointerException.Eitherthecheckisuseless(thevariablewillneverbe"null")orit'sincorrect. publicclassFoo{voidbar(){if(a.equals(baz)&&a!=null)}}publicclassFoo{voidbar(){if(a.equals(baz)||a==null)}}UnusedNullCheckInEquals:Aftercheckinganobjectreferencefornull,youshouldinvokeequals()onthatobjectratherthanpassingittoanotherobject'sequals()method.解决方案使用equals()时无用的空检查:在对一个对象进行完空检查后,你应该在这个对象上调用equals()方法而不是将它传给另一个对象的equals()方法作为AvoidThreadGroup:AvoidusingThreadGroup;althoughitisintendedtobeusedinathreadedenvironmentitcontainsmethodsthatarenotthread publicclassBar{voidbuz(){ThreadGrouptg=newThreadGroup("Mythreadgroup");tg=newThreadGroup(tg,"mythreadgroup");tg=tg=}}BrokenNullCheck:ThenullcheckisbrokensinceitwillthrowaNullPointerExceptionitself.Itislikelythatyouused||insteadof&&orvice解决方 代替&&classFooStringbar(Stringstring)//这里应该是if(string!=null||!string.equals(""))returnstring;//这里应该是if(string==null&&string.equals(""))returnstring;}}BigIntegerInstantiation:Don'tcreateinstancesofalreadyexistingBigInteger(BigInteger.ZERO,BigInteger.ONE)andfor1.5on,BigInteger.TENandBigDecimal(BigDecimal.ZERO,BigDecimal.ONE,BigDecimal.TEN) BigInteger实例化:不要创建已经存在的BigInteger类型的实例,(如BigInteger.ZERO,BigInteger.ONE),对于JDK.1.5以上,BigInteger.TENBigDecimal(BigDecimal.ZERO,BigDecimal.ONE,BigDecimal.TEN)publicclassTestpublicstaticvoidmain(String[]args){BigIntegerbi=newBigInteger(1);BigIntegerbi2=newBigInteger("0");BigIntegerbi3=newBigInteger(0.0);BigIntegerbi4;bi4=new}}AvoidUsingOctalValues:Integerliteralsshouldnotstartwithzero.Zeromeansthattherestofliteralwillbeinterpretedasanoctalvalue. 避免使用八进制值:整型字面量不要以0开头,0意味着之后的值要被解AvoidUsingHardCodedIP:AnapplicationwithhardcodedIPmay impossibletodeployinsomecase.ItneverhurtstoexternalizeIP 避免使用IP硬编码:一个应用中的硬编码IP将使系统在某些情况下无法CheckResultSet:Alwayscheckthereturnofoneofthenavigationmethod(next,previous,first,last)ofaResultSet.Indeed,ifthevaluereturnis'false',thedevelopershoulddealwithit!解决方 检查ResultSet:总是需要检查ResultSet对象的导航方(next,previous,first,last)的返回,事实上,如果返回false,开发者需要处理//ThisisNOTappropriateStatementstat=ResultSetrst=stat.executeQuery("SELECTnameFROM");rst.next();//whatifitreturnsa'false'?StringfirstName=//ThisisStatementstat=ResultSetrst=stat.executeQuery("SELECTnameFROM");if(rst.next()){StringfirstName=}{//hereyoudealwiththeerror(atleastlog}AvoidMultipleUnaryOperators:Usingmultipleunaryoperatorsmaybeabug,and/orisconfusing.Checktheusageisnotabug,orconsidersimplifyingtheexpression. 避免使用多重的一元运算符:使用多重的一元运算符可能是一个bug,并且可能令人迷惑。检查确保你的用法不是一个bug,或者考虑简化表达//Thesearetypobugs,oratbestneedlesslycomplexandconfusing:inti=--1;intj=+-+1;intz=~~2;booleanb=booleanc=//Theseareinti=1;intj=-1;intz=2;booleanb=true;booleanc=//Andthesejustmakeyourbrainhurt:inti=~-2;intj=-EmptyInitializer:Anemptyinitializerwas解决方 publicclassFoostatic{}//Why{}//Again,why}PMDBracesIfStmtsMustUseBraces:Avoidusingifstatementswithoutusingcurly解决方案if块必须用括号:避免使用if块时不使用花括号WhileLoopsMustUseBraces:Avoidusing'while'statementswithoutusingcurlybraces.解决方案while循环必须使用括号:避免使用while块时不使用IfElseStmtsMustUseBraces:Avoidusingif..elsestatementswithoutusingcurlybraces.解决方案if…else…块必须使用括号:避免使用if…else…块时不使用ForLoopsMustUseBraces:Avoidusing'for'statementswithoutusingcurly解决方案for循环必须使用括号:避免在for循环时不使用PMDCloneImplementationProperCloneImplementation:Objectclone()shouldbeimplementedwith解决方案适当的克隆实现:对象的clone()方法中应该包含super.clone()CloneThrowsCloneNotSupportedException:Themethodclone()shouldthrowaCloneNotSupportedException.解决方案克隆方法要抛出不支持克隆异常:clone()CloneMethodMustImplementCloneableThemethodcloneshouldonlybeimplementediftheclassimplementstheCloneableinterfacewiththeexceptionofafinalmethodthatonlythrowsCloneNotSupportedException.解决方案克隆方法必须实现Cloneable接口:如果类实现Cloneable接口,clone()方法应该被实现为一个final的方法并且只抛出CloneNotSupportedException的异常PMDCodeSizeplexity:TheNPathcomplexityofamethodisthenumberofacyclicexecutionpathsthroughthatmethod.Athresholdof200isgenerallyconsideredthepointwheremeasuresshouldbetakentoreducecomplexity.解决方案200作为考虑降低复杂度的临界点ExcessiveMethodLength:Violationsofthisruleusuallyindicatethatthemethodisngtoomuch.Trytoreducethemethodsizebycreatinghelpermethodsandremovinganycopy/pastedcode.解决方案方法太长:这种违例就是方法中做了太多事,通过创建辅助方法或移除拷贝/ExcessiveParameterList:Longparameterlistscanindicatethatanewobjectshouldbecreatedtowrapthenumerousparameters.Basically,trytogrouptheparameterstogether.解决方案太多的参数:过长的参数列表表明应该创建一个新的对象包装众多的参数值,ExcessiveClassLength:LongClassfilesareindicationsthattheclassmaybetryingtodotoomuch.Trytobreakitdown,andreducethesizetosomethingmanageable.解决方案太长的类:太长的类文件表明类试图做太多的事,试着分解它,减少到易于管plexity:Complexityisdeterminedbythenumberofdecisionpointsinamethodplusoneforthemethodentry.Thedecisionpointsare'if','while','for',and'caselabels'.Generally,1-4islowcomplexity,5-7indicatesmoderatecomplexity,8-10ishighcomplexity,and11+isveryhigh解决方案秩复杂性:由if,while,for,caselabels等决策点确定的复杂度,1-4是低复杂度,5-7为中,810是高复杂度,11以上是非常高ExcessivePublicCount:Alargenumberofpublicmethodsandattributesdeclaredinaclasscanindicatetheclassmayneedtobebrokenupasincreasedeffortwillberequiredtothoroughlytestit.解决方案过多的公共成员:一个类中如果了大量的公共方法和属性表明类需要分TooManyFields:Classesthathavetoomanyfieldscouldberedesignedtohavefewerfields,possiblythroughsomenestedobjectgrouofsomeoftheinformation.Forexample,aclasswithcity/state/zipfieldscouldinsteadhaveoneAddressfield.解决方案太多的域:类包含太多域可以被重新设计为包含更少的域,可以通过将一些信息组织为嵌套类。比如:一个类包含了city/state/zip域,可以用一个Address域组NcssMethodCount:ThisruleusestheNCSS(NonCommentingSourceStatements)algorithmtodeterminethenumberoflinesofcodeforagivenmethod.NCSSignorescomments,andcountsactualstatements.Usingthisalgorithm,linesofcodethataresplitarecountedasone.解决方案NCSS方法代码计算:这个规则采用NCSS(非注释代码块)算法计算给定的1.(也同时忽略空行)NcssTypeCount:ThisruleusestheNCSS(NonCommentingSourceStatements)algorithmtodeterminethenumberoflinesofcodeforagiventype.NCSSignorescomments,andcountsactualstatements.Usingthisalgorithm,linesofcodethataresplitarecountedasone.解决方案NCSSNCSS(非注释代码块)算法计算给定类型的1.(也同时忽略空行)NcssConstructorCount:ThisruleusestheNCSS(NonCommentingSourceStatements)algorithmtodeterminethenumberoflinesofcodeforagivenconstructor.NCSSignorescomments,andcountsactualstatements.Usingthisalgorithm,linesofcodethataresplitarecountedasone.解决方案NCSSNCSS(非注释代码块)算法计算给定的构造方法的代码行数。NCSS忽略代码中的注释并且计算实际代码行数。用这种算法,1.(也同时忽略空行)TooManyMethods:Aclasswithtoomanymethodsisprobablyagoodforrefactoring,inordertoreduceitscomplexityandfindawaytohavemorefinegrainedobjects.解决方案太多的方法:类中包含太多方法可能需要重构,以减低复杂度和获取更加细粒PMDControversialUnnecessaryConstructor:Thisruledetectswhenaconstructorisnotnecessary;i.e.,whenthere'sonlyoneconstructor,it'spublic,hasanemptybody,andtakesnoarguments.解决方案非必要的构造器:本规则检查不必要的构造器,例如:只存在一个公共的,空NullAssignment:Assigninga"null"toavariable(outsideofitsdeclaration)isusuallybadform.Sometimes,theassignmentisanindicationthattheprogrammerdoesn'tcompleyunderstandwhatisgoingoninthecode.NOTE:Thissortofassignmentmayinrarecasesbeusefultoencouragegarbagecollection.Ifthat'swhatyou'reusingitfor,byallmeans,disregardthisrule:-)解决方案Null赋值:将null赋值给变量(在之外)常常是不好的形式。某些时候这备注:当你需要把变量赋值为null提示收集器去进行收集时这是有用的,那么OnlyOneReturn:Amethodshouldhaveonlyoneexitpoint,andthatshouldbethelaststatementinthemethod.解决方案只有一个返回:一个方法应该有且只有一处返回点,且应该是方法的最后一条UnusedModifier:Fieldsininterfacesareautomaticallypublicstaticfinal,andmethodsarepublic .Classesorinterfacesnestedinaninterfaceareautomaticallypublicandstatic(allnestedinterfacesareautomaticallystatic).Forhistoricalreasons,modifierswhichareimpliedbythecontextareacceptedbythecompiler,butaresuperfluous.解决方案无用的修饰符:在接口中定义的域自动为publicstaticfinal的,方法自动是 AssignmentInOperand:Avoidassignmentsinoperands;thiscanmakecodemorecomplicatedandhardertoread.publicclassFoo{publicvoidbar(){intx=2;if((x=getX())==3)}}privateintgetX(){return3;}}AtLeastOneConstructor:Eachclassshoulddeclareatleastone解决方案至少有一个构造器:每个类应该至少一个构造DontImportSun:Avoidimportinganythingfromthe'sun.*'packages.Thesepackagesarenotportableandarelikelytochange.解决方案不要引入Sun”sun.*”SuspiciousOctalEscape:AsuspiciousoctalescapesequencewasfoundinsideaStringliteral.TheJavalanguagespecification(section3.10.6)saysanoctalescapesequenceinsidealiteralStringshallconsistofabackslashfollowedby:OctalDigit|OctalDigitOctalDigit|ZeroToThreeOctalDigitOctalDigitAnyoctalescapesequencefollowedbynon-octaldigitscanbeconfusing,e.g."/038"isinterpretedastheoctalescapesequence"/03"followedbytheliteralcharacter"8".列。Java语言规范(3.10.6节)讲到:在一个字面量字符串中的八进制转义序列应该||0~3CallSuperInConstructor:Itisagoodpracticetocallsuper()inaconstructor.Ifsuper()isnotcalledbutanotherconstructor(suchasanoverloadedconstructor)iscalled,thisrulewillnotreportit.解决方案在构造器中调用super():在构造器中调用super()方法是很好的做法.如果没有调用super(),但是调用了另外的构造器,那么这个规则不会报告出来。UnnecessaryParentheses:Sometimesexpressionsarewrappedinunnecessaryparentheses,makingthemlooklikeafunctioncall.解决方案不必要的圆括号:有时候表达式被包在一个不必要的圆括号中,使它们看起来publicclassFoobooleanbar(){return(true);}}DefaultPackage:UseexplicitscoinsteadofthedefaultpackageprivateBooleanInversion:Usebitwiseinversiontoinvertbooleanvalues-it'sthefastestwaytodothis.Seeen_USforspecific解决方案布尔转换:使用按位转换来转换布尔值-en_USforspecificdetailspublicclassFoo{publicvoidmain(bar){booleanb=true;b=!b;//b^=true;//}}DataflowAnomalyysis:Thedataflowysistrackslocaldefinitions,undefinitionsandreferencestovariablesondifferentpathsonthedataflow.Fromthoseinformationstherecanbefoundvariousproblems.1.UR-Anomaly:Thereisareferencetoavariablethatwasnotdefinedbefore.Thisisabugandleadstoanerror.2.DU-Anomaly:Arecentlydefinedvariableisundefined.Theseanomaliesmayappearinnormalsourcetext.3.DD-Anomaly:Arecentlydefinedvariableisredefined.Thisisominousbutdon'thavetobeabug.解决方案数据流异常分析数据流分析是本地的变量定义与否及在数据流中不同路是bug2.DU-异常:一个刚刚定义的变量是未定义的。这些异常可能出现3.DD-异常:一个刚刚定义的变量重新定义。这是不好的但并非一定是个bug。publicclassFoo{publicvoidfoo(){intbuz=buz=6;//redefinitionofbuz->dd-anomalybuz=}//buzisundefinedwhenleavingscope->du-}AvoidFinalLocalVariable:Avoidusingfinallocalvariables,turntheminto解决方案避免Final类型的本地变量:避免使用final类型的本地变量,将它们转为类publicclassMyClass{publicvoidfoo()finalString}}AvoidUsingShortType:Javausesthe'short'typetoreducememoryusage,nottooptimizecalculation.Infact,thejvmdoesnothaveanyarithmeticcapabilitiesfortheshorttype:thejvmmustconverttheshortintoanint,dothepropercaculationandconverttheintbacktoashort.So,theuseofthe'short'typemayhaveagreaterimpactthanmemoryusage.解决方案避免使用short类型:Java使用’short’类型来减少内存开销,而不是优化计算。事实上,JVM不具备short类型的算术能力:jvm必须将short类型转化为int类型,然后进行适当的计算再把int类型转回short类型。因此,和内存开销比起来使AvoidUsingVolatile:Useofthekeyword'volatile'isgeneralusedtofinetuneaJavaapplication,andtherefore,requiresagoodexpertiseoftheJavaMemoryModel.Moreover,itsrangeofactionissomewhatmisknown.Therefore,thevolatilekeywordshouldnotbeusedformaintenancepurposeandportability.解决方案避免使用Volatile’volatile’Java需要一个专业的Java内存模型。此外,它的作用范围一定程度上是令人误解的。因此,volatile关键字应该不要被用做和移植的目的。AvoidUsingNativeCode:AsJVMandJavalanguageofferalreadymanyhelpincreatingapplication,itshouldbeveryraretohavetorelyonnon-javacode.Eventhough,itisraretoactuallyhavetouseJavaNativeInterface(JNI).AstheuseofJNImakeapplicationlessportable,andhardertomaintain,itis解决方案避免使用本地代码:jvm和Java语言已经提供了很多创建应用程序的帮助,依赖非Java代码应该是非常罕见的。即使如此,事实上必须使用Java本地接口也是罕见的。因为使用JNI使得应用可移植性降低,而且难以,所以是不推荐的。AvoidAccessibilityAlteration:MethodssuchasgetDeclaredConstructors(),getDeclaredConstructor(Class[])andsetAccessible(),astheinterfacePrivilegedAction,allowtoalter,atruntime,thevisilibiltyofvariable,classes,ormethods,eveniftheyareprivate.Obviously,nooneshoulddoso,assuchbehaviorisagainsteverythingencapsulationprincipalstandsfor.解决方案避免变控制gtclardCostrucor(),gtclardCosrucr(Cass[])和stccssil(),还有PiilgdctionDoNotCallGarbageCollectionExplicitly:CallstoSystem.gc(),Runtime.getRuntime().gc(),andSystem.runFinalization()arenotadvised.Codeshouldhavethesamebehaviorwhetherthegarbagecollectionisdisabledusingtheoption-Xdisableexplicitgcornot.Moreover,"modern"jvmsdoaverygoodjobhandlinggarbagecollections.Ifmemoryusageissuesunrelatedtomemoryleaksdevelopwithinanapplication,itshouldbedealtwithJVMoptionsratherthanwithinthecodeitself.解决方案不要显示的调用收集器:调用System.gc(),Runtime.getRuntime().gc(),和System.runFinalization()是不推荐的。当收集器使用配置项-Xdisableexplicitgc关闭时,使用代码可以同样进行收集。此外,现代JVM对于收集工作做得很棒。当开发一个应用时内存使用的影响无关于内存泄露时,收集应该交给JVM配置项进行管理而非代码本身。PMDCouplingCouplingBetweenObjects:Thisrulecountsuniqueattributes,localvariablesandreturntypeswithinanobject.Anumberhigherthanspecifiedthresholdcanindicateahighdegreeofcoupling.解决方案对象间的耦合:这个规则统计一个对象中单个的属性、本地变量和返回类型的ExcessiveImports:Ahighnumberofimportscanindicateahighdegreeofcouplingwithinanobject.Rulecountsthenumberofuniqueimportsandreportsaviolationifthecountisabovetheuserdefinedthreshold.解决方案过多的引入:大量的importimport数目,如果数目大于用户定义的上限则报告一个违例LooseCoupling:Avoidusingimplementationtypes(i.e.,HashSet);usetheinterface(i.e,Set)instead解决方案松耦合:避免使用具体实现类型(如:HashSet);用接口(如:Set)PMDDesignUseSingleton:Ifyouhaveaclassthathasnothingbutstaticmethods,considermakingitaSingleton.Notethatthisdoesn'tapplyto sincetheirsubclassesmaywellincludenon-staticmethods.Also,ifyouwantthisclasstobeaSingleton,remembertoaddaprivateconstructortoprevent解决方案使用单例:如果有一个类包含的只有静态方法,可以考虑做成单例的。注意这SimplifyBooleanReturns:Avoidunnecessaryif..then..elsestatementswhenreturningaboolean.解决方案简化布尔量的返回:避免在返回布尔量时写不必要的if..then..else表达式。publicclassFoo{privateintbar=2;publicbooleanisBarEqualsTo(intx)//thisbitofcodeif(bar==x){returntrue;}else{returnfalse;}////returnbar==}}SimplifyBooleanExpressions:Avoidunnecessarycomparisonsinbooleanexpressions-thiscomplicatessimplecode.解决方案简化布尔表达式:避免布尔表达式之间无用的比较——只会使代码复杂化publicclassBar//下面可以简化为:bar=isFoo();privatebooleanbarisFootrue);publicisFoo(){return}SwitchStmtsShouldHaveDefault:Switchstatementsshouldhaveadefault解决方案Switch表达式应该有defaultAvoidDeeplyNestedIfStmts:Deeplynestedif..thenstatementsarehardto解决方案避免深度嵌套的if表达式:深度嵌套的if..thenAvoidReassigningParameters:Reassigningvaluestoparametersisaquestionablepractice.Useatemporarylocalvariableinstead.解决方案避免给参数重新赋值:给传入方法的参数重新赋值是一种需要商榷的行为。使SwitchDensity:Ahighratioofstatementstolabelsinaswitchstatementimpliesthattheswitchstatementisngtoomuchwork.Considermovingthestatementsintonewmethods,orcreatingsubclassesbasedontheswitch解决方案密集的switch:switch表达式的case块中出现很高比例的表达式语句表明switch表达式做了太多的工作。考虑将表达式语句写进一个新的方法,或者创建基于switch变量的子类。publicclassFoo{publicvoidbar(intx){switch(x){case1:{//lotsofstatements}case2://lotsofstatements}}}}ConstructorCallsOverridableMethod:Callingoverridablemethodsduringconstructionposesariskofinvokingmethodsonan pleyconstructedobjectandcanbedifficulttodiscern.Itmayleavethesub-classunabletoconstructitssuperclassorforcedtoreplicatetheconstructionprocesscompleywithinitself,losingtheabilitytocallsuper().Ifthedefaultconstructorcontainsacalltoanoverridablemethod,thesubclassmaybecompleyuninstantiable.Notethatthisincludesmethodcallsthroughoutthecontrolflowgraph-i.e.,ifaconstructorFoo()callsaprivatemethodbar()thatcallsapublicmethodbuz(),thisdenotesaproblem.解决方案构造器调用了可重写的方法在构造器中调用可被覆盖的方法可能在一个的方法调用——例如:如果构造器Foo()调用了私有方法bar(),而bar()又调用了公开的方法buz(),这就会导致问题。publicclassSeniorClass{publicSeniorClass(){toString();//maythrowNullPointerExceptionif}publicStringtoString(){return"IAmSeniorClass";}}publicclassJuniorClassextendsSeniorClass{privateStringname;publicsuper();//AutomaticcallleadstoNullPointerExceptionname="JuniorClass";}publicStringtoString(){returnname.toUpperCase();}}AccessorClassGeneration:Instantiationbywayofprivateconstructorsfromoutsideoftheconstructor'sclassoftencausesthegenerationofanaccessor.Afactorymethod,ornon-privitizationoftheconstructorcaneliminatethissituation.Thegeneratedclassfileisactuallyaninterface.Itgivestheaccessingclasstheabilitytoinvokeanewhiddenpackagescopeconstructorthattakestheinterfaceasasupplementaryparameter.Thisturnsaprivateconstructoreffectivelyintoonewithpackagescope,andischallengingtodiscern.解决方案存取器类生成:从一个具有私有构建器的类的外部实例化这个类通常会导致存publicclassOuter{voidmethod(){Inneric=newInner();//Causesgenerationofaccessor}publicclassInner{privateInner(){}}}FinalFieldCouldBeStatic:Ifafinalfieldisassignedtoacompile-timeconstant,itcouldbemadestatic,thussavingoverheadineachobjectat解决方案final类型的域可以同时是static的:如果一个final类型的域在编译时被赋值为常量,它也可以是static的,那样就在每个对象运行时节省开支。CloseResource:Ensurethatresources(likeConnection,Statement,andResultSetobjects)arealwaysclosedafteruse.解决方案关闭资源:确保这些资源(譬如:Connection,Statement,和ResultSet对NonStaticInitializer:Anonstaticinitializerblockwillbecalledanytimeaconstructorisinvoked(justpriortoinvokingtheconstructor).Whilethisisavalidlanguageconstruct,itisrarelyusedandisconfusing.解决方案非静态的初始化器:非静态的初始化块将在构造器被调用的时候被(优先publicclassMyClass//thisblockgetsrunbeforeanycalltoa{System.out.println("Iamabouttoconstruct}}DefaultLabelNotLastInSwitchStmt:Byconvention,thedefaultlabelshouldbethelastlabelinaswitchstatement.解决方案switch表达式中default块应该在最后:按照惯例,default应该switch表达式的最后一个NonCaseLabelInSwitchStatement:Anon-caselabel(e.g.anamedbreak/continuelabel)waspresentinaswitchstatement.Thislegal,butconfusing.Itiseasytomixupthecaselabelsandthenon-caselabels.解决方案switch表达式中没有case在switch表达式中没有case,是合法的,但是容易造成迷惑。容易将case和非case。OptimizableToArrayCall:AcalltoCollection.toArraycanusetheCollection'ssizevsanemptyArrayofthedesiredtype.解决方案优化toArray调用:调用Collection.toArray时使用集合的规模加上目标类classFoovoidbar(Collectionx)//Abitinefficientx.toArray(newFoo[0]);//Muchbetter;thisonesizesthedestinationarray,//areflectioncallinsomeCollectionimplementationsx.toArray(newFoo[x.size()]);}}parison:AvoidequalitycomparisonswithDouble.NaN-thesearelikelytobelogicerrors.解决方案错误的比较:避免Double.NaN的相等性比较-EqualsNull:Inexperiencedprogrammerssometimesconfusecomparisonconceptsanduseequals()tocomparetonull.equals()方法和null比较ConfusingTernary:Inan"if"expressionwithan"else"clause,avoidnegationinthetest.Forexample,rephrase:if(x!=y)diff();elsesame();as:if(x==y)same();elsediff();Most"if(x!=
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2022年个人年度工作计划
- 社区年度工作计划大全8篇
- 普通员工辞职申请书合集5篇
- 2024年度镍矿贸易代理佣金合同范本3篇
- 2024年度汽车品牌授权销售代理合同3篇
- 家具活动销售工作总结
- 关于大一新生对大学四年规划的调查报告
- 《大自然的文字》教学课件 张建昊
- 《工作态度与心态》课件
- 卷05-备战2022年中考生物【名校地市好题必刷】全真模拟卷(福建卷)(解析版)
- 应用PDCA提高入院宣教的知晓率
- 医疗质量(安全)不良事件报告制度
- 清热泻火药-黄芩、黄连、黄柏(方剂学课件)
- 【老年糖尿病患者夜间易发低血糖的原因及预防措施分析报告(论文)4600字】
- 居家养老服务组织(社区居家养老服务课件)
- 消防安全重点单位规范化管理手册
- 【拓展阅读】类文阅读《王羲之吃墨》
- 国家开放大学《高等数学基础》形考任务1-4参考答案
- 食品营养学(华东理工大学)智慧树知到答案章节测试2023年
- 液压升降机设计02
- 油墨检验报告表
评论
0/150
提交评论