【问题标题】:Why should you avoid the then keyword in Ruby?为什么要避免 Ruby 中的 then 关键字?
【发布时间】:2011-04-14 06:20:55
【问题描述】:

在几个 Ruby 风格指南中都提到了你应该“永远不要使用”。就个人而言,我认为“then”关键字可以让您使代码更密集,这往往更难阅读。这个建议还有其他理由吗?

【问题讨论】:

    标签: ruby coding-style


    【解决方案1】:

    我几乎从不使用then 关键字。但是,有一种情况我认为它极大地提高了可读性。考虑以下多条件 if 语句。

    示例 A

    if customer.jobs.present? && customer.jobs.last.date.present? && (Date.today - customer.jobs.last.date) <= 90
      puts 'Customer had a job recently'
    end
    

    行长度过长。难以阅读。

    示例 B

    if customer.jobs.present? &&
       customer.jobs.last.date.present? &&
       (Date.today - customer.jobs.last.date) <= 90
      puts 'Customer had a job recently'
    end
    

    条件在哪里结束,内部代码从哪里开始。根据must Ruby Style Guides,你可以为多行条件多留一个缩进空间,但我仍然觉得它不是那么容易阅读。

    示例 C

    if customer.jobs.present? &&
       customer.jobs.last.date.present? &&
       (Date.today - customer.jobs.last.date) <= 90
    then
      puts 'Customer had a job recently'
    end
    

    对我来说,示例 C 是迄今为止最清楚的。正是使用then 才能达到目的。

    【讨论】:

      【解决方案2】:

      如果我没记错的话,then 只是将条件与真实部分分开的分隔符之一(分号和换行符是其他部分)

      如果您有一个单行 if 语句,则必须使用其中一个分隔符。

      if (1==2) then puts "Math doesn't work" else puts "Math works!" end

      对于多行 ifs,then 是可选的(换行有效)

      if (1==2) 
          puts "Math doesn't work" 
      else 
          puts "Math works!" 
      end
      

      您能否发布指向您提到的样式指南之一的链接...

      【讨论】:

      • 当然,我们可以经常(总是?)用三元运算符替换单行,例如puts 'Math ' + (1==2 ? "doesn't work" : 'works!') 不一定说我们应该,请注意,只是它是一种选择
      • 三元运算符是 if/then/else 语句的替代品。它不能替代 if/then。
      • @Mike - 有趣的一点。我对三元运算符的唯一问题是它有时会损害可读性(而且它们对于初学者来说有点迟钝)。对于小型单线,我同意这可能是一种可行的替代方案或greet_user if someone_is_logged_in 的 if-modifier 方法
      【解决方案3】:

      我认为“永远不要使用then”是错误的。使用过多的非字母字符会使代码像 perl 或 APL 一样难以阅读。使用自然语言单词通常会让程序员更舒服。这取决于代码的可读性和紧凑性之间的平衡。三元运算符有时很方便,但如果误用会很丑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-09
        • 2021-06-25
        • 1970-01-01
        • 2018-11-13
        • 2011-11-15
        • 1970-01-01
        • 2013-04-16
        • 1970-01-01
        相关资源
        最近更新 更多