a business case for ajax with google web toolkit bruce johnson google

54
A Business Case for Ajax with Google Web Toolkit Bruce Johnson Google

Upload: others

Post on 03-Feb-2022

4 views

Category:

Documents


0 download

TRANSCRIPT

A Business Case for Ajaxwith Google Web Toolkit

Bruce Johnson

Google

Defining our goal

• Deliver great products to users

• Tons of debate about web technology

– JavaScript on the server! Lisp on the client!Ruby everywhere! Browsers suck! Browsersrock!

• Yet user happiness never seems to figurein as a primary decision criterion

How we’re gonna roll today

• Ajax is very buzzword-ish at the moment

• Easy to get caught up in fads and FUD

• The only solution: just say no to the noise

• Think for yourself, question authority

– (Especially self-proclaimed authorities)

Don’t believe everything you think

• We can’t trust ourselves, either

• Software is part logic and engineering…

• …and part zealous chest-thumping

• Decisions are all too often influenced byintellectual bullying, jumping toconclusions, profit motives, expediency,inertia, and fear

Example: The slippery slope

• We need Web 2.0 features to compete!

• Where are places we can put some script?

• Let’s make it really cool and dynamic!

• Why are our pages so slow to load now?

• Why don’t fonts resize correctly now?

• Our users are complaining…

• Oh, we’ll just optimize it…wait…uh…

Working backwards

• Let’s start from our goal

• No presupposed solution

• Let’s take a walk from Z to A

– Yell if we mis-step

• Deliver great products to users

What makes a product great?

• We developers can’t assert it

• Great: users love using it

• Some key attributes:

– Easy to learn through experimentation

– Powerful enough to reward you for learning it

– Users remember extremes, bad and good

– It’s easier to remember the bad things

What doesn’t make a product great

• It has nothing to do with your source code

– Elegance, maintainability? Irrelevant

– How much fun it is to develop? Irrelevant

– Choice of programming languages? Irrelevant

• Do you buy a car based on the CAD systemused to design it?

– If it gets 7 MPG, does the manufacturer say,“But our CAD system makes us efficient!”

Exactly who are these users, anyway?

• For web apps, lots of things vary…

• Language, grammar, RTL, character sets, …

• Cultural norms for icons, colors, …

• Interaction aids (IMEs, screen readers, …)

• Hardware/OS (Mac, Windows, Linux, …)

• RAM and CPU speed (+mobile)

• Screen resolution (+mobile)

Exactly who are these users, anyway?

• Things that vary by user, continued…

• Network characteristics (dial-up, DSL, cable,satellite, cell, …)

• Tolerance for responsiveness, reliability, andUI complexity

• Browsers (FF, IE, Safari, WebKit, +mobile)…

And then there are the commonalities

• Slow apps are annoying

• Crashy apps are annoying

• Slow, crashy apps are not worth using

• Truly great apps should at least know wherethey stand on all of the above issues

– It’s exhausting just thinking about it

– Easy to fixate on the aspects you can wrap yourhead around: staring at code in a vacuum

Simplifying principles

• The need for applications crosses all borders

• You don't need to be at your desk to need access toan application

• Minimize usability compromises due toimplementation challenges

• “Fast is better than slow” is an understatementwhen switching costs are low

The GWT Mission Statement

To radically improvethe web experience for usersby enabling developersto use existing Java toolsto build no-compromise Ajaxfor any modern browser

Tech prereq: Why a compiler?

• Vital to separate the maintainability of the sourcecode from the effectiveness of the executable

• Handwritten JavaScript has a conflict of interest

– Long, useful identifiers = bigger, slower apps

– Nice formatting = bigger, slower apps

– Comments = bigger, slower apps

• The solution isn’t to try to strike a balance inhandwritten JavaScript, it’s to create a level ofindirection, so that you compromise neither

Example: Type tightening• Eliminating runtime costs of polymorphism

Shape s = new Square(2); // side length of 2int a = s.getArea();

– can become

Square s = new Square(2);int a = (s.length * s.length);

– which, if the constructor has no side effects, can become

int a = 4;

• Uses type information across the entire app

• Smaller script/faster execution are oftencomplementary, which is really fun

Tech prereq: Deferred binding

• “No-compromise” means we must use allconceivable optimizations

• “Portable” is the opposite of optimized

– Must avoid least-common-denominator syndrome

– Yet, abstractions are vital to effective development

• Solution: GWT deferred binding

• Using polymorphism as a permutation axis

• Fully optimize each permutation separately

Single Java

Code Base

Download exactly what you need in

a single, optimized,

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

Java implementation in GWT source:

class Button {

public void setText(String text) {

DOM.setInnerText(getElement(), text);

} }

Safari version:

class DOMImpl {

public native void setInnerText(Element elem, String text) /*-{

// Remove all children first.

while (elem.firstChild) {

elem.removeChild(elem.firstChild);

}

// Add a new text node.

if (text != null) {

elem.appendChild($doc.createTextNode(text));

}

}-*/;

}

Internet Explorer version:

class DOMImplIE6 {

public native void setInnerText(Element elem,

String text) /*-{

elem.innerText = text || '';

}-*/;

}

Java call site in GWT source:

b.setText(”Click Me!");

Compiled Javascript (IE):

b.element.innerText = ’Click Me!';Compiled Javascript (Safari):$setInnerText(b.element, 'Click Me!’);

function $setInnerText(elem, text) {

while (elem.firstChild) {

elem.removeChild(elem.firstChild);

}

if (text != null) {

elem.appendChild($doc.createTextNode(text));

}

}

246915209182477innerText

-1386908-textContent

4078 ms2053 ms1276 ms2876 msTypical portablesetInnerText()

IEOperaSafariFirefox

39%32%29%14%Speedup

Bottom-line: Faster-than-possible

The need for applications crosses all borders

• Internationalization (i18n) isn’t just strings

• “Constants” for locale-specific values and settings

• “Messages” for localized strings with arguments

• “Localizable” for locale-sensitive algorithms

• “DateTimeFormat” for parsing/formatting

• “NumberFormat” for parsing/formatting

• All client-side, no round-trips (for speed)

• Statically checkable (for correctness)

Messages: Maximally-efficient I18N

• Interfaces define type-safe template methodsinterface ErrorMessages extends Messages

{ String accessDenied(int errorCode,

String username); }

• Corresponding localized properties filesaccessDenied=Error {0}:{1} cannot access {2}

• Connected via compile-time code generationWindow.alert(msgs.accessDenied(515, user))

• The above wouldn’t compile :-)

Messages: The code that executes

• Message references get inlined

• This Java sourceString s = msgs.accessDenied(42, user, ftr))

• Compiles into this JavaScript source (per locale)var s = "Error 42:" + user

+ " cannot access " + ftr

• Zero-cost abstractions make I18N easier to useand perfectly affordable at runtime

I18N Wrap-up

• Good I18N must be infused throughout your app

• Must be easy enough to be approachable…

• …and efficient enough to be affordable

• Coming soon: RTL layout, ARIA accessibility,more keyboard support

Onward!

You don't need to be at your desk…

• This fact alone justifies the choice of web apps vs.locally-installed apps

• Lots of other implications of web apps

• Direct collaboration

– Far better than emailing application data files around

– Hard to design apps that support live collaboration

– Need MVC-like architecture and good RPC

– On the web, you can’t not think about it

Additional implications of web apps

• Multiple browsers used, even by the same user

– Mobile only adds complexity

– Mobile is happening

• Do you really want to depend on plug-ins?

– At the least, apps should gracefully degrade

• Speed matters even here

– Users need to think of your app as at-the-ready…

– Not something with a “high activation energy”

Did I mention mobile?

• Very complicating

• Screen resolutions

• Touchscreen vs. not

• Crazy-different network characteristics

• Net: Need fast, small code tailored for eachdevice’s form-factor and capabilities

• GWT can help here

Only pay for what you use

Reuse without sacrificing efficiency

Shared client-side

application logic

Desktop UI Mobile UI #1 Mobile UI #2

Minimize usability compromises…

• Easy to make little concessions toimplementation concerns throughout

• At a technical level, deferred binding lets youcreate specializations easily

• But the more subtle point is how you designyour app in the first place

• And, of course, this all costs time and money

Minimize usability compromises…

History & Back is hard

Minimize usability compromises…

Don’t refresh ! we’ll charge you twice

Usability fundamentals

• Focus on the basics

• Prefer native UI elements

• Support keyboard-only use

• Honor font size preferences

• User in control of browser at all times

• Speed is vital, especially at startup

• The ideal: feels like a traditionalweb app, just better

Ask users

• User feedback and usability testing are vital

• You will never get it right the first N times

• Being able to iterate quickly is key

• Developers need tools and libraries with lotsof leverage

Things developers shouldn’t have to worry about early

• JavaScript funkiness

– spelling bugs

– “null” vs. “undefined” vs. “false” vs. “” (empty)

– speed

• Cross-browser support

• Memory leaks

• And…

Framework-itis

• Nice abstractions are for later

• JavaScript => difficulty in refactoring

• Refactoring difficulty => maintenance worry

• Maintenance worry => the need to “get itright” from the beginning: framework-itis

• But you don’t know what “it” is until you’vedone several iterations of user testing

• Worse than wasteful: creates bad inertia

Get residual value from prototype code

• User testing implies lots of prototype code

• Face it: you’re going to try to reuse it anyway

• GWT gives you enough leverage to build real,working prototypes for usability testing

– Reduces the distance between “mock” and “real”

– Prevents paper features that users love but can’t beimplemented in reality

• Ability to refactor makes all the difference

Modularizing your Ajax code

• “Obviously” you factor out JS library scripts

– Include only the ones you need using <script>

• The only problem…the performance sucks

• Why? Two reasons you can’t get around

– HTTP round-trips dominate speed, esp. startup

– <script> tags block parallel downloads

• Bad decisions beget more bad decisions

– You start wasting time inventing JS concat tools

• Another example of why you want a compiler

Before we get to #1…

• Of course, there are other businessconsiderations besides app greatness

• Minimizing development costs and maximizingproductivity

• Minimizing server hardware and managementcosts

• Maximizing competitive advantage

• Interoperability with existing code

HTML

Ajax

Stateless

HTML

Browser

Every user action

Totally new page

01100110

01111001

01101011

011001101101

111110010100

011010111101

110011010110

Stateful

Server

Events

handled

locally

0110

0111

0110

1001

1011

Stateful

JS and DHTML

Browser

Stateless

(i.e. any)

ServerData only, not HTML

Remote procedure calls

Responsiveness and efficient network usage

1.01.0

1.4

1.4

0

5

10

15

20

25

First Run Subsequent Runs

# H

TT

P R

eq

uests

We count HTTP requests for you

Upgrade + recompile = smaller code

1.0

1.0

1.4

1.4

0

20,000

40,000

60,000

80,000

100,000

120,000

Uncompressed Compressed

Scri

pt

Siz

e (

byte

s)

Upgrade + recompile = faster code

1.0

1.0

1.0

1.0

1.4

1.4

1.4

1.4

0

100

200

300

400

500

600

700

FireFox 1.0.7 Internet Explorer 6 Opera 9.2 Safari 2.0

RP

C R

ou

nd

Tri

p T

ime (

ms)

User Interface

DOM, AbsolutePanel, AbstractImagePanel, AbstractImagePrototype, Button, ButtonBase, CellPanel, ChangeListenerCollection,

CheckBox, ClickListenerCollection, ClippedImagePrototype, ComplexPanel, Composite, DeckPanel, DialogBox, DisclosurePanel,

DockPanel, FileUpload, FlexTable, FlowPanel, FocusListenerAdapter, FocusListenerCollection, FocusPanel, FocusWidget,

FormHandlerCollection, FormPanel, FormSubmitCompleteEvent, FormSubmitEvent, Frame, Grid, HorizontalPanel,

HorizontalSplitPanel, HTML, HTMLPanel, HTMLTable, Hyperlink, Image, KeyboardListenerAdapter, KeyboardListenerCollection,

Label, ListBox, LoadListenerCollection, MenuBar, MenuItem, PushButton, MouseListenerAdapter, MouseListenerCollection,

NamedFrame, Panel, PasswordTextBox, PopupListenerCollection, PopupPanel, RadioButton, RichTextArea, RootPanel,

ScrollListenerCollection, ScrollPanel, SimplePanel, StackPanel, SuggestBox, TabBar, TableListenerCollection, TabListenerCollection,

TabPanel, TextArea, TextBox, TextBoxBase, ToggleButton, Tree, TreeItem, TreeListenerCollection, UIObject, VerticalPanel,

VerticalSplitPanel, Widget, WidgetCollection

Client/Server Data Exchange (RPC, HTTP, JSON, XML)

DOMException, XMLParser, Attr, CDATASection, CharacterData, Comment, Document, DocumentFragment, Element,

EntityReference, NamedNodeMap, Node, NodeList, ProcessingInstruction, Text, AsyncCallback, IsSerializable, RemoteService,

RemoteServiceServlet, RPC, ServiceDefTarget, JSONArray, JSONBoolean, JSONException, JSONNull, JSONNumber, JSONObject,

JSONParser, JSONString, JSONValue, Header, Request, RequestBuilder, RequestCallback, RequestException, Response, URL

Quality and Usability (JUnit, Benchmarking, History, Bundling, I18N)

GWTTestCase, Benchmark, Command, DeferredCommand, IncrementalCommand, History, Timer, Localizable, Constants,

DateTimeFormat, Dictionary, ConstantsWithLookup, Messages, NumberFormat, ImageBundle

JRE Emulation

Boolean, Byte, Character, Double, Float, Integer, Long, Math, Number, Object, Short, String, StringBuffer, System, CharSequence,

Comparable, AbstractCollection, AbstractList, AbstractMap, AbstractSet, ArrayList, Arrays, Collections, Date, EventObject, HashMap,

HashSet, Stack, Vector, Collection, Iterator, List, ListIterator, Map, Set

Interoperation with existing code

• native methods using JavaScript// This is Java source

private native String flipName(String

name) /*-{

// This is JavaScript source

var re = /(\w+)\s(\w+)/;

return name.replace(re, "$2, $1");

}-*/;

• Call back and forth from Java source to JS

• Interop or hand-tweaking script

Share code between client and server

• Java source (sort of) on both sides of thewire

• If you’re careful, you can share sourcecode that rightfully should be in bothplaces (e.g. validation code)

• Migrate logic from client-to-serverwithout total rewrite

Getting Started Guide Widget Gallery

Developer Guide Class Reference

We’re covering some substantive ground here

• Notice what we haven’t talked about…

• “So-and-so said on his blog this was a really neat

way to build Ajax apps”

• "The Right Way to build Ajax apps is to use only

DOM Level 1-compliant APIs”

– (Even if it’s worse for the user?)

• “But I love Lisp!”

– (or Ruby, Python, JavaScript, C++, or whatever)

Fast is better than slow

• Maybe we’ve covered this one already after all :-)

• Upcoming GWT 1.5 builds on the speed

improvements in GWT 1.4 but goes further still

• Our speed goal: produce faster apps than anyone

could write by hand

– In all our latest tests, we’re there

– Yet we can still think of a lot more optimizations

– We also want to optimize and enhance the GWT

widgets

Things we didn’t cover

• Unit testing

• Javadoc

• RPC

• Benchmarking

• Design patterns

• Training (as in, you don’t need much)

• Tools!

Reference checks

• GWT is open source; code/design is scrutinized

• No check-ins without public code review

• 500+ members on the Contributors Forum

• 10,000+ members on the Developer Forum

• Millions of downloads

• Happy developers (see GWT Blog and Groups)

• Most importantly, happy end users

– If end users don’t know an app is GWT-based,

but they “just really like it”, then we have succeeded

The most important metric

• Happy end users

• If end users don’t know an app is GWT-based,

but they “just really like it”, then we have

succeeded

From the real world

And we've seen great success, with thousands ofusers in Fortune 500 companies around the world.And opposite the Web 2.0 / Enterprise 2.0 concern,users actually pay for our app!

Alex Moffat

Engineering Manager, Lombardi