Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Groovy's assert a good idea for production code, unlike Java's assert?

In Java it's known that using the assert keyword is usually a bad idea, as its behavior is dependant on the runtime enviornment (it doesn't do anything by default, unless the -enableassertion is passed to the java runtime).

Is Groovy's assert different? Is it always executed in production code, and is it recommended to use in production code? (In Java you would use something like Preconditions instead)

From my sanity tests it seems that by default assert works well without any flags, and that it's actually way more powerful than the Java keyword (see Power Assert) - I'm just looking for an official/complete answer, as opposed to my anecdotal one.

like image 229
ripper234 Avatar asked Nov 10 '11 10:11

ripper234


1 Answers

Groovy assert is always executed in production code, and I recommended to use in production. I see the following as being roughly equivalent, but the Groovy version is more compact

Groovy

assert file.exists(), "$file does not exist"

Java

if (!file.exists()) {
    throw new SomeRuntimeException(file + " does not exist");
}
like image 94
Dónal Avatar answered Nov 16 '22 11:11

Dónal