在scala中需要和断言之间选择什么 [英] what to choose between require and assert in scala

查看:44
本文介绍了在scala中需要和断言之间选择什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

requireassert 都用于在运行时执行某些检查以验证某些条件.

Both require and assert are used to perform certain checks during runtime to verify certain conditions.

那么它们之间的基本区别是什么?

So what is the basic difference between them?

我看到的唯一一个是 require 抛出 IllegalArgumentExceptionassert 抛出 AssertionError.

The only one I see is that require throws IllegalArgumentException and assert throws AssertionError.

我该如何选择使用哪一种?

How do I choose which one to use?

推荐答案

正如 Kigyo 提到的,存在语义差异

As Kigyo mentioned there is a semantic difference

  • assert 表示您的程序已达到不一致的状态,这可能是当前方法/函数的问题(我喜欢将其视为 HTTP 500 InternalServerError)
  • require 表示方法的调用者有问题,应该修复它的调用(我喜欢把它想象成 HTTP 400 BadRequest)

还有一个主要的技术差异:

There is also a major technical difference:

assert@elidable(ASSERTION) 注释这意味着您可以使用 -Xelide-below ASSERTION-Xdisable-assertions 编译您的程序,并且编译器不会为断言生成字节码.如果您有大量断言,这可以显着减少字节码大小并提高性能.

assert is annotated with @elidable(ASSERTION) meaning you can compile your program with -Xelide-below ASSERTION or with -Xdisable-assertions and the compiler will not generate the bytecode for the assertions. This can significantly reduce bytecode size and improve performance if you have a large number of asserts.

知道了这一点,您可以使用assert 来验证所有 程序中无处不在 的不变量(每个单独的前提条件/后置条件)方法/函数调用),而不是在生产中付出代价.

Knowing this, you can use an assert to verify all the invariants everywhere in your program (all the preconditions/postconditions for every single method/function calls) and not pay the price in production.

您通常会在启用所有断言的情况下进行test"构建,它会更慢,因为它会始终验证所有断言,然后您可以拥有生产" 没有断言的产品构建,您将消除通过断言完成的所有内部状态检查

You would usually have the "test" build with all the assertions enabled, it would be slower as it would verify all the assertions at all times, then you could have the "production" build of your product without the assertions, which you would eliminate all the internal state checks done through assertion

require 不可省略,在库(包括内部库)中使用更有意义,通知调用者调用给定方法/函数的前提条件.

require is not elidable, it makes more sense for use in libraries (including internal libraries) to inform the caller of the preconditions to call a given method/function.

这篇关于在scala中需要和断言之间选择什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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