断言总是不好的吗? [英] Are assertions always bad?

查看:27
本文介绍了断言总是不好的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经在一家公司工作,该公司的一些首席架构师/开发人员在各种项目中都要求不得使用断言,并且它们会经常从代码中删除并替换为异常.

I used to work for a company where some of the lead architect/developers had mandated on various projects that assertions were not to be used, and they would routinely be removed from code and replaced with exceptions.

我觉得它们对于编写正确的代码非常重要.谁能建议如何证明这样的授权是合理的?如果是这样,断言有什么问题?

I feel they are extremely important in writing correct code. Can anyone suggest how such a mandate could be justified? If so, what's wrong with assertions?

推荐答案

根据 JaredPar 的评论,我们使用了 assert 的修改版本,它的作用类似于合同.这个版本被编译到发布代码中,所以有一个小的开销,但是除非设置了诊断开关,否则禁用,这样性能开销被最小化.我们在这个实例中的断言处理程序可以设置为禁用、静默模式(例如记录到文件)或嘈杂模式(例如在屏幕上显示中止/忽略,其中中止抛出异常).

We use a modified version of assert, as per JaredPar's comment, that acts like a contract. This version is compiled into the release code so there is a small size overhead, but disabled unless a diagnostics switch is set, such that performance overhead is minimized. Our assert handler in this instance can be set to disabled, silent mode (e.g. log to file), or noisy mode (e.g. display on screen with abort / ignore, where abort throws an exception).

我们使用自动回归测试作为预发布测试的一部分,断言在这里非常重要,因为它们允许我们发现在 GUI 级别无法发现的潜在内部错误,并且最初可能不会致命用户级别.通过自动化,我们可以在有或没有诊断的情况下运行测试,除了执行时间之外几乎没有开销,因此我们还可以确定断言是否有任何其他副作用.

We used automated regression testing as part of our pre-release testing, and asserts are hugely important here as they allow us to find potential internal errors that cannot be picked up at a GUI level, and may not be initially fatal at a user level. With automation, we can run the tests both with and without diagnostics, with little overhead other than the execution time, so we can also determine if the asserts are having any other side effects.

断言需要注意的一件事是副作用.例如,您可能会看到类似 assert(MyDatabasesIsOk()) 的内容,它无意中更正了数据库中的错误.这是一个错误,因为断言不应该改变正在运行的应用程序的状态.

One thing to be careful of with asserts is side effects. For example, you might see something like assert(MyDatabasesIsOk()), which inadvertently corrects errors in the database. This is a bug, as asserts should never change the state of the running application.

这篇关于断言总是不好的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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