what to choose between require and assert in scala

前端 未结 5 1977
谎友^
谎友^ 2020-12-23 13:37

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

So what is the basic difference bet

5条回答
  •  醉话见心
    2020-12-23 13:45

    As Kigyo mentioned there is a semantic difference

    • 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)

    There is also a major technical difference:

    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.

    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.

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

提交回复
热议问题