At work we have a lot of AS3 code that conditionally performs logging or assertions like so:
CONFIG::debug
{
assert(blah > 2);
}
I would really rather just write:
assert(blah > 2);
And have the definition of assert()
specify that in release mode, any calls to it, and the expressions for its arguments, should not be evaluated -- that is, it should be as if the line was empty. Not only should assert()
never be called in release, but the condition blah > 2
itself should not be evaluated.
In C# this would look like:
[Conditional("DEBUG")]
public static void assert(...) { ... }
or, in C++ (roughly):
#ifdef DEBUG
#define assert(cond) if(!(cond)) { explode(); }
#else
#define assert(cond) /* nothing */
#endif
Is there any way to do something similar in AS3, or do we have to do the co开发者_开发问答nditional compilation blocks around everything? I have been looking around manuals but have found nothing useful yet.
I don't think it is possible to make the flex compiler ignore all calls to a function by annotating its declaration like that. In fact, I'd be very interested if you ever find a way to do this - it would help to clean up the source code of my projects quite a bit...
You could specify two versions of a method, as described in this example. So you could have a fully functional assert(...args)
in your debug version, and an empty one in the release version, but you'd still have the function calls and argument evaluations in the byte code. :(
There is a way to do this.
If you use the -omit-trace-statements
flex compiler flag(automatically enabled in release builds), then all calls to the trace
function will be stripped out completely, including evaluation of their arguments.
So simply wrap your assert call in a call to trace:
trace(assert(blah > 2));
You can verify that this works correctly by doing a test with some side-effects inside your assert
.
The -omit-trace-statements
advice no longer works with recent SDKs. According to Flex 4.6 docs, all it does now is: Enables trace() statements from being written to the flashlog.txt file.
I guess enables is a typo, what is meant is prevents.
You can test it with this code, for example:
var err:Error;
trace(err = new Error('trace() arguments are still being evaluated.'));
if (err != null)
throw err;
I tried hard to accomplish what the OP wanted, but so far haven't found a better solution. AS3 doesn't have support for macros, and conditional compilation can get rid of asserts body, but not the arguments evaluation. Short of using a preprocessor (e.g. asserts stripper), the rather ugly syntax seems to be the only choice:
CONFIG::debug { assertTrue(fontDescription != null, 'fontDescription != null'); }
精彩评论