Tải bản đầy đủ - 0 (trang)
Chapter 3. Ajax Design: Principles and Patterns

Chapter 3. Ajax Design: Principles and Patterns

Tải bản đầy đủ - 0trang

3.1.DesirableAttributesofAjaxApplications

Ajaxisaboutimprovinguserexperienceanddeliveringvalueto

theorganizationsthatownandusewebapplications.Here,we'll

lookatthekeyattributesofanidealAjaxapplication.Reality

dictatesthatyou'llnevergetthebestofallworlds,soyou'll

havetomaketrade-offsbasedonhowimportantyouconsider

eachattribute.TheAjaxPatternsareintendedtohelpyoudeal

withthesetrade-offs.



Usability

Ajaxapplicationsshouldbeasintuitive,productive,andfun

touseaspossible.



Developerproductivity

Developmentshouldbeasefficientaspossible,witha

clean,maintainablecodebase.



Efficiency

Ajaxapplicationsshouldconsumeminimalbandwidthand

serverresources.



Reliability

Ajaxapplicationsshouldprovideaccurateinformationand

preservetheintegrityofdata.



Privacy

Whileuser-generateddatacanandshouldbeusedto

improvetheuserexperience,users'privacyshouldalsobe

respected,andusersshouldbeawareofwhenandhow

theirdataisused.



Accessibility

Ajaxapplicationsshouldworkforuserswithparticular

disabilitiesandofdifferentagesandculturalbackgrounds.



Compatibility

Asanextensiontoaccessibility,Ajaxapplicationsshould

workonawiderangeofbrowserapplications,hardware

devices,andoperatingsystems.



3.2.DesigningforAjax

BystudyingexistingAjaxapplications,aswellasanyrelevant

precursors,it'sbeenpossibletodistillanumberofimportant

designprinciplesforAjax,whichareshowninthissection.The

thinkingbehindtheprincipleswasabiginfluenceonthepattern

discoveryprocess,andknowingthemwillhelptoapplythe

patterns.

We'llbeginbylookingatprinciplesofuser-centereddesign,

followedbythoseofsoftwaredesign.Ofcourse,youcannever

fullyseparatethoseconcerns,andthey'reofteninconflictwith

eachother.Dealingwiththoseconflictsisreallyakeyconcern

ofthepatterns.Incidentally,it'sworthcheckingoutagood

onlineresourcethattakestheoppositeperspective:Ajax

Mistakes(http://swik.net/Ajax/Ajax+Mistakes)isalonglistof

Ajaxmistakesandgotchas,aswellasanti-patternsoriginally

authoredbyAlexBosworthandnowmaintainedonawiki.



3.2.1.UsabilityPrinciples



Followwebstandards

Tryhardenough,andyoucandosomeveryconfusing

thingswithAjax,evenmoresoasrichgraphicsbecome

commonplace.RatherthanreinventingtheWebasweknow

it,useAjaxtobuilda"betterWeb,"anenhancedlayerover

what'salreadythere.Respecttheconventionsthatusers

arealreadyfamiliarwith.



Thebrowserisnotadesktop



Furthertothepreviousprinciple,Ajaxisaricherbrandof

thetraditionalwebsiteratherthanawebifiedbrandofthe

traditionaldesktop.True,desktopwidgetslikeslidersare

migratingtowardsAjax,butonlywhentheymakesensein

awebcontextandofteninamodifiedform.We'realso

seeingapplicationcategorieslikewordprocessorshead

onlineaswell,butagain,thebestproductswillbethose

thatfitinwiththeWebratherthanblindlyreplicatingthe

desktopexperience.



Ifit'sdifferent,makeitreallydifferent

Subtledifferencesconfusepeople.Ifyou'vedecidedit

makessensetodivergefromastandardoracommon

idiom,ensureyourdesignisdistinctenoughtoavoid

confusion.



Provideaffordances

Affordances(http://en.wikipedia.org/wiki/Affordance)are

asimportantaseverinAjax.Youmayhaveafancynew

drag-and-droptechniqueforupdatingaform,butwillthe

userevenknowit'spossible?Visualdesign,dynamicicons,

andstatusareasallhelphere.



Smooth,continuousinteraction

Avoidthestart-stoprhythmofconventionalwebapps.Full

pagerefreshesareadistractionandatime-waster.Ifused

atall,theyshouldbereservedforsignificant,infrequent

activitiessuchasnavigatingtoaconceptuallynewplaceor

submittingalargeform.



Customization

Applicationpreferenceshaven'tbeenveryimportantonthe

Web.Whybotherpersonalizingbackgroundcolorsfora

shoppingsiteyouuseonceamonth,especiallyifitmeans

sittingthroughatedioussequenceofformsubmissions?

Butforsomewebapplications,theusermightbespending

eighthoursadayworkingwiththem,andcustomization

suddenlyfeelsawholelotmoreuseful.WithAjaxdriving

thecustomizationprocess,it'saloteasiertoo.



Makeitfun

AjaxmakestheWebalotmorefunthanitusedtobe.

Techniqueslikevisualeffects,drag-and-drop,andperiodic

updatesaresometimeslabelled"gimmicks"or"eyecandy,"

asifusersdon'tactuallyenjoythosethings.Appliedwith

careandideally,usertesting,theycandefinitelyaddreal

value,evenin"serious"applications.



3.2.2.SoftwareDesignPrinciples



EmbraceJavaScript

ThanksmostlytotheinterestinAjax,JavaScript

(http://www.crockford.com/javascript/javascript.html)isno

longerseenasabasketcaselanguagetobeavoidedatall

costs.Itcanactuallybesurprisinglypowerful(cutthe

sniggeringalready!),providedthatdevelopersarewillingto

studytheidioms,patterns,andidiosyncrasies.



Acceptworkaroundswherenecessary

BecauseAjaxisfirmlybasedonstandardbrowserfacilities,

there'ssimplynogettingaroundthemanyconstraints

imposedbymodernbrowsers.Ifyouseekthebenefitsofa

richwebapplicationthatwillrunimmediatelyonany

modernbrowser,andyouconsiderusabilitytobecritical,

thenyoucanonlyusewhateverhacksarenecessary.You

mightwelllamentthatAjaxdevelopmentisinherently

troublesomeandpineforacleanerwaytogetthejobdone

(IknowIdo).Butthepointisthatyoudon'tgetalotofsay

inwhatthevastmajorityoftheworldisalreadyusing,and

willcontinuetouseinthenextfewyears.Maybeweb

developmentwillbeneateroneday,buthereinthe

present,thelandofreality,it'sadvisabletodealwiththe

technologyathandandworkaroundorexploitwhatever

cheaptricksareavailableiftheyultimatelyenableuseful

functionalitythatwouldotherwisebeunachievable.



Tameasynchrony

Thebrowser-servercommunicationofanAjaxAppis

asynchronousbynature.Thisleadstoseveralrisks:users

mightnotbetoldthatacallhasfailedortimedout;calls

mightbeprocessedinanonatomicmanner;orthebrowser

mightforgetwhyacallwasmadebythetimeitsresponse

hasarrived.Asexplainedinseveralpatterns,thereare

techniquesavailabletomonitorandcontrolcallssothat

thesesituationsdon'tarise.



Developforcompatibility



WhereJavaScriptprogrammingstillhasissuesisin

portability.Atasyntaxlevel,JavaScriptisreasonably

consistentacrossbrowsers,astheECMAstandardization

process(anefforttodefineJavaScriptstandards;see

http://en.wikipedia.org/wiki/ECMAScript)hasgenerally

beenrespectedbyallthemajorbrowsermakers.However,

it'sstillamovingtarget,soolderbrowsersofanyvariety

simplywon'tsupportsomefeatures.Moreover,theDOM

remainsaseriousportabilityconcern.Despitegradual

improvementsovertheyears,thereremainmanysubtle

differences,andwe'resetformoredivergenceinthefuture.

Developingforcompatibilitymeansbeingexplicitabout

whichversionsaretargeted,usingportablelibrarieswhere

available,andarchitectingsothatportabilityconcernsare

isolatedfromcorelogic.



Reducebandwidth

Ifthere'sfrequentnetworkactivity,you'llwanttothink

carefullyaboutthesizeofthemessagesbeingpassedback

andforth.



Dealwithlatency

Whenpeopletalkabout"howfast"theirconnectionis,

they'reusuallydiscussingthroughputrate;e.g.,"a4

megabitconnection."That'sgreatfordownloadinglarge

content,butwhataboutinteractivity?Latencybasicallythe

timeforabittotravelbetweenbrowserandserverisusually

moreimportantthanthroughputrate

(http://richui.blogspot.com/2005/09/ajax-reducing-latencywith-cdn.html).Inwebappswheretheservermaybe

halfwayacrosstheworld,youcan'treasonablyrespondto

eachkeystrokeormousemovementduetolatency



overheads.Thechallengeistomaketheapplicationfeel

responsivewhilereducingthefrequencyofinteractions.

TechniqueslikeSubmissionThrottlingandPredictiveFetch

makethetrade-offbydecreasingfrequencybutincreasing

theamountofdatasenteachtime.



Partitionintomultipletiers

Asinanywebarchitecture,Ajaxapplicationsshoulduse

multipletierstohelpseparateconcerns.Thisadviceis

commonlymisinterpretedasimplying"keepthe

presentationsimple,"amistakethatunfortunatelyleadsto

patheticallybarrenuserinterfaces.Don'tbeafraidtocreate

rich,intelligentuserinterfaceswithJavaScript;justbesure

todevelopforcompatibilityandensureyourbusinesslogic

isseparatefromyourpresentationlogic.Inaddition,

practice"unobtrusiveJavaScript"and"unobtrusiveCSS."

Thatis,keepyourinitialHTMLpagecleanbyreferencing

externalJavaScriptandCSSfiles;noembeddedJavaScript

orCSS.JavaScriptandCSSshouldbekeptaparttoo;where

possible,thescriptshouldchangeanelement'sdisplayby

switchingitsCSSclassratherthanmicromanagingstyle

informationdirectly.



Goeasyonthebrowser

Unfortunately,yourAjaxAppwillprobablyendupbeingone

ofmanythingsrunningintheclientmachine.Thisis

exacerbatedbythefactthatJavaScriptisprettyslow

anyway,meaningthatyouhavetoexerciserestraintinhow

muchhappensinthebrowser.



Practicegracefuldegradation

Whereabrowserdoesn'tsupportadvancedfeatures,Ajax

applicationsshouldgracefullyfallbacktousewhateveris

possible.Inanidealworld,thesamefunctionalitywould

stillbeavailable,albeitwithlessbellsandwhistles.But

evenifyouneedtosacrificefunctionalityandyouoftenwillit

shouldbedoneinagracefulmanner.(Think"politeerror

messages"andnot"complicatedstacktraces.")







3.3.AjaxPatternsOverview

TheAjaxPatternsshowhowpeoplehaveusedthedesign

principleseffectivelyinreal-worldAjaxapplications.Itmight

seemfunnythatwecanhavesomanypatternsaboutAjax,a

termthatwascoinedonlyafewmonthsbeforeworkonthese

patternsbegan.However,theideasarenotnew;therewere

manyAjaxfeaturesontheWebbeforethetermcameaboutto

describethem.ThehealthyNeteconomyhashelpedalottoo,

withhundredsofnewsitesnowusingAjax,alongwithpowerful

tools(RSS,Technorati,Google,andwikis)tolocatethemas

soonasthey'reavailable.

Withover60patterns,it'susefultoclassifythepatterns

hierarchically.Atahighlevel,thebookisdividedintofour

parts,eachcorrespondingtoadifferentfocusareaFoundational

Technology,Programming,FunctionalityandUsability,and

Development.Beyondthat,eachpartisdividedintoseveral

chapters,whereeachchapterincludesrelatedpatterns.For

instance,FoundationalTechnologyPatterns(PartII),includes

WebRemoting(Chapter6),whichincludesseveralpatternsfor

webremoting.Here'sasummaryofeachpart:



FoundationalTechnologypatterns(11patterns)

Thefoundationaltechnologiesarethebuildingblocksthat

differentiateAjaxfromconventionalapproaches,andthis

sectionexplainstypicalusage.



Programmingpatterns(23patterns)

Thesearethefeaturesofarchitectureandcodethatserve



thesoftwaredesignprincipleslistedpreviously.These

include,amongotherthings,designofwebservices;

managinginformationflowbetweenbrowserandserver;

populatingtheDOMwhenaresponsearrives;and

optimizingperformance.



FunctionalityandUsabilitypatterns(28patterns)

Thesearethethingsthatmattertousers,includingwidgets

andinteractiontechniques;structuringandmaintaining

what'sonthepage;visualeffects;andfunctionalitythat

Ajaxmakespossible.



Developmentpatterns(8patterns)

Theseareprocesspatternsadvisingonbestpracticesfor

development,asopposedtoallthepreviouspatterns,which

are"things"thatliveinsideanAjaxapplication.The

practicesareaboutdiagnosingproblemsandrunningtests.

Figure3-1showswherethefourpartssitinthecontextofan

Ajaxapplication.Mostpatternsthoseinthefirstthreepartsare

abouttheproduct,whiletheremainingpart,Development

patterns,isabouttheprocess.Oftheproduct-oriented

patterns,theFoundationalTechnologiesexplainhowtousethe

crudewebtechnologiessuchasXMLHttpRequestandtheDOM.Ata

mediumlevelaretheProgrammingpatterns,guidingon

strategiestousethesetechnologies.Atahighlevelarethe

FunctionalityandUsabilitypatterns.Overall,theFoundational

TechnologypatternsareatthecoreoftheAjaxPatterns

language;theremainingthreepartsallbuildonthese,andare

fairlyindependentfromoneother.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 3. Ajax Design: Principles and Patterns

Tải bản đầy đủ ngay(0 tr)

×