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

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

问题描述

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

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).

Groovy 的断言是否不同?是否总是在生产代码中执行,是否推荐在生产代码中使用?(在 Java 中你会使用类似 先决条件代替)

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)

从我的健全性测试来看,默认情况下 assert 在没有任何标志的情况下运行良好,而且它实际上比 Java 关键字更强大(请参阅 Power Assert) - 我只是在寻找官方/完整的答案,而不是我的轶事.

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 总是在生产代码中执行,我推荐在生产中使用.我认为以下内容大致相同,但 Groovy 版本更紧凑

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

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

Java

if (!file.exists()) {
    throw new SomeRuntimeException(file + " does not exist");
}

这篇关于与 Java 的断言不同,Groovy 的断言是生产代码的好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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