The Java language offers the keyword assert
, which is a native way of writing assertions. In the previous example, instead of throwing an exception, we could write assert
value
>=
0
:
"Value
cannot
be
negative."
. If value
is not greater than or equal to 0, the Java Virtual Machine (JVM) will throw an AssertionError
. In the following listing, I show a version of the TaxCalculator
using asserts.
Listing 4.3 TaxCalculator
with pre- and post-conditions implemented via asserts
public class TaxCalculator {
public double calculateTax(double value) {
assert value >= 0 : "Value cannot be negative"; ❶
double taxValue = 0;
// some complex business rule here...
// final value goes to 'taxValue'
assert taxValue >= 0 : "Calculated tax value
➥ cannot be negative."; ❷
return taxValue;
}
}
❶ The same pre-condition, now as an assert statement
❷ The same post-condition, now as an assert statement
Deciding whether to use assert
instructions or simple if
statements that throw exceptions is something to discuss with your team members. I’ll give you my opinion about it later in section 4.5.3.
The assert
instruction can be disabled via a parameter to the JVM, so it does not have to be executed at all times. If you disable it in production, for example, the pre-conditions will not be checked while running the system. If you do not have full control of your production environment, you may want to opt for exceptions so you can be sure your pre-conditions will be checked.
An argument against the use of assert
s is that they always throw AssertionError
, which is a generic error. Sometimes you may want to throw a more specific exception that the caller can handle. For simplicity.
We differentiate between pre-conditions and validations. This may also be taken into account when deciding between asserts and exceptions.
Leave a Reply