您好,欢迎访问三七文档
当前位置:首页 > 临时分类 > sonar检测规则初步整理
sonar检测规则初步整理title英文详解错误示例中文解释AnonInnerLengthChecksforlonganonymousinnerclasses匿名内部类长度限制AvoidArrayLoopsInsteadofcopyingdatabetweentwoarrays,useSystem.arrayCopymethod两个数组之间复制数据,使用System.arrayCopy方法AvoidAssertAsIdentifierFindsallplaces'assert'isusedasanidentifierisused.避免'assert'做为标识AvoidCallingFinalizeObject.finalize()iscalledbythegarbagecollectoronanobjectwhengarbagecollectiondeterminesthattherearenomorereferencestotheobject.禁止使用Object.finalize()AvoidCatchingNPECodeshouldneverthrowNPEundernormalcircumstances.Acatchblockmayhidetheoriginalerror,causingothermoresubtleerrorsinitswake.代码可能会抛出无法被TRY捕获的异常.AvoidCatchingThrowableThisisdangerousbecauseitcaststoowideanet;itcancatchthingslikeOutOfMemoryError.AvoidDecimalLiteralsInBigDecimalConstructorOnemightassumethatnewBigDecimal(.1)isexactlyequalto.1,butitisactuallyequalto.1000000000000000055511151231257827021181583404541015625.Thisissobecause.1cannotberepresentedexactlyasadouble(or,forthatmatter,asabinaryfractionofanyfinitelength).Thus,thelongvaluethatisbeingpassedintotheconstructorisnotexactlyequalto.1,appearancesnotwithstanding.The(String)constructor,ontheotherhand,isperfectlypredictable:'newBigDecimal(.1)'isexactlyequalto.1,asonewouldexpect.Therefore,itisgenerallyrecommendedthatthe(String)constructorbeusedinpreferencetothisone.Key:AvoidDecimalLiteralsInBigDecimalConstructor尽量避免BigDecimal(.1)因为它实际上等于它实际上等于.1000000000000000055511151231257827021181583404541015625.而不是0.1AvoidDuplicateLiteralsCodecontainingduplicateStringliteralscanusuallybeimprovedbydeclaringtheStringasaconstantfield.Example:map.put(tyName,0);AvoidDuplicateLiterals:TheStringliteraltyNameappears4timesinthisfile;thefirstoccurrenc代码包含重复的字符串,通常可以声明为一个常量字段的字符串AvoidEnumAsIdentifierFindsallplaces'enum'isusedasanidentifierisused.避免'enum'作为标识符AvoidInstanceofChecksInCatchClauseEachcaughtexceptiontypeshouldbehandledinitsowncatchclause每个捕获的异常类型应该是在自己的catch子句处理AvoidPrintStackTraceAvoidprintStackTrace();usealoggercallinstead.避免打印堆栈跟踪(printStackTrace())AvoidRethrowingExceptionCatchblocksthatmerelyrethrowacaughtexceptiononlyaddtocodesizeandruntimecomplexity.避免在catch块重新抛出异常AvoidThrowingNullPointerExceptionAvoidthrowingaNullPointerException-it'sconfusingbecausemostpeoplewillassumethatthevirtualmachinethrewit.ConsiderusinganIllegalArgumentExceptioninstead;thiswillbeclearlyseenasaprogrammer-initiatedexception.避免抛出一个NullPointerException-这会混淆,因为多数人会认为已经被虚拟机回收。考虑使用一个IllegalArgumentException代替,这将让程序员清楚知道开始出现何种异常。AvoidThrowingRawExceptionTypesAvoidthrowingcertainexceptiontypes.RatherthanthrowarawRuntimeException,Throwable,Exception,orError,useasubclassedexceptionorerrorinstead.BigIntegerInstantiationDon'tcreateinstancesofalreadyexistingBigInteger(BigInteger.ZERO,BigInteger.ONE)andfor1.5on,BigInteger.TENandBigDecimal(BigDecimal.ZERO,BigDecimal.ONE,BigDecimal.TEN)BooleanExpressionComplexityRestrictsnestedbooleanoperators(&&,||and^)toaspecifieddepth(default=3).if(gameName!=&&tyName!=&&aaName!=&&srName!=&&typeName!=){BooleanExpressionComplexity:Booleanexpressioncomplexityis4布尔表达式的个数个数不能超过4个BooleanInstantiationAvoidinstantiatingBooleanobjects;youcanreferenceBoolean.TRUE,Boolean.FALSE,orcallBoolean.valueOf()instead免布尔对象实例化,你可以使用Boolean.TRUE,Boolean.FALSE,或Boolean.valueOf()代替BrokenNullCheckThenullcheckisbrokensinceitwillthrowaNullpointeritself.Thereasonisthatamethodiscalledontheobjectwhenitisnull.Itislikelythatyouused||insteadof&&orviceversa.在使用一个对象的方法时,对象已经为空,抛出异常NullpointerClassCastExceptionWithToArrayifyouneedtogetanarrayofaclassfromyourCollection,youshouldpassanarrayofthedesideredclassastheparameterofthetoArraymethod.OtherwiseyouwillgetaClassCastException.从集合中通过.toArray()获取数组时候应该传递一个类型参数.(String[]tt=(String[])list.toArray(newString[0]);).否则会返回类型转换异常错误CloneThrowsCloneNotSupportedExceptionThemethodclone()shouldthrowaCloneNotSupportedException.不支持CloneNotSupportedException异常。CloseResourceEnsurethatresources(likeConnection,Statement,andResultSetobjects)arealwaysclosedafteruse.ItdoesthisbylookingforcodepatternedlikeConnectionc=openConnection();try{//dostuff,andmaybecatchsomething}finally{c.close();}CollapsibleIfStatementsSometimestwo'if'statementscanbeconsolidatedbyseparatingtheirconditionswithabooleanshort-circuitoperator如果有两个IF可以通过短路条件替代CompareObjectsWithEquals用equals()而不是==ConstantNameChecksthatconstantnamesconformtoaformatspecifiedbytheformatproperty.privatestaticfinalLoggerlogger=LoggerFactory.getLogger(SearchController.class);ConstantName:Name'logger'mustmatchpattern'^[A-Z][A-Z0-9]*(_[A-Z0-常量命名应该全大写ConstructorCallsOverridableMethodCallingoverridablemethodsduringconstructionposesariskofinvokingmethodsonanincompletelyconstructedobjectandcanbedifficulttodiscern.Itmayleavethesub-classunabletoconstructitssuperclassorforcedtoreplicatetheconstructionprocesscompletelywithinitself,losingtheabilitytocallsuper().Ifthedefaultconstructorcontainsacalltoanoverridablemethod,thesubclassmaybecompletelyuninstantiable.Notethatthisincludesmethodcallsthroughoutthecontrolflowgraph-i.e.,ifaconstructorFoo()callsaprivatemethodbar()thatcallsapublicmeth
本文标题:sonar检测规则初步整理
链接地址:https://www.777doc.com/doc-7845911 .html