Wednesday, December 5, 2012

ASSERT in JS

Usually asserts are not destructive. I.e. even if condition false-d, the code still working. Your evaluations throw-ing exceptions and changing the logic. Also there is a some additional logic resides in assert call:
  • in release build the code is disabled, ideally removed by compiler
  • log output with caller function
  • log evaluated value
  • log comment string
  • breakpoint call
Extra things I do in C++ and could potentially port to JS:
  • modal dialog with assert info(above)
  • ability to ignore further( do not display dialog), retry(repeat the condition call)
  • counter for particular assert failures
  • log not just to comsole but also to external target like FS or server.
There are some related patterns applied in debug mode
  • automatic parameters and return value check against type and permitted values. That should have the type definition and values/validators be available in run-time. Used Annotation for that. The call traps need enumeration of object's methods and wrapping by aspect.
  • Profiler( call counts+timing, call graph, etc) is not a hot topic anymore since most of browsers have them implemented. But in many cases like mobile, it worth to have the profiler be implemented by JS and hooked into server-side logger.
Final assert call I envision as such:

while( assert && assert( isDomNode(param1), "should be a valid dom node") );

or simpler form:

assert && assert( isDomNode(param1), "should be a valid dom node");

assert && assert(...) gives ability to disable assert for release build on AMD module switch level. It also could be used for individual module tuning.
while( assert(...) ) needed for "Retry" option. Handy for debugging. When problem found, the same condition could be reevaluated for step-through debugging.

Annotations and aspects are the gears for such functionality. 25% of above I have done earlier but not made a shippable tool. It is too big effort to be justified by projects I was working on at the time. If anyone interested we could talk further.

1 comment:

  1. C++ with pseudocode:
    http://blog.firsov.net/2010/11/assert-how-it-should-be.html

    ReplyDelete