Ruby中的Guard子句并不总是那么方便

Ruby中的Guard子句并不总是那么方便,ruby,Ruby,我对Ruby中使用Guard子句感到有点不安 Rubocop建议的风格是使用“如果条件_失败,则执行” 通常,我想用guard子句生成有用的错误消息,如果我想继续使用上述样式,就会产生长行,并且“if”通常会被从屏幕上删除(我不喜欢换行) 问题是,作为一名开发人员,我并不真正关心错误消息,而是关心代码条件本身(有时比错误消息更明确) 隐藏开发人员可见性的Guard子句示例 def crtical_function(params) fail Exception.new("Useful mess

我对Ruby中使用Guard子句感到有点不安

Rubocop建议的风格是使用“如果条件_失败,则执行”

通常,我想用guard子句生成有用的错误消息,如果我想继续使用上述样式,就会产生长行,并且“if”通常会被从屏幕上删除(我不喜欢换行)

问题是,作为一名开发人员,我并不真正关心错误消息,而是关心代码条件本身(有时比错误消息更明确)

隐藏开发人员可见性的Guard子句示例

def crtical_function(params)
  fail Exception.new("Useful message for the user, but not often useful message for the dev, and as you can see this line is veeeeeeerrrrrry long and just annoying because the dev is rather looking for the condition itself which is often more einteresting than an error message") if not_enough_params
end
如果没有Guard子句样式,您将立即理解

def crtical_function(params)
  if not_enough_params
    fail Exception.new("Useful message for the user, but not often useful message for the dev, and as you can see this line is veeeeeeerrrrrry long and just annoying because the dev is rather looking for the condition itself which is often more einteresting than an error message") 
  end
end
嗯,是的,故事是我刚刚安装了rubycop,它开始突出显示很多东西,包括那些
if-condition fail-end
代码块,建议将它们转换为保护子句。我不知道该如何应对这些


是否有一个设置来配置,或者可能有一个解决方案来保持开发人员的可见性,同时避免没有编写保护条款的抱怨?您对降低可视性/指南合规性有何建议?

这是非常主观的。首先,在这两种情况下,您都违反了另一个事实上的约定,即希望一行代码不超过80个字符

所有这些约定都是从监视器相当小的时代继承下来的,因此排长队是不舒服的,可能会隐藏您注意到的重要语句

就我个人而言,我仅在执行预验证时使用单行样式,通常在方法开始时,或者在序列中有几个短条件时使用单行样式

不管您使用的样式如何,您也可以考虑在变量中提取消息,以便最终代码更可读。

def critical_function(params)
  message = "Useful message for the user, but not often useful message for the dev, and as you can see this line is veeeeeeerrrrrry long and just annoying because the dev is rather looking for the condition itself which is often more einteresting than an error message"
  fail Exception.new(message) if not_enough_params
end

def critical_function(params)
  message = "Useful message for the user, but not often useful message for the dev, and as you can see this line is veeeeeeerrrrrry long and just annoying because the dev is rather looking for the condition itself which is often more einteresting than an error message"

  if not_enough_params
    fail Exception.new(message) 
  end
end
提取消息还允许您将其存储在常量中和/或将其冻结,和/或执行其他解释器优化

此外,还可以考虑包装字符串。

最后,说到约定,我更担心的是遵循方法的命名约定,而不是为if语句强制使用一种样式

Ruby方法是
下划线\u case
,而不是
camelCase

critical_function
而不是

criticalFunction

你的问题是什么?如果生成的行超过80个字符,Rubocop不建议使用修饰符
。WTF异常是否会出现应用程序最终用户会看到的消息?在当前版本的Ruby下,优化字符串与在方法外提取字符串无关,或者冻结它。
80个字符
限制是否仍然在附近或有点放松-可能是140个字符,因为大多数显示器/笔记本电脑都能容纳这么多字符?@WandMaker StackOverflow的代码块大约有80个字符宽。@Simone感谢您的建议,并对snake_的案例表示抱歉,我通常对此也很认真。是的,这确实是主观的,但我想知道人们实际上是如何应对的。此外,拥有小型显示器实际上仍然是一个问题,因为如今,即使我们拥有大型显示器,我们通常也会在几个应用程序之间分割屏幕,问题依然存在。