Thursday, February 26th, 2009

Aurora: Class types and invariants in JavaScript

Category: Examples, JavaScript

Ryan Morr has created a really fun experiment that shows the versatility of JavaScript. He just announced Aurora, fun times with class types and invariants in JavaScript.

He introduces the project:

The goal of the project is to provide a means of defining instance variables bound to a specific data type as you would find in Java or a variety of other languages. All subsequent calls to the methods of the instance result in automatic variable validation after the method call is complete. If a type violation is found, a descriptive exception is thrown and that specific variables value will be reverted back to what it was before the method call took place.

In addition to that, there is added support for class invariants, inspired by Eiffel, each class can declare a set of invariants for each instance variable which outlines the rules of that variable. For example, a variable called month in the class calendar must be an integer between the values of 1 and 12, if that rule is broken an exception is thrown.

The main pieces are:

  • Data Types: E.g., items: [Object], collection: Array(Element). You can create your own via define: Aurora.define('Hash', Aurora.isHash);
  • Invariants: E.g. a calendar class set:

    invariant: {
    day: function(){
    return >= 1 && < = 31; }, month: function(){ return this.month >= 1 && this.month < = 12; }, year: function(){ return this.year >= 1 && this.year < = new Date().getFullYear(); } } [/javascript]

  • Classes: The declare method is used to define a new class and has a similar syntax to the dojo.declare method. The method can accept either two or three arguments depending on whether the new class will inherit from a superclass.
  • Inheritance: Classical inheritance is also supported and maintains the same behaviour and functionality that you would expect. However, in additon to the inherited methods and the ability to call superclass methods, both declared types and invariants of a superclass will also be inherited by all subclasses.
  • Exceptions: Whenever a violation occurs, whether it be a type or invariant violtation, an exception is thrown that indicates the type of violation, the class and method in which the violation occurred, the variable that failed the validation, and in the case of type violations the expected type.

Nice stuff Ryan!

Posted by Dion Almaer at 2:21 pm
Comment here

3.7 rating from 37 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.