FindBugs 准绳收拾:Performance

代码审查:C#常见错误提醒,代码审查

Methods should not be empty

不要写空方法,除非这种情况:An abstract class may have empty methods, in
order to providedefault implementations for child classes.

Source files should not have any duplicatedblocks

源文件中不要出现任何重复的代码段或行或字符串等。没理解。

“switch case” clauses should not havetoo many lines

“switch case”
每个case里面的代码不要太长,太长的话可以考虑写个方法代替,主要是为了增强代码可读性

Nested blocks of code should not be leftempty

嵌套代码块不要是空的,比如 if( a > 0 ) {doSomething() } else {
},这时候应该把后面的else{}去掉。

Methods should not be too complex

方法不要太复杂,否则难以理解和维护。

Unused private fields should be removed

没有使用的private的成员变量应该移除掉。

Dead stores should be removed

没有用到的本地变量或其他死存储应该移除掉,也就是写方法的时候,定义的变量如果后来发现根本用不到,要记得删掉那行代码。

“switch” statements should endwith a “default” clause

switch语句应该以default结束,这是一种defensiveprogramming思想

Unused method parameters should be removed

没有用到的方法参数应该移除掉

Control flow statements “if”,”for”, “while”, “switch” and “try”should
not be nested too deeply

if /for/while/try这样的嵌套不要太复杂

Useless parentheses around expressionsshould be removed to prevent any
misunderstanding

没有意义的括号不要随便加,以免造成误解,比如”=”两边对象类型是相同的,就不要强转。

“for” loop stop conditions shouldbe invariant

for循环的结果条件不能是变量,而应该是常量

“static” members should beaccessed statically

static成员是与类、静态方法相联系的。

Catches should be combined

我还没理解

Primitives should not be boxed just for”String” conversion

不要使用 4+” “这样的方式将int值转变为字符串,而是使用
Integer.toString(4)这样的方式。就像Integer.parseInt(“我是字符串”)这样,不要偷懒。

Classes should not be empty

不要写空类

Unused local variables should be removed

没有用到的本地变量要删掉

“entrySet()” should be iteratedwhen both the key and value are needed

直接看英文更直接:When only the keys from a map are needed in a loop,
iterating thekeySet makes sense. But when both the key and the value are
needed, it’s moreefficient to iterate theentrySet, which will give
access to both the key andvalue, instead.

也就是说,如果只需要Map的Key,那么直接iterate这个Map的keySet就可以了,但是如果Key和value都需要,就iterate这个Map。

Method parameters, caught exceptions andforeach variables should not be
reassigned

方法参数/捕获的异常/foreach的变量不应该被重新赋值。

Collection.isEmpty() should be used to testfor emptiness

当判断集合是否为空的时候,不要使用if (myCollection.size() == 0)
这样的方式,而是使用if(myCollection.isEmpty()这样的方式,后者性能更高。

Standard outputs should not be useddirectly to log anything

标准输出不直接打印任何东西,也就是打log的时候,不要使用System.out.println(“My
Message”)这样的方式,而是使用logger.log(“MyMessage”)这种方式。

Methods
should not be empty 不要写空方法,除非这种情况:An abstract class may
have empty methods, in order to provi…

更多原创测试技术文章同步更新到微信公众号
:三国测,敬请扫码关注个人的微信号,感谢!

目前已转至个人博客,本系列地址:Lam’s Blog – Knowledge as
Action

 图片 1

BX_BOXING_IMMEDIATELY_UNBOXED

Primitive value is boxed and then immediately unboxed
对原始值进行装箱,然后立即取消装箱。这可能是在一个未要求装箱的地方进行了手动装箱,从而迫使编译器进行立即撤消装箱的操作

摘要:公司部署了一套sonar,经过一段时间运行,发现有一些问题出现频率很高,因此有必要将这些问题进行整理总结和分析,避免再次出现类似问题。

BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION

Primitive value is boxed then unboxed to perform primitive coercion
对原始值进行装箱然后立即把它强制转换为另外一种原始类型。例如:
new Double(d).intValue()应该直接进行强制转换例如:(int) d

作者原创技术文章,转载请注明出处
id: 83 name: A method/constructor shouldnt explicitly throw
java.lang.Exception type: CODE SMELL severity: MAJOR Comment: It is
unclear which exceptions that can be thrown from the methods. It might
be difficult to document and understand the vague interfaces. Use either
a class derived from RuntimeException or a checked exception.
definition: 目前还不清楚可以从方法中抛出哪些异常。
可能难以记录和了解模糊界面。 advice:
建议使用从RuntimeException派生的类或checked的异常。
id: 144 name: Avoid really long methods. type: CODE SMELL severity:
MAJOR Comment: Violations of this rule usually indicate that the method
is doing too much. Try to reduce the method size by creating helper
methods and removing any copy/pasted code. definition:
违反此规则通常表明该方法做得太多。
尝试通过创建帮助方法并删除任何复制/粘贴代码来减少方法大小。 advice:
建议方法代码行数不超过75行
id: 1032 name: Redundant nullcheck of tbOfflinePay, which is known to be
non-null in
com.ctrip.market.web.controller.OrderController.getOrderPrintDetail(String,
Integer, Long, String, String, String) type: CODE SMELL severity: MAJOR
Comment: This method contains a redundant check of a known non-null
value against the constant null. definition:
此方法包含对常量null的已知非空值的冗余检查。 advice:
建议:先检查是否为空再进行相关操作
id: 1097 name: Write to static field
com.ctrip.market.materialfile.utils.SpringContextHolder.applicationContext
from instance method
com.ctrip.market.materialfile.utils.SpringContextHolder.destroy() type:
CODE SMELL severity: CRITICAL Comment: This instance method writes to a
static field. This is tricky to get correct if multiple instances are
being manipulated, and generally bad practice. definition:
此实例方法写入静态字段。如果多个实例被操纵,这是很难获得正确的。这通常是坏的做法。
advice: 不要通过实例方法给静态变量赋值
id: 1217 name: input must be non-null but is marked as nullable type:
CODE SMELL severity: MAJOR Comment: This parameter is always used in a
way that requires it to be non-null, but the parameter is explicitly
annotated as being Nullable. Either the use of the parameter or the
annotation is wrong. definition:
该参数始终以使其不为空的方式使用,但是将该参数显式注释为Nullable。
所以,参数或注释是错误的。 advice:
参数值在任何情况下都不能为空,但是有明确的注释它可以为空。
id: 1624 name: Assign this magic number 3 to a well-named constant, and
use the constant instead. type: CODE SMELL severity: MAJOR Comment: “A
magic number is a number that comes out of nowhere, and is directly used
in a statement. Magic numbers are often used, for instance to limit the
number of iterations of a loops, to test the value of a property, etc.

DM_BOXED_PRIMITIVE_TOSTRING

Method allocates a boxed primitive just to call toString
仅仅为了调用封装类的toString()而对原始类型进行封装操作。比这种方法更有效的是调用封装类的toString(…)方法例如:
new Integer(1).toString() 替换为 Integer.toString(1)
new Long(1).toString() 替换为 Long.toString(1)
new Float(1.0).toString() 替换为 Float.toString(1.0)
new Double(1.0).toString() 替换为 Double.toString(1.0)
new Byte(1).toString() 替换为 Byte.toString(1)
new Short(1).toString() 替换为 Short.toString(1)
new Boolean(true).toString() 替换为 Boolean.toString(true)

Using magic numbers may seem obvious and straightforward when you’re
writing a piece of code, but they are much less obvious and
straightforward at debugging time.

DM_FP_NUMBER_CTOR

Method invokes inefficient floating-point Number constructor; use
static valueOf instead

使用new
Double(double)方法总是会创建一个新的对象,然而使用Double.valueOf(double)方法可以把值保存在编辑器或者class
library、JVM中。使用存储值的方式来避免对象的分配可以或得更好的代码性能
除非类必须符合Java
1.5以前的JVM,否则请使用自动装箱或valueOf()方法创建Double和Float实例。

That is why magic numbers must be demystified by first being assigned to
clearly named variables before being used.

DM_NUMBER_CTOR

Method invokes inefficient Number constructor; use static valueOf
instead

使用new
Integer(int)方法总是会创建一个新的对象,然而使用Integer.valueOf(int)方法可以把值保存在编辑器或者class
library、JVM中。使用存储值的方式来避免对象的分配可以或得更好的代码性能
除非类必须符合Java
1.5以前的JVM,否则请使用自动装箱或valueOf()方法创建Long, Integer,
Short, Character, Byte实例。

-1, 0 and 1 are not considered magic numbers.” definition:
“一个魔术数字是一个从无处出现的数字,直接用在一个语句中。
经常使用魔数,例如限制循环的迭代次数,以测试属性的值等。
当您编写一段代码时,使用魔术数字可能看起来显而易见,但在调试时间上它们不那么明显和直截了当。
这就是为什么魔术数字必须被神秘化,首先被分配给明确命名的变量才能使用。
-1,0和1不被视为魔术数字。” advice: “不合规:
public static void doSomething() {
for(int i = 0; i < 4; i++){ // Noncompliant, 4 is a magic number

}
}
合规:
public static final int NUMBER_OF_CYCLES = 4;
public static void doSomething() {
for(int i = 0; i < NUMBER_OF_CYCLES ; i++){

}
}
例外:
这条规则忽略 hashCode 方法。”
id: 1645 name: This method has 158 lines, which is greater than the 100
lines authorized. Split it into smaller methods. type: CODE SMELL
severity: MAJOR Comment: A method that grows too large tends to
aggregate too many responsibilities. Such method inevitably become
harder to understand and therefore harder to maintain. definition:
增长太大的方法往往会累积太多的责任。
这种方法不可避免地变得难以理解,因此更难维护。 advice:
较小的方法不但会更容易理解,也可能更容易测试。
id: 1701 name: Remove this empty statement. type: BUG severity: MINOR
Comment: “Empty statements, i.e. ;, are usually introduced by mistake,
for example because:

DMI_BLOCKING_METHODS_ON_URL

The equals and hashCode methods of URL are blocking
使用equals和hashCode方法来对url进行资源标识符解析时会引起堵塞。考虑使用java.net.URI来代替。

It was meant to be replaced by an actual statement, but this was
forgotten.
There was a typo which lead the semicolon to be doubled, i.e. ;;.”
definition: “空的声明,即.;,通常是错误的引入,例如:
这意味着被一个实际的陈述所取代,但这被遗忘了。
有一个拼写错误,导致分号增加一倍,即. ;;。” advice: “不合规:
void doSomething() {
; // Noncompliant – was used as a kind of TODO marker
}

DMI_COLLECTION_OF_URLS

Maps and sets of URLs can be performance hogs
方法或者字段使用url的map/set集合。因为equals方法或者hashCode方法来进行资源标识符解析时都会引起堵塞。考虑使用java.net.URI来代替。

void doSomethingElse() {
System.out.println(“”Hello, world!””);; // Noncompliant – double ;

for (int i = 0; i < 3; System.out.println(i), i++); // Noncompliant –
Rarely, they are used on purpose as the body of a loop. It is a bad
practice to have side-effects outside of the loop body

}
合规:
void doSomething() {}

DM_BOOLEAN_CTOR

Method invokes inefficient Boolean constructor; use
Boolean.valueOf(…) instead

使用new方法创建一个java.lang.Boolean类型能够的实例对象是浪费空间的,因为Boolean对象是不可变的而且只有两个有用的值。使用Boolean.valueOf()或者Java1.5中的自动装箱功能来创建一个Boolean实例。

void doSomethingElse() {
System.out.println(“”Hello, world!””);

for (int i = 0; i < 3; i++){
System.out.println(i);
}

}”
id: 1722 name: Reduce the number of conditional operators (4) used in
the expression (maximum allowed 3). type: CODE SMELL severity: CRITICAL
Comment: The complexity of an expression is defined by the number of &&,
|| and condition ? ifTrue : ifFalse operators it contains. A single
expression’s complexity should not become too high to keep the code
readable. definition: 表达式的复杂性由&&,||的数量定义
和它所包含的条件判断? ifTrue:ifFalse等操作符所决定。
单个表达式的复杂度不应该变得太高,以致不能保持代码的可读性。 advice:
“不合规代码范例:

DM_GC

Explicit garbage collection; extremely dubious except in benchmarking
code

在代码中显式的调用垃圾回收命名,这样做并不能起作用。在过去,有人在关闭操作或者finalize方法中调用垃圾回收方法导致了很多的性能浪费。这样大规模回收对象时会造成处理器运行缓慢。

默认阈值为3的情况:

DM_NEXTINT_VIA_NEXTDOUBLE

Use the nextInt method of Random rather than nextDouble to generate a
random integer

如果r是一个java.util.Random对象,你可以使r.nextInt(n)生成一个0到n-1之前的随机数,而不是使用(int)(r.nextDouble()
* n)

if (((condition1 && condition2) || (condition3 && condition4)) &&
condition5) { … }
合规范例:

DM_STRING_CTOR

Method invokes inefficient new String(String) constructor
使用java.lang.String(String)构造函数会浪费内存因为这种构造方式和String作为参数在功能上容易混乱。只是使用String直接作为参数的形式

if ( (myFirstCondition() || mySecondCondition()) && myLastCondition()) {
… }”
id: 1728 name: This method has 122 lines, which is greater than the 100
lines authorized. Split it into smaller methods. type: CODE SMELL
severity: MAJOR Comment: A method that grows too large tends to
aggregate too many responsibilities. Such method inevitably become
harder to understand and therefore harder to maintain. Above a specific
threshold, it is strongly advised to refactor into smaller methods which
focus on well-defined tasks. Those smaller methods will not only be
easier to understand, but also probably easier to test. definition:
方法增长太大往往会累积太多的责任/干系。
这种方法不可避免地变得难以理解,更难维护。 advice:
建议方法中最大行数:75
id: 1738 name: The Cyclomatic Complexity of this method
“remarketingDataHandler” is 15 which is greater than 10 authorized.
type: CODE SMELL severity: CRITICAL Comment: “The cyclomatic complexity
of methods should not exceed a defined threshold.

DM_STRING_TOSTRING

Method invokes toString() method on a String
调用String.toString()是多余的操作,只要使用String就可以了。

Complex code can perform poorly and will in any case be difficult to
understand and therefore to maintain.” definition:
方法的循环复杂度不应超过定义的阈值。复杂的代码表现较差,在任何情况下都难以理解,需要维护。
advice: 复杂度建议为10
id: 1759 name: Add a default case to this switch. type: CODE SMELL
severity: MAJOR Comment: 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. Even when
the switch covers all current values of an enum, a default case should
still be used because there is no guarantee that the enum won’t be
extended. definition: switch语句应该以default结束,这是一种defensive
programming思想 advice: “不合规:
switch (param) { //missing default clause
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
}

DM_STRING_VOID_CTOR

Method invokes inefficient new String() constructor
使用没有参数的构造方法去创建新的String对象是浪费内存空间的,因为这样创建会和空字符串“”混淆。Java中保证完成相同的构造方法会产生描绘相同的String对象。所以你只要使用空字符串来创建就可以了。

switch (param) {
default: // default clause should be the last one
error();
break;
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
}
合规:
switch (param) {
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
default:
error();
break;
}”
id: 1809 name: Remove this call from a constructor to the overridable
“setFormat” method. type: CODE SMELL severity: CRITICAL Comment:
Calling an overridable method from a constructor could result in
failures or strange behaviors when instantiating a subclass which
overrides the method. definition:
从构造函数调用一个可覆盖的方法,可能导致在实例化覆盖该方法的子类时出现故障或奇怪的行为。
advice: “不合规:

ITA_INEFFICIENT_TO_ARRAY

Method uses toArray() with zero-length array argument
当使用集合的toArray()方法时使用数组长度为0的数组作为参数。比这更有效的一种方法是
myCollection.toArray(new
Foo[myCollection.size()]),如果数组的长度足够大就可以直接把集合中的内容包装到数组中直接返回从而避免了第二次创建一个新的数组来存放集合中值。

public class Parent {

SBSC_USE_STRINGBUFFER_CONCATENATION

Method concatenates strings using + in a loop
在循环中构建一个String对象时从性能上讲使用StringBuffer来代替String对象
例如:
// This is bad String s = ""; for (int i = 0; i < field.length; ++i) { s = s + field[i]; }
// This is better StringBuffer buf = new StringBuffer(); for (int i = 0; i < field.length; ++i) { buf.append(field[i]); } String s = buf.toString();

public Parent () {
doSomething(); // Noncompliant
}

SS_SHOULD_BE_STATIC

Unread field: should this field be static?
类中所包含的final属性字段在编译器中初始化为静态的值。考虑在定义时就把它定义为static类型的。

发表评论

电子邮件地址不会被公开。 必填项已用*标注