Google Closure: A New Way of Developing in JavaScript

Preface

Every day million people make use of Google products and these products are written mainly using one well known language: JavaScript!

What makes this online software stable, fast and responsive is a good use of the language and an excellent system of data compression and asynchronous loading. Today this power is available to everyone, since Google has released its magic tool under Apache 2 license. In the box we will find:

  1. a bullet-proof, OOP structured and complete js library called Closure
  2. an utility to merge js files into a single one (solving dependencies)
  3. a compiler to compress and optimize JavaScript code
  4. a FireBug extension for a better debug
  5. a template engine for both JavaScript and Java

Library overview

This is an huge (more than 400 JavaScript files!) JavaScript library organized into well documented "packages", "classes" and "subclasses" (quotes are mandatory because in JavaScript these entities don't exist but we can only think and realize a Java-like architecture). It makes intense use of a Java-doc syntax (http://java.sun.com/j2se/javadoc/) to describe each component, so it's possible learning functionalities and behaviors of the classes by reading these comments and generate an HTML document from the js files by using tools such jsdoc-toolkit (http://code.google.com/p/jsdoc-toolkit/) or the integrated Aptana's tool (http://docs.aptana.com/docs/index.php/Generating_HTML_documentation_from_ScriptDoc).

What makes Closure different from other libraries available nowadays is its goal, its structure and its approach to client side developing with JavaScript. Let me explain, jQuery, YUI, Dojo and others work really well and make possible great things with no effort and fast (both in terms of coding time required and code execution speed), so the "promise" of Closure is not to offer better algorithms (fine tuned loops to improve speed, faster DOM selector and so on) but rather a really better, organized and maintainable way of deploying JavaScript applications. And this is the point! Coding in Closure means thinking with object oriented principles in mind, create several js files, each representing a single class (customer.js, mediaplayer.js, loader.js and similar), organize the application architecture into packages and finally deploying it using the tools provided, obtaining a single, compressed, and safe JavaScript file which run extremely faster and doesn't contain dead code (unused functions and objects).

Thus, Closure is not simply a new js library, but a new way of programming in JavaScript! Google's team has engineered a framework which makes possible to write JavaScript at the same level as writing Java (in terms of the approach), by making Java developers more comfortable with an otherwise "foreign" and "poor" client side language and at the same time by offering new exciting tools and possibilities to frontend developers and promote good object oriented design. This design is realizable through an intense use of the JavaScript prototype mechanism, which is the natural way to realize "classes" in this language. Closure also provides tools to "simulate" packages definitions and imports (goog.provide() and goog.require()) and to easily subclassing custom class (goog.inherits(subClass, superClass)). Access modifiers (http://en.wikibooks.org/wiki/Java_Programming/Access_Modifiers) are defined through jsdoc syntax and checked at compile time (using the java tool provided), so a variable marked with /** @private */, will rise an error during the compilation if accessed from the outside. It's also possible to create and implement interfaces! You can create an interface in this way:

/**
 * Shape interface
 * @interface
 */
function IShape() {};
IShape.prototype.draw = function() {};

Then implement it:

/**
 * @constructor
 * @implements {IShape}
 */
function Square() {};
Square.prototype.draw = function() {
  // draw a square
};

If, after implementing an interface, you will not provide all the methods declared in that interface's body, the compiler will throws an error.

The library includes then a series of objects coming from the Java world, such collections (Map, Set, Queue and so on) which will help you to work with data structures, buffers, logging and test/debugging tools (which can be used with every browser), classes to work with Gears (http://gears.google.com/) and to draw vector graphic in the browser (SVG and VML).

As their competitors, the library offers of course a set of normalizations in order to work easily across browsers:

  • an excellent event framework (which also enable us to dispatch custom events)
  • dom utilities (select, create and remove nodes, monitoring font size changes, monitor viewport changes and so on)
  • the most complete ajax toolkit I ever seen (which enable us to handle queues of xhr calls and even make cross domain requests)
  • several user interface components (tabs, editors, combo boxes, datepickers, sliders, menus and so on)
  • drag and drop management
  • animation effects
  • date utilities (create, add, subtract dates and times, get numbers of days in a month and so on)
  • a timer class to work with repeated/delayed task (it works very similar to the Actionscript 3 Timer)

...and more!

Deploying Closure web applications

Once we have written and tested our new powerful JavaScript classes and organized them into functional packages, it's time to deploy our application, in order to have only a single, optimized and high performance js file!

To reach this goal, we have to use 2 different tools: the first is the python script called "calcdeps.py" located in the folder "bin" under "closure" (you have first to do a checkout from the svn repository in order to get this folders), which will automatically recognize all the js files needed (by analyzing the several goog.require() inside files) and will generate a single js file including all the code required and the second is the compiler, which will compress and optimize the content of that file.

The compiler is the Closure's ace in the hole and, as Google says, converts JavaScript into better JavaScript (much better!) and it's available in three flavors: an online gui application, a Java command line tool (the best choice in my opinion) and a web API service.

The first is the easier way to compile our js files and consist in an application divided into two main areas, in the first we can add script urls and/or paste/write js code that will be then elaborated and rendered into the second area.

Is possible to choose among three different compressions: "whitespace only", as the name says, would removes only white spaces and lines feeds from the source but it also removes comments (every type of comment), "simple" which will also rename arguments names into a single letter in order to limit file size and "advanced", that will also remove unused functions, objects and arguments and will analyze the code in order to cleverly decide how it could be rewritten in a better way. Let's suppose to have a function like:

function hello(name) {
  alert('Hello, ' + name);
}

and this function is called only once inside the code:

hello('New user');

...then the compiler will convert the original source to:

alert("Hello, New user");

The command line tool instead, consists in a Java utility (a jar file), which can be used from the terminal and allows us to write the converted code to a desired file under a desired directory. To use this tool, we have to download the archive from this url: http://closure-compiler.googlecode.com/files/compiler-latest.zip, unzip it, open the terminal, change the directory to "compiler-latest" (the folder we will get after unzipping the archive) and then run the following into the terminal: "java -jar compiler.jar [parameters]", where [parameters] are a series of commands allowed by the tool. To display the full commands/options list, we can just type "java -jar compiler.jar --help".

However the best solution is to invoke the compiler directly when running the python script, thus we will aggregate and compress our files at the same time (Follow the links at the bottom of this post to learn how to use this tools).

Conclusion

Google Closure is a mature and complex JavaScript framework with the goal of allow developers to realize the best stable and high performances client-side applications. It's not a "tool for everyone", it requires a good JavaScript experience, at least a minimun of OOP knowledge and basic knowledge of SVN (because it's the only way to download and obtain the sources), moreover you well need more time in order to realize a project, but for skilled developers and big projects it is definitely the framework to adopt... it takes JavaScript to a new level!

Useful links

Library home: http://code.google.com/p/closure-library/

API reference: http://closure-library.googlecode.com/svn/trunk/closure/goog/docs/index.html

Compiler download (Java): http://closure-compiler.googlecode.com/files/compiler-latest.zip

Web based compiler: http://closure-compiler.appspot.com/home

Dependencies script guide: http://code.google.com/closure/library/docs/calcdeps.html

Closure Templates home: http://code.google.com/p/closure-templates/

JsDoc Toolkit: http://code.google.com/p/jsdoc-toolkit/

Closure JsDoc tags: http://code.google.com/closure/compiler/docs/js-for-compiler.html#tags

...and finally, the dedicated section of my blog:

http://www.daveoncode.com/category/google-closure/

About this Entry

This page contains a single entry by Davide Zanotti published on November 19, 2009 12:00 PM.

Using Google Analytics With AJAX was the previous entry in this blog.

Validation in Flex with Hamcrest-AS3 is the next entry in this blog.

Find content using the provided navigation or look in the archives to find all content.

Authors

Archives

This content archive is licensed under a Creative Commons License.