jsContract: Design by Contract library
In: web resources
4
Feb
2010

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;
-
}
-
Go to Source
2 Responses to jsContract: Design by Contract library
KathyM
March 12th, 2010 at 10:57 pm
here's the Chinese:
我在這裡寫中文, 所以你醒來的時候要作中文功課.
It means (literal translation):
I am writing chinese here, so that when you wake up you have to do chinese homework.
mizzblackparader
April 3rd, 2010 at 8:44 am
Let x = the divisor and y = the quotient, then
y = 5600/x and x-y =10
Plug 5600/x into the second equation in place of y.
x – 5600/x = 10
Multiply both sides by x.
x^2 – 5600 = 10x
x^2 – 10x – 5600 = 0
(x-80)(x+70) = 0
x = 80 or x = -70
If x = 80, then y = 5600/80 = 70.
If x = -70, then y = 5600/-70 = -80