jsContract: Design by Contract library

 

Fan of Eiffel or the design by contract pattern that it espouses?

Øyvind Kinsey is, and he just created jsContract an alpha library to give you some pre and post condition abilities.

Here is an example:

JAVASCRIPT:

  1.  
  2. function _internalMethod(a, b){
  3.     Contract.expectNumber(a);
  4.     Contract.expectNumber(b);
  5.     Contract.expectWhen(config.mode === “divide”, b> 0, “Divisor cannot be 0″);
  6.     Contract.expectWhen(config.mode === “multiply”, a> 0 && b> 0, “The multiplicands cannot be 0″);
  7.     Contract.guaranteesNumber();
  8.     Contract.guarantees(function(result){
  9.         return result> 0;
  10.     }, “Result must be> 0″);
  11.  
  12.     if (config.mode == “divide”) {
  13.         return a / b;
  14.     }
  15.     // At this point config.mode must be "multiply"
  16.     return a * b;
  17. }
  18.  

A lot of contract code for little functionality…. good old contracts ;)

It is interesting to read how Øyvind instruments the code. Run a test through the translator tool and you get:

JAVASCRIPT:

  1.  
  2. function _internalMethod(a, b){
  3.     arguments.callee.isInstrumented = true;
  4.     /*preconditions*/
  5.     Contract.expectNumber(a);
  6.     Contract.expectNumber(b);
  7.     Contract.expectWhen(config.mode === “divide”, b> 0, “Divisor cannot be 0″);
  8.     Contract.expectWhen(config.mode === “multiply”, a> 0 && b> 0, “The multiplicands cannot be 0″);
  9.     var __return = (function(a, b){
  10.         if (config.mode == “divide”) {
  11.             return a / b;
  12.         }
  13.         // At this point config.mode must be "multiply"
  14.         return a * b;
  15.     }(a, b));
  16.     /*postconditions*/
  17.     Contract.guaranteesNumber(__return);
  18.     Contract.guarantees(__return, function(result){
  19.         return result> 0;
  20.     }, “Result must be> 0″);
  21.     return __return;
  22. }
  23.  

jsContract: Design by Contract library

Tags:

 
 
 

0 Comments

 

You can be the first one to leave a comment.

 

Leave a Comment

 




XHTML: You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>