Ruby 进行多少错误检查才合适?

发布于 2024-07-25 12:45:08 字数 275 浏览 15 评论 0原文

我正在 Ruby 中实现一些东西,我想知道多少错误检查是合适的(或者更准确地说,按照惯例应该进行多少错误检查)?

例如,我正在实现一种交换数组中两个元素的方法。 该方法非常简单:

def swap(a,b)
  @array[a], @array[b] = @array[b], @array[a]
end

它确实很简单,但是检查给定索引是否有效是 ruby​​-ish,还是不必要的开销(请记住,我不打算让该方法使用像这样的环绕值) -1)?

I'm implementing a few things in Ruby and I was wondering how much error checking is appropriate (or, more precisely, how much error checking should be done by convention)?

For example, I'm implementing a method which swaps two elements in an array. The method is very simple:

def swap(a,b)
  @array[a], @array[b] = @array[b], @array[a]
end

It's really simple, but is it ruby-ish to check whether the given indexes are valid, or is that an unnecessary overhead (bearing in mind I do not intend for the method to work with wrap-around values like -1)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌辣 2024-08-01 12:45:08

这取决于您正在寻找的行为。 您调用的 Array#[] 方法将为您进行检查,如果您使用不存在的索引,则返回 nil,因此我认为不需要重复错误检查你想要那种标准行为。 如果您想要其他东西,您需要实现您想要的行为。

但是,此方法将在索引为 -1 的情况下工作,因此如果您想禁止这样做,则需要对此进行检查。

基本上,我认为一个好的规则是:检查您的方法将出现错误行为的条件,并实现您想要的行为。 越界索引条件将被数组捕获并以某种方式处理——如果处理正确,则不需要执行任何操作。 与方法的某些自定义期望不匹配的索引根本不会被捕获,因此您肯定需要检查它。

It depends on the behavior that you're looking for. The Array#[] method that you're calling will do that check for you and return nil if you're using a nonexistent index, so I don't see a need to duplicate the error checking if you want that standard behavior. If you want something else, you'll need to implement the behavior you want.

However, this method will work with an index of -1, so if you want to disallow that, you will need to put a check for that.

Basically, I think a good rule is: Check for conditions in which your method will behave incorrectly, and implement the behavior you want. The out-of-bounds index condition will be caught by the array and handled a certain way -- if that handling is correct, you don't need to do anything. An index that does not match some custom expectation of the method will not be caught at all, so you definitely need to check for it.

情何以堪。 2024-08-01 12:45:08

我无法帮助您处理负索引,但

@array.fetch(a)

如果 a 是无效索引,您可以用来引发异常。

当我将无效索引视为“不可能发生”的情况时,我应该使用 fetch ,但有时我只考虑“快乐路径”场景。

I can't help you with negative indexes, but you can use

@array.fetch(a)

to raise an exception if a is an invalid index.

I ought to use fetch when I regard an invalid index as a "Can't happen" case, but sometimes I think only about the "happy path" scenario.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文