Sonar代码规则之TOP30详解

  • 1. 规则简述:String literals should not be duplicated.
  • 2. 规则简述:Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used.
  • 3. 规则简述:Cognitive Complexity of methods should not be too high.
  • 4. 规则简述:Dead stores should be removed.
  • 5. 规则简述:Generic exceptions should never be thrown.
  • 6. 规则简述:Nested blocks of code should not be left empty.
  • 7. 规则简述:Unused "private" methods should be removed.
  • 8. 规则简述:Conditionals should start on new lines.
  • 9. 规则简述:Standard outputs should not be used directly to log anything.
  • 10. 规则简述:String function use should be optimized for single characters.
  • 11. 规则简述:Constant names should comply with a naming convention.
  • 12. 规则简述:Utility classes should not have public constructors.
  • 13. 规则简述:Constructors should not be used to instantiate "String", "BigInteger", "BigDecimal" and primitive-wrapper classes.
  • 14. 规则简述:Try-catch blocks should not be nested.
  • 15. 规则简述:Resources should be closed.
  • 16. 规则简述:Unused method parameters should be removed.
  • 17. 规则简述:Methods should not be empty.
  • 18. 规则简述:Collapsible "if" statements should be merged.
  • 19. 规则简述:Unused "private" fields should be removed.
  • 20. 规则简述:A conditionally executed single line should be denoted by indentation.
  • 21. 规则简述:Null pointers should not be dereferenced.
  • 22. 规则简述:Boolean expressions should not be gratuitous.
  • 23. 规则简述:Methods should not have too many parameters.
  • 24. 规则简述:Constants should not be defined in interfaces.
  • 25. 规则简述:Local variables should not shadow class fields.
  • 26. 规则简述:"@Override" should be used on overriding and implementing methods.
  • 27. 规则简述:Credentials should not be hard-coded.
  • 28. 规则简述:"switch" statements should have "default" clauses.
  • 29. 规则简述:Instance methods should not write to "static" fields.
  • 30. 规则简述:Child class methods named for parent class methods should be overrides.

1. 规则简述:String literals should not be duplicated.

字符串文本不应重复。
规则内容:Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
例外情况:To prevent generating some false-positives, literals having less than 5 characters are excluded.
违规代码示例

合规解决方案

2. 规则简述:Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used.

线程安全的类Vector,Hashtable,Stack和StringBuffer不应该被使用。
规则内容:Early classes of the Java API, such as Vector, Hashtable and StringBuffer, were synchronized to make them thread-safe. Unfortunately, synchronization has a big negative impact on performance, even when using these collections from a single thread.
It is better to use their new unsynchronized replacements:

  • ArrayList or LinkedList instead of Vector
  • Deque instead of Stack
  • HashMap instead of Hashtable
  • StringBuilder instead of StringBuffer

例外情况:Use of those synchronized classes is ignored in the signatures of overriding methods.

@Override
public Vector getCats(){...}

违规代码示例

Vector cats = new Vector();

合规解决方案

 ArrayList cats = new ArrayList();

3. 规则简述:Cognitive Complexity of methods should not be too high.

方法的认知复杂性不应太高。
规则内容:Cognitive Complexity is a measure of how hard the control flow of a method is to understand. Methods with high Cognitive Complexity will be difficult to maintain.

4. 规则简述:Dead stores should be removed.

没用的存储应该被移除。
规则内容:A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it’s not an error, it is at best a waste of resources. Therefore all calculated values should be used.
例外情况:This rule ignores initializations to -1, 0, 1, null, true, false and “”.
违规代码示例

合规解决方案

5. 规则简述:Generic exceptions should never be thrown.

通用异常不应抛出。
规则内容:Using such generic exceptions as Error, RuntimeException, Throwable, and Exception prevents calling methods from handling true, system-generated exceptions differently than application-generated errors.
例外情况:Generic exceptions in the signatures of overriding methods are ignored, because overriding method has to follow signature of the throw declaration in the superclass. The issue will be raised on superclass declaration of the method (or won’t be raised at all if superclass is not part of the analysis).

