Thursday, May 11, 2006

haXe: to Type or Not to Type?

haXe is a very cool language with a uniquely versatile type system. It's the only language I know that supports both static typing (explicit and inferred) and dynamic typing. For instance, in haXe, you can type

var str = "hello";

and the compiler will realize that 'str' refers to a String type. In fact, the above statement is equivalent to

var str:String = "hello";

This type inference mechanism is inspired by that of ML-derived languages (Haskell supports type inference as well). Although in most cases, you probably want to explicitly state the types of your variables for because type tags make the code more readable, I find it very convenient to rely on type inference in short code segments that use many temporary variables.

haXe is statically typed by default, so its compiler will complain if you try to do something silly such as

var str = "hello";

because the String class doesn't have the method setColor.

The fun thing about haXe is that it allows you to cheat. Using the 'untyped' keyword or by declaring an object as Dynamic, you can tell haXe to let you bend the rules and stop complaining. Take this example

var str:Dynamic = "hello";
str.setColor = function(color:String) {str.color = color;};

This is perfectly legal in haXe and it works as expected. Another way of doing the same thing is

var str = "hello";
untyped {
str.setColor = function(color:String) { str.color = color;};

Again, the haXe compiler accepts this code segment and moves along in its merry way. haXe's support for Dynamic typing is useful because it allows extend and manipulate objects in ways that don't really fit traditional OOP inheritence chains. For example, aspect-oriented design patterns can be implemented fairly easily in dynamic languages. In addition, the ability to temporarily sidestep its strict static typing typing allows haXe to play well with its dynamic predecessors -- Javascript and Actionscript.

I really like haXe's type system. It gives you all the flexibility of Ruby and Python without abandoning you at times when the compiler has enough knowledge about your code to be useful in finding errors. Dynamic languages fanatics would argue that static type checking provides only a marginal benefit because you have to test your code for correctness anyway, but I think they're underestimating static typing's advantages. By my experience, static typing speeds up development quite a lot -- especially during refactoring, when the compiler often points out where the refactored code has broken existing interactions. On the other hand, static typing zealots often dismiss the benefits of dynamic typing, which great frameworks such as Ruby on Rails show to allow the kind of "magic" that makes programming productive and fun. haXe gives you the best of both worlds. What more can you ask for?

More Worlds, of course!

No comments: