为什么要使用断言? [英] Why should I use asserts?

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

问题描述

我从来没有想过的断言 - 为什么你应该使用它们?

I never got the idea of asserts -- why should you ever use them?

我的意思是说,我是一个公式驱动程序,所有的断言都是安全带,头盔等。

I mean, let's say I were a formula driver and all the asserts were things like security belt, helmet, etc.

测试(在调试)都没​​关系,但现在我们想做赛车(发布)!
是否应该放弃所有安全性,因为测试时没有问题?

The tests (in debug) were all okay, but now we want to do racing (release)! Should we drop all security, because there were no issues while testing?

我永远不会删除它们。我认为大多数家伙声称,删除类似于断言的东西从来没有描述他们的代码,或者断言是绝对取代。
我从来没有见过任何真正的性能优势,特别是对于80/20规则。

I will never ever remove them. I think most of the guys that claim that removing something comparable to asserts never profiled their code or the asserts were absolute displaced. I've never seen any real performance advantage especially regarding the 80 / 20 rule.

所以,我错过了点,或者任何人告诉我,为什么我应该使用断言?
顺便说一下,我使用单元测试。

So, am I missing the point somehow, or could anybody tell me, why I should use asserts? By the way, I'm using unit tests.

推荐答案

Andrew Koenig曾经有有关使用例外和声明的良好哲学讨论在运费代码中。

Andrew Koenig used to have a good philosophical discussion over the usage of exceptions and assertions in shipping code. In the end, you're guarding against doing wild things when the program is in an irreparably broken state.


>我相信,因此,当一个
程序发现的东西是
无可辩驳的内部
状态错误,最好是终止在
一次,而不是给它的调用者
机会假装
没有错误。

I believe, therefore, that when a program discovers something that is irrefutably wrong with its internal state, it is better off terminating at once, rather than giving its caller the opportunity to pretend that nothing is wrong.

如果你喜欢,我认为例外情况
应该保留
它可以在捕获异常后做一些事情

当你发现一个条件,你
认为是不可能的,很难让
说明可能发生的事情
后。

If you like, I think that exceptions should be reserved for situations in which it is possible to do something sensible after catching the exception. When you discover a condition that you thought was impossible, it's hard to say much about what might happen afterward.

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

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