Generic exceptions are also ignored in the signatures of methods that make calls to methods that throw generic exceptions.

违规代码示例

合规解决方案

6. 规则简述:Nested blocks of code should not be left empty.

嵌套代码块不应是空的。
规则内容:Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed.
例外情况:When a block contains a comment, this block is not considered to be empty unless it is a synchronized block. synchronized blocks are still considered empty even with comments because they can still affect program flow.
违规代码示例

7. 规则简述:Unused “private” methods should be removed.

没用的私有方法应该被移除。
规则内容:private methods that are never executed are dead code: unnecessary, inoperative code that should be removed. Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced.
Note that this rule does not take reflection into account, which means that issues will be raised on private methods that are only accessed using the reflection API.
例外情况:This rule doesn’t raise any issue on annotated methods.
违规代码示例

合规解决方案

8. 规则简述:Conditionals should start on new lines.

条件表达式应该起始新行。
规则内容:Code is clearest when each statement has its own line. Nonetheless, it is a common pattern to combine on the same line an if and its resulting then statement. However, when an if is placed on the same line as the closing } from a preceding else or else if, it is either an error - else is missing - or the invitation to a future error as maintainers fail to understand that the two statements are unconnected.
违规代码示例

合规解决方案

9. 规则简述:Standard outputs should not be used directly to log anything.

用日志记录代替标准输出。
规则内容:When logging a message there are several important requirements which must be fulfilled:

  • The user must be able to easily retrieve the logs
  • The format of all logged message must be uniform to allow the user to
    easily read the log
  • Logged data must actually be recorded
  • Sensitive data must only be logged securely

If a program directly writes to the standard outputs, there is absolutely no way to comply with those requirements. That’s why defining and using a dedicated logger is highly recommended.
违规代码示例

合规解决方案

10. 规则简述:String function use should be optimized for single characters.

字符串方法操作中单字符建议优先用单引号。
规则内容:An indexOf or lastIndexOf call with a single letter String can be made more performant by switching to a call with a char argument.
违规代码示例

合规解决方案

11. 规则简述:Constant names should comply with a naming convention.

常量名应该符合命名规则。
规则内容:Shared coding conventions allow teams to collaborate efficiently. This rule checks that all constant names match a provided regular expression.
违规代码示例

合规解决方案

12. 规则简述:Utility classes should not have public constructors.

工具类不应该有公共构造函数,工具类不宜实例化,且应有一个私有构造方法。
规则内容:Utility classes, which are collections of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.
例外情况:When class contains public static void main(String[] args) method it is not considered as utility class and will be ignored by this rule.
违规代码示例

合规解决方案

13. 规则简述:Constructors should not be used to instantiate “String”, “BigInteger”, “BigDecimal” and primitive-wrapper classes.

构造函数不应用于实例化"String", “BigInteger”, "BigDecimal"和原始包装类。
规则内容:Constructors for Strings, BigInteger, BigDecimal and the objects used to wrap primitives should never be used. Doing so is less clear and uses more memory than simply using the desired value in the case of strings, and using valueOf for everything else.
Further, these constructors are deprecated in Java 9, which is an indication that they will eventually be removed from the language altogether.
违规代码示例
合规解决方案

14. 规则简述:Try-catch blocks should not be nested.

try-catch不应该被嵌套。
规则内容:Nesting try/catch blocks severely impacts the readability of source code because it makes it too difficult to understand which block will catch which exception.

15. 规则简述:Resources should be closed.

打开的资源应该被关闭。
规则内容:Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using “try-with-resources” pattern and will be closed automatically.
Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box it’s on to their knees.
例外情况:Instances of the following classes are ignored by this rule because close has no effect:

  • java.io.ByteArrayOutputStream
  • java.io.ByteArrayInputStream
  • java.io.CharArrayReader
  • java.io.CharArrayWriter
  • java.io.StringReader
  • java.io.StringWriter

