ruby – 重构if else语句
我已经尝试阅读一些关于重构的教程,我正在努力解决条件问题。 我不想使用三元运算符,但也许这应该在方法中提取? 或者有一种聪明的方式来使用地图吗?
detail.stated = if value[:stated].blank? nil elsif value[:stated] == "Incomplete" nil elsif value[:is_ratio] == "true" value[:stated] == "true" else apply_currency_increment_for_save(value[:stated]) end
如果将此逻辑移动到一个方法中,由于早期return
(和关键字参数),它可以变得更加清晰:
def stated?(stated:, is_ratio: nil, **) return if stated.blank? || stated == "Incomplete" return stated == "true" if is_ratio == "true" apply_currency_increment_for_save(stated) end
然后…
detail.stated = stated?(value)
stated = value[:stated] detail.stated = case when stated.blank? || stated == "Incomplete" nil when value[:is_ratio] == "true" value[:stated] == "true" else apply_currency_increment_for_save stated end
发生了什么:如果在没有表达的case
使用case
,它就会变成文明等同于if ... elsif ... else ... fi.
你也可以使用它的结果,就像if...end
。
将代码移动到apply_currency_increment_for_save
并执行:
def apply_currency_increment_for_save(value) return if value.nil? || value == "Incomplete" return "true" if value == "true" # rest of the code. Or move into another function if its too complex end
逻辑是封装的,只需要2行
我喜欢@Jordan的建议。 但是,似乎调用不完整 – ‘is_ratio’参数也是从值中选择但未提供。
仅仅为了论证,我建议你可以更进一步,提供一个非常专注于评估“陈述”价值的课程 。 这似乎是极端的,但它符合单一责任的概念(责任在于评估陈述的“价值” – 而“细节”对象可能专注于其他事物而仅仅是利用评估)。
它看起来像这样:
class StatedEvaluator attr_reader :value, :is_ratio def initialize(value = {}) @value = ActiveSupport::StringInquirer.new(value.fetch(:stated, '')) @is_ratio = ActiveSupport::StringInquirer.new(value.fetch(:is_ratio, '')) end def stated return nil if value.blank? || value.Incomplete? return value.true? if is_ratio.true? apply_currency_increment_for_save(value) end end detail.stated = StatedEvaluator.new(value).stated
请注意,这使用了Rails的StringInquirer类 。