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:

  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.  

Go to Source

2 Responses to jsContract: Design by Contract library

Avatar

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.

Avatar

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

Comment Form

About this blog

This blog delivers stylish and dynamic news for designers and web-developers on all subjects of design, ranging from: CSS, Ajax, Javascript, web design, graphics, typography, advertising & much more. Our goal is to help you communicate effectively on the web with an engaging website or functional interface.