题记
按照公司内部搭建的代码质量平台,修复项目中存在的问题,本篇文章记录一些修改这些问题的一些理解。
问题
静态变量不要在构造函数中赋值
规则详细描述:
Assigning a value to a static field in a constructor could cause unreliable behavior at runtime since it will change the value for all instances of the class.
Instead remove the field’s static modifier, or initialize it statically.
中文对应:在构造函数中为静态字段赋值可能会导致运行时不可靠的行为,因为它会更改类的所有实例的值。
相反,删除字段的静态修饰符,或者静态初始化。也就是说当定义了静态变量的时候,切记在构造方法中进行初始化;因为静态变量是属于类的,当在构造函数进行赋值时,不同对象实例化的时候,会对静态变量进行修改,进而影响到其他对象。
Noncompliant Code Example(有问题示例)
public class Person {
static Date dateOfBirth;
static int expectedFingers;
public Person(date birthday) {
dateOfBirth = birthday; // Noncompliant; now everyone has this birthday
expectedFingers = 10; // Noncompliant
}
}
Compliant Solution(解决方案示例)
public class Person {
Date dateOfBirth;
static int expectedFingers = 10;
public Person(date birthday) {
dateOfBirth = birthday;
}
}
- 重写equals 和 hashcode
描述:Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass
简单的说就是,重写equals方法时,必须要重写hashcode;
ps:当判断对象是否相等时,应该先判断hashcode是否相等,若再使用equals判断,因为hashcode是int值的判断,效率较快。
具体的可参照如下链接:hashcode与equals
代码示例:
// this is bad
public class Bar {
public boolean equals(Object o) {
// do some comparison
}
}
// and so is this
public class Baz {
public int hashCode() {
// return some hash value
}
}
// this is OK
public class Foo {
public boolean equals(Object other) {
// do some comparison
}
public int hashCode() {
// return some hash value
}
}
- Mutable fields should not be “public static”
易变的字段应该不要定义为public static,
示例:
public interface MyInterface {
public static String [] strings; // Noncompliant
}
public class A {
public static String [] strings1 = {"first","second"}; // Noncompliant
public static String [] strings2 = {"first","second"}; // Noncompliant
public static List<String> strings3 = new ArrayList<>(); // Noncompliant
// ...
}
This rule raises issues for public static array, Collection, Date, and awt.Point members.
规则原因:
1. 程序声明一个数组为public final static,并不能放在数组的内容发生变化,所以声明 final 无效。
2. 声明为public,一些恶意的程序可以改变存储在数组里的值。
数组,集合,Date、Point类型,尽量声明为private。