Tải bản đầy đủ - 0 (trang)
Chapter 12. Code Generation and Reuse

Chapter 12. Code Generation and Reuse

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

12.1.Server-SideCodeGeneration



AutoGenerated,CodeGen,Framework,Library



Figure12-1.Server-SideCodeGeneration



12.1.1.DeveloperStory

Dave'screatingawebappwithatrendynewserver-side

framework,ZeroWeb.Theframeworkletshimwriteeverything

inJavaasifhe'swritingastandaloneGUIapplication.It's

capableofusingthatcodetogenerateaconventionaleditionof

theapplication,AnAjaxedition,adesktopedition,andforan

extra$99.95asmartphoneapptoo.



12.1.2.Problem

HowdoyouavoidusingHTMLandJavaScript?



12.1.3.Forces

HTMLandJavaScriptaretheonlycoderecognizedby

standardbrowseranyAjaxAppmustberepresentedina

combinationoftheseformats.

AjaxisincreasingthecomplexityofHTMLandJavaScript.

WhereasJavaScriptwaspreviouslyusedforsimpletasks

likenavigationsupportorformvalidation,it'snowdriving

theinteractioninmanyapplications.

MostAjaxAppsalsohaveasubstantialbackend,whichis

rarelyimplementedinJavaScript.

It'sdifficulttocompletelyseparatetherolesofbrowser-side

developerandserver-sidedeveloper.Infact,it'softenmore

desirabletohavethesamedeveloperworkingonavertical

sliceoffunctionality;i.e.,contributingalittletoalltiersin

ordertodeliveranewrequirement.Thus,thesame

developerisoftenexpectedtoworkacrosstiers,wherethe

environmentdifferssignificantly.

Server-sidedevelopmenthascertainadvantagesover

JavaScriptdevelopment.Insomecases,there'sbetter

supportforcodeediting,refactoring,testing,andsoon.

Sometimes,youwantdifferentuserinterfacesforthesame

applicationanon-Ajaxversionoradesktopversion,for

example.



12.1.4.Solution

AutomaticallygenerateHTMLandJavaScriptfrom

server-sidecode.Youwritecodeinastandardserver-side

languagelikeJavaandit'sconvertedtoHTMLandJavaScript.

Dependingontheframework,youmightnotneedtocode

directlyinHTMLorJavaScriptatall.Sinceyou'reunlikelyto

createsuchaframeworkyourself,thispatternreliesona

certaincategoryofpubliclyavailableAjaxframework(see

AppendixA).

Inthecaseofallcodebeingauto-generated,thecodeis

somethinglikeaconventionaldesktopapplication.Widgetsand

eventhandlersaredefined,andthebrowsergeneratesthe

appropriateHTML,alongwithXMLHttpRequestCalls(Chapter6)

andgeneralJavaScripthandling.Aswell,theframeworkwill

oftengenerateAjaxStubstodealwithincomingcallsandpass

themtoappropriateapplicationcode.

Inotherframeworks,theapproachismoremixed.The

frameworkmightletyoucreateaSliderwithjustasingletag,

forexample.Butinthetag,you'llspecifyaJavaScriptfunction

tobecalledwhenevertheslidervaluechanges.

ThereareseveralargumentsforServer-SideCodeGeneration:

Itmaybemoreproductive,astheserver-sidelanguageand

frameworkmaybemoreexpressiveandalsobecausethe

frameworkmightremoveredundancyacrossthetiers(such

asadatastructurehavingaJavaScriptrepresentationas

wellasaserver-siderepresentation).

Developersdon'thavetoknowHTMLandJavaScript;they

canworkintheserver-sidelanguageandenvironment

they'remostfamiliarwith.



Theframeworkcanhelpwithgracefuldegradation.Inother

words,itcanfreethedeveloperofworryingaboutbrowser

portability,JavaScript,orcookiesbeingturnedoff,or

XMLHttpRequestCallstimingout.

Theframeworkcan,intheory,delivermultipleplatforms

simultaneously.Asinglecodebasecanbeusedtogenerate

awebapplication(Ajaxianornot),standalonedesktop

application,andmaybeevenamobileapplication.

However,codegenerationdoescomesatacosttousability.

Lookatitthisway:anythingyoucouldgeneratefromthe

server,askilleddevelopercouldalsohandcode.Thereverseis

nottrue;givenenoughtimeandtalent,it'salwayspossibleto

buildacustomsolutionthat'ssuperiorintermsofusability.So,

tobeworthwhile,theframeworkmustaddenoughvaluein

termsofproductivityandsupportfornon-experts,tobe

compensatedforthedropinusability.Whetherthiscanbe

achievedreallydependsontwothings:howmuchuserswill

gainfromacustom-builtapplication,andhowmuchofaboost

theframeworkwillgiveyou.Onthesecondpoint,considera

fewcounter-argumentstothebenefitsabove:

Thefirstpoint,aboutdevelopersnothavingtolearnHTML

andJavaScript,hastraditionallyheldthemostweight.

Server-sidedevelopersinthepastproducedminimalist

satisficinginterfacesratherthanoptimalones,allowing

themtofocusontheserverside.It'snotuncommontosee

adviceagainstanythingrelativelycomplexbeingperformed

ontheserverside.ButasAjaxbecomesmoreprominent,

thisargumentbecomeslesscompelling.AsdiscussedinFat

Client(Chapter13),JavaScriptisundergoinga

renaissancedevelopersarelearningmoreaboutit,toolsand

librariesareevolving,andpatternsareemerging.Allthis

reducestheargumentforisolatingdevelopersfromHTML

andJavaScript.



Aserver-sideframeworkmaywellbeabletohandle

gracefuldegradationandbrowserversionstransparently.

Buttotheextentthat'spossibleintheserver,ascriptcan

equallyachievethesameeffectinthebrowser,asdiscussed

laterinCross-BrowserComponent(seelaterinthis

chapter).Portabilityisreallyalame-duckargumentfor

usingserver-sideframeworks.

Thedreamoftransformingasinglecodebaseintoavariety

ofdifferentuser-interfacestyleshasbeenaroundfora

while.Certainly,manymodernUItoolkitsarecrossplatform,runningondifferentoperatingsystemsfromthe

samecodebase.However,canasinglecodebaseleadto

bothawebappandadesktopapplication?It'spossiblein

theoryandinproof-of-conceptdemos,butinpractice,users

expectapplicationstofollowtheconventionsoftheplatform

andthat'sdifficulttoachievewithasinglegeneration.

AninterestingvariantofServer-SideCodeGenerationis

"Browser-SideCodeGeneration";theBackbaseframework

(http://backbase.com)isacaseinpoint.WithBackbase,the

serveroutputsaspecializedmarkuplanguage,BXML,andthe

browserconvertsitintoHTML,CSS,andJavaScript.

Iexpectthefull-featuredframeworkstobecomeparticularly

prominentonintranetapplications,wherenewfunctionalityis

oftenmorecriticalthanusability,anduserscanbetrainedto

workaroundproblems.Hand-codedHTMLandJavaScriptis

morelikelyforpublicdot-comswherealternativesareabundant

andthepressureofcompetitionmeansit'scriticaltooptimize

theuserinterface.Inthoseenvironments,thereisstillsome

roleforServer-SideCodeGeneration,butmainlyasahelperfor

veryspecifictasksandwithsomeflexibility,ratherthanasthe

overarchingarchitecturalstyle.



12.1.5.Real-WorldExamples

Theseexamplesdescribeframeworksthatsupportthispattern

indifferentways.



12.1.5.1.Echo2

Echo2(http://www.nextapp.com/products/echo2/)isanopen

sourceframeworkbyNextApp,whichtakesthe"wholehog"

approachandgeneratesallHTMLandJavaScriptfromJava

sourcecode.Anonlinedemo

(http://demo.nextapp.com/InteractiveTest/ia)showshow

Echo2'suser-interfacewidgetclassesmanifestthemselvesin

thebrowser(Figure12-2).



Figure12-2.Echo2demo



12.1.5.2.RubyOnRailsframework



RubyOnRails(http://rubyonrails.com)isawebframeworkthat

embedsRubyinsidewebpages.Thatinitselfisnotnew,but

Railsoffersbuilt-inhelperclassestospeeduppage

construction.TheyoftenleadtotheScriptaculouslibrarybeing

invoked,buttheprogrammerdoesn'tuseitdirectly.For

example,youcanissueanXMLHttpRequestCallfollowedby

DisplayMorphing,usingthefollowingembeddedRubycall

(http://www.onlamp.com/pub/a/onlamp/2005/06/09/rails_ajax.html

<%=link_to_remote("clickhere",

:update=>"time_div",

:url=>{:action=>:say_when})%>



12.1.5.3.Backbase

Backbase(http://backbase.com/)isacommercialframework

thatextendsstandardXHTMLwithBackbase-specifictags

(BXML).ABackbaseclient-sideframeworktranslatestheBXML

toHTML,CSS,andJavaScript,makingiteasytoimplement

manystandardAjaxfeatures.Sothere'sawidgettagthatlooks

likethis:





andanothertagforvariousvisualeffects:





ThereareseveralinnovativedemosavailablefromtheBackbase

homepage



(http://www.backbase.com/#home/pulldown/demos.xml[2])

(Figure12-3).Ontheserver,Backbaseoffersprogramming

interfacesforboth.NETandJSFandoffersvisualdevelopment

toolsforVisualStudio.NETaswell.Aswiththeothertools

here,thedeveloperdoesn'thavetodealwithHTMLor

JavaScript,buttheframeworkalsoletspeoplecustomizethe

generationforspecializedbrowserappearancesandbehavior.

Notethat,asmentionedearlierinthe"Solution,"Backbaseis

actuallyakindofclient-side,ratherthanserver-side,code

generation.



Figure12-3.BackbaseTraveldemo



12.1.5.4.AjaxTagslibrary

AjaxTags(http://ajaxtags.sourceforge.net/)isacollectionof



JSPtagstoeasedevelopmentofAjaxinteraction.There'san

tagforSuggestionandanfieldto

performaDisplayMorphing(Chapter5)withtheresponseofan

XMLHttpRequestCall(Chapter6).



12.1.5.5.Comfort.ASPlibrary

Comfort.ASP(http://www.daniel-zeiss.de/ComfortASP/)takes

anunusualapproachbyautomaticallyaddingWebRemoting

(Chapter6)toaconventional,non-Ajaxapplication.By

instrumentingtheHTML,theframeworkcaninterceptstandard

formsubmissionsandtransformthemintoXMLHttpRequest

Calls.Bymonitoringserveroutput,Comfort'sserver-sidescript

canrespondtothesecallsbysendingbackonlydeltasthe

differencebetweenthecurrentHTMLandthedesiredHTML.



12.1.6.CodeExample:Echo2NumberGuess

Echo2(http://www.nextapp.com/products/echo2/)providesfull

sourceforatutorialapplication,NumberGuess

(http://www.nextapp.com/products/echo2/doc/tutorial/application.html

Theuserguessesanumberbetween1and100,theapplication

tellsthemifit'shigherorlower,theusertriesagain,andsoon.

Notethatthecodeisavailable,butthere'snoonlinedemoat

present.

AnEcho2applicationisrunasaJavaservletextendingEcho2's

WebContainerServlet.Thesuperclasstakescareofmost

interaction;theconcreteservletmustdojustonething:declare

anApplicationInstance.InEcho2,anApplicationInstanceobjectis

theapplicationstateforagivenuser:



/**

*Guess-a-numberTutorialApplicationServletImplementatio

*/



publicclassNumberGuessServletextendsWebContainerServlet{



/**

*@seenextapp.echo2.webcontainer.WebContainerServlet#new

*/

publicApplicationInstancenewApplicationInstance(){

returnnewNumberGuessApp();

}

}



Themainapplicationobjectinitializesanewwindowand

controlstwotop-leveluser-interfaceelements:aGamePaneon

startup,whichiswherethemainactiontakesplace,anda

CongratulationsPaneuponvictory:[*]

[*]Allcommentsareomittedinthecodesample.



publicclassNumberGuessAppextendsApplicationInstance{

privateWindowmainWindow;

publicWindowinit(){

mainWindow=newWindow();

mainWindow.setTitle("Echo2Guess-A-Number");

startNewGame();

returnmainWindow;

}

voidstartNewGame(){

...

mainWindow.setContent(newGamePane());

}

voidcongratulate(intnumberOfTries){

mainWindow.setContent(newCongratulationsPane(numberO

}

}

classGamePaneextendsContentPaneimplementsActionListener



...

}

classCongratulationsPaneextendsContentPaneimplementsActi

...

}



TheGamePaneisbuiltupbyaddingsubelementsandregistering

events.ItactsasanActionListenerforthebuttonsitcontains;

hence,there'sanactionPerformedevent,whichencapsulatesthe

guessevaluationlogic.Thecodeillustratesthataframework

likeEcho2pavesthewayforastyleofwebprogrammingthat's

almostidenticaltotraditionaldesktopcoding.



classGamePaneextendsContentPaneimplementsActionListener



privateintrandomNumber=((int)Math.floor(Math.random()

privateintlowerBound=1;

privateintupperBound=100;

privateintnumberOfTries=0;

privateTextFieldguessEntryField;

privateLabelstatusLabel=newLabel();

privateLabelcountLabel=newLabel("Youhavemadenogues

privateLabelpromptLabel=newLabel("Guessanumberbetwee

privateintguess;

GamePane(){

super();

ColumnlayoutColumn=newColumn();

layoutColumn.setCellSpacing(newExtent(10));

add(layoutColumn);

...

ButtonsubmitButton=newButton("SubmitYourGuess");

submitButton.setActionCommand("submitguess");

submitButton.setForeground(Color.BLACK);



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

Chapter 12. Code Generation and Reuse

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

×