Java 如何重构初始代码段以获得目标(例如R.C.Martin的干净代码)
我现在正在阅读R.C.Martin的“干净的代码”,我试图通过从初始代码到目标代码,特别是在作者没有解释步骤的情况下,了解干净重构的诀窍。在第17章中,作者有一个关于布尔参数丑陋性的例子:Java 如何重构初始代码段以获得目标(例如R.C.Martin的干净代码),java,refactoring,Java,Refactoring,我现在正在阅读R.C.Martin的“干净的代码”,我试图通过从初始代码到目标代码,特别是在作者没有解释步骤的情况下,了解干净重构的诀窍。在第17章中,作者有一个关于布尔参数丑陋性的例子: public int calculateWeeklyPay(boolean overtime) { int tenthRate = getTenthRate(); int tenthsWorked = getTenthsWorked(); int straightTime = Math.min(400,
public int calculateWeeklyPay(boolean overtime) {
int tenthRate = getTenthRate();
int tenthsWorked = getTenthsWorked();
int straightTime = Math.min(400, tenthsWorked);
int overTime = Math.max(0, tenthsWorked - straightTime);
int straightPay = straightTime * tenthRate;
double overtimeRate = overtime ? 1.5 : 1.0 * tenthRate;
int overtimePay = (int)Math.round(overTime*overtimeRate);
return straightPay + overtimePay;
}
谈到这一点:
public int straightPay() {
return getTenthsWorked() * getTenthRate();
}
public int overTimePay() {
int overTimeTenths = Math.max(0, getTenthsWorked() - 400);
int overTimePay = overTimeBonus(overTimeTenths);
return straightPay() + overTimePay;
}
private int overTimeBonus(int overTimeTenths) {
double bonus = 0.5 * getTenthRate() * overTimeTenths;
return (int) Math.round(bonus);
}
我成功地(我希望)找到了除overtimePay之外的所有步骤:我不明白为什么会这样(我只是简单地取了相应的行并开始替换变量):
可以转化为:
overtimePay = round(0.5 * tenthRate * max(0, tenthsWorked - 400));
overtimePay = round(0.5 * tenthRate * max(0, tenthsWorked - 400));
另外,我发现max(0,tenthworksworked-min(400,tenthworksworked))与max(0,tenthworksworked-400)相同。然后,替换初始最大值,我们得到:
这:
应转变为:
overtimePay = round(0.5 * tenthRate * max(0, tenthsWorked - 400));
overtimePay = round(0.5 * tenthRate * max(0, tenthsWorked - 400));
如果超过规定时间:
double overtimeRate = overtime ? 1.5 : 1.0 * tenthRate;
此外,乘法运算符的优先级高于三元运算符,因此它意味着tenthRate仅在false条件下乘法,而在true条件下仅给出1.5,不乘以任何值。
请您指出如何完成此重构?“tenthRate仅在错误条件下才会相乘”确实如此。看起来是个错误。它应该是
(加班?1.5:1.0)*云梯。也许可以指出,这段代码是故意损坏的。。。但我认为这是一个不好的例子。作为一名程序员,鲍勃叔叔被完全高估了。他真正的天赋是善于自我推销和营销。我相信他是个好人,但还是。谢谢你!!!那么最后一点,为什么新函数中有0.5?