2016-02-08 124 views
0

我试过阅读一些关于重构的教程,我正在努力解决条件问题。我不想使用三元运算符,但也许应该用一种方法提取它?或者有一个聪明的方式来使用地图?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 
+0

这是一个Rails代码? - 'blank?'由Rails定义,不属于Ruby –

+0

如果它是零,你想要做什么?像提出一个错误/死亡/退出? – zee

+0

是的,这是轨道 – user3437721

回答

3

,它可以制成大量清洁器由于早期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) 
1
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而不表达式中使用,它成为一个if ... elsif ... else ... fi.

您可以使用它的结果的文明等同,太,就像if...end

0

移动代码到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行仅

+0

'apply_currency_increment_for_save'的逻辑现在会变得混乱,因为它比“应用货币增量”做得更多,就像它返回“true”时一样 - 在某种程度上,它会违反单一责任原则(SRP) –

+0

我不同意,因为责任是从'value'获取'陈述'。所以你可以将它重命名为'parse_stated'或类似的东西。或者,正如我所评论的,您可以将其余的代码移动到另一个函数中。对于当前的代码,它也不是很清楚为什么一个名为'apply_currency_increment_for_save'的函数返回一个状态。主要想法是删除案例,并将其推到一个函数中,它更易读 – dgmora

0

我喜欢@乔丹的建议。但是,看起来呼叫并不完整 - “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 class

+0

“但是,它似乎是不完整的......”这听起来像你可能不熟悉[关键字参数](在Ruby中https://www.google.com/search?q=ruby+keyword+arguments)。方法签名'def声明?(说明:,is_ratio:nil)''表示该方法将一个Hash作为参数,并使用':stated'和':is_ratio'键将哈希值从其中提取到局部变量'stated'和'is_ratio '(分别在缺失情况下缺省值为'nil')。 –

+0

谢谢,乔丹。实际上,我对关键字参数很熟悉。我的评论有点偏离。您的示例中可能出现的问题与hash的潜在可能性不仅仅是“陈述”和“is_ratio”有关。对不起,混音。 – AndyV

+0

哦,我明白了。接得好。我已经更新了我的答案。 –