Java断言未得到充分利用 [英] Java assertions underused

查看:126
本文介绍了Java断言未得到充分利用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么断言关键字在Java中未得到充分利用?我几乎从未见过它们,但我认为它们是个好主意。我当然更喜欢简洁:

I'm wondering why the assert keyword is so underused in Java? I've almost never seen them used, but I think they're a great idea. I certainly much prefer the brevity of:

assert param != null : "Param cannot be null";

详细信息:

if (param == null) {
    throw new IllegalArgumentException("Param cannot be null");
}

我怀疑他们未被充分利用,因为

My suspicion is that they're underused because


  • 他们来得相对较晚(Java 1.4),到那时许多人已经建立了他们的Java编程风格/习惯

  • 他们默认情况下在运行时关闭,为什么为什么?

推荐答案

断言理论上,用于测试不变量,假设必须才能使代码正确完成。

assertions are, in theory, for testing invariants, assumptions that must be true in order for the code to complete properly.

显示的示例是测试有效输入,这不是断言的典型用法,因为它通常是用户提供的。

The example shown is testing for valid input, which isn't a typical usage for an assertion because it is, generally, user supplied.

断言通常不会在生产代码中使用,因为存在开销,并且假设不变量失败的情况在开发和测试期间被捕获为编码错误。

Assertions aren't generally used in production code because there is an overhead and it is assumed that situations where the invariants fail have been caught as coding errors during development and testing.

关于他们对Java迟到的观点也是他们没有被广泛看到的原因。

Your point about them coming "late" to java is also a reason why they aren't more widely seen.

此外,单元测试框架允许程序化断言的某些需要在被测试代码的外部。

Also, unit testing frameworks allow for some of the need for programmatic assertions to be external to the code being tested.

这篇关于Java断言未得到充分利用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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