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:
-
-
function _internalMethod(a, b){
-
Contract.expectNumber(a);
-
Contract.expectNumber(b);
-
Contract.expectWhen(config.mode === “divide”, b> 0, “Divisor cannot be 0″);
-
Contract.expectWhen(config.mode === “multiply”, a> 0 && b> 0, “The multiplicands cannot be 0″);
-
Contract.guaranteesNumber();
-
Contract.guarantees(function(result){
-
return result> 0;
-
}, “Result must be> 0″);
-
-
if (config.mode == “divide”) {
-
return a / b;
-
}
-
// At this point config.mode must be "multiply"
-
return a * b;
-
}
-
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:
-
-
function _internalMethod(a, b){
-
arguments.callee.isInstrumented = true;
-
/*preconditions*/
-
Contract.expectNumber(a);
-
Contract.expectNumber(b);
-
Contract.expectWhen(config.mode === “divide”, b> 0, “Divisor cannot be 0″);
-
Contract.expectWhen(config.mode === “multiply”, a> 0 && b> 0, “The multiplicands cannot be 0″);
-
var __return = (function(a, b){
-
if (config.mode == “divide”) {
-
return a / b;
-
}
-
// At this point config.mode must be "multiply"
-
return a * b;
-
}(a, b));
-
/*postconditions*/
-
Contract.guaranteesNumber(__return);
-
Contract.guarantees(__return, function(result){
-
return result> 0;
-
}, “Result must be> 0″);
-
return __return;
-
}
-
jsContract: Design by Contract library



















































0 Comments
You can be the first one to leave a comment.