到目前为止,我已经做了一年的专业软件工程师,并获得了计算机科学学位。我知道c++和C中的断言有一段时间了,但直到最近才知道它们存在于c#和。net中。

我们的生产代码不包含任何断言,我的问题是这个…

我应该开始在我们的生产代码中使用断言吗?如果可以,什么时候使用它最合适?这样做会更有意义吗

Debug.Assert(val != null, "message");

or

if ( val == null )
    throw new exception("message");

当前回答

在我的书里几乎从来没有。 在绝大多数情况下,如果你想检查一切是否正常,那么就扔掉。

我不喜欢的是,它使调试构建在功能上与发布构建不同。如果调试断言失败,但功能在发布中工作,那么这有什么意义呢?如果断言者早已离开公司,没有人知道这部分代码,那就更好了。然后你就得花点时间去探索这个问题,看看它是不是真的是个问题。如果这是一个问题,那为什么那个人不第一时间扔呢?

对我来说,这建议使用调试。声称你把问题推给别人,自己解决问题。如果某件事应该是这样,但事实并非如此,那就扔掉。

我猜可能有一些性能关键的场景,你想要优化你的断言,它们在那里很有用,但是我还没有遇到这样的场景。

其他回答

使用断言检查开发人员的假设,使用异常检查环境的假设。

我不会在产品代码中使用它们。抛出异常,捕获和记录。

在asp.net中也需要小心,因为断言可以显示在控制台上并冻结请求。

仅在希望为发布版本删除检查的情况下使用断言。请记住,如果不在调试模式下编译,断言将不会触发。

对于检查为空的示例,如果这是在仅限内部的API中,我可能会使用断言。如果它在一个公共API中,我肯定会使用显式检查和抛出。

摘自《实用程序员:从熟练工到高手》

Leave Assertions Turned On There is a common misunderstanding about assertions, promulgated by the people who write compilers and language environments. It goes something like this: Assertions add some overhead to code. Because they check for things that should never happen, they'll get triggered only by a bug in the code. Once the code has been tested and shipped, they are no longer needed, and should be turned off to make the code run faster. Assertions are a debugging facility. There are two patently wrong assumptions here. First, they assume that testing finds all the bugs. In reality, for any complex program you are unlikely to test even a miniscule percentage of the permutations your code will be put through (see Ruthless Testing). Second, the optimists are forgetting that your program runs in a dangerous world. During testing, rats probably won't gnaw through a communications cable, someone playing a game won't exhaust memory, and log files won't fill the hard drive. These things might happen when your program runs in a production environment. Your first line of defense is checking for any possible error, and your second is using assertions to try to detect those you've missed. Turning off assertions when you deliver a program to production is like crossing a high wire without a net because you once made it across in practice. There's dramatic value, but it's hard to get life insurance. Even if you do have performance issues, turn off only those assertions that really hit you.

您应该使用Debug。断言来测试程序中的逻辑错误。编译器只能通知您语法错误。因此,您肯定应该使用Assert语句来测试逻辑错误。比如测试一个销售汽车的项目,只有蓝色的宝马可以得到15%的折扣。编译器不能告诉你你的程序在执行这个操作时逻辑上是否正确,但是assert语句可以。