为什么java中默认不启用assert

2022-01-16 00:00:00 assert jvm java

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

My question is from the perspective of language design.

为什么 assert 的处理方式不同,即它引发错误而不是异常,默认情况下不启用等等.

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.

相关文章