重构第八章
13.Replace Type Code With Class(以类取代型别码)
class之中有一个数值型别码,但它不影响class的行为。以一个新的class替换该数值型别码。
Example:
class Person {
public static final int O=0;
public static final int A=1;
public static final int B=2;
public static final int C=3;
private int _bloodGroup;
public Person(int bloodGroup) {
_bloodGroup = bloodGroup;
}
public void setBloodGroup(int arg) {
_bloodGroup = arg;
}
public int getBloodGroup() {
return _bloodGroup;
}
}
End:
class Person...
public int getBloodGroupCode() {
return _bloodGroup.getCode();
}
public BloodGroup getBloodGroup() {
return _bloodGroup;
}
public Person(BloodGroup bloodGroup) {
_bloodGroup = bloodGroup;
}
public void setBloodGroup(BloodGroup arg) {
_bloodGroup = arg;
}
class BloodGroup...
public static final BloodGroup O = new BloodGroup(0);
public static final BloodGroup A = new BloodGroup(1);
public static final BloodGroup B = new BloodGroup(2);
public static final BloodGroup AB = new BloodGroup(3)
private static final BloodGroup[] _values = {O,A,B,AB};
private final int _code;
private BloodGroup(int code) {
_code = code;
}
public int getCode() {
return _code;
}
public static BloodGroup code(int arg) {
return _values[arg];
}
Conclusion:
Replace Type Code With Class(以类取代型别码)的方法,Person class在构造的时候直接传入BloodGroup 对象,相当于有了参数校验的功能(即运行期校验功能)。
注意
重构必须在有单元测试的情况下,保证之前的功能修改后不收影响。切记!!!