Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #17513

Re: Cheap runtime asserts

From JJ <jaejunks@glegooilma-swapit.com>
Newsgroups comp.lang.javascript
Subject Re: Cheap runtime asserts
Date 2012-12-06 07:29 +0000
Organization A noiseless patient Spider
Message-ID <XnsA121943364577jaejunksglegooilma@0.0.0.23> (permalink)
References <1892433a-7696-4b03-a94c-0b1f0a984134@googlegroups.com>

Show all headers | View raw


glathoud <glathoud@yahoo.fr> wrote:
> To check argument types in functions that are used in many different
> places, I have been using this:
> 
> function someCoreFunction( domnode, text ) {
> 
>     // "Cheap runtime assert": fails when `domnode` is not a DOM node.
>     domnode.childNodes.a;
>          
>     // Same idea, for a string.
>     text.substring.a;
> 
>     // Rest of the function
>     // ...
> 
> }
> 
> It helps to catch mistakes early, including during development. I am
> *not* advocating to litter the code with thousands such statements,
> but in a few strategical places the benefits can exceed the costs.
> 
> Hopefully this can help someone. Constructive feedback is welcome.
> 
> Guillaume

Some conditions might still won't cause an exception. For example:

function theFunc(node, txt) {
  //the cheap assert (pre-access the property)
  node.childNodes[0].data;
  //actual code here
  if (node.childNodes[0].data === '') {
    node.childNodes[0].data = txt;
  }
}
theFunc(document.body);

Now, assuming that "document.childNodes[0]" is a HTMLDivElement, the 
assert won't cause an exception and the next "if..." statement will be 
executed.

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Cheap runtime asserts glathoud <glathoud@yahoo.fr> - 2012-12-04 22:00 -0800
  Re: Cheap runtime asserts Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-12-05 20:18 +0100
    Re: Cheap runtime asserts glathoud <glathoud@yahoo.fr> - 2012-12-06 11:19 -0800
      Re: Cheap runtime asserts Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-12-06 23:41 +0100
  Re: Cheap runtime asserts Patricia Shanahan <pats@acm.org> - 2012-12-05 12:00 -0800
    Re: Cheap runtime asserts glathoud <glathoud@yahoo.fr> - 2012-12-06 11:34 -0800
  Re: Cheap runtime asserts JJ <jaejunks@glegooilma-swapit.com> - 2012-12-06 07:29 +0000
    Re: Cheap runtime asserts glathoud <glathoud@yahoo.fr> - 2012-12-06 11:40 -0800
      Re: Cheap runtime asserts JJ <jaejunks@glegooilma-swapit.com> - 2012-12-07 12:03 +0000
        Re: Cheap runtime asserts glathoud <glathoud@yahoo.fr> - 2012-12-10 23:46 -0800
  Re: Cheap runtime asserts Stefan Weiss <krewecherl@gmail.com> - 2012-12-06 23:00 +0100
    Re: Cheap runtime asserts glathoud <glathoud@yahoo.fr> - 2012-12-11 00:07 -0800

csiph-web