// 不推荐写法:
public class MyClass {
private int numberOfItems = 0;
private boolean flag = false;
private String title = null;
...
}
// 推荐写法:
public class MyClass {
private int numberOfItems;
private boolean flag;
private String title;
...
}
说明:字段声明时若无初始化语句,会自动初始化到默认值,此默认值多数情况下符合需求。
interface声明中多余的修饰词
// 不推荐写法:
public class MyClass {
public abstract static interface MyInterface {
public void doSomething();
}
...
}
// 推荐写法:
public class MyClass {
public interface MyInterface {
void doSomething();
}
...
}
说明:所有interface都隐式地是abstract且static的,interface中所有的方法声明都隐式地是public的,对它们添加这类修饰词只会增加阅读代码的难度。
instanceof关键字时避免做多余的非空检查
void f(CharSequence s) {
// 这里的非空检查是多余的
if (s != null && s instanceof String) {
// do something
}
...
}
说明:Java语言规定null出现在instanceof左边时表达式值为false。
for循环,在需要用到下标无法使用时应缩小下标变量的作用域
// 未最小化变量作用域的写法
void f(int[] widthArray, int[] heightArray) {
int length = widthArray.length;
for (int i = 0; i < length; i++) {
// 使用 widthArray[i] 和 heightArray[i] 做计算
}
// length变量泄露到了此作用域
...
}
// 推荐写法:
void f(int[] widthArray, int[] heightArray) {
for (int i = 0, length = widthArray.length; i < length; i++) {
// 使用 widthArray[i] 和 heightArray[i] 做计算
}
// length变量自动失效
...
}
valueOf静态方法,不要使用new创建新对象
void modifyList(List<Integer> list) {
list.add(new Integer(0)); // 不推荐,应使用自动装箱
list.add(0); // 正确写法
// remove方法是重载的,故必须手动装箱,应使用valueOf方法
list.remove(new Integer(0)); // 不推荐,不应使用new
list.remove(Integer.valueOf(0)); // 正确,使用valueOf方法
}
说明:包装类的valueOf静态方法会缓存一定范围内的值对象(能做缓存的原因是包装类被设计为不可变的),比用new的方式开销小。
this关键字会导致错误或混淆时才使用它
public class MyClass {
private int number;
public int getNumber() {
return number; // 此处不使用this
}
public void setNumber(int number) {
this.number = number; // 必须依靠this区分成员变量与局部变量时,使用this
}
}
comments powered by Disqus