Sonar代码规则之TOP30详解

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.
违规代码示例
Sonar代码规则之TOP30详解_第1张图片
合规解决方案
Sonar代码规则之TOP30详解_第2张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第3张图片
合规解决方案
Sonar代码规则之TOP30详解_第4张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第5张图片
合规解决方案
在这里插入图片描述

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.
违规代码示例
Sonar代码规则之TOP30详解_第6张图片
合规解决方案
Sonar代码规则之TOP30详解_第7张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第8张图片
合规解决方案
Sonar代码规则之TOP30详解_第9张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第10张图片
合规解决方案
Sonar代码规则之TOP30详解_第11张图片

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.
违规代码示例Sonar代码规则之TOP30详解_第12张图片
合规解决方案
Sonar代码规则之TOP30详解_第13张图片

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.
Sonar代码规则之TOP30详解_第14张图片
违规代码示例
Sonar代码规则之TOP30详解_第15张图片
合规解决方案
Sonar代码规则之TOP30详解_第16张图片

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.

Sonar代码规则之TOP30详解_第17张图片
违规代码示例
在这里插入图片描述
合规解决方案
在这里插入图片描述

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.
在这里插入图片描述
违规代码示例
Sonar代码规则之TOP30详解_第18张图片
合规解决方案
Sonar代码规则之TOP30详解_第19张图片

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

可合并的“if”语句应该合并。
规则内容:Merging collapsible if statements increases the code’s readability.
违规代码示例Sonar代码规则之TOP30详解_第20张图片
合规解决方案
Sonar代码规则之TOP30详解_第21张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第22张图片
合规解决方案
Sonar代码规则之TOP30详解_第23张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第24张图片
合规解决方案
Sonar代码规则之TOP30详解_第25张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第26张图片
Sonar代码规则之TOP30详解_第27张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第28张图片
合规解决方案
Sonar代码规则之TOP30详解_第29张图片

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.
违规代码示例
在这里插入图片描述
合规解决方案
Sonar代码规则之TOP30详解_第30张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第31张图片

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(), …
违规代码示例
Sonar代码规则之TOP30详解_第32张图片
合规解决方案
Sonar代码规则之TOP30详解_第33张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第34张图片
合规解决方案
Sonar代码规则之TOP30详解_第35张图片

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:
Sonar代码规则之TOP30详解_第36张图片
违规代码示例
Sonar代码规则之TOP30详解_第37张图片
合规解决方案
Sonar代码规则之TOP30详解_第38张图片

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.
违规代码示例
Sonar代码规则之TOP30详解_第39张图片

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详解_第40张图片
合规解决方案
Sonar代码规则之TOP30详解_第41张图片

你可能感兴趣的:(代码规范,sonar规则)