Google Web Toolkit

56
Google Web Toolkit Performance and Interoperability Bruce Johnson Google, Inc.

description

This deck explains the _why_ of GWT

Transcript of Google Web Toolkit

Google Web ToolkitPerformance and Interoperability

Bruce JohnsonGoogle, Inc.

2

Topics

Borrowing Trouble with Ajax

Google Web Toolkit Does What?

Productivity

Interoperability

Performance, Performance, Performance

Parting Thoughts

3

The Slippery Slope of Ajax

Product management and engineering decide to add script…

I begin experimenting with JavaScriptCool! 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

4

State of the “Art”

The world of Ajax is crazy and nigh unmanageable

You need regexs to list all the technologies on one pageHTTPS?, [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 appsMacromedia and Flash are trademarks or registered trademarks of Macromedia, Inc. in the United States and/or other countries.

5

To Be Crystal Clear

It is very easy to slip into buildinga poorly planned Ajax code base

...but you'll live with the consequences

for a long, long time

6

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?

7

Requirements Laundry List

Ajax features with web usability

Use the JavaTM 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.

8

Topics

Borrowing Trouble with Ajax

Google Web Toolkit Does What?

Productivity

Interoperability

Performance, Performance, Performance

Parting Thoughts

9

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

10

Code Sample – Hello, AJAX

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

}

Without further ado…

Demo

Hello, Ajax

12

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 headachesMantra: 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

Wow, That’s So Much Easier

13

Topics

Borrowing Trouble with Ajax

Google Web Toolkit Does What?

Productivity

Interoperability

Performance, Performance, Performance

Parting Thoughts

14

Have Your Cake XOR Eat It?

Why switch from a "powerful" dynamic language to a "weaker" static language?

It depends on what you mean by "powerful"

Static languages Tools and static analysis

Dynamic languages Flexibility and (arguably) less typing in a plain text editor

"Powerful" Languageswith Dynamic Typing

"Weaker" Languageswith Static Typing

JavaScript Java

15

typos + expandos = bug-o-s

Imagine this gem on line 5912 of your scriptx.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…

Stop Bugs Before They Start

16

Interactive Source Browsing

Interactive source browsingis the new pink

17

Code Completion

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

18

Great Debugging

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

19

Automated Refactoring

Refactoring tools do, in fact, rock

Demo

"Hello, Ajax" Reloaded

Debugging and Refactoring

21

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!

Demo

The Obligatory Mail Example

Widgets and Layout

23

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

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

Demo

KitchenSink

History and Bookmarks

25

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 languageSide benefit: Client & server can share validation code

Remote Procedure Calls

Demo

DynaTable

Remote Procedure Calls

27

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

28

Unit Testing

JUnit integrationDirect IDE support

Run tests in hosted modeEasy to debug and analyze

Run tests in web modeIn-the-wild verification

Works with a farm of remote browsers

DemoTesting the ListBox and Tree widgets

29

Topics

Borrowing Trouble with Ajax

Google Web Toolkit Does What?

Productivity

Interoperability

Performance, Performance, Performance

Parting Thoughts

30

Not All-or-Nothing

GWT does not force you to start over!Attach code to existing pages with a <meta> tag

Your Java source is loosely-coupled

Works with any HTML-generating server approach

<html>…<meta name="gwt:module" content="…"/>…<h1>Welcome to GWTravel Services</h1>…<div id="reservationWizard">…</html>

Panel p = RootPanel.get("reservationWizard");Wizard wiz = new ReservationWizard();p.add(wiz);

31

Have Your Cake XOR Eat It? (Again)

Why aren't there great JavaScript tools already?

Aren't they just around the corner?

"Powerful" Languageswith Dynamic Typing

"Weaker" Languageswith Static Typing

JavaScript Java

32

Don't Hold Your Breath For Code Completion

Imagine you want to write a JavaScript IDE…

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 completionPartially correct prompting may be the worst case

// JavaScriptfunction enhanceString() {String.prototype.usefulMethod = myUsefulMethod;

}

var str = window.prompt("Method name?");eval(str)();str.usefulMethod(); // hmmmm...

33

Don't Hold Your Breath For Optimizations

Imagine you want to write a JavaScript optimizer…

Can we inline constants to shrink our script?

It depends on what checkBandwidth() does

Extreme flexibility has a price

// JavaScriptcoolImportMechanism("bandwidth_check.js");var MAX_PREFETCHED_IMAGES = 12;checkBandwidth();prefetchImages(MAX_PREFETCHED_IMAGES);

function checkBandwidth() {if (thisConnectionIsSlow())MAX_PREFETCHED_IMAGES = 2;

}

// JavaScriptcoolImportMechanism("bandwidth_check.js");checkBandwidth();prefetchImages(12);

34

Also Don't Hold Your Breath For…

Comprehensive Syntax HighlightingIs it a field or a method?

RefactoringInability to analyze → inability to refactor

Comprehensive Source Browsing

Full Compile-time CheckingImpossible to say if a "spelling bug" is a bug or not

Machine-checkable RPC

35

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

36

Have Your Cake AND Eat It!

"Powerful" LanguagesDynamic Typing

"Weaker" LanguagesStatic 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

JSNI

Demo

"Hello, Ajax" Revolutions

JavaScript Native Interface (JSNI)

38

Topics

Borrowing Trouble with Ajax

Google Web Toolkit Does What?

Productivity

Interoperability

Performance, Performance, Performance

Parting Thoughts

39

Stateful Client → Scalability

StatelessHTML View

Browser

StatefulServer

User action

New HTML page

011001100111100101101011

011001101101111110010100011010111101110011010110

StatefulJavaScript UI

Browser

Stateless(i.e. any)

Server

Remote procedure call

Data only, not HTML

Events handled locally

01100111

011010011011

Traditional HTML

GWT/Ajax

40

Tough decision not to support reflection and class loading

Worth it! Three words: Whole program optimization

For example, type tightening to eliminate polymorphismShape s = new Circle(2); // radius of 2

double a = s.getArea();

becomesCircle s = new Circle(2); // radius of 2

double a = (s.radius * s.radius * Math.PI);

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

Optimize Like Crazy

41

Startup Time

Absolutely crucialShould be measured in millisecondsIf startup time isn't acceptable, nothing else matters

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

GWT gives you leverageCompiled output includes only what a particular user needsOutput is JS wrapped in HTML, which is safely gzip'ableLoads code in an <iframe> in parallel with the pageScripts are named uniquely and are perfectly cacheable

42

Compilation: Only Pay for What You Use

0

10000

20000

30000

40000

50000

60000

Empty

Window

.alert

("hell

o")Vert

icalPan

elButt

onChe

ckBox

Tree (3

items)

Labe

lTex

tBox

Grid (4

x 4)

HTML

Imag

e

TabPan

el (3

tabs)

ListB

ox (3

items)

Radio

Button

(3)

Hyperl

inkHori

zonta

lPanel

FlowPan

elAbs

oluteP

anel

Scrip

t Siz

e (b

ytes

)

Additional Widgets Used

43

Compilation: Optimized Per Client

Single Java Code Base

Download exactly what you need in a single

can't-go-wrong chunk

Then cache it on the client until the sun explodes

FireFox 1.0.x

Your Code

en_US

1D04ADDA.cache.html

Safari 2.0.x

Your Code

fr_FR…

7EFE4D24.cache.html

IE 6

Your Code

en_UK

15F361BB.cache.html

Opera 9

Your Code

fr_CA

D415D917.cache.html

44

Less Bandwidth: Lower Costs and Faster Apps

0

10000

20000

30000

40000

50000

60000

70000

80000

90000

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

Byt

es T

rans

ferr

ed

Traditional HTML GWT First Run GWT Other Runs

45

Topics

Borrowing Trouble with Ajax

Google Web Toolkit Does What?

Productivity

Interoperability

Performance, Performance, Performance

Parting Thoughts

46

Why Do Users Love Web Apps?

No installationEvery application is just a URL awayNo such thing as "DLL Hell" – it just worksCapable of super-fast startup time

Secure… the mantra we teach our parentsSurfing = safeInstalling = unsafe

Simple usabilityPages have a simple, friendly look and feelNot much to learn: back, forward, bookmarks, links, URLs

47

Don't Throw the Baby Out With the Bathwater

No installation…sort ofIn a sense, it’s also always-reinstall (had better be small)Don't penalize users for your engineering convenienceNever be willing to sacrifice fast startup

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

Ajax has tricky usability quirksHistory, bookmarks and even hyperlinks misbehaveBadly coded Ajax is worse than traditional HTML

48

To Be Crystal Clear

It is very tempting to build frameworks that

make life easier for developers

…at the expense of user experience

49

Not Enough Time to Demo Everything

Internationalization supportHighly optimizedExternalized string ids are checked during compilation

Automatic, dynamic dependency inclusionSlurp in external CSSSlurp in external JS

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

Your choice of development platformsMac OS X, Linux, Windows

Your choice of IDEsIntelliJ IDEA, Eclipse, NetBeans, JCreator, JBuilder

50

GWT Library Overview

User InterfaceUser Interface

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

Usability and I18NUsability and I18N

History, DeferredCommand, Localizable, Constants, Dictionary, ConstantsWithLookup, Messages

RPCRPC

AsyncCallback, IsSerializable, RemoteService, RemoteServiceServlet

JSONJSON

JSONArray, JSONBoolean, JSONException, JSONNull, JSONNumber, JSONObject, JSONParser, JSONString, JSONValue

XMLXML

DOMException, XMLParser, Attr, CDATASection, CharacterData, Comment, Document, DocumentFragment, Element, EntityReference, NamedNodeMap, Node, NodeList, ProcessingInstruction, Text

HTTPHTTP

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

51

GWT is Actually Documented

Getting Started Guide Widget Gallery

Developer Guide Class Reference

52

Growing GWT Community

Community and SupportOver 4900 members on the developer forum and growingBooks and articles Meta-sites (e.g. gwtPowered.org)

Libraries and ApplicationsGWT Widgets on SourceForge25 projects on Google Code Project HostingDiverse products built completely with GWTJetBrains' JET markup framework for GWT

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

53

Did I Mention Tools?

Instantiations GWT DesignerWYSIWYG Layout

54

Did I Mention Tools?

Instantiations GWT DesignerInternationalization

55

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!

Q & A