Java 7 introduced the try-with-resources statement, which implicitly closes Closeables. All resources opened in a try-with-resources statement are ignored by this rule.

违规代码示例

合规解决方案

16. 规则简述:Unused method parameters should be removed.

未使用的方法参数应该被移除。
规则内容:Unused parameters are misleading. Whatever the values passed to such parameters, the behavior will be the same.
例外情况:The rule will not raise issues for unused parameters:
that are annotated with @javax.enterprise.event.Observes

  • in overrides and implementation methods
  • in interface default methods
  • in non-private methods that only throw or that have empty bodies
  • in annotated methods, unless the annotation is @SuppressWarning(“unchecked”) or @SuppressWarning(“rawtypes”), in which case the annotation will be ignored
  • in overridable methods (non-final, or not member of a final class,
    non-static, non-private), if the parameter is documented with a
    proper javadoc.


违规代码示例

合规解决方案

17. 规则简述:Methods should not be empty.

方法不应该为空。
规则内容:There are several reasons for a method not to have a method body:

  • It is an unintentional omission, and should be fixed to prevent an
    unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an
    UnsupportedOperationException should be thrown.
  • The method is an intentionally-blank override. In this case a nested
    comment should explain the reason for the blank override.

例外情况:Default (no-argument) constructors are ignored when there are other constructors in the class, as are empty methods in abstract classes.

违规代码示例

合规解决方案

18. 规则简述:Collapsible “if” statements should be merged.

可合并的“if”语句应该合并。
规则内容:Merging collapsible if statements increases the code’s readability.
违规代码示例
合规解决方案

19. 规则简述:Unused “private” fields should be removed.

无用的私有属性应该被移除。
规则内容:If a private field is declared but not used in the program, it can be considered dead code and should therefore be removed. This will improve maintainability because developers will not wonder what the variable is used for.
Note that this rule does not take reflection into account, which means that issues will be raised on private fields that are only accessed using the reflection API.
例外情况:The Java serialization runtime associates with each serializable class a version number, called serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.
A serializable class can declare its own serialVersionUID explicitly by declaring a field named serialVersionUID that must be static, final, and of type long. By definition those serialVersionUID fields should not be reported by this rule:

Moreover, this rule doesn’t raise any issue on annotated fields.
违规代码示例

合规解决方案

20. 规则简述:A conditionally executed single line should be denoted by indentation.

一个可执行的单行条件块应该用缩进表示。
规则内容:In the absence of enclosing curly braces, the line immediately after a conditional is the one that is conditionally executed. By both convention and good practice, such lines are indented. In the absence of both curly braces and indentation the intent of the original programmer is entirely unclear and perhaps not actually what is executed. Additionally, such code is highly likely to be confusing to maintainers.
违规代码示例

合规解决方案

21. 规则简述:Null pointers should not be dereferenced.

空指针引用不应被访问。
规则内容:A reference to null should never be dereferenced/accessed. Doing so will cause a NullPointerException to be thrown. At best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or it could allow an attacker to bypass security measures.
Note that when they are present, this rule takes advantage of @CheckForNull and @Nonnull annotations defined in JSR-305 to understand which values are and are not nullable except when @Nonnull is used on the parameter to equals, which by contract should always work with null.
违规代码示例

22. 规则简述:Boolean expressions should not be gratuitous.

如果boolean表达式的值是已定的,那么boolean表达式是没有必要的可以移除。
规则内容:If a boolean expression doesn’t change the evaluation of the condition, then it is entirely unnecessary, and can be removed. If it is gratuitous because it does not match the programmer’s intent, then it’s a bug and the expression should be fixed.
违规代码示例

合规解决方案

23. 规则简述:Methods should not have too many parameters.

方法不应该有太多的的参数。
规则内容:A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things.
例外情况:Methods annotated with Spring’s @RequestMapping (and related shortcut annotations, like @GetRequest) or @JsonCreator may have a lot of parameters, encapsulation being possible. Such methods are therefore ignored.
违规代码示例

合规解决方案

24. 规则简述:Constants should not be defined in interfaces.

常量不应在接口中定义。
规则内容:According to Joshua Bloch, author of “Effective Java”:
The constant interface pattern is a poor use of interfaces.
That a class uses some constants internally is an implementation detail.
Implementing a constant interface causes this implementation detail to leak into the class’s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface,
all of its subclasses will have their namespaces polluted by the constants in the interface.
违规代码示例

合规解决方案

25. 规则简述:Local variables should not shadow class fields.

局部变量不应该影响类属性。
规则内容:Shadowing fields with a local variable is a bad practice that reduces code readability: it makes it confusing to know whether the field or the variable is being used.
违规代码示例

26. 规则简述:"@Override" should be used on overriding and implementing methods.

重写的和实现在方法要加Override标注。
规则内容:Using the @Override annotation is useful for two reasons :

  • It elicits a warning from the compiler if the annotated method
    doesn’t actually override anything, as in the case of a misspelling.
  • It improves the readability of the source code by making it obvious
    that methods are overridden.

例外情况:This rule is relaxed when overriding a method from the Object class like toString(), hashcode(), …
违规代码示例

合规解决方案

27. 规则简述:Credentials should not be hard-coded.

凭证不应该硬编码。
规则内容:Because it is easy to extract strings from a compiled application, credentials should never be hard-coded. Do so, and they’re almost guaranteed to end up in the hands of an attacker. This is particularly true for applications that are distributed.
Credentials should be stored outside of the code in a strongly-protected encrypted configuration file or database.
违规代码示例

合规解决方案

28. 规则简述:“switch” statements should have “default” clauses.

“switch”语句应以“default”子句结尾。
规则内容:The requirement for a final default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.
例外情况:If the switch parameter is an Enum and if all the constants of this enum are used in the case statements, then no default clause is expected.
Example:

违规代码示例

合规解决方案

29. 规则简述:Instance methods should not write to “static” fields.

静态属性更新需同步。
规则内容:Correctly updating a static field from a non-static method is tricky to get right and could easily lead to bugs if there are multiple class instances and/or multiple threads in play. Ideally, static fields are only updated from synchronized static methods.
This rule raises an issue each time a static field is updated from a non-static method.
违规代码示例

30. 规则简述:Child class methods named for parent class methods should be overrides.

以父类方法名字命名的子类方法应该被覆盖。
bug 主要
以下情况不是重写:
a、父类方法是static的而子类方法不是static的
b、子类方法的参数或返回值与父类方法不是同一个包
c、父类方法是private
为了不产生混乱,不要与父类方法同名
规则内容:When a method in a child class has the same signature as a method in a parent class, it is assumed to be an override. However, that’s not the case when:

  • the parent class method is static and the child class method is not.
  • the arguments or return types of the child method are in different
    packages than those of the parent method.
  • the parent class method is private.

Typically, these things are done unintentionally; the private parent class method is overlooked, the static keyword in the parent declaration is overlooked, or the wrong class is imported in the child. But if the intent is truly for the child class method to be different, then the method should be renamed to prevent confusion.
违规代码示例

合规解决方案

Sonar代码规则之TOP30详解相关推荐

  1. 国际C语言混乱代码大赛优胜作品详解之“A clock in one line

    国际C语言混乱代码大赛优胜作品详解之"A clock in one line" 发表于2013-04-11 17:22| 9419次阅读| 来源StackOverflow| 53  ...

  2. DL之YoloV3:Yolo V3算法的简介(论文介绍)、各种DL框架代码复现、架构详解、案例应用等配图集合之详细攻略

    DL之YoloV3:Yolo V3算法的简介(论文介绍).各种DL框架代码复现.架构详解.案例应用等配图集合之详细攻略 目录 Yolo V3算法的简介(论文介绍) 0.YoloV3实验结果 1.Yol ...

  3. java构造块_java中的静态代码块、构造代码块、构造方法详解

    运行下面这段代码,观察其结果: package com.test; public class HelloB extends HelloA { public HelloB() { } { System. ...

  4. python代码覆盖率测试_unittest+coverage单元测试代码覆盖操作实例详解_python

    这篇文章主要为大家详细介绍了unittest+coverage单元测试代码覆盖操作的实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 基于上一篇文章,这篇文章是关于使用coverage来实现代码 ...

  5. yolov5——detect.py代码【注释、详解、使用教程】

    yolov5--detect.py代码[注释.详解.使用教程] yolov5--detect.py代码[注释.详解.使用教程] 1. 函数parse_opt() 2. 函数main() 3. 函数ru ...

  6. python的爱心曲线公式_六行python代码的爱心曲线详解

    前些日子在做绩效体系的时候,遇到了一件囧事,居然忘记怎样在Excel上拟合正态分布了,尽管在第二天重新拾起了Excel中那几个常见的函数和图像的做法,还是十分的惭愧.实际上,当时有效偏颇了,忽略了问题 ...

  7. 消除冗长Java代码的工具——Lombok详解

    消除冗长Java代码的工具--Lombok详解 文章目录 消除冗长Java代码的工具--Lombok详解 什么是Lombok Lombok的作用 Lombok常用注解 Lombok安装 什么是Lomb ...

  8. vc读取北通手柄按键_噬血代码手柄怎么操作 噬血代码北通手柄按键功能详解-游侠网...

    噬血代码手柄怎么操作?应该很多朋友都还不是很清楚吧,所以呢小编今天给大家带来的就是噬血代码北通手柄按键功能详解,需要的朋友不妨进来看看. 北通手柄按键功能详解 游戏介绍 本作是由<噬神者> ...

  9. yolov5——train.py代码【注释、详解、使用教程】

    yolov5--train.py代码[注释.详解.使用教程] yolov5--train.py代码[注释.详解.使用教程] yolov5--train.py代码[注释.详解.使用教程] 前言 1. p ...

  10. 泛型java 代码讲解_Java泛型详解

    2516326-5475e88a458a09e4.png 一,打破砂锅问到底 泛型存在的意义? 泛型类,泛型接口,泛型方法如何定义? 如何限定类型变量? 泛型中使用的约束和局限性有哪些? 泛型类型的继 ...

最新文章

  1. 以太坊代币空投合约的实现
  2. Asp.net基础概念之 HttpModule
  3. HBase不同版本集群之间数据迁移
  4. 如何求解两个数的最大公约数
  5. 数据结构-树的进阶代码
  6. Java集合框架之Collection实例解析
  7. 深入理解Scala的隐式转换
  8. 2021年8月下旬好文收藏
  9. python中4j什么意思_Python学习:4.数据类型以及运算符详解
  10. 【学习 OpenCV】—— core.hpp 核心api
  11. IdentityServer的基本概念与特性
  12. 小程序源码:收款码三合一制作
  13. ftp 服务器管理工具,5款最好用的ftp 服务器管理工具
  14. esxi导出ovf报错
  15. Photoshop滤镜巧制超级美女插画效果(转)
  16. c语言海报,竞选海报 c语言
  17. 华为云弹性文件服务 SFS
  18. 10个最好的无器械训练项目
  19. CSS学习之position属性
  20. 使用命令行工具,如何创建nicelooking DMG的Mac OS X?

热门文章

  1. 电脑重启桌面 计算机图标消失,电脑重启后计算机图标不见了怎么办
  2. 瑞吉外卖QQ邮箱登录
  3. win7无法连接打印机拒绝访问_打印机拒绝访问,小编教你打印机拒绝访问无法连接怎么解决...
  4. 再谈王垠/王垠—写给清华大学的退学申请
  5. 上传图片到淘宝接口调用展示
  6. 微信怎么找群聊?找回微信群聊只需要这样…
  7. English--基础知识点--3--动名词做主语
  8. 亚马逊Rating和Review的这些区别你知多少?
  9. 银行那些事儿--银行会计
  10. gitlab修改服务器地址,GitLab服务器IP地址设置