Saturday, October 4, 2008

Type Constraints and Type Coercions

Jeremy and me continue to work on the type contraint and type coercion system for Joose.
Just a quick heads up to what this actually means using an example from the test suite (please be aware that the naming of types will likely change until the next release)
Class("CoercionTest", {
has: {
numAttr: {
isa: TYPE.Num,
coerce: true,
is: "rw"
strAttr: {
isa: TYPE.Str,
coerce: true,
is: "rw"
The class above has two attributes numAttr and strAttr. These are constraint to be of TYPE.Num and TYPE.Str. That means that it will not be possible to set these attributes to anything that does not match those types. However, the coerce: true property activates coercion which in turn activates magic that can convert a value from one type to another.

Some examples from the case above
  • coerce.setNumAttr("2") will assign the number 2 to the attribute numAttr (not the string "2")
  • coerce.setStrAttr(2) will assign the string "2" to the attribute strAttr
  • coerce.setStrAttr(["a", "b"]) will assign the string ["a", "b"].toString() to the attribute strAttr.
Type constraints will help to make your code
  • more correct (because values are contrained to the correct type)
  • more correct (because we already tested the type checks in Joose's test suite)
  • more declarative
  • shorter (because of centralized coercions)
  • more correct (because we already tests the type coercions in Joose's test suite)
The next steps are to provide a standard type system for Joose with all general coercions in place. This will make working with JavaScript in the browser a lot more fun, because
  • you get a validation framework for free
  • all data coming from the user (like input fields, etc.) is text based and coercions turn these into meaningful data automatically.
The type system is actually in place already, but most of the coercions are still missing. Since most coercions turn strings into structured data, many coercions must actually be localized (think "13,000.45" va. "13.000,45"). Thus, we will also provide hooks to activate coercions based on the current locale. Joose will ship with coercions for english speaking countries and I'll write extentions for Germany.

We'll keep you posted with updates about the type system.
Post a Comment