与Java的断言不同,Groovy是否声明了生产代码的一个好主意? [英] Is Groovy's assert a good idea for production code, unlike Java's assert?

查看:95
本文介绍了与Java的断言不同,Groovy是否声明了生产代码的一个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,众所周知,使用 assert 关键字通常是一个坏主意,因为它的行为取决于运行时环境(默认情况下它不会执行任何操作,除非-enableassertion传递给java运行时)。



Groovy的断言是否有所不同?它是否始终在生产代码中执行,是否建议在生产代码中使用? (在Java中,您可以使用 Preconditions



从我的理智测试看来,默认情况下 assert 标志,并且它实际上比Java关键字更强大(参见 Power Assert ) - 我只是在寻找官方/完整的答案,而不是我的轶事。

Groovy assert总是在生产代码中执行,我建议在生产中使用。我认为以下内容大致相当,但Groovy版本更紧凑

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是否声明了生产代码的一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