如下代码,存在坏味道
public Length as(Unit target_unit) {
Length result = this;
if (this.unit == Unit.FOOT) {
if (target_unit == Unit.YARD) {
result = new Length(this.value / 3, target_unit);
} else if (target_unit == Unit.INCH) {
result = new Length(this.value * 12, target_unit);
}
}
if (this.unit == Unit.YARD) {
if (target_unit == Unit.INCH) {
result = new Length(this.value * 36, target_unit);
} else if (target_unit == Unit.FOOT){
result = new Length(this.value * 3, target_unit);
}
}
return result;
}
注:以下只展示最关键的代码,降低认知负载,做了变化的地方,在代码上都会注释
例如:下面代码中new Length()
为重复创建
public Length as(Unit target) {
// 提取了重复的new创建
Length result = new Length(this.value, target);
if (this.unit == Unit.FOOT) {
if (target == Unit.YARD) {
// 提取了重复的new创建
result = new Length(this.value /3, target);
} else if (target == Unit.INCH) {
// 提取了重复的new创建
result = new Length(this.value * 12, target);
}
}
//省略...,其他代码同理
}
return result;
}
例如:下面代码中this.value
是会变化的
public Length as(Unit target) {
// 提取会变化的信息
double value = this.value;
Length result = new Length(value, target);
if (this.unit == Unit.FOOT) {
if (target == Unit.YARD) {
// 提取会变化的信息
value = value / 3;
result = new Length(value, target);
} else if (target == Unit.INCH) {
// 提取会变化的信息
value = value * 12;
result = new Length(value, target);
}
}
//省略...,其他代码同理
return result;
}
例如:下面代码中,共有信息new Length() 和 value
,因为使用了共有信息,此时原有信息result
就没用了
注:当没用引用时,result变量名会变灰,此时可以用 alt + enter,会有个安全删除,选择安全删除,则会吧所有的result都同步删掉
public Length as(Unit target) {
double value = this.value;
if (this.unit == Unit.FOOT) {
if (target == Unit.YARD) {
value = value / 3;
} else if (target == Unit.INCH) {
value = value * 12;
}
}
// 使用抽取出来的信息
return new Length(value, target);
}
public Length as(Unit target) {
// 提炼函数
double value = getValue(target);
return new Length(value, target);
}
// 提炼函数
private double getValue(Unit target) {
...
}
public Length getValue(Unit target) {
if (this.unit == Unit.FOOT) {
if (target == Unit.YARD) {
// 提前返回,消除else
return this.value / 3;
}
if (target == Unit.INCH) {
// 提前返回,消除else
return this.value * 12;
}
}
//省略...
return this.value;
}
因篇幅问题不能全部显示,请点此查看更多更全内容