簡體   English   中英

ruby - 重構if else語句

[英]ruby - refactoring if else statement

我已經嘗試閱讀一些關於重構的教程,我正在努力解決條件問題。 我不想使用三元運算符,但也許這應該在方法中提取? 或者有一種聰明的方式來使用地圖嗎?

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 ... 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類

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM