sonar检测规则初步整理.docx

上传人:rrsccc 文档编号:9853674 上传时间:2021-03-30 格式:DOCX 页数:57 大小:37.34KB
返回 下载 相关 举报
sonar检测规则初步整理.docx_第1页
第1页 / 共57页
sonar检测规则初步整理.docx_第2页
第2页 / 共57页
sonar检测规则初步整理.docx_第3页
第3页 / 共57页
sonar检测规则初步整理.docx_第4页
第4页 / 共57页
亲,该文档总共57页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

《sonar检测规则初步整理.docx》由会员分享,可在线阅读,更多相关《sonar检测规则初步整理.docx(57页珍藏版)》请在三一文库上搜索。

1、sonar检测规则初步整理title英文详解错误示例中文解释Anon Inner Length Checks for long anonymous innerclasses匿名内部类长度限制Avoid Array Loops Instead of copying data betweentwo arrays, useSystem.arrayCopy method两个数组之间复制数据,使用System.arrayCopy方法Avoid Assert As Identifier Finds all places assert isused as an identifier is used.避免as

2、sert做为标识Avoid Calling Finalize Object.finalize() is called bythe garbage collector on anobject when garbage collectiondetermines that there are nomore references to the object.禁止使用Object.finalize()Avoid Catching NPE Code should never throw NPEunder normal circumstances. Acatch block may hide theorig

3、inal error, causing othermore subtle errors in its wake.代码可能会抛出无法被TRY捕获的异常.Avoid Catching Throwable This is dangerous because it casts too wide a net; it can catch things like OutOfMemoryError.Avoid Decimal Literals In Big Decimal Constructor One might assume that newBigDecimal(.1) is exactly equalt

4、o .1, but it is actually equalto.1000000000000000055511151231257827021181583404541015625. Thisis so because .1 cannot berepresented exactly as a double(or, for that matter, as abinary fraction of any finitelength). Thus, the long valuethat is being passed in to theconstructor is not exactlyequal to

5、.1, appearancesnotwithstanding. The (String)constructor, on the other hand,is perfectly predictable: newBigDecimal(.1) is exactlyequal to .1, as one wouldexpect. Therefore, it isgenerally recommended that the(String) constructor be used inpreference to this one.Key:AvoidDecimalLiteralsInBigDecimalCo

6、nstructor尽量避免BigDecimal(.1) 因为它实际上等于它实际上等于.1000000000000000055511151231257827021181583404541015625.而不是0.1Avoid Duplicate Literals Code containing duplicateString literals can usually beimproved by declaring theString as a constant field.Example :map.put(tyName,0);AvoidDuplicateLiterals: TheStringlit

7、eraltyNameappears 4times inthisfile; thefirstoccurrenc代码包含重复的字符串,通常可以声明为一个常量字段的字符串Avoid Enum As Identifier Finds all places enum is usedas an identifier is used.避免enum作为标识符Avoid Instanceof Checks In Catch Clause Each caught exception typeshould be handled in its owncatch clause每个捕获的异常类型应该是在自己的catch子

8、句处理Avoid Print Stack Trace Avoid printStackTrace(); use alogger call instead.避免打印堆栈跟踪(printStackTrace()Avoid Rethrowing Exception Catch blocks that merelyrethrow a caught exception onlyadd to code size and runtimecomplexity.避免在catch块重新抛出异常Avoid Throwing Null Pointer Exception Avoid throwing aNullPoi

9、nterException - itsconfusing because most peoplewill assume that the virtualmachine threw it. Considerusing anIllegalArgumentExceptioninstead; this will be clearlyseen as a programmer-initiatedexception.避免抛出一个NullPointerException - 这会混淆,因为多数人会认为已经被虚拟机回收。考虑使用一个IllegalArgumentException代替,这将让程序员清楚知道开始出

10、现何种异常。Avoid Throwing Raw Exception Types Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use a subclassed exception or error instead.Big Integer Instantiation Dont create instances of already existing BigInteger (BigInteger.ZERO,BigIn

11、teger.ONE) and for 1.5 on, BigInteger.TEN and BigDecimal (BigDecimal.ZERO,BigDecimal.ONE, BigDecimal.TEN)Boolean Expression Complexity Restricts nested booleanoperators (&, | and ) to aspecified depth (default = 3).if(gameName != & tyName!= &aaName != &srName != &typeName!= )BooleanExpressionComplex

12、ity :Booleanexpressioncomplexity is 4布尔表达式的个数个数不能超过4个Boolean Instantiation Avoid instantiating Booleanobjects; you can referenceBoolean.TRUE, Boolean.FALSE, orcall Boolean.valueOf() instead免布尔对象实例化,你可以使用Boolean.TRUE,Boolean.FALSE,或Boolean.valueOf()代替Broken Null Check The null check is broken sinceit

13、 will throw a Nullpointeritself. The reason is that amethod is called on the objectwhen it is null. It is likelythat you used | instead of &or vice versa.在使用一个对象的方法时,对象已经为空,抛出异常NullpointerClass Cast Exception With To Array if you need to get an array ofa class from your Collection,you should pass an

14、 array of thedesidered class as theparameter of the toArraymethod. Otherwise you will geta Class Cast Exception.从集合中通过.toArray()获取数组时候应该传递一个类型参数.(String tt =(String)list.toArray(newString0);).否则会返回类型转换异常错误Clone ThrowsClone Not Supported Exception The method clone() should throwa CloneNotSupportedExc

15、eption.不支持CloneNotSupportedException异常。Close Resource Ensure that resources (likeConnection, Statement, andResultSet objects) are alwaysclosed after use. It does thisby looking for code patternedlikeConnection c =openConnection();try / do stuff, and maybecatch something finally c.close();Collapsible

16、 If Statements Sometimes two if statementscan be consolidated byseparating their conditionswith a boolean short-circuitoperator如果有两个IF可以通过短路条件替代Compare ObjectsWith Equals用equals()而不是=Constant Name Checks that constant namesconform to a format specifiedby the format property.privatestaticfinalLoggerl

17、ogger =LoggerFactory.getLogger(SearchController.class);ConstantName :NameloggermustmatchpatternA-ZA-Z0-9*(_A-Z0-常量命名应该全大写Constructor Calls Overridable Method Calling overridable methods during construction poses arisk of invoking methods on an incompletely constructed object and can be difficult to

18、discern. It may leave the sub-class unable to construct its superclass or forced to replicate the construction process completely within itself, losing the ability to call super(). If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable. Not

19、e that this includes method calls throughout the control flow graph - i.e., if a constructor Foo() calls a private method bar() that calls a public method buz(), this denotes a problem.Cyclomatic Complexity Checks cyclomatic complexity ofmethods against a specifiedlimit. The complexity ismeasured by

20、 the number of if,while, do, for, ?:, catch,switch, case statements, andoperators & and | (plus one)in the body of a constructor,method, static initializer, orinstance initializer. It is ameasure of the minimum numberof possible paths through thesource and therefore the numberof required tests. Gene

21、rally 1-4 is considered good, 5-7 ok,8-10 consider re-factoring, and11+ re-factor now !RequestMappingCyclomaticComplexity :CyclomaticComplexity is 54(maxallowedis 10).圈复杂度是54(最大允许是10)Default Comes Last Check that the default is afterall the cases in a switchstatement.DEFAULT否是在switch分支最后一项Design For

22、 Extension Checks that classes are designed for inheritance.Dont Import Java Lang Avoid importing anything fromthe package http:/ Theseclasses are automaticallyimported (JLS 7.5.3).不要导入http:/ Import Sun Avoid importing anything fromthe sun.* packages. Thesepackages are not portable andare likely to

23、change.不要导入sun.* .因为它无法移植且经常变化Double Checked Locking Detect the double-checked locking idiom, a technique that tries to avoid synchronization overhead but is incorrect because of subtle artifacts of the java memory model.Empty Finalizer If the finalize() method isempty, then it does not need toexist

24、.如果finalize()方法是空的,那么它并不需要存在Empty Finally Block Avoid empty finally blocks - thesecan be deleted避免空finally块 - 如果为空可以删除Empty If Stmt Empty If Statement findsinstances where a condition ischecked but nothing is doneabout it.空IF块Empty Statement Detects empty statements(standalone ;).空语句(独立;).Empty Stat

25、ic Initializer An empty static initializer wasfound.空静态初始化Empty SwitchStatementsAvoid empty switch statements避免空switch语句Empty Synchronized Block Avoid empty synchronized blocks- theyre useless.避免空synchronized块Empty Try Block Avoid empty try blocks - whatsthe point?避免空的try块Empty While Stmt Empty Whil

26、e Statement finds allinstances where a whilestatement does nothing. If itis a timing loop, then youshould use Thread.sleep() forit; if its a while loop thatdoes a lot in the exitexpression, rewrite it to makeit clearer.Key: EmptyWhileStmt一个while语句不执行任何操作。如果它是一个循环的时间,那么你应该使用它Thread.sleep()方法Equals Ha

27、sh Code Checks that classes that override equals() also override hashCode().Equals Null Inexperienced programmerssometimes confuse comparisonconcepts and use equals() tocompare to null.有经验的程序员有时混淆比较运算的概念 使用equals()来比较空。Exception As Flow Control Using Exceptions as flowcontrol leads to GOTOish codean

28、d obscures true exceptionswhen debugging.使用GOTO会导致流程不明Final Class Checks that class which hasonly private constructors isdeclared as final.类只用于私有,无需PUBLICFinal Field Could Be Static If a final field is assigned toa compile-time constant, itcould be made static, thussaving overhead in each objectat r

29、untime.如果字段是常数,可以使它静态化,从而节省每个对象在运行时开销Finalize Does Not Call Super Finalize If the finalize() isimplemented, its last actionshould be to callsuper.finalize.最终finalize()应该调用父类finalize()Finalize Overloaded Methods named finalize() shouldnot have parameters. It isconfusing and probably a bug tooverload

30、finalize(). It willnot be called by the VM方法命名为finalize()不应该有参数。这会混乱,可能是错误的重载finalize()。它不会被虚拟机调用For Loops Must Use Braces Avoid using for statementswithout using curly braces,like for (int i=0; ifoo();for 代码块没有使用大阔号Hidden Field Checks that a local variable ora parameter does not shadow afield that

31、is defined in thesame class局部变量或参数不要和同一个类中定义的字段同名Hide Utility Class Constructor Make sure that utility classes(classes that contain onlystatic methods) do not have apublic constructor.publicclassProductConstants HideUtilityClassConstructor :Utilityclassesshouldnot havea publicordefaultconstruct确保工具类

32、(类只包含静态方法)没有公共构造函数(需隐藏工具类构造函数)。Idempotent Operations Avoid idempotent operations -they are have no effect.Example :int x = 2;x = x;有无用的代码行,例如int x =2;x = x;If Else Stmts Must Use Braces Avoid using if.else statementswithout using curly braces.if else 使用大阔号If Stmts Must Use Braces Avoid using if stat

33、ementswithout using curly braces.if(servers= null)|(servers.size() =0)returnnull;IfStmtsMust UseBraces :Avoidusing ifstatements withoutcurlyIF代码块缺少大扩号Illegal Throws Throwing http:/ or http:/ is almost never acceptable.Inefficient String Buffering Avoid concatenating nonliterals in a StringBuffercons

34、tructor or append().避免在一个StringBuffer构造函数或append()追加连接非文字Inner Assignment Checks for assignments insubexpressions, such as inString s = Integer.toString(i =2);.检查子表达式Instantiation To Get Class Avoid instantiating an objectjust to call getClass() on it;use the .class public memberinstead. Example : r

35、eplaceClass c = newString().getClass(); with Classc = String.class;避免只为了调用它的getClass()而实例化一个对象;Integer Instantiation In JDK 1.5, calling newInteger() causes memoryallocation. Integer.valueOf()is more memory friendly.在JDK 1.5中Integer.valueOf()比new Integer() 更优化Local Final Variable Name Checks that lo

36、cal finalvariable names conform to aformat specified by the formatproperty变量名规范检查Local Variable Name Checks that local, non-finalvariable names conform to aformat specified by the formatproperty.非final变量名符合规定的格式Loose coupling Avoid using implementationtypes (i.e., HashSet); use theinterface (i.e, Se

37、t) instead避免使用实现类型(即HashSet的);使用接口Magic Number Checks for magic numbers.StringtradeType=ObjectUtils.toString(list.get(3);MagicNumber :3 is amagicnumber.数字应该设置成可配长量Member Name Checks that instance variablenames conform to a formatspecified by the formatproperty.实例变量名符合规定的格式Method Name Checks that met

38、hod namesconform to a format specifiedby the format property.方法名符合规定的格式Missing Static Method In Non Instantiatable Class A class that has privateconstructors and does not haveany static methods or fieldscannot be used.类包含私有的构造函数,并且没有任何静态方法或字段可以被使用。Modifier Order Checks that the order of modifiers co

39、nforms to the suggestions in the Java Language specification, sections 8.1.1, 8.3.1 and8.4.3. The correct order is : public, protected, private, abstract, static, final, transient, volatile, synchronized, native, strictfp.Naming - Avoid dollar signs Avoid using dollar signs invariable/method/class/i

40、nterfacenames.避免使用美元符号命名变量/方法/类/接口的名字。Naming - Class naming conventions Class names should always beginwith an upper case character.类的名字应该是首字符大写。Naming - Method with same name as enclosing class Non-constructor methods shouldnot have the same name as theenclosing class. Example:public class MyClass

41、/ this is bad because it isa methodpublic void MyClass() / this is OK because it is aconstructorpublic MyClass() 非构造方法不应和类有相同的名称Naming -Suspicious Hashcode method name The method name and return typeare suspiciously close tohashCode(), which may mean youare intending to override thehashCode() method

42、. Example :public class Foo public int hashcode() / oops, this probably wassupposed to be hashCode方法名和返回类型不要用hashCode,这样会引起混淆Naming -Suspicious constant field name A field name is all inuppercase characters, which inSuns Java naming conventionsindicate a constant. However,the field is not final. Exa

43、mple: public class Foo / this is bad, since someonecould accidentally/ do PI = 2.71828; which isactualy e/ final double PI = 3.16; isokdouble PI = 3.16;字段名称不应该是大写字符,大写字母一般表明一个常数。Naming -Suspicious equals method name The method name and parameternumber are suspiciously closeto equals(Object), which m

44、aymean you are intending tooverride the equals(Object)method. Example :public class Foo public int equals(Object o) / oops, this probably wassupposed to be boolean equalspublic boolean equals(Strings) / oops, this probably wassupposed to be equals(Object)方法名和参数不要用equals(object),这样会引起混淆Ncss Method Count This rule uses the NCSS (NonCommenting Source Statements)algorithm to determine thenumber of lines of code for agiven method. NCSS ignorescomments, and counts actualstatements. Using thisalgorithm, lines of code thatare split are counted as one.publicModelAnd

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

当前位置:首页 > 社会民生


经营许可证编号:宁ICP备18001539号-1