为什么在java中默认不启用断言 [英] Why is assert not enabled by default in java

查看:59
本文介绍了为什么在java中默认不启用断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是从语言设计的角度.

My question is from the perspective of language design.

为什么断言被区别对待,即它引发错误而不是异常,默认情况下未启用等.

Why is assert treated differently i.e. it raises a error and not an exception, it is not enabled by default etc..

它看起来很优雅(非常主观的意见),易于阅读(再次主观)进行验证和;还有一些工具(IDE)可以对其进行实时评估并根据断言提供警告.

It does seem elegant(very subjective opinion), easy to read(again subjective) for doing validations & also there are tools(IDE) which can live-evaluate it and provide warnings based on assertions.

推荐答案

我想说的原因是 Java 的默认值是用于生产代码(软件的发布"版本) - 如果用户需要构建您的他们将使用提供的默认代码,如果您是开发人员并希望获得更好的报告,您可以随时做出一些额外的努力.

I'd say that the reason is that defaults for Java are meant for production code (the "release" version of software) - if users need to build your code they will use provided defaults and if you are developer and want to have better reporting you can always make some additional effort.

通常您不希望随发布版本一起发布断言.为什么?你总是可以设计你的代码来执行一些不干扰的后台错误处理,并且在用户面前抛出 AssertionError 并不总是可行的方法.

Usually you don't want to ship assertions with a release version. Why? You can always design your code to perform some not disturbing background error handling and throwing AssertionError in users face is not always the way to go.

大多数时候我看到它们被用作额外的代码测试 - 当您运行回归测试并且代码覆盖率很高时,没有断言错误表明您的代码中没有(显而易见的)错误.如果发生了某些情况,您可以从堆栈跟踪中推断出问题所在以及原因.另一方面,客户不应该因为看到描述性错误信息而烦恼.

Most of the time I see them used as additional code testing - when you run regression tests and code coverage is high no assertion error suggest that there are no (obvious to spot) errors in your code. If some happens, you can deduce from stack trace what went wrong and why. On the other hand clients shouldn't be bothered with seeing descriptive error information.

那么你应该如何实际使用它们?根据我的经验,您应该设计代码以不使用断言来执行错误处理.如果你想在某个地方抛出异常,你自己明确地抛出它.一旦代码可以自行处理,您就可以添加断言来检查前置条件和后置条件以及不变量——所以基本上使用它们来检查算法正确性而不是数据正确性.它对开发人员而不是用户具有价值.一旦您对您的解决方案有足够的信心,您就可以禁用断言,您的程序仍然可以正常工作,您的用户不必运行具有额外运行时开销的程序.

So how should you actually use them? In my experience you should design code to not use assertions to perform error handling. If you want exception to be thrown somewhere throw it explicitly yourself. Once code can handle itself, you can add assertions to check pre- and postconditions as well as invariants - so basically used them to check algorithm correctness instead of data correctness. It has value for developers rather than users. Once you have enough confidence in your solution, you can disable assertions, your program still works fine and your users don't have to run program with additional runtime overhead.

这篇关于为什么在java中默认不启用断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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