【发布时间】:2015-04-15 00:52:49
【问题描述】:
我经常发现自己的 if/else 语句在与不同的值进行比较时基本上是重复的同一行。在这里,我正在编写代码来预测致命流感爆发造成的死亡人数。它已被重构为一个 case 语句,仍然很 WET:
def predicted_deaths(population_density, population, state)
case
when population_density >= 200 then number_of_deaths = (population * 0.4).floor
when population_density >= 150 then number_of_deaths = (population * 0.3).floor
when population_density >= 100 then number_of_deaths = (population * 0.2).floor
when population_density >= 50 then number_of_deaths = (population * 0.1).floor
else number_of_deaths = (population * 0.05).floor
end
ap "#{state} will lose #{number_of_deaths} people in this outbreak"
end
我尝试了一些可以使用的东西
j = 0.4
i = 200
until i <= 50 do
@population_density >= i then number_of_deaths = (@population * j).floor
i -= 50
j -= 0.1
end
但这并没有真正做同样的事情。
如何使重复的 case 语句更 DRY?
编辑
这里的两个建议看起来像是两个非常不同但同样好的重构:
为了便于阅读:
def predicted_deaths(population_density, population, state)
factor = case population_density
when 0...50 then 0.05
when 50...100 then 0.1
when 100...150 then 0.2
when 150...200 then 0.3
else 0.4
end
number_of_deaths = (population * factor).floor
ap "#{state} will lose #{number_of_deaths} people in this outbreak"
end
更简洁但可读性较差:
def predicted_deaths(population_density, population, state)
number_of_deaths = (population * 0.05).floor
for i in 1..4
number_of_deaths = (0.1 * i * population).floor if population_density.between?(50*i, 50*(i+1)) || population_density >= 200
end
ap "#{state} will lose #{number_of_deaths} people in this outbreak"
end
【问题讨论】:
-
这是一件小事,但我不认为在方法内打印结果是好的编程习惯。最好删除
state参数并返回死亡人数,然后将其打印在方法之外。这样,如果您以后在代码中的其他地方需要死亡人数,您就不必更改方法。
标签: ruby if-statement case dry