Google Web Toolkit

Performance and Interoperability

Bruce Johnson Google, Inc.

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

2

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
3

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.

4

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

5

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?
6

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

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

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

8

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…

9

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);

10

Demo
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
12

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

13

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

JavaScript

Java

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

14

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…
15

Interactive Source Browsing
Interactive source browsing is the new pink

16

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

17

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

18

Automated Refactoring
Refactoring tools do, in fact, rock

19

Demo
"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!

21

Demo
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.addHistoryListener(myController);

History support leads to bookmark support
http://google.com/gulp.html#beta_carroty

23

Demo
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

25

Demo
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

27

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

Demo
Testing the ListBox and Tree widgets
28

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

29

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
30

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

JavaScript

Java

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

31

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
32

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
33

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

Refactoring
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

34

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?!?!
35

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

JSNI

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
36

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

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

38

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

User action

Stateful Server
New HTML page
011001101101 111110010100 011010111101 110011010110

GWT/Ajax
Stateful JavaScript UI Browser

0110 0111

Events handled locally

Remote procedure call

Stateless (i.e. any) Server

Data only, not HTML
0110 1001 1011
39

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
40

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
41

Script Size (bytes) 10000 20000 30000 40000 50000 60000

0

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
42

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


1D04ADDA.cache.html

Single Java Code Base

15F361BB.cache.html

Your Code Safari 2.0.x fr_FR

Your Code Opera 9


7EFE4D24.cache.html

Then cache it on the client until the sun explodes

fr_CA


D415D917.cache.html
43

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

80000

70000

60000 Bytes Transferred

50000

40000

30000

20000

10000

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

44

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

45

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
46

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
47

To Be Crystal Clear

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

48

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
49

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

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

RPC RPC

JSON JSON

HTTP HTTP

50

GWT is Actually Documented
Getting Started Guide Widget Gallery

Developer Guide

Class Reference

51

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

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

52

Did I Mention Tools?
Instantiations GWT Designer
WYSIWYG Layout

53

Did I Mention Tools?
Instantiations GWT Designer
Internationalization

54

Summary
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!
55

Q&A