Friday, September 26, 2008

Type Constraints in Joose

Jeremy Wall of Google provided a great patch to Joose to actually hook up the long standing implementation of type constraints and coercions into the default attribute meta class.

So what does this actually mean:

First: You can build Types which are basically just things that express certain contraints for a value containers like an instance variable.
This is a type that will only allow boolean values:
Type('BooleanTest', {
where: function(value) {
if (typeof value == 'boolean') {
return true;
}
return false;
}
})
Now where this gets useful is if you add what is called coercions, which are just little functions that look at data and tranform them in a way that they match a type. Here is the type declaration with a coercion added, that turns 0 into false and other integers into true:
Type('BooleanTest', {
where: function(value) {
if (typeof value == 'boolean') {
return true;
}
return false;
},
coerce: [{
from: TYPE.Integer,
via: function (value) {
if ( value == 0 )
return false;
return true;
}
}]
}
);
Now we can build a class that constraints it's instance variables to be of type BooleanTest like this:
Class("BooleanTypeConstrained", {
has: {
attr1: {
is: 'rw',
isa: TYPE.BooleanTest,
coerce: true
}
}
})
We have to add the extra coerce: true, in order to enable the coercion because it does have a certain impact on runtime performance. What we can do now is this:
var constrained = new BooleanTypeConstrained();
constrained.setAttr1(1)
Without the coercion this would fail, because the field attr1 is contrained to be a boolean. However, because we added a coercion that transforms integers into booleana, this still works (and it actually sets the value of the instance variable to true).

I think that this can be a big thing for JavaScript programing, because when we do client side programming, dealing with user input is very important. With type coercions this becomes very declarative and easy. For example, you can have the user input a date in many different formats and then have coercions that transform these strings into instances of Date.
Post a Comment