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

查看:353
本文介绍了为什么在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天全站免登陆