scala 在scala中需要和断言之间选择什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26140757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:36:40  来源:igfitidea点击:

what to choose between require and assert in scala

scala

提问by Roshan

Both requireand assertare used to perform certain checks during runtime to verify certain conditions.

二者requireassert用于在运行时期间执行某些检查,以验证某些条件。

So what is the basic difference between them?

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

The only one I see is that requirethrows IllegalArgumentExceptionand assertthrows AssertionError.

我唯一看到的是requirethrowsIllegalArgumentExceptionassertthrows AssertionError

How do I choose which one to use?

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

回答by Jean

As Kigyomentioned there is a semantic difference

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

  • assert means that your program has reached an inconsistent state this might be a problem with the current method/function (I like to think of it a bit as HTTP 500 InternalServerError)
  • require means that the caller of the method is at fault and should fix its call (I like to think of it a bit as HTTP 400 BadRequest)
  • 断言意味着您的程序已达到不一致的状态,这可能是当前方法/函数的问题(我喜欢将其视为 HTTP 500 InternalServerError)
  • require 意味着方法的调用者有问题,应该修复它的调用(我喜欢把它想象成 HTTP 400 BadRequest)

There is also a major technical difference:

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

assertis annotated with @elidable(ASSERTION)meaning you can compile your program with -Xelide-below ASSERTIONor with -Xdisable-assertionsand 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被注释的@elidable(ASSERTION)意思是你可以用-Xelide-below ASSERTION或编译你的程序, -Xdisable-assertions编译器不会为断言生成字节码。如果您有大量断言,这可以显着减少字节码大小并提高性能。

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

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

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

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

requireis 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.

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

回答by Kigyo

This is only my subjective point of view.

这只是我的主观观点。

I use requirewhenever I want a constraint on parameters.

require每当我想要对参数进行约束时,我都会使用。

As an example we can take the factorial for natural numbers. As we do not want to address negative numbers, we want to throw an IllegalArgumentException.

例如,我们可以采用自然数的阶乘。因为我们不想处理负数,所以我们想抛出一个IllegalArgumentException.

I would use assert, whenever you want to make sure some conditions (like invariants) are always true during execution. I see it as a way of testing.

assert每当您想确保某些条件(如不变量)在执行期间始终为真时,我都会使用, 。我认为这是一种测试方式。

Here is an example implementation of factorial with requireand assert

下面是阶乘示例实现与requireassert

def fac(i: Int) = {
  require(i >= 0, "i must be non negative") //this is for correct input

  @tailrec def loop(k: Int, result: Long = 1): Long = {
    assert(result == 1 || result >= k)   //this is only for verification

    if(k > 0) loop(k - 1, result * k) else result
  }

  loop(i)
}

When result > 1is true, then the loop was executed at least once. So the result has to be bigger or equal to k. That would be a loop invariant.

result > 1为真时,循环至少执行一次。所以结果必须大于或等于k。那将是一个循环不变式。

When you are sure that your code is correct, you can remove the assert, but the requirewould stay.

当您确定您的代码正确时,您可以删除assert,但require会保留。

回答by Animesh Srivastava

In very simple language:

用非常简单的语言:

Requireis used to enforce a precondition on the caller of a function or the creator of an object of some class. Whereas, assertis used to check the code of the function itself. So, if a precondition fails, then you get an illegal argument exception. Whereas, if an assertion fails and it's not the caller's fault and consequently you get an assertion error.

Require用于对函数的调用者或某个类的对象的创建者强制执行前提条件。而,assert用于检查函数本身的代码。因此,如果先决条件失败,那么您会得到一个illegal argument exception. 然而,如果断言失败并且不是调用者的错,那么您会得到一个assertion error.

回答by San D

require, ensure and invariance are concepts in Contract By Design (CBD) development process.

要求、确保和不变性是合同设计 (CBD) 开发过程中的概念。

require checks for the pre-conditions that the caller should satisfy to consume the routine.

require 检查调用者使用例程应满足的先决条件。

ensure checks for the correctness in the return value (and to also verify only the desired change has happened and nothing more)

确保检查返回值的正确性(并且还验证仅发生了所需的更改,仅此而已)

invariance checks for the validness of the class at all critical times.

不变性在所有关键时刻检查类的有效性。

CBD is a development methodology to build correct/robust software. For more details on CBD Google and you should hit a link from Eiffel Software. Hope this helps.

CBD 是一种构建正确/健壮软件的开发方法。有关 CBD Google 的更多详细信息,您应该点击 Eiffel Software 的链接。希望这可以帮助。