关于在Ruby中使用Guard子句我有点缓和。
Rubocop建议的风格是使用" do if condition_fails"
我经常希望使用guard子句生成有用的错误消息,如果我想继续使用上述样式,则会产生长行,并且" if"经常会被推离屏幕(我不喜欢换行)。
问题在于,作为开发人员,我并不关心错误消息,而是关注代码条件本身(有时比错误消息更明确)。
隐藏隐藏可见性的保护条款示例
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并开始突出显示很多内容,包括那些建议将它们转换为Guard子句的if condition fail end
代码块。我不确定如何对这些做出反应。
答案 0 :(得分:6)
这是非常主观的。首先,在这两种情况下,你都要打破另一个要求一行代码不超过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方法是underscore_case
,而不是camelCase
:
critical_function
而不是
criticalFunction