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

旧街凉风 提交于 2019-11-29 11:13:32

问题


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.


回答1:


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");
}


来源:https://stackoverflow.com/questions/8077757/is-groovys-assert-a-good-idea-for-production-code-unlike-javas-assert

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!