ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

SonarQube Java 规则描述

2020-11-26 19:01:31  阅读:573  来源: 互联网

标签:次要 used Java SonarQube should 主要 序列化 bug 描述


1、".equals()" should not be used to test the values of “Atomic” classes.
bug 主要
不要使用 equals 方法对 AtomicXXX 进行是否相等的判断
Atomic 变量永远只会和自身相等,Atomic 变量没有覆写 equals () 方法.
2、"=+" should not be used instead of "+="
bug 主要
“=+” 与 “=+” 意义不同
a =+ b; 虽然正确但写法不合规,应写成 a = +b;
3、"@NonNull" values should not be set to null
bug 次要
标注非空假定非空且在使用之前不进行非空检查,设置为空会导致空指针异常
4、“BigDecimal(double)” should not be used
bug 主要
因为浮点的不精确,可能使用 BigDecimal (double) 得不到期望的值
5、“compareTo” results should not be checked for specific values
bug 次要
compareTo 可能返回不是具体的值(除 0 外),建议用 >0、<0、=0
6、“compareTo” should not return "Integer.MIN_VALUE"
bug 次要
compareTo 只代表一个不等标识,不代表不等的程度,应返回 - 1,0,1 标识即可
7、 “Double.longBitsToDouble” should not be used for "int"
bug 主要
Double.longBitsToDouble 返回给定的位所代表的 double 值,需要一个 64 位的 long 类型参数.
8、 “equals” method overrides should accept “Object” parameters
bug 主要
equals 作为方法名应该仅用于重写 Object.equals (Object) 来避免混乱.
9、 “equals(Object obj)” should test argument type
bug 次要
要比较 obj 的 class type 是否一样
10、“equals” methods should be symmetric and work for subclasses
bug 次要
equals 应是对等并且在有子类参与时能正常工作
11、“equals(Object obj)” and “hashCode()” should be overridden in pairs
bug 次要
成对重写
12、“Externalizable” classes should have no-arguments constructors
bug 主要
Externalizable (可序列化与返序列化) 类应该有无参构造器
13、“getClass” should not be used for synchronization
bug 主要

{synchronized (this.getClass ())} 错误 子类继承此方法时不能做到同步
{synchronized (MyClass.class)} 正确

14、“hashCode” and “toString” should not be called on array instances
bug 主要
使用 Arrays.toString (args) 和 Arrays.hashCode (args) 代替.
15、“instanceof” operators that always return “true” or “false” should be removed
bug 主要
16、“InterruptedException” should not be ignored
bug 主要

try {
while (true) {
// do stuff
}
}catch (InterruptedException e) {
LOGGER.log(Level.WARN, "Interrupted!", e);
// Restore interrupted state...
Thread.currentThread().interrupt();
}

17、“Iterator.hasNext()” should not call "Iterator.next()"
bug 主要
18、“Iterator.next()” methods should throw "NoSuchElementException"
bug 次要

public String next(){
if(!hasNext()){
throw new NoSuchElementException();
}
...
}

19、“notifyAll” should be used
bug 主要
notify 可能不能唤醒正确的线程,notifyAll 代之。
20、“null” should not be used with "Optional"
bug 主要
把判空包装起来使用而不直接使用!=null
21、“PreparedStatement” and “ResultSet” methods should be called with valid indices
bug 阻断
PreparedStatement 与 ResultSet 参数设置与获取数据由序号 1 开始而非 0
22、“read” and “readLine” return values should be used
bug 主要

BufferedReader.readLine (), Reader.read () 及子类中的相关方法都应该先存储再比较
buffReader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = buffReader.readLine()) != null) {
// ...
}

23、“runFinalizersOnExit” should not be called
bug 严重
JVM 退出时不可能运行 finalizers,System.runFinalizersOnExit 和 Runtime.runFinalizersOnExit 可以在 jvm 退出时运行但是因为他们不安全而弃用.
正确用法:

Runtime.addShutdownHook(new Runnable() {
public void run(){
doSomething();
}
});

24、“ScheduledThreadPoolExecutor” should not have 0 core threads
bug 严重
java.util.concurrent.ScheduledThreadPoolExecutor 由属性 corePoolSize 指定线程池大小,如果设置为 0 表示线程执行器无线程可用且不做任何事.
25、“Serializable” inner classes of non-serializable classes should be "static"
bug 次要
序列化非静态内部类将导致尝试序列化外部类,如果外部类不是序列化类,会产生运行时异常,内部类静态化会避免这种情况
26、“SingleConnectionFactory” instances should be set to "reconnectOnException"
bug 主要
使用 Spring SingleConnectionFactory 而不启用 reconnectOnException 设置当连接恶化将阻止自动连接恢复。
27、“StringBuilder” and “StringBuffer” should not be instantiated with a character
bug 主要
StringBuffer foo = new StringBuffer (‘x’); 错 equivalent to StringBuffer foo = new StringBuffer (120);
StringBuffer foo = new StringBuffer (“x”); 对
28、 “super.finalize()” should be called at the end of “Object.finalize()” implementations
bug 严重

protected void finalize() {
releaseSomeResources();
super.finalize (); // 调用,最后调用
}

29、“toArray” should be passed an array of the proper type
bug 次要
toArray () 无参且强制类型转换会产生运行时异常,应传入一个合适的类弄作参数

public String [] getStringArray(List<String> strings) {
return strings.toArray(new String[0]);
}

30、“toString()” and “clone()” methods should not return null
bug 主要
可返回 “”
31、 “wait” should not be called when multiple locks are held
bug 阻断
32、 “wait”, “notify” and “notifyAll” should only be called when a lock is obviously held on an object
bug 主要
先要获得对象锁才能进行上述操作

private void removeElement() {
synchronized(obj) {
while (!suitableCondition()){
obj.wait();
}
... // Perform removal
}  
}
or
private synchronized void removeElement() {
while (!suitableCondition()){
wait();
}
... // Perform removal
}

33、“wait(…)” should be used instead of “Thread.sleep(…)” when a lock is held
bug 阻断
当持有锁的当前线程调用 Thread.sleep (…) 可能导致性能和扩展性问题,甚至死锁因为持有锁的当前线程已冻结。合适的做法是锁对象 wait () 释放锁让其它线程进来运行.
34、A “for” loop update clause should move the counter in the right direction
bug 主要
检查 for 循环下标递增或递减正确
35、All branches in a conditional structure should not have exactly the same implementation
bug 主要
分支中不应该有相同的实现
36、Blocks should be synchronized on “private final” fields or parameters
bug 主要
synchronized 同步块应该锁在 private final fields 或 parameters 对象上,因为同步块内非 final 锁对象可能改变导致其它线程进来运行.
37、Boxing and unboxing should not be immediately reversed
bug 次要
自动拆箱和装箱不需手动转换
38、Child class methods named for parent class methods should be overrides
bug 主要
以下情况不是重写:
a、父类方法是 static 的而子类方法不是 static 的
b、子类方法的参数或返回值与父类方法不是同一个包
c、父类方法是 private
为了不产生混乱,不要与父类方法同名
39、Classes extending java.lang.Thread should override the “run” method
bug 主要
线程类应该重写 run 方法
40、Classes should not be compared by name
bug 主要
不要用类名称比较类是否相同,而用 instanceof 或者 Class.isAssignableFrom () 进行底动类型比较
41、Classes that don’t define “hashCode()” should not be used in hashes
bug 主要
没有定义 hashCode () 方法的类不能作为 hash 集合中的键值,因为 equal 相同的实例对像可能返回不同的 hash 值.
42、Collections should not be passed as arguments to their own methods
bug 主要
集合实例不应该作为参数被传给集合实你还自已的方法中
43、Conditionally executed blocks should be reachable
bug 主要
条件执行块应该可达
44、Constructor injection should be used instead of field injection
bug 主要
构造器注入应该替代属性注入 (非 Spring framework)
因为任何非 Spring framework 实例化而是通过构造器实例化的实例不能注入属性,这样公有的构造器实化化后可能产生 NullPointerException,除非所有的构造器都是私有的
45、Consumed Stream pipelines should not be reused
bug 主要
流不应该重用
46、Custom resources should be closed
bug 阻断
资源应该关闭
47、Custom serialization method signatures should meet requirements
bug 主要
自定义类序列化方法签名应该合法
49、Dependencies should not have “system” scope
bug 严重
maven 依赖不要在 system scope
50、Dissimilar primitive wrappers should not be used with the ternary operator without explicit casting
bug 主要
不同的原始包装类如果没有明确的类转换不能用于三元操作中
51、Double Brace Initialization should not be used
bug 次要
双构造初始不要用

Map source = new HashMap(){{ // Noncompliant
put("firstName", "John");
put("lastName", "Smith");
}};

此操作如一个 anonymous inner class,如果 anonymous inner class 返回且被其它对象引用,可能产生 memory leaks,既使不产生 memory leaks 也会让大多维护者感到迷惑
52、Double-checked locking should not be used
bug 阻断
重复检查的锁块不要使用

public static Resource getInstance() {
if (resource == null) {
synchronized (DoubleCheckedLocking.class) {
if (resource == null)
resource = new Resource();
}
}
return resource;
}

public synchronized static Resource getInstance() {
if (resource == null)
resource = new Resource();
return resource;
}

53、Equals Hash Code
bug 严重
成对重写 equals () 与 hashCode ()
54、Exception should not be created without being thrown
bug 主要
不被抛出的异常不要创建
55、Expressions used in “assert” should not produce side effects
bug 主要
assert 表达式不要产生负影响,不要改变数据状态
56、Failed unit tests should be fixed
bug 主要
失败的单元测试应该尽快解决掉
57、Floating point numbers should not be tested for equality
bug 主要
浮点数不要进行比较
58、Getters and setters should be synchronized in pairs
bug 主要
get 与 set 应该成对进行同步操作
59、Identical expressions should not be used on both sides of a binary operator
bug 主要
相同的表达式不要作为二进制操作的操作数使用,应该简化
60、Inappropriate “Collection” calls should not be made
bug 主要
正确使用集合元素类型
61、Inappropriate regular expressions should not be used
bug 主要
正确使用正则表达式
62、Intermediate Stream methods should not be left unused
bug 主要
中间流应该被使用
63、Ints and longs should not be shifted by zero or more than their number of bits-1
bug 次要
整型与长整型位移操作数应该价于 1 与类型占位数 - 1
64、Invalid “Date” values should not be used
bug 主要
正确使用日期
65、Jump statements should not occur in “finally” blocks
bug 主要
finally 块中使用 return, break, throw 等 Jump statements,会阻止在 try catch 中抛出的未处理异常的传播
66、Locks should be released
bug 严重
保证锁的能够释放
67、Loop conditions should be true at least once
bug 主要
循环应该至少走一次
68、Loops should not be infinit
bug 阻断
循环不应该死循环
69、Math operands should be cast before assignment
bug 次要
数字操作在操作或赋值前要转化
70、Math should not be performed on floats
bug 次要
BigDecimal 代替 floats 进行大数精确运算
71、Methods “wait(…)”, “notify()” and “notifyAll()” should not be called on Thread instances
bug 阻断
不要在线程中使用 “wait (…)”, “notify ()” and “notifyAll ()”
72、Methods should not be named “hashcode” or "equal"
bug 主要
除非 Override 重写这些方法
73、Multiline blocks should be enclosed in curly braces
bug 主要
多列块应用大括号括起来
74、Neither “Math.abs” nor negation should be used on numbers that could be "MIN_VALUE"
bug 次要
不要对数值类型的 MIN_VALUE 值或返回值为此值进行 Math.abs 与取反操作,因为不会起作用。
75、Non-public methods should not be "@Transactional"
bug 主要
非 public 方法不要注解 Transactional, 调用时 spring 会抛出异常
76、Non-serializable classes should not be written
bug 主要
执行写操作的类要序列化,否则会抛出异常
77、Non-serializable objects should not be stored in “HttpSession” objects
bug 主要
HttpSession 要保存序列化的对象
78、Non-thread-safe fields should not be static
bug 主要
非线程安全的域不应该静态化
79、Null pointers should not be dereferenced
bug 主要
空指针引用不应被访问
80、Optional value should only be accessed after calling isPresent()
bug 主要
Optional 实例值的获取要 isPresent () 之后再做操作
90、Printf-style format strings should not lead to unexpected behavior at runtime
bug 阻断
因为 Printf 风格格式化是在运行期解读,而不是在编译期检验,会存在风险
91、Raw byte values should not be used in bitwise operations in combination with shifts
bug 主要
原始字节值不应参与位运算

result = (result << 8) | readByte(); // Noncompliant

正:

result = (result << 8) | (readByte() & 0xff);

92、Reflection should not be used to check non-runtime annotations
bug 主要
反射操作不应该运于检查非运行时注解
93、Related “if/else if” statements should not have the same condition
bug 主要
if/else if 中不应该有相同的条件
94、Resources should be closed
bug 阻断
打开的资源应该关闭并且放到 finally 块中进行关闭
95、Return values from functions without side effects should not be ignored
bug 主要
操作对函数返回值没有影响的应该忽略

public void handle(String command){
command.toLowerCase(); // Noncompliant; result of method thrown away
...
}

96、Servlets should not have mutable instance fields
bug 主要
servlet 容器对每一个 servlet 创建一个实例导致实例变量共享产生问题
struts1.x 也是单例
97、Short-circuit logic should be used to prevent null pointer dereferences in conditionals
bug 主要
应正确使用短路逻辑来防止条件中的空指针引用访问
98、Silly equality checks should not be made
bug 主要
愚蠢的相等检查不应该做
非同类型的对象 equal
99、Spring “@Controller” classes should not use "@Scope"
bug 主要
保持 spring controller 的单例
100、Synchronization should not be based on Strings or boxed primitives
bug 主要
字符串和封箱类不应该被用作锁定对象,因为它们被合并和重用。
101、The non-serializable super class of a “Serializable” class should have a no-argument constructor
bug 次要
序列化的类的非序列化父类应有一个无参构造器
102、The Object.finalize() method should not be called
bug 主要
Object.finalize () 不要人为去调用
103、The Object.finalize() method should not be overriden
bug 主要
Object.finalize () 不要重写
104、The signature of “finalize()” should match that of "Object.finalize()"
bug 主要
Object.finalize () 不要重写
105、The value returned from a stream read should be checked
bug 次要
从流中读取的值应先检查再操作
106、Thread.run() should not be called directly
bug 主要
调用 start ()
107、Useless “if(true) {…}” and “if(false){…}” blocks should be removed
bug 主要
无用的 if (true) 和 if (false) 块应移除
108、Value-based classes should not be used for locking
bug 主要
基于值的类不要用于锁对象
109、Value-based objects should not be serialized
bug 次要
基于值的对象不应被用于序列化
110、Values should not be uselessly incremented
bug 主要
值增减后不存储是代码浪费甚至是 bug
111、Variables should not be self-assigned
bug 主要
变量不应该自分配如下:

public void setName(String name) {
name = name;
}

112、Week Year (“YYYY”) should not be used for date formatting
bug 主要
日期格式化错误
113、Zero should not be a possible denominator
bug 严重
零不应该是一个可能的分母
114、Loops should not be infinite
Bug 阻断
循环不应该是无限的

标签:次要,used,Java,SonarQube,should,主要,序列化,bug,描述
来源: https://blog.csdn.net/fujuacm/article/details/110200155

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有