断言总是坏吗? [英] Are assertions always bad?

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

问题描述

我曾经在一家公司工作,其中一些领导架构师/开发人员已经强制要求各种项目不要使用断言,并且他们将常规地从代码中删除并替换为异常。

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?

推荐答案

我们使用assert的修改版本,合同。此版本被编译为释放代码,因此存在小型开销,但禁用,除非设置了诊断开关,以使性能开销最小化。在这个实例中,我们的断言处理程序可以设置为禁用,静默模式(例如,日志到文件)或噪声模式(例如,屏幕上显示abort / ignore,其中abort引发异常)。

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天全站免登陆