字符串文本不应重复。
规则内容: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.
违规代码示例:
合规解决方案:
线程安全的类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:
例外情况: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();
方法的认知复杂性不应太高。
规则内容: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.
没用的存储应该被移除。
规则内容: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 “”.
违规代码示例:
合规解决方案:
通用异常不应抛出。
规则内容: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.
违规代码示例:
合规解决方案:
嵌套代码块不应是空的。
规则内容: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.
违规代码示例:
没用的私有方法应该被移除。
规则内容: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.
违规代码示例:
合规解决方案:
条件表达式应该起始新行。
规则内容: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.
违规代码示例:
合规解决方案:
用日志记录代替标准输出。
规则内容:When logging a message there are several important requirements which must be fulfilled:
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.
违规代码示例:
合规解决方案:
字符串方法操作中单字符建议优先用单引号。
规则内容:An indexOf or lastIndexOf call with a single letter String can be made more performant by switching to a call with a char argument.
违规代码示例:
合规解决方案:
常量名应该符合命名规则。
规则内容:Shared coding conventions allow teams to collaborate efficiently. This rule checks that all constant names match a provided regular expression.
违规代码示例:
合规解决方案:
工具类不应该有公共构造函数,工具类不宜实例化,且应有一个私有构造方法。
规则内容: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.
违规代码示例:
合规解决方案:
构造函数不应用于实例化"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.
违规代码示例:
合规解决方案:
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.
打开的资源应该被关闭。
规则内容: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 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.
违规代码示例:
合规解决方案:
未使用的方法参数应该被移除。
规则内容: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
方法不应该为空。
规则内容:There are several reasons for a method not to have a method body:
例外情况:Default (no-argument) constructors are ignored when there are other constructors in the class, as are empty methods in abstract classes.
违规代码示例:
合规解决方案:
可合并的“if”语句应该合并。
规则内容:Merging collapsible if statements increases the code’s readability.
违规代码示例:
合规解决方案:
无用的私有属性应该被移除。
规则内容: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.
违规代码示例:
合规解决方案:
一个可执行的单行条件块应该用缩进表示。
规则内容: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.
违规代码示例:
合规解决方案:
空指针引用不应被访问。
规则内容: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.
违规代码示例:
如果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.
违规代码示例:
合规解决方案:
方法不应该有太多的的参数。
规则内容: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.
违规代码示例:
合规解决方案:
常量不应在接口中定义。
规则内容: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.
违规代码示例:
合规解决方案:
局部变量不应该影响类属性。
规则内容: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.
违规代码示例:
重写的和实现在方法要加Override标注。
规则内容:Using the @Override annotation is useful for two reasons :
例外情况:This rule is relaxed when overriding a method from the Object class like toString(), hashcode(), …
违规代码示例:
合规解决方案:
凭证不应该硬编码。
规则内容: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.
违规代码示例:
合规解决方案:
“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:
违规代码示例:
合规解决方案:
静态属性更新需同步。
规则内容: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.
违规代码示例:
以父类方法名字命名的子类方法应该被覆盖。
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:
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.
违规代码示例:
合规解决方案: