问题描述
在Java中,众所周知,使用 assert
关键字通常是一个坏主意,因为它的行为取决于运行时环境(默认情况下它不会执行任何操作,除非-enableassertion传递给java运行时)。 Groovy的断言是否有所不同?它是否始终在生产代码中执行,是否建议在生产代码中使用? (在Java中,您可以使用)
从我的理智测试看来,默认情况下 assert
标志,并且它实际上比Java关键字更强大(参见) - 我只是在寻找官方/完整的答案,而不是我的轶事。
Groovy
assert file.exists(),$ file does not exist
Java
if(!file.exists()){
throw new SomeRuntimeException(file +does not exist) ;
}
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.
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");
}
这篇关于与Java的断言不同,Groovy是否声明了生产代码的一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!