集成myeclipse附使用說明-pmd規(guī)則翻譯合集_第1頁
集成myeclipse附使用說明-pmd規(guī)則翻譯合集_第2頁
集成myeclipse附使用說明-pmd規(guī)則翻譯合集_第3頁
集成myeclipse附使用說明-pmd規(guī)則翻譯合集_第4頁
集成myeclipse附使用說明-pmd規(guī)則翻譯合集_第5頁
已閱讀5頁,還剩57頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

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塊沒做任何異常處理的事,在大多數(shù)情形EmptyIfStmt:EmptyIfStatementfindsinstanceswhereaconditionischeckedbutnothingisdoneaboutit.解決方 空的if表達(dá)式:發(fā)現(xiàn)使用if進行了條件判斷,但是判斷之后沒做任何處EmptyWhileStmt:EmptyWhileStatementfindsallinstanceswhereawhilestatementdoesnothing.Ifitisatimingloop,thenyoushoulduseThread.sleep()forit;ifit'sawhileloopthatdoesalotintheexitexpression,rewriteittomakeitclearer.解決方案空的while表達(dá)式:發(fā)現(xiàn)空的while表達(dá)式,如果是一個定時的循環(huán),你應(yīng)該在循環(huán)體內(nèi)使用Thread.sleep();如果是對于退出處理做的一個處理大量事情的while循環(huán),重寫代碼使它更清晰EmptyTryBlock:Avoidemptytryblocks-what'sthe解決方案空的try塊:避免空的tryEmptyFinallyBlock:Avoidemptyfinallyblocks-thesecanbe解決方案空的finally塊:避免空的finally塊-EmptySwitchStatements:Avoidemptyswitch解決方案空的switch表達(dá)式:避免空的switchJumbledIncrementer:Avoidjumbledloopincrementers-it'susuallyamistake,andit'sconfusingevenifit'swhat'sintended.解決方案避免的循環(huán)增量-它常常是一個錯誤,而且容易讓人迷publicclassJumbledIncrementerRule1{publicvoidfoo(){for(inti=0;i<10;i++){for(intk=0;k<20;i++){}}}}ForLoopShouldBeWhileLoop:Someforloopscanbesimplifiedtowhileloops-thismakesthemmoreconcise.解決方案有些for循環(huán)可以簡化為while循環(huán)-這樣可以更加簡明publicclassFoo{voidbar(){fortruetrue;//沒有初始化塊和變化塊,相當(dāng)于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中有時候創(chuàng)建的對象是通過雙重檢查機制獲取的,一個優(yōu)化的JRE可能在真正創(chuàng)建對象之前先將指向這個對象的賦給一個變量,如baz,需要細(xì)節(jié)參考: publicclassFoo{Objectbaz;Objectbar(){/**這里當(dāng)對象沒創(chuàng)建完時也可能判斷不為空,那么在多線程環(huán)境下,就可能導(dǎo)致某些線程使用bar()方法后直接返回一個未指向完整對象的baz,從而發(fā)生錯誤,.aspx if(baz==null){if(baz==baz=new}}}return}}ReturnFromFinallyBlock:Avoidreturningfromafinallyblock-thiscandiscardexceptions. 從finally塊中返避免從finally塊中返回-這會導(dǎo)致異常捕獲后又被拋棄.publicclassBar{publicStringfoo(){try{thrownewException("MyException"}catch(Exceptione){throwe;}finallyreturnAOK.";//.這句導(dǎo)致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表達(dá)式:當(dāng)表達(dá)式總是為真或總為假時,不要用ifpublicclassFoo{publicvoidclose(){if(true){//}}}EmptyStatementNotInLoop:Anemptystatement(akaasemicolonbyitself)thatisnotusedasthesolebodyofaforlooporwhileloopisprobablyabug.Itcouldalsobeadoublesemicolon,whichisuselessandshouldbe解決方案非循環(huán)中不要有空的表達(dá)式:在一個非for循環(huán)或非while循環(huán)體中使用的一個空的表達(dá)式(或者稱為一個分號)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修飾符:注意當(dāng)一個類被fianl修飾時,所有這個類的方法就自動變?yōu)閒inal類型了CollapsibleIfStatements:Sometimestwo'if'statementscanbeconsolidatedbyseparatingtheirconditionswithabooleanshort-circuit 分解的if表達(dá)式:有時候兩個if語句可以通過布爾短路操作符分隔條件表UselessOverridingMethod:Theoverridingmethodmerelycallsthesamemethoddefinedinasuperclass解決方 ClassCastExceptionWithToArray:ifyouneedtogetanarrayofaclassfromyourCollection,youshouldpassanarrayofthedesideredclassastheparameterofthetoArraymethod.Otherwiseyouwillgeta toArray時類型轉(zhuǎn)換異常:如果你想從一個枚舉類型中得到某個類型的數(shù)組,你應(yīng)該傳給toArray()方法一個目的類型的數(shù)組作為參數(shù),否則你可能得到一個類型轉(zhuǎn)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類型的構(gòu)造方法中用小數(shù)類型的字面量:人們常常以為”newBigDecimal(0.1)”能精確等于0.1,其實不然,它等于“0.5”,這0.1long類型不等0.1,而傳入String類型的構(gòu)造器newBigDecimal(“0.1”)可以精確等于0.1,故推薦這種情形時用String類型的構(gòu)造器UselessOperationOnImmutable:AnoperationonanImmutableobject(String,BigDecimalorBigInteger)won'tchangetheobjectitself.Theresultoftheoperationisanewobject.Therefore,ignoringtheoperationresultisan 對于不變類型的無用操作:對于不變類型對象(String,BigDecimal或BigInteger)的操作不會改變對象本身,但操作結(jié)果是產(chǎn)生新的對象,所以,忽略操作importjava.math.*;classTest{voidmethod1()BigDecimalbd=newBigDecimal(10);bd.add(newBigDecimal(5這里違背了規(guī)則}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()時無用的空檢查:在對一個對象進行完空檢查后,你應(yīng)該在這個對象上調(diào)用equals()方法而不是將它傳給另一個對象的equals()方法作為AvoidThreadGroup:AvoidusingThreadGroup;althoughitisintendedtobeusedinathreadedenvironmentitcontainsmethodsthatarenotthread publicclassBar{voidbuz(){ThreadGrouptg=newThreadGroup("Mythreadgroup");tg=newThreadGroup(tg,"mythreadgroup");tg=tg=}}BrokenNullCheck:ThenullcheckisbrokensinceitwillthrowaNullPointerExceptionitself.Itislikelythatyouused||insteadof&&orvice解決方 代替&&classFooStringbar(Stringstring)//這里應(yīng)該是if(string!=null||!string.equals(""))returnstring;//這里應(yīng)該是if(string==null&&string.equals(""))returnstring;}}BigIntegerInstantiation:Don'tcreateinstancesofalreadyexistingBigInteger(BigInteger.ZERO,BigInteger.ONE)andfor1.5on,BigInteger.TENandBigDecimal(BigDecimal.ZERO,BigDecimal.ONE,BigDecimal.TEN) BigInteger實例化:不要創(chuàng)建已經(jīng)存在的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硬編碼:一個應(yīng)用中的硬編碼IP將使系統(tǒng)在某些情況下無法CheckResultSet:Alwayscheckthereturnofoneofthenavigationmethod(next,previous,first,last)ofaResultSet.Indeed,ifthevaluereturnis'false',thedevelopershoulddealwithit!解決方 檢查ResultSet:總是需要檢查ResultSet對象的導(dǎo)航方(next,previous,first,last)的返回,事實上,如果返回false,開發(fā)者需要處理//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,或者考慮簡化表達(dá)//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循環(huán)必須使用括號:避免使用while塊時不使用IfElseStmtsMustUseBraces:Avoidusingif..elsestatementswithoutusingcurlybraces.解決方案if…else…塊必須使用括號:避免使用if…else…塊時不使用ForLoopsMustUseBraces:Avoidusing'for'statementswithoutusingcurly解決方案for循環(huán)必須使用括號:避免在for循環(huán)時不使用PMDCloneImplementationProperCloneImplementation:Objectclone()shouldbeimplementedwith解決方案適當(dāng)?shù)目寺崿F(xiàn):對象的clone()方法中應(yīng)該包含super.clone()CloneThrowsCloneNotSupportedException:Themethodclone()shouldthrowaCloneNotSupportedException.解決方案克隆方法要拋出不支持克隆異常:clone()CloneMethodMustImplementCloneableThemethodcloneshouldonlybeimplementediftheclassimplementstheCloneableinterfacewiththeexceptionofafinalmethodthatonlythrowsCloneNotSupportedException.解決方案克隆方法必須實現(xiàn)Cloneable接口:如果類實現(xiàn)Cloneable接口,clone()方法應(yīng)該被實現(xiàn)為一個final的方法并且只拋出CloneNotSupportedException的異常PMDCodeSizeplexity:TheNPathcomplexityofamethodisthenumberofacyclicexecutionpathsthroughthatmethod.Athresholdof200isgenerallyconsideredthepointwheremeasuresshouldbetakentoreducecomplexity.解決方案200作為考慮降低復(fù)雜度的臨界點ExcessiveMethodLength:Violationsofthisruleusuallyindicatethatthemethodisngtoomuch.Trytoreducethemethodsizebycreatinghelpermethodsandremovinganycopy/pastedcode.解決方案方法太長:這種違例就是方法中做了太多事,通過創(chuàng)建輔助方法或移除拷貝/ExcessiveParameterList:Longparameterlistscanindicatethatanewobjectshouldbecreatedtowrapthenumerousparameters.Basically,trytogrouptheparameterstogether.解決方案太多的參數(shù):過長的參數(shù)列表表明應(yīng)該創(chuàng)建一個新的對象包裝眾多的參數(shù)值,ExcessiveClassLength:LongClassfilesareindicationsthattheclassmaybetryingtodotoomuch.Trytobreakitdown,andreducethesizetosomethingmanageable.解決方案太長的類:太長的類文件表明類試圖做太多的事,試著分解它,減少到易于管plexity:Complexityisdeterminedbythenumberofdecisionpointsinamethodplusoneforthemethodentry.Thedecisionpointsare'if','while','for',and'caselabels'.Generally,1-4islowcomplexity,5-7indicatesmoderatecomplexity,8-10ishighcomplexity,and11+isveryhigh解決方案秩復(fù)雜性:由if,while,for,caselabels等決策點確定的復(fù)雜度,1-4是低復(fù)雜度,5-7為中,810是高復(fù)雜度,11以上是非常高ExcessivePublicCount:Alargenumberofpublicmethodsandattributesdeclaredinaclasscanindicatetheclassmayneedtobebrokenupasincreasedeffortwillberequiredtothoroughlytestit.解決方案過多的公共成員:一個類中如果了大量的公共方法和屬性表明類需要分TooManyFields:Classesthathavetoomanyfieldscouldberedesignedtohavefewerfields,possiblythroughsomenestedobjectgrouofsomeoftheinformation.Forexample,aclasswithcity/state/zipfieldscouldinsteadhaveoneAddressfield.解決方案太多的域:類包含太多域可以被重新設(shè)計為包含更少的域,可以通過將一些信息組織為嵌套類。比如:一個類包含了city/state/zip域,可以用一個Address域組NcssMethodCount:ThisruleusestheNCSS(NonCommentingSourceStatements)algorithmtodeterminethenumberoflinesofcodeforagivenmethod.NCSSignorescomments,andcountsactualstatements.Usingthisalgorithm,linesofcodethataresplitarecountedasone.解決方案NCSS方法代碼計算:這個規(guī)則采用NCSS(非注釋代碼塊)算法計算給定的1.(也同時忽略空行)NcssTypeCount:ThisruleusestheNCSS(NonCommentingSourceStatements)algorithmtodeterminethenumberoflinesofcodeforagiventype.NCSSignorescomments,andcountsactualstatements.Usingthisalgorithm,linesofcodethataresplitarecountedasone.解決方案NCSSNCSS(非注釋代碼塊)算法計算給定類型的1.(也同時忽略空行)NcssConstructorCount:ThisruleusestheNCSS(NonCommentingSourceStatements)algorithmtodeterminethenumberoflinesofcodeforagivenconstructor.NCSSignorescomments,andcountsactualstatements.Usingthisalgorithm,linesofcodethataresplitarecountedasone.解決方案NCSSNCSS(非注釋代碼塊)算法計算給定的構(gòu)造方法的代碼行數(shù)。NCSS忽略代碼中的注釋并且計算實際代碼行數(shù)。用這種算法,1.(也同時忽略空行)TooManyMethods:Aclasswithtoomanymethodsisprobablyagoodforrefactoring,inordertoreduceitscomplexityandfindawaytohavemorefinegrainedobjects.解決方案太多的方法:類中包含太多方法可能需要重構(gòu),以減低復(fù)雜度和獲取更加細(xì)粒PMDControversialUnnecessaryConstructor:Thisruledetectswhenaconstructorisnotnecessary;i.e.,whenthere'sonlyoneconstructor,it'spublic,hasanemptybody,andtakesnoarguments.解決方案非必要的構(gòu)造器:本規(guī)則檢查不必要的構(gòu)造器,例如:只存在一個公共的,空NullAssignment:Assigninga"null"toavariable(outsideofitsdeclaration)isusuallybadform.Sometimes,theassignmentisanindicationthattheprogrammerdoesn'tcompleyunderstandwhatisgoingoninthecode.NOTE:Thissortofassignmentmayinrarecasesbeusefultoencouragegarbagecollection.Ifthat'swhatyou'reusingitfor,byallmeans,disregardthisrule:-)解決方案Null賦值:將null賦值給變量(在之外)常常是不好的形式。某些時候這備注:當(dāng)你需要把變量賦值為null提示收集器去進行收集時這是有用的,那么OnlyOneReturn:Amethodshouldhaveonlyoneexitpoint,andthatshouldbethelaststatementinthemethod.解決方案只有一個返回:一個方法應(yīng)該有且只有一處返回點,且應(yīng)該是方法的最后一條UnusedModifier:Fieldsininterfacesareautomaticallypublicstaticfinal,andmethodsarepublic .Classesorinterfacesnestedinaninterfaceareautomaticallypublicandstatic(allnestedinterfacesareautomaticallystatic).Forhistoricalreasons,modifierswhichareimpliedbythecontextareacceptedbythecompiler,butaresuperfluous.解決方案無用的修飾符:在接口中定義的域自動為publicstaticfinal的,方法自動是 AssignmentInOperand:Avoidassignmentsinoperands;thiscanmakecodemorecomplicatedandhardertoread.publicclassFoo{publicvoidbar(){intx=2;if((x=getX())==3)}}privateintgetX(){return3;}}AtLeastOneConstructor:Eachclassshoulddeclareatleastone解決方案至少有一個構(gòu)造器:每個類應(yīng)該至少一個構(gòu)造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語言規(guī)范(3.10.6節(jié))講到:在一個字面量字符串中的八進制轉(zhuǎn)義序列應(yīng)該||0~3CallSuperInConstructor:Itisagoodpracticetocallsuper()inaconstructor.Ifsuper()isnotcalledbutanotherconstructor(suchasanoverloadedconstructor)iscalled,thisrulewillnotreportit.解決方案在構(gòu)造器中調(diào)用super():在構(gòu)造器中調(diào)用super()方法是很好的做法.如果沒有調(diào)用super(),但是調(diào)用了另外的構(gòu)造器,那么這個規(guī)則不會報告出來。UnnecessaryParentheses:Sometimesexpressionsarewrappedinunnecessaryparentheses,makingthemlooklikeafunctioncall.解決方案不必要的圓括號:有時候表達(dá)式被包在一個不必要的圓括號中,使它們看起來publicclassFoobooleanbar(){return(true);}}DefaultPackage:UseexplicitscoinsteadofthedefaultpackageprivateBooleanInversion:Usebitwiseinversiontoinvertbooleanvalues-it'sthefastestwaytodothis.Seeen_USforspecific解決方案布爾轉(zhuǎn)換:使用按位轉(zhuǎn)換來轉(zhuǎn)換布爾值-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.解決方案數(shù)據(jù)流異常分析數(shù)據(jù)流分析是本地的變量定義與否及在數(shù)據(jù)流中不同路是bug2.DU-異常:一個剛剛定義的變量是未定義的。這些異常可能出現(xiàn)3.DD-異常:一個剛剛定義的變量重新定義。這是不好的但并非一定是個bug。publicclassFoo{publicvoidfoo(){intbuz=buz=6;//redefinitionofbuz->dd-anomalybuz=}//buzisundefinedwhenleavingscope->du-}AvoidFinalLocalVariable:Avoidusingfinallocalvariables,turntheminto解決方案避免Final類型的本地變量:避免使用final類型的本地變量,將它們轉(zhuǎn)為類publicclassMyClass{publicvoidfoo()finalString}}AvoidUsingShortType:Javausesthe'short'typetoreducememoryusage,nottooptimizecalculation.Infact,thejvmdoesnothaveanyarithmeticcapabilitiesfortheshorttype:thejvmmustconverttheshortintoanint,dothepropercaculationandconverttheintbacktoashort.So,theuseofthe'short'typemayhaveagreaterimpactthanmemoryusage.解決方案避免使用short類型:Java使用’short’類型來減少內(nèi)存開銷,而不是優(yōu)化計算。事實上,JVM不具備short類型的算術(shù)能力:jvm必須將short類型轉(zhuǎn)化為int類型,然后進行適當(dāng)?shù)挠嬎阍侔裪nt類型轉(zhuǎn)回short類型。因此,和內(nèi)存開銷比起來使AvoidUsingVolatile:Useofthekeyword'volatile'isgeneralusedtofinetuneaJavaapplication,andtherefore,requiresagoodexpertiseoftheJavaMemoryModel.Moreover,itsrangeofactionissomewhatmisknown.Therefore,thevolatilekeywordshouldnotbeusedformaintenancepurposeandportability.解決方案避免使用Volatile’volatile’Java需要一個專業(yè)的Java內(nèi)存模型。此外,它的作用范圍一定程度上是令人誤解的。因此,volatile關(guān)鍵字應(yīng)該不要被用做和移植的目的。AvoidUsingNativeCode:AsJVMandJavalanguageofferalreadymanyhelpincreatingapplication,itshouldbeveryraretohavetorelyonnon-javacode.Eventhough,itisraretoactuallyhavetouseJavaNativeInterface(JNI).AstheuseofJNImakeapplicationlessportable,andhardertomaintain,itis解決方案避免使用本地代碼:jvm和Java語言已經(jīng)提供了很多創(chuàng)建應(yīng)用程序的幫助,依賴非Java代碼應(yīng)該是非常罕見的。即使如此,事實上必須使用Java本地接口也是罕見的。因為使用JNI使得應(yīng)用可移植性降低,而且難以,所以是不推薦的。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.解決方案不要顯示的調(diào)用收集器:調(diào)用System.gc(),Runtime.getRuntime().gc(),和System.runFinalization()是不推薦的。當(dāng)收集器使用配置項-Xdisableexplicitgc關(guān)閉時,使用代碼可以同樣進行收集。此外,現(xiàn)代JVM對于收集工作做得很棒。當(dāng)開發(fā)一個應(yīng)用時內(nèi)存使用的影響無關(guān)于內(nèi)存泄露時,收集應(yīng)該交給JVM配置項進行管理而非代碼本身。PMDCouplingCouplingBetweenObjects:Thisrulecountsuniqueattributes,localvariablesandreturntypeswithinanobject.Anumberhigherthanspecifiedthresholdcanindicateahighdegreeofcoupling.解決方案對象間的耦合:這個規(guī)則統(tǒng)計一個對象中單個的屬性、本地變量和返回類型的ExcessiveImports:Ahighnumberofimportscanindicateahighdegreeofcouplingwithinanobject.Rulecountsthenumberofuniqueimportsandreportsaviolationifthecountisabovetheuserdefinedthreshold.解決方案過多的引入:大量的importimport數(shù)目,如果數(shù)目大于用戶定義的上限則報告一個違例LooseCoupling:Avoidusingimplementationtypes(i.e.,HashSet);usetheinterface(i.e,Set)instead解決方案松耦合:避免使用具體實現(xiàn)類型(如:HashSet);用接口(如:Set)PMDDesignUseSingleton:Ifyouhaveaclassthathasnothingbutstaticmethods,considermakingitaSingleton.Notethatthisdoesn'tapplyto sincetheirsubclassesmaywellincludenon-staticmethods.Also,ifyouwantthisclasstobeaSingleton,remembertoaddaprivateconstructortoprevent解決方案使用單例:如果有一個類包含的只有靜態(tài)方法,可以考慮做成單例的。注意這SimplifyBooleanReturns:Avoidunnecessaryif..then..elsestatementswhenreturningaboolean.解決方案簡化布爾量的返回:避免在返回布爾量時寫不必要的if..then..else表達(dá)式。publicclassFoo{privateintbar=2;publicbooleanisBarEqualsTo(intx)//thisbitofcodeif(bar==x){returntrue;}else{returnfalse;}////returnbar==}}SimplifyBooleanExpressions:Avoidunnecessarycomparisonsinbooleanexpressions-thiscomplicatessimplecode.解決方案簡化布爾表達(dá)式:避免布爾表達(dá)式之間無用的比較——只會使代碼復(fù)雜化publicclassBar//下面可以簡化為:bar=isFoo();privatebooleanbarisFootrue);publicisFoo(){return}SwitchStmtsShouldHaveDefault:Switchstatementsshouldhaveadefault解決方案Switch表達(dá)式應(yīng)該有defaultAvoidDeeplyNestedIfStmts:Deeplynestedif..thenstatementsarehardto解決方案避免深度嵌套的if表達(dá)式:深度嵌套的if..thenAvoidReassigningParameters:Reassigningvaluestoparametersisaquestionablepractice.Useatemporarylocalvariableinstead.解決方案避免給參數(shù)重新賦值:給傳入方法的參數(shù)重新賦值是一種需要商榷的行為。使SwitchDensity:Ahighratioofstatementstolabelsinaswitchstatementimpliesthattheswitchstatementisngtoomuchwork.Considermovingthestatementsintonewmethods,orcreatingsubclassesbasedontheswitch解決方案密集的switch:switch表達(dá)式的case塊中出現(xiàn)很高比例的表達(dá)式語句表明switch表達(dá)式做了太多的工作??紤]將表達(dá)式語句寫進一個新的方法,或者創(chuàng)建基于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.解決方案構(gòu)造器調(diào)用了可重寫的方法在構(gòu)造器中調(diào)用可被覆蓋的方法可能在一個的方法調(diào)用——例如:如果構(gòu)造器Foo()調(diào)用了私有方法bar(),而bar()又調(diào)用了公開的方法buz(),這就會導(dǎo)致問題。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.解決方案存取器類生成:從一個具有私有構(gòu)建器的類的外部實例化這個類通常會導(dǎo)致存publicclassOuter{voidmethod(){Inneric=newInner();//Causesgenerationofaccessor}publicclassInner{privateInner(){}}}FinalFieldCouldBeStatic:Ifafinalfieldisassignedtoacompile-timeconstant,itcouldbemadestatic,thussavingoverheadineachobjectat解決方案final類型的域可以同時是static的:如果一個final類型的域在編譯時被賦值為常量,它也可以是static的,那樣就在每個對象運行時節(jié)省開支。CloseResource:Ensurethatresources(likeConnection,Statement,andResultSetobjects)arealwaysclosedafteruse.解決方案關(guān)閉資源:確保這些資源(譬如:Connection,Statement,和ResultSet對NonStaticInitializer:Anonstaticinitializerblockwillbecalledanytimeaconstructorisinvoked(justpriortoinvokingtheconstructor).Whilethisisavalidlanguageconstruct,itisrarelyusedandisconfusing.解決方案非靜態(tài)的初始化器:非靜態(tài)的初始化塊將在構(gòu)造器被調(diào)用的時候被(優(yōu)先publicclassMyClass//thisblockgetsrunbeforeanycalltoa{System.out.println("Iamabouttoconstruct}}DefaultLabelNotLastInSwitchStmt:Byconvention,thedefaultlabelshouldbethelastlabelinaswitchstatement.解決方案switch表達(dá)式中default塊應(yīng)該在最后:按照慣例,default應(yīng)該switch表達(dá)式的最后一個NonCaseLabelInSwitchStatement:Anon-caselabel(e.g.anamedbreak/continuelabel)waspresentinaswitchstatement.Thislegal,butconfusing.Itiseasytomixupthecaselabelsandthenon-caselabels.解決方案switch表達(dá)式中沒有case在switch表達(dá)式中沒有case,是合法的,但是容易造成迷惑。容易將case和非case。OptimizableToArrayCall:AcalltoCollection.toArraycanusetheCollection'ssizevsanemptyArrayofthedesiredtype.解決方案優(yōu)化toArray調(diào)用:調(diào)用Collection.toArray時使用集合的規(guī)模加上目標(biāo)類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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論