加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 验证nil的方法参数

发布时间:2020-12-17 02:22:51 所属栏目:百科 来源:网络整理
导读:我在方法声明后显示了一个带有验证的 Java方法: public Integer executeComputation(Integer a,Integer b) { Validate.notNull(a); Validate.notNull(b); Validate.isTrue(b != 0); return a/b;} 将此方法调用转换为ruby代码是一种很好的做法,如下所示: de
我在方法声明后显示了一个带有验证的 Java方法:

public Integer executeComputation(Integer a,Integer b) {
   Validate.notNull(a);
   Validate.notNull(b);
   Validate.isTrue(b != 0);
   return a/b;
}

将此方法调用转换为ruby代码是一种很好的做法,如下所示:

def execute_computation(a,b)
  raise 'a is nil' if a.nil?
  raise 'b is nil' if b.nil?
  raise 'zero division' if b == 0
  a/b
end

这是一个微不足道的例子,但我觉得对于Ruby来说它太健谈了.然而,我习惯用Java中的公共方法检查我的参数,以防止一些难以发现的NPE.

有人可以解释Ruby中的参数验证是如何工作的吗?理想情况下,一些参考文献.

解决方法

最好快速失败.仅当您有一些要满足的强限制时才检查类型.除了运行时异常将被抛出.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读