Small is beautiful…and fast… and obfuscated… and

Closure: The definitive guide by Michael Brolin

This is a really interesting book that offers lots of tips on Javascript as well as providing an in depth guide to the Closure Tools, both in terms of how to use them and, more importantly, the reasons behind the design. I got the book from the library because I’d heard about Closure from its use in the recently released Clojure to Javascript compiler. In this project the Closure compiler is used to minimise the Javascript, optimising it in the process. This allows the code generator of the compiler to generate relatively inefficient Javascript in the knowledge that it will be optimised by the Closure compiler. This simplifies the compiler greatly.

First, what is Closure? It is a package of five tools– a Javascript library, an HTML templating mechanism, a compiler (from javaScript to Javascript), a testing framework and an inspector. It was produced by Google to help them maintain and build rich web applications like Gmail. Such applications need to be portable across a large range of browsers and also need to be written in maintainable code which can be loaded quickly and efficiently by the relevant browsers. Closure contains a portable library that isolates the code base from the tweaks that are often required  to get the user interface to look good (or even work) on all of the various browsers.

First the compiler, the thing that drew me to this book. This takes Javascript code, parses it to an abstract syntax tree which can be transformed in a number of ways before it is output again. This transformation is extensible by the user, who can add their own rules and transforms. To get the most from the compiler, the user is expected to  annotate their Javascript functions with JSDoc annotations giving the types of the various entities. The compiler can then type check the Javascript for you, getting rid of many potential errors before runtime. The compiler works best if your code uses the Clojure Library and its idioms for modularisation and class definition. The code can be split into separate groups of files corresponding to functionality, and by using provide and require the compiler can determine the dependencies between the groups. This information can be used to be compress multiple Javascript files into a multiple result files, with these files set up so that code is demand loaded when a piece of functionality is used – think Gmail and the fact that you don’t need to load the calendar code until the user goes to the calendar.

With relevant type information, which includes a notion of subtyping, the compiler can report type errors, and even a full program analysis to determine dead code which it can throw away. Most importantly, the compiler freely renames variables and folds constants to reduce the size of the code considerably, drastically improving the start up time for an application.

The Closure Library offers a standard platform to program against. It implements standard Javascript functions that aren’t implemented natively in some browsers, and also provides whole lot of extra utility functionality. For example, the object goog.array implements a whole lot of utility functions on arrays such as forEach and goog.object offers functions such as get and setIfUndefined. There are also functions for generating and parsing JSON, and a whole load of DOM manipulation functions such as goog.dom.getElementsByTagNameAndClass and goog.dom.getAncestorByTagNameAndClass. As mentioned above it implements a modularisation mechanism via goog.provide and goog.require which is build upon an accessible lower level dependency mechanism. There’s also a whole mass of code for getting details about the current Javascript host (browser). A standard user extensible event abstraction is also provided for handling both bubbling and tunneling events which are abstracted across the many browser implementations. Typically IE has different behaviour from the rest of the crowd, so the library needs to work around these differences.

Closure Library also offers a pattern for implementing standard class based object orientation in Javascript. There are standard patterns of class, inheritance, interfaces, override and calling base methods. If you follow the pattern, then the Closure Compiler can detect errors in the code much more easily.

As you’d expect, given the types of applications that Google produces, there’s a lot of functionality concerned with implementing Ajax client-server applications. For example, goog.net.XhrIo is a wrapper over the basic XmlHttpRequest which offers events for completion and errors. goog.net.XhrManager allows the application to configure the timeouts and retries, and there’s a bulk loader for firing off downloads and getting notified on completion. There’s support for communication between independent iframes and support for COMET, the standard long running request trick which allows clients to avoid polling while still getting timely notifications from a server.

The Closure Library offers a standard set of widgets and a component model for writing more. This component model offers a lifecycle, with events being used to communicate transitions between the states. The model offers two ways for the component to affect the DOM – either by generating a tree of elements which can be patched into the DOM (rendering) or by attaching to existing DOM elements (decorating). This latter technique allows a web page to be loaded quickly, with the behaviour part only getting added later when the Javascript finishes loading. This technique makes it appear to the user that the page has loaded and is ready, using the delay before they start interacting with it for loading the code that handles the behaviour.  The book goes into lots of details and implements a component to make everything very clear. The Library also implements Rich Text Editor, and there is a whole chapter in the book on how to configure and use it.

Closure Templates allow you to write a template for a particular pattern of HTML, avoiding the need to inline a lot of construction code which can be really hard to edit. The book covers this area really well.

This is followed by several chapters on implementing your own compiler extensions, followed by coverage of the Testing Framework. This framework allows you to write tests in Javascript and run them and display the results in a browser. There is good support for mocking and testing asynchronous methods. There’s a chapter after this on the Closure Inspector, a Firefox add-in for debugging code that has been through the Closure Compiler. The compiler can generate information relating the output Javascript to the original source code, and the add-in  allows you to seamlessly jump from the compressed code that you are debugging back to the original code.

This book covers everything really well, making it clear what the various features are designed to help with, and explaining why they were designed in that way. Moreover, the appendixes of the book, one on implementing inheritance in Javascript and the other on common Javascript pitfalls are a fantastic read. The latter makes some really good points on problems you can have with the difference between the prototype property and the object’s prototype (which is accessible via the _proto_ property).

The book is 500 pages long which requires some effort to read, but I learned a lot about the Closure Tools and during the course of the book a fair amount of material about writing rich internet applications too.

Advertisements
This entry was posted in Books. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s