【问题标题】:Anyone have a DRYer solution to these Nested If Statements?有人对这些嵌套的 If 语句有 DRYer 解决方案吗?
【发布时间】:2014-04-10 21:13:44
【问题描述】:

此方法的目的是标记用户参加活动。你可以这样理解:如果今天有事件发生,如果用户存在,如果他的状态是订阅或确认,如果这个现有用户尚未签到,则将该用户添加到该事件的用户大批。

对更优雅的解决方案有什么建议吗?

def mark_attendance(user)
  if current_event(current_merchant)
    if user
      if user.status == 'subscribed' || user.status == 'confirmed'
        if current_event(current_merchant).users.where(id: user.id) == []
          current_event(current_merchant).users << user
        end
      end
    end
  end

【问题讨论】:

  • 这应该发布在codereview.stackexchange.com
  • @EliranMalka 我不知道 codereview。我想这是新的,因为它仍处于测试阶段。我上面的问题不是关于解决这个特定问题,而是更多关于如何重构嵌套的 if 语句,因为我经常遇到它们。谢谢你的建议!

标签: if-statement dry


【解决方案1】:

我可能会这样写:

def mark_attendance(user)

  event = current_event(current_merchant)
  attending = ['subscribed', 'confirmed']

  event.users << user if (event && user) &&
      attending.include?(user.status) &&
      event.users.where(id: user.id).any?

end

没有太多短路,但更清晰的 IMO。

【讨论】:

    【解决方案2】:

    我的方法是:

    def mark_attendance(user)
    
      if !user
        return
      end
    
      current_merchant_event = current_event(current_merchant)
    
      if !current_merchant_event
        return
      end
    
      if (user.status != 'subscribed' && user.status != 'confirmed')
        return
      end
    
      if current_merchant_event.users.where(id: user.id) == []
            current_merchant_event.users << user
    
      end
    

    它更长,但是执行效率更高,并且更容易确定到达函数的“内容”所需的内容。

    current_event 只被调用一次,这也是 louism 所指出的。

    在原始代码中,无论用户如何,都会调用 current_event 函数,如果用户无效,这是无缘无故的额外代码执行。

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2020-09-16
      • 2014-08-11
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多