nongnu.org

Syntax improvements:

Consider the classic assert macro:

#define assert(x) if(!(x)) { throw new Error("Assertion failed: " + #x) } 

This macro allows one to use a very natural syntax, assert(status != 'dead') let's say, and still get a meaningful error message when the assertion fails. If you wanted to do this in pure Javascript, you'd either just have a regular assert function check whether its argument is true, in which case you won't have a meaningful error message, or you'd use something like this:

assert(function() { return x })

and have the assert function call the passed-in function. If it returns false, assert could decompile the passed-in function and use the code to construct an error messge. That approach, however, is verbose, ugly, and delicate (not all browsers support function decompilation).

Another approach would be to just call assert with a string giving the error message to use. But who wants to repeat himself? Using an assert macro with the C preprocessor provides a way to use a simple syntax that always does the right thing.

Also, a assert macro can be #ifdefed away, so it can have no effect on production code.

Read the original on nongnu.org ↗