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

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

问题描述

我想知道为什么 assert 关键字在 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天全站免登陆