我们为什么要避免以修饰符形式使用抢救? [英] Why should we avoid using rescue in its modifier form?

查看:55
本文介绍了我们为什么要避免以修饰符形式使用抢救?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将定义价值。但是该值可能是哈希键的值。如果此键不存在,我将使用 rescue 来定义值为nil。例如,

I will define value. But this value may be in value of key of hash. I will use rescue for define value is nil if this keys is not exist. for example

foo = bar [:a] [:b] [:c]取消nil

但是实际上告诉我糟糕的风格,因为我以修饰符形式使用了救援。我将更改逻辑以使用检查三个条件。

But in practice tell me bad style because me using rescue in its modifier form. I will change logic to use check three condition.

foo = bar [:a] [:b] [:c]如果bar.key ?(:a)&& bar [:a] .key?(:b)&& bar [:a] [:b] .key?(:c)

我真的很想知道为什么我们应该避免使用救援

I really would like to know Why should we avoid using rescue in its modifier form in rails?

推荐答案


为什么我们应该避免在其修改器形式中使用救援

Why should we avoid using rescue in its modifier form in rails?

首先,因为它隐藏了所有错误,包括您所期望的错误和您不知道的错误't,而全面的救援并不能使将来的代码读者清楚地知道哪些错误是预期的还是意外的。使用简单的 foo [:a] [:b] [:c] now 现在可能不是问题,但是在任何给定的点随着时间的流逝,有人可能会修改该语句以读取 foo [:a] [:b] [some_method] 并突然出现应该冒出来的任何错误 some_method 也被吞下。

Firstly, because it hides all errors, including the ones you expect and the ones you don't, and a blanket rescue doesn't make it clear to future readers of your code which errors were expected or unexpected. This might not be a problem now, with a simple foo[:a][:b][:c], but at any given point in time somebody might modify that statement to read foo[:a][:b][some_method] and suddenly any errors that should bubble out of some_method are also swallowed.

其次,通常有一个更好的,较少包含所有内容的解决方案,该解决方案更明确地设计为仅处理您打算忽略的错误:索引丢失或 nil 返回值。

Secondly, there is usually a better less all-encompassing solution that is more explicitly designed to handle only the error you intend to ignore: A missing index or a nil return value.

在您的情况下,替代方法是 not 大型如果&& && && 您的建议。对于哈希,您可以使用 dig ,它具有 rescue 的所有优点,而不会吞噬可能引发的每种异常:

In your case, the alternative is not the massive if && && && you're suggesting. For a hash, you can use either dig, which has all the benefits of rescue without swallowing every type of exception that could be raised:

foo = bar.dig(:a, :b, :c)

类似地,对于链式方法调用,可以使用 try (在Rails中)或安全导航运算符(在Ruby 2.3中) ):

Similarly, for chained method invocations, you can use try (in Rails) or the safe navigation operator (in Ruby 2.3):

foo = bar.try(:a).try(:b).try(:c)
# or
foo = bar&.a&.b&.c

这篇关于我们为什么要避免以修饰符形式使用抢救?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