Google Web Toolkit

Performance and Interoperability

Bruce Johnson Google, Inc.

Borrowing Trouble with Ajax Google Web Toolkit Does What? Productivity Interoperability Performance, Performance, Performance Parting Thoughts


The Slippery Slope of Ajax
Product management and engineering decide to add script… I begin experimenting with JavaScript
Cool! The boss loves it – and it's fun! Maybe I’ll get a raise!

The salespeople love it… We’re an Ajax shop? Oh yeah, we can’t just support Internet Explorer Wait…this is hard I hate browsers with all my heart I quit – find another sucker to maintain this spaghetti

State of the “Art”
The world of Ajax is crazy and nigh unmanageable You need regexs to list all the technologies on one page
HTTPS?, [DX]?HTML, CSS[1-3] DOM Level[0-3] (Java|ECMA|J|VB)Script (X|VR?|Math)ML SVG, Canvas, Macromedia® Flash® JSONP?, SOAP, XML-RPC

Poor interoperation and consistency across browsers JavaScript is too flexible for big projects and team projects Yet browsers are an unbeatable way to distribute apps
Macromedia and Flash are trademarks or registered trademarks of Macromedia, Inc. in the United States and/or other countries.


To Be Crystal Clear

It is very easy to slip into building a poorly planned Ajax code base ...but you'll live with the consequences for a long, long time


Hello? Software Engineering?
Hey, what happened to all that software engineering stuff we figured out in the last few decades? Static type checking? Design patterns? Unit testing?

Code reuse?

IDEs?!?! Debugging?!?!
How can we restore some sanity?

Requirements Laundry List
Ajax features with web usability Use the Java language, developers and technologies

Debugging, JUnit, findbugs, profiling, coverage, javadoc Eliminate browser-specific coding with very low overhead Simple reuse via jars Rich remote procedure call (RPC) semantics Minimum size and maximum speed, especially at startup Great scalability Basically: the impossible… Unless you compile Java source into JavaScript :-)
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries. 7

Borrowing Trouble with Ajax Google Web Toolkit Does What? Productivity Interoperability Performance, Performance, Performance Parting Thoughts


What is Google Web Toolkit (GWT)?
What is GWT?
A set of tools for building AJAX apps in the Java language

What makes GWT interesting?
Write, run, test, and debug everything in a Java environment Client-side UI code and server-side business logic

Isn’t that called an applet?
No JVM required GWT converts your working Java source into pure JavaScript

GWT is a compiler?
GWT’s Java-to-JavaScript compiler is a big part of it, but there’s really a lot more to the story than that…


Code Sample – Hello, AJAX
Without further ado…
public class Hello implements EntryPoint { public void onModuleLoad() { Button b = new Button("Click me", new ClickListener() { public void onClick(Widget sender) { Window.alert("Hello, Ajax"); } }); } } RootPanel.get().add(b);


Hello, Ajax

Wow, That’s So Much Easier
Redefining the problem has been fruitful Session state? All client…not a server issue UI event handling? All client…no round trips Deployment? Use any web server…just copy compiled JS Leverage for the biggest Ajax headaches
Mantra: Solve the problem once & wrap it in a class History? Create a History class Cross-browser? Create a DOM class RPC? Create an all-Java RPC mechanism

And having a true compiler is a huge win

Borrowing Trouble with Ajax Google Web Toolkit Does What? Productivity Interoperability Performance, Performance, Performance Parting Thoughts


Have Your Cake XOR Eat It?
"Powerful" Languages with Dynamic Typing "Weaker" Languages with Static Typing



Why switch from a "powerful" dynamic language to a "weaker" static language?
It depends on what you mean by "powerful" Tools and static analysis Flexibility and (arguably) less typing in a plain text editor

Static languages

Dynamic languages


Stop Bugs Before They Start
typos + expandos = bug-o-s Imagine this gem on line 5912 of your script
x.compnent = document.getElementById("x"); // a "spelling bug" that will bite much later

There’s a reason static type checking was invented Java source instead of JS = fewer bugs to begin with Reuse is a good way to not write bugs Don’t forget code completion This starts to matter a lot for big projects And then, of course, there are the tools…

Interactive Source Browsing
Interactive source browsing is the new pink


Code Completion
<Ctrl>+<Space> is the other new pink


Great Debugging
Powerful debugging with breakpoints, etc. is the other, other new pink


Automated Refactoring
Refactoring tools do, in fact, rock


"Hello, Ajax" Reloaded Debugging and Refactoring

Widgets and Layout
Build cross-browser widgets in straight Java code Constraint-based layout with panels Easily create new widgets from existing ones
public class InboxWidget extends Composite { private EmailList list = new EmailList(); private EmailPreview pvw = new EmailPreview(); // combine them together in a simple panel to // create a new, reusable composite widget }

Styled with CSS!


The Obligatory Mail Example Widgets and Layout

History and Bookmarks
History is the first thing to go in most AJAX apps Excruciating hidden <iframe> and/or timer tricks Different solutions work best in each browser Solve it once and reuse

History support leads to bookmark support


KitchenSink History and Bookmarks

Remote Procedure Calls
Many solutions out there (JSON, XML-RPC, …) But a pure Java RPC interface sure is nice!
interface SpellService extends RemoteService { /** * Checks spelling and suggests alternatives. * @param the word to check * @return the list of alternatives, if any */ String[] suggest(String word) }

Client and server speak the same language
Side benefit: Client & server can share validation code


DynaTable Remote Procedure Calls

Usability and Performance
Demo: User Admin Dialog Box GWT saves you round trips Very fast startup time Separation of concerns in the code Keyboard support On-the-fly font resizing Reduce server load and improve usability


Unit Testing
JUnit integration
Direct IDE support

Run tests in hosted mode
Easy to debug and analyze

Run tests in web mode
In-the-wild verification Works with a farm of remote browsers

Testing the ListBox and Tree widgets

Borrowing Trouble with Ajax Google Web Toolkit Does What? Productivity Interoperability Performance, Performance, Performance Parting Thoughts


Not All-or-Nothing
GWT does not force you to start over! Attach code to existing pages with a <meta> tag
<html> …<meta name="gwt:module" content="…"/> …<h1>Welcome to GWTravel Services</h1> …<div id="reservationWizard"> …</html>

Your Java source is loosely-coupled
Panel p = RootPanel.get("reservationWizard"); Wizard wiz = new ReservationWizard(); p.add(wiz);

Works with any HTML-generating server approach

Have Your Cake XOR Eat It? (Again)
"Powerful" Languages with Dynamic Typing "Weaker" Languages with Static Typing



Why aren't there great JavaScript tools already? Aren't they just around the corner?


Don't Hold Your Breath For Code Completion
Imagine you want to write a JavaScript IDE…
// JavaScript function enhanceString() { String.prototype.usefulMethod = myUsefulMethod; } var str = window.prompt("Method name?"); eval(str)(); str.usefulMethod(); // hmmmm...

Hard (impossible, actually) in the general case But I would never write code like that!
Yes, but would that new guy on your team write code like that? And if he did, when would you find out?

Maybe "best effort" code completion is good enough?
If you don't mind sometimes-incorrect code completion Partially correct prompting may be the worst case

Don't Hold Your Breath For Optimizations
Imagine you want to write a JavaScript optimizer…
// JavaScript coolImportMechanism("bandwidth_check.js"); var MAX_PREFETCHED_IMAGES = 12; checkBandwidth(); prefetchImages(MAX_PREFETCHED_IMAGES);

Can we inline constants to shrink our script?
// JavaScript coolImportMechanism("bandwidth_check.js"); checkBandwidth(); prefetchImages(12);

It depends on what checkBandwidth() does
function checkBandwidth() { if (thisConnectionIsSlow()) MAX_PREFETCHED_IMAGES = 2; }

Extreme flexibility has a price

Also Don't Hold Your Breath For…
Comprehensive Syntax Highlighting
Is it a field or a method?

Inability to analyze → inability to refactor

Comprehensive Source Browsing Full Compile-time Checking
Impossible to say if a "spelling bug" is a bug or not

Machine-checkable RPC


To Be Crystal Clear

Extreme flexibility has a price …but JavaScript is the ideal language for the browser Yes, I said it. JavaScript rocks! Why can't we just have both?!?!

Have Your Cake AND Eat It!
"Powerful" Languages Dynamic Typing "Weaker" Languages Static Typing


JavaScript Native Interface (JSNI)
Include JavaScript directly in your Java source! And you can still debug Write no-compromise JS and make it reusable Expose existing JavaScript libraries into Java projects

"Hello, Ajax" Revolutions JavaScript Native Interface (JSNI)

Borrowing Trouble with Ajax Google Web Toolkit Does What? Productivity Interoperability Performance, Performance, Performance Parting Thoughts


Stateful Client → Scalability
Traditional HTML
Stateless HTML View Browser
01100110 01111001 01101011

User action

Stateful Server
New HTML page
011001101101 111110010100 011010111101 110011010110

Stateful JavaScript UI Browser

0110 0111

Events handled locally

Remote procedure call

Stateless (i.e. any) Server

Data only, not HTML
0110 1001 1011

Optimize Like Crazy
Tough decision not to support reflection and class loading Worth it! Three words: Whole program optimization For example, type tightening to eliminate polymorphism
Shape s = new Circle(2); double a = s.getArea(); becomes Circle s = new Circle(2); // radius of 2 double a = (s.radius * s.radius * Math.PI); // radius of 2

Inlining lets us discard the entire getArea() method! Imagine those sorts of optimizations across your entire app In JavaScript, reducing size and increasing speed are complementary goals, which makes optimizations really fun

Startup Time
Absolutely crucial
Should be measured in milliseconds If startup time isn't acceptable, nothing else matters

Very hard to do well
Loading code with synchronous XHR is out of the question <script> tags serialize HTTP requests GZip your script ahead of time? Good idea, but… Some versions of IE6 fail on gzipped .js files Script versioning vs. cacheability

GWT gives you leverage
Compiled output includes only what a particular user needs Output is JS wrapped in HTML, which is safely gzip'able Loads code in an <iframe> in parallel with the page Scripts are named uniquely and are perfectly cacheable

Script Size (bytes) 10000 20000 30000 40000 50000 60000


W in Em do w pt .a y le rt( "h el lo Ve ") rti ca lP an el Bu tto n C he ck Bo Tr ee x (3 ite m s) La be l

Te xt Bo x G rid (4 x 4) H TM L Ta bP a Li st Bo x R ad io (3 ta bs ) Bu tto n H ite m s) (3 ) ne l( 3 Im ag e

Compilation: Only Pay for What You Use

Additional Widgets Used
H yp er or lin iz k on ta lP an el Fl ow Pa Ab ne so l lu te Pa ne l

Compilation: Optimized Per Client
Download exactly what you need in a single can't-go-wrong chunk
Your Code IE 6 en_UK

Your Code FireFox 1.0.x en_US


Single Java Code Base


Your Code Safari 2.0.x fr_FR

Your Code Opera 9


Then cache it on the client until the sun explodes



Less Bandwidth: Lower Costs and Faster Apps
Traditional HTML 90000 GWT First Run GWT Other Runs



60000 Bytes Transferred






0 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7


Borrowing Trouble with Ajax Google Web Toolkit Does What? Productivity Interoperability Performance, Performance, Performance Parting Thoughts


Why Do Users Love Web Apps?
No installation
Every application is just a URL away No such thing as "DLL Hell" – it just works Capable of super-fast startup time

Secure… the mantra we teach our parents
Surfing = safe Installing = unsafe

Simple usability
Pages have a simple, friendly look and feel Not much to learn: back, forward, bookmarks, links, URLs

Don't Throw the Baby Out With the Bathwater
No installation…sort of
In a sense, it’s also always-reinstall (had better be small) Don't penalize users for your engineering convenience Never be willing to sacrifice fast startup

Secure…sort of
Hard enough just to make AJAX work at all! Lots of handwritten JS = lots of attack surface

Ajax has tricky usability quirks
History, bookmarks and even hyperlinks misbehave Badly coded Ajax is worse than traditional HTML

To Be Crystal Clear

It is very tempting to build frameworks that make life easier for developers …at the expense of user experience


Not Enough Time to Demo Everything
Internationalization support
Highly optimized Externalized string ids are checked during compilation

Automatic, dynamic dependency inclusion
Slurp in external CSS Slurp in external JS

Everything is cross-browser
IE6+, FF 1.0.x, FF 1.5.x, Safari 2.0.x, Opera 9.x

Your choice of development platforms
Mac OS X, Linux, Windows

Your choice of IDEs
IntelliJ IDEA, Eclipse, NetBeans, JCreator, JBuilder

GWT Library Overview
AbsolutePanel, Button, ButtonBase, CellPanel, ChangeListenerCollection, CheckBox, ClickListenerCollection, ComplexPanel, Composite, DeckPanel, DialogBox, DockPanel, FileUpload, FlexTable, FlowPanel, FocusListenerAdapter, FocusListenerCollection, FocusPanel, FocusWidget, FormHandlerCollection, FormPanel, FormSubmitCompleteEvent, FormSubmitEvent, Frame, Grid, HorizontalPanel, HTML, HTMLPanel, HTMLTable, Hyperlink, Image, KeyboardListenerAdapter, KeyboardListenerCollection, Label, ListBox, LoadListenerCollection, MenuBar, MenuItem, MouseListenerAdapter, MouseListenerCollection, NamedFrame, Panel, PasswordTextBox, PopupListenerCollection, PopupPanel, RadioButton, RootPanel, ScrollListenerCollection, ScrollPanel, SimplePanel, StackPanel, TabBar, TableListenerCollection, TabListenerCollection, TabPanel, TextArea, TextBox, TextBoxBase, Tree, TreeItem, TreeListenerCollection, UIObject, VerticalPanel, Widget, WidgetCollection

User Interface User Interface
History, DeferredCommand, Localizable, Constants, Dictionary, ConstantsWithLookup, Messages DOMException, XMLParser, Attr, CDATASection, CharacterData, Comment, Document, DocumentFragment, Element, EntityReference, NamedNodeMap, Node, NodeList, ProcessingInstruction, Text

Usability and I18N Usability and I18N
AsyncCallback, IsSerializable, RemoteService, RemoteServiceServlet JSONArray, JSONBoolean, JSONException, JSONNull, JSONNumber, JSONObject, JSONParser, JSONString, JSONValue

Header, Request, RequestBuilder, RequestCallback, RequestException, Response, URL





GWT is Actually Documented
Getting Started Guide Widget Gallery

Developer Guide

Class Reference


Growing GWT Community
Community and Support
Over 4900 members on the developer forum and growing Books and articles Meta-sites (e.g.

Libraries and Applications
GWT Widgets on SourceForge 25 projects on Google Code Project Hosting Diverse products built completely with GWT JetBrains' JET markup framework for GWT

Tools, Tools, Tools
JetBrains IntelliJ IDEA support for GWT built into Version 6.0 Instantiations GWT Designer (Live Webinar on Wed 10/25) VistaFei for GWT Googlipse, an open source Eclipse plug-in for GWT


Did I Mention Tools?
Instantiations GWT Designer


Did I Mention Tools?
Instantiations GWT Designer


PhD in browser quirks is no longer an Ajax prereq Ajax is a lot of work… Make sure to build a code base you're glad to own Ajax is about improving the user experience… Don't let your development approach compromise it Leverage is needed to use Ajax well with minimum risk Turn Ajax development into software engineering We will share our best work and ideas with you, and we hope you will return the favor Much more to come…see you online!