-
枚举类不应该使用setter方法
枚举类是JDK1.5带来的一个语法糖(为了向后兼容,编译器会帮我们写的源代码做很多事情,比如泛型为什么会擦除类型,为什么会生成桥接方法,foreach迭代,自动装箱/拆箱等,这有个术语叫“语法糖”),其本质是继承了java.lang.enum的枚举类型的同名类(编译的时候会生成),其中每个枚举的常量,其实是在这个同名类的一个final的静态常量。
这些静态常量,会在同名类的static方法里面初始化:生成相应的内部类,创建内部类对象、调用内部类的<init>方法,生成对象后赋值。
枚举类是不建议修改枚举常量的内部值的。
枚举类使用setter方法 -
可变的field不应该使用public static修饰
例子 -
new BigDecimal不应该传入double、float此类浮点数为参数,这样将得不到精确的数值
BigDecmal错误使用.png 不应该接口中定义常量
interface中一般只定义api,但是常量不是api;
如果继承了该类,定义相同的常量并且修改了值也是可能的,这种细节的东西应该定义在底层,而不是放在上层。
如果哪天interface不需要这个变量了,会造成命名空间污染;
接口常量.png
-
log4j 使用规范
log4j使用规范.png - boolean值运用
不推荐的写法
if (booleanMethod() == true) { /* ... / }
if (booleanMethod() == false) { / ... / }
if (booleanMethod() || false) { / ... */ }
doSomething(!false);
doSomething(booleanMethod() == true);
booleanVariable = booleanMethod() ? true : false;
booleanVariable = booleanMethod() ? true : exp;
booleanVariable = booleanMethod() ? false : exp;
booleanVariable = booleanMethod() ? exp : true;
booleanVariable = booleanMethod() ? exp : false;
推荐的写法
if (booleanMethod()) { /* ... / }
if (!booleanMethod()) { / ... / }
if (booleanMethod()) { / ... */ }
doSomething(true);
doSomething(booleanMethod());
booleanVariable = booleanMethod();
booleanVariable = booleanMethod() || exp;
booleanVariable = !booleanMethod() && exp;
booleanVariable = !booleanMethod() || exp;
booleanVariable = booleanMethod() && exp;
boolean字面量.png
-
钻石语法(java 7及以上)
钻石语法.png -
判断集合为空
集合为空判断.png
虽然使用集合的size()来判断是否为空也没有问题,但是Collections.isEmpty()使得代码更易阅读。并且size()的时间复杂度是O(N),但是isEmpty()时间复杂度为O(1)。
switch 需要写default
方法名和变量名首字母小写
public的常量和fields在声明的时候应该使用"static final"而不是单单只用"final"
只有final的话,每个实例中都会存在在这些变量,但是加上static就不一样了。
进一步说,对于非public,final修饰的field,如果不是static,则意味着每个实例都可以有自己的不同的值。
final private.png