Ajax Architecture with Stuart Halloway

When should you use Ajax? Whenever you want to create a rich client application with the universal reach of the Internet. Stuart Halloway, speaking Friday afternoon at this fall's Northern Virginia Software Symposium, predicts Ajax will be part of nearly all web applications within the next year. Stuart's first session of the day focused on the architectural issues involving Ajax, from technical features to selling Ajax to management. In 90 minutes he discussed:
  • the reasons to use Ajax
  • how to introduce Ajax at your company
  • the resistance you'll encounter when you do
  • the tools and libraries to use in Ajax development
  • the architectural decisions you'll need to make
  • how Ajax isn't a panacea for all applications
Stuart demonstrated Ajax in action by showing how to build several incarnations of a web form that, once you input a U.S. Zip code, the address's city and state fields fill in automatically from an asynchronous JavaScript server call. Low-tech stuff compared to Google Maps, but simple enough to demonstrate several ways to get the job done.

The interest in Ajax has been increasing over the last couple of years not because of a breakthrough in technology, Stuart said, but because of a breakthrough in how we look at using asynchronous JavaScript to make web forms more dynamic. Instead of having web user-interface developers deal with the vagaries of the different browser versions, different implementations of JavaScript, different implementations of Cascading Style Sheets, and different implementations of the web page document object model, they learned in February 2005 from
Jesse James Garrett photo
Jesse James Garrett
Jesse James Garrett to hide browser differences behind an adaptive interface provided by a library like Prototype or Dojo. Garrett coined the term Ajax in his seminal paper, "Ajax: A New Approach to Web Applications." Of course, it also helps, Stuart added, that the functionality provided by Internet Explorer and Firefox have converged over the years.

The reason to use Ajax in your web applications is to create a better experience for your users. Ajax allows your web page to communicate to the server in order to update the page "behind the user's back," making the application more responsive to the user's actions without having to reload the page.

The best way to introduce Ajax at your company, he said, is in non-core web applications. Depending on your company's culture, Stuart said, you can sell Ajax either as proven technology -- XML, HTTP requests, and JavaScript -- or by saying "Ajax is the revolution and we're all on board." When introducing Ajax, he said, stay "degradable." That is, ensure your web application still works if the user turns off JavaScript or uses a browser that doesn't support it. The fewer negative issues you create, the more the benefits will shine through and convince others to introduce Ajax into more web applications. If you want to be conservative, he said, wait until the web MVC frameworks, like JavaServer Faces, provide better support for Ajax in their page widgets.

Stuart mentioned several open source development tools and JavaScript libraries to use in your Ajax applications:
  • Firefox
    Consider the Firefox browser (with its extensions that follow) your development platform and Internet Explorer as your deployment platform, Stuart said.
  • JavaScript Shell
    a Firefox bookmarklet that allows you to dynamically run JavaScript statements against your current page in a debugging window. This tool is useful, Stuart said, "for poking around the page to figure out what's broken."
  • FireBug
    a Firefox add-on with debugging features to monitor your page's JavaScript, CSS, and HTML. One feature allows you to spy on all HTTP traffic JavaScript functions send to the server.
  • Web Developer
    a Firefox add-on toolbar that allows you to disable JavaScript, cookies, view and modify a page's CSS, view a page's generated source rather than the HTML originally loaded, and a host of other useful development tools.
  • Tamper Data
    a Firefox add-on that logs all web navigation. It not only allows you to see what requests and responses are traveling between the Ajax components and the server, but it allows you to modify them or completely stop the request and see how the application reacts.
Ajax Libraries

Stuart mentioned several Ajax libraries. Since JavaScript libraries generally don't trample on each other, he said, you can often use more than one in a web application.
  • Prototype
    A survey at an Ajaxian conference showed that more than half of the Ajax developers were using Prototype, Stuart said. Most of the rest were using Scriptaculous (next). Prototype allows you to register multiple event handlers to events (Event.observe()). You can register events outside of the HTML widget to allow you to separate concerns: your HTML page designer doesn't have to worry about coding the JavaScript events. Prototype also provides the Ajax.Request function that works as a factory to return the appropriate function that works with the user's browser version.
  • Scriptaculous
    A library built on Prototype to provide page effects (highlight, fade), drag and drop, auto-complete and other features.
  • Dojo
    This is a heavy-weight "kitchen sink" library, Stuart said, that provides almost everything you need for an Ajax application.
  • Google Web Toolkit
    This toolkit allows Java developers to build front-end components in Java. The toolkit converts the Java code to JavaScript and HTML.
  • Direct Web Remoting
    Stuart said DWR is No. 3 in popularity, behind Prototype and Scriptaculous. It's Java RMI like. You write JavaScript stubs that run in the browser and make RMI calls to the server. It assumes you have Java running on the server side.
Introducing Ajax into an application raises two key architectural questions, Stuart said. These are the questions to think about early and thoroughly because changing the answers later could undermine previous development work.
  1. What to send on the wire?
    When JavaScript calls to the server for updated information, does the server send back HTML, XML, JavaScript, or JSON? HTML is view centric, JavaScript is code-centric, and XML and JSON are model-centric. (See also this blog for a discussion.)

    Stuart said he believes 95% of all Ajax traffic soon will be HTML. It's developer-efficient (no parsing and XML creation) and the snippet of HTML can simply be rendered on the page. JSON will dominate applications that focus on data exchange because it is easier to parse than XML. XML will be the loser. Sending back JavaScript allows you to send back code that the browser would evaluate.

  2. What library to use?
    Choose a library that supports the features you need. The library should hide the browser differences in the XMLHttpRequest. Prototype does this and builds upon JavaScript to make it more like a regular programming language.

    Use Scriptaculous if you need to adds page effects and you'd like to use its widgets.

    Dojo is the library beloved by Java programmers, Stuart said. It's bigger than all the other libraries, but it does more. Its API provides fixes for Back-button issues, client-side data storage, and other features.

    Stuart dislikes Google Web Toolkit. "I think it's architecturally wrong," he said, but I think I zoned out when he described the reasons for his dislike.

Although Ajax is useful, it won't be a panacea for all applications, Stuart said. Learning to design with Ajax correctly will involve some of the same growing pains the development community learned in creating n-tier applications. Stuart likened the future growing pains in the Ajax world to the pains Java programmers suffered in implementing n-tier web applications using EJB. "We're going to make a ton of mistakes" implementing Ajax applications, he said. "Asynchronous is hard. Asynchronous is as hard as threads, except you don't have an API in front of you reminding you how hard it is."

Filling in my No Fluff dance card

Today begins the fall session of the Northern Virginia Software Symposium put on by No Fluff Just Stuff (Jay Zimmerman and crew). That means I have to decide which one of the six concurrent sessions to attend in each time slot. That means I have to decide which of five sessions to miss during each time period.

Today has three time slots in the afternoon, followed by an after-dinner keynote by pragprog co-founder Andy Hunt. For the 1:15 p.m. session, I'd like to attend Stuart Halloway's "Ajax Architecture" session, Brian Goetz's "Java Performance Myths" session, and Venkat Subramaniam's "Open Source Tools for Agile Development" session. I'm not a web UI designer, but knowing the browser's asynchronous JavaScript abilities would help on a current project. We want to add dynamic page updates to an existing web application. The design of the server code I'm working on will be affected by what services the client needs. Brian Goetz's session promises to show how common Java idioms we use, thinking it helps the Java compiler optimize our code, actually make it harder for the JIT compiler to figure out how to optimize. Venkat Subramaniam will recommend open source tools he finds most useful to develop code and improve its quality. The open source world changes so fast, it would be good to get these tips from the good doctor.

See how hard Jay makes it to decide which session to attend? I'm leaning toward Stuart's Ajax session just because it's the area I know the least about. I'd like to know what cool features Ajax libraries Prototype and Scriptaculous provide.

Later in the afternoon, Venkat has sessions on test-driven design for Spring applications and working with rules engines. But these sessions conflict with sessions on how Acegi supports JavaScript for better user authentication interaction, and a session on Jini (the technology whose coolness keeps it alive despite being almost wholly ignored for years). Decisions, decisions.

I plan to blog more this weekend on the sessions I attend and what I learn.

java.util.concurrent backport to Java 1.4

When I blogged in September about using the Java threading classes introduced in Java 1.5, I didn't know a similar library was available in Java 1.4. It is, courtesy of the backport-util-concurrent package maintained by Dawid Kurzyniec at Emory University.

The package provides versions of most of the java.util.concurrent classes, but converted to Java 1.4. The key feature missing is the ability to use generics. For example, using Java 1.4, you can't define a Callable anonymous inner class using syntax like:
void showSearch(final String target) throws InterruptedException {
Future<String> future = executor.submit(new Callable<String>() {
public String call() { return searcher.search(target); }
});
displayOtherThings(); // do other things while searching
try {
displayText(future.get()); // use future
} catch (ExecutionException ex) { cleanup(); return; }
}
to specify the call method returns a string, as in the above code excerpted from the Java 1.5 API for the Future interface. And, of course, you can't define a Future of type string that would be returned from the ExecutorService's submit method, as shown above. Without generics, you're confined to returning Objects and casting them to the expected type. You don't get the compile-time validity checking provided by Java 1.5 generics, but most Java developers are used to using narrowing casts like this.

This backport of the concurrent package came in handy this week when I wanted to use its features on a project that had to run in Java 1.4. It seems a lot of code from Java 1.5 has been backported to earlier Java versions, like Java annotations. Thank you, Dawid and Emory, and thank you for releasing the code into the public domain so the code may be "may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial."

UPDATE 7 hours later:

I should mention that some of the code for the backport, as well as much of Java 1.5's java.util.concurrent package, came from Doug Lea's util.concurrent package. I woke up this morning and realized I had neglected to mention where the initial ideas for the Java 1.5 concurrency classes came from. Professor Lea, from the State University of New York at Oswego, created most of the ideas and code behind the improved multi-threading techniques that made it into Java 1.5. He also is a co-author of Java Concurrency in Practice, which Stuart Halloway recommended in my September 27 blog as being a great source to learn the effective use of the Java 1.5 concurrency package (and thus the backported version).

The benefit of favoring the Emory University backport over Doug Lea's original code is that code using the backport allows a smooth transition to Java 1.5. The transition mostly would involve renaming your imports. The backport's class names and APIs are identical to what's in Java 1.5. Doug Lea favors using the Emory backport over his older util.concurrent package.