断言可以在生产中使用还是仅在开发时使用? [英] Can assertions be used in production or only while developing?

查看:148
本文介绍了断言可以在生产中使用还是仅在开发时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下问题:避免!=空语句我问我们的一位高级开发人员,为什么不为什么要使用断言.尽管他的回答被证明是合理的(我们使用自定义例外),但他还声称断言应在开发和测试时使用,而不是在生产中使用.

Following this question: Avoiding != null statements I asked one of our senior developers why wouldn't why use assertions. While his answer proved reasonable (we use custom exceptions), he also claimed that assertions are meant to be used while developing and testing, but not in production.

但是在Oracle文档中 http://docs.oracle.com/javase/6/docs/technotes/guides/language/assert.html 看来断言应该在测试之外使用,甚至可以禁用它们.

But in Oracle's documentation http://docs.oracle.com/javase/6/docs/technotes/guides/language/assert.html it looks like assertions are meant to be used beyond testing, even more given the possibility of disabling them.

那么,有没有更好的理由或良好实践不使用断言?

So, is there any better reason or good practice not to use assertions?

推荐答案

断言的行为因语言而异.在C语言中,它们经常被错误地使用,并且错误的用法非常普遍,以至于许多人建议根本不要使用它们.它们不应在生产中使用(即C的生产编译应为预处理器定义 NDEBUG ),因为它们仅用于减慢执行速度.

Assertions behave differently depending on the language. In C, they are often used incorrectly, and the incorrect usage is so common that many advise that they not be used at all. They should not be used in production (ie, production compiles of C should define NDEBUG for the preprocessor) as they only serve to slow down execution.

声明的目的是陈述逻辑上的必要性,而不是检查结果.例如,写(用C语言编写)是正确的:

The purpose of an assertion is to state a logical necessity, not to check a result. For example it is correct (in C) to write:

f = malloc( s );
if( f == NULL ) {
   ...; exit( 1 );
}
assert( f != NULL );   # This is logically necessary.

但是永远写错了:

f = malloc( x );        # THIS IS AN EXAMPLE OF INCORRECT USAGE
assert( f != NULL );    # DO NOT DO THIS

这实际上很有用,因为编写代码是完全有效的:

This is actually useful, since it is perfectly valid to write:

f = xmalloc( x );
assert( f != NULL ); 

作为读者的文档,xmalloc的定义永远不会返回空值.

Which acts as documentation to the reader that xmalloc is defined in such a way that it will never return a null value.

它们通常在功能开始时使用:

They are often used at the start of functions:

void f( void *p ) { assert( p != NULL ); ... }

这种用法不是是错误检查.而是用来表明函数 f 希望它永远不会传递空指针.给开发人员的文档是,将空指针传递给 f 是编程错误.将其设置为断言可以使在启用断言时在运行时检测到错误.

Such usage is not an error check. Rather it serves to indicate that the function f expects that it will never be passed a null pointer. It is documentation to developers that passing a null pointer to f is a programming error. Making it an assertion enables the error to be detected at run time when assertions are enabled.

这篇关于断言可以在生产中使用还是仅在开发时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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