Saturday, February 25, 2012

Checked Dart Views

Yesterday, I began exploring type checking in Dart by running my test suite in checked mode (starting Dartium with --enable_type_checks). It did not have quite the effect that I expected and I cannot say that it improved my test suite. So today, am going to have a type-checked look at some of my code that is not yet tested. Perhaps type checking will prove of more use there.

So I load up my application in test mode and... it still works:

When I try to delete one of those test comic books, however, I get a big old stack trace:

Dart has a funny view of truthiness—everything but the boolean true is false. So even if my collection is non-null, the above will always return an empty string. So, yay! Type checking found a bug. I address it by explicitly comparing to null:

This turns out to be a bit more subtle. When an instance of AddComicForm is created, I am not assigning the optional el parameter in the constructor. Thus el is null, which is not an Element, resulting in a document.query() of null. Since document.query() expects a String, I am now getting a type checking error.

In this particular case, it is not a bug because AddComicForm overrides post_initialize to create this.el. Thus, any other view operations will succeed because this.el is defined. But that is only true for this particular class. If someone else created a view with no el, there would be errors. What I really need is something like Backbone.js's ensureElement. I will worry about that another day. For now, I make the this.el assigment conditional on el being supplied and I assert that this.el has been defined after post_initialize:

With the post_initialize() method in place, I am again able to bring up the add-new-comic form:

Everything else seems to work. I can again add, delete and view my comics collection—even in type checking mode.

The type checking option seemed more of an annoyance with testing than a help, but it definitely seems to help when actually coding. Without it, I had allowed at least one bug to get into my Hipster MVC framework along some questionable choices. It seems that coding in type checking mode is good advice—even if most users will run in regular mode.