Scala seems to define 3 kinds of assertions: assert
, require
and assume
.
As far as I can understand, the difference (compared to a generic assertion) of require
is that it is specifically meant for checking inputs (arguments, incoming messages etc). And what's the meaning of assume
then?
assert is a precondition in Scala that evaluates a boolean expression as true or false. It's generally used to validate the execution of the program during runtime. We can see assert is used commonly in testing the functionality of programs.
Do not use assertions to check the parameters of a public method. An assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type.
Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state of a code which is expected before it starts running, or the state after it finishes running. Unlike normal error handling, assertions are generally disabled at run-time.
Preconditions refer to some conditions in Scala that need to be fulfilled before going further with any code or program. In Scala, the process of Designing by Contract(DbC), a software designing process gives significance and meaning to Scala preconditions.
If you look at the code in Predef.scala
you'll see that all three do very similar job:
def assert(assertion: Boolean) { if (!assertion) throw new java.lang.AssertionError("assertion failed") } def assume(assumption: Boolean) { if (!assumption) throw new java.lang.AssertionError("assumption failed") } def require(requirement: Boolean) { if (!requirement) throw new IllegalArgumentException("requirement failed") }
There are also versions which take extra arguments for reporting purposes (see http://harrah.github.com/browse/samples/library/scala/Predef.scala.html).
The difference is in the exception type they throw and error message they generate.
However, static checkers could treat all three differently. The intention is for assert
to specify a condition that a static check should attempt to prove, assume
is to be used for a condition that the checker may assume to hold, while require
specifies a condition that the caller must ensure. If a static checker finds a violation of assert
it considers it an error in the code, while when require
is violated it assumes the caller is at fault.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With