我想重构这个ruby代码
class UtilService
def summer_start
...
end
def summer_end
...
end
def calc(date, charge, quantity, winter_rate, winter_service_charge, summer_rate)
if date < summer_start || date > summer_end
chargeamt = quantity * winter_rate + winter_service_charge
else
chargeamt = quantity * summer_rate
end
chargeamt
end
end
由于没有使用充电,我知道我可以摆脱这种情况,但除了摆脱那个参数之外,我无法想到我还能做些什么。
我还在考虑分手&#39; calc&#39;进入不同的方法
class UtilService
def summer_start
end
def summer_end
end
def calc_summer_rate(date, quantity, summer_rate)
if date > summer_start || date < summer_end
chargeamt = quantity * summer_rate
end
chargeamt
end
def calc_winter_rate(date, quantity, winter_rate, winter_service_charge)
if date < summer_start || date > summer_end
chargeamt = quantity * winter_rate + winter_service_charge
end
chargeamt
end
end
但似乎我的重构没有多大意义。
答案 0 :(得分:3)
我倾向于写下以下内容。
rates = { winter: { per_unit: 123, service_charge: 456 },
summer: { per_unit: 135, service_charge: 0 } }
def calc(date, quantity, rates)
rate = summer?(date) ? rates[:summer] : rates[:winter]
quantity * rate[:per_unit] + rate[:service_charge]
end
def summer?(date)
date.between?(summer_start, summer_end)
end
答案 1 :(得分:2)
我没有看到需要进行大量重构,也许只是将是夏天?逻辑转移到另一种方法并删除不必要的chargeamt
变量;像这样的东西:
class UtilService
def summer_start
end
def summer_end
end
def calc(date, quantity, winter_rate, winter_service_charge, summer_rate)
if summer?(date)
quantity * winter_rate + winter_service_charge
else
quantity * summer_rate
end
end
private
def summer?(date)
date > summer_start || date < summer_end
end
end