Tải bản đầy đủ (.pdf) (667 trang)

Distributed net programming in c sharp

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.24 MB, 667 trang )

Distributed.NET
ProgramminginC#
ISBN:1590590392
byTom
Barnaby
Apress©2002(494pages)
Thistextdescribeshowto
usethesenew.NET
technologiestobuildfast,
scalable,androbust
distributedapplications,and
answersthemanyquestions
aboutthe.NETRemoting
Framework.
TableofContents
Distributed.NETProgramminginC#
Foreword
AbouttheTechnicalReviewer
IntroductionandAFAQ(Anticipated
FrequentlyAskedQuestions)
TheEvolutionof
Chapter1 DistributedProgramming
Chapter2 - Thisis.NET
Introductionto.NET
Chapter3 Remoting
DistributedProgramming
Chapter4 with.NETRemoting
AdditionalRemoting
Chapter5 Techniques



Chapter6 - UnderstandingXMLWeb
Services
UnderstandingCOM
Chapter7 Interop
LeveragingComponent
Chapter8 Services
Chapter9 - .NETMessageQueuing
DataAccesswith
AppendixA ADO.NET
Index
ListofFigures
ListofTables


BackCover
Presentsinformationusingastylethathasbeen
testedwhileteachingprofessionaldevelopers
Coversdistributedprogrammingwith.NET
remotingandWebservices
WrittenbyanexperiencedtraineratIntertech,Inc.,
aleaderinhands-onworkshopsforenterpriseWeb
developers
Withthereleaseof.NET,Microsofthasonceagain
alteredthedistributedprogramminglandscape.Almost
everythinghaschanged,fromdataaccesstoremote
objectcallstothedeploymentofsoftwarecomponents.
And,ofcourse,.NETintroducesanewtechnologyin
XMLWebservicesthatmayrevolutionizeWeb
development.
Distributed.NETProgramminginC#describeshowto

usethesenew.NETtechnologiestobuildfast,
scalable,androbustdistributedapplications.Alongthe
way,itanswerscommonquestions,suchas,HowdoI
usethe.NETRemotingFramework?Whatroledoes
COM+playinthe.NETuniverse?HowcanI
interoperatewithCOMcomponents?What’sthe
differencebetween.NETRemotingandWebservices?
Howwillthesechangesaffectthearchitectureand
designofadistributedapplication?
TomBarnabyassumesthereaderisalreadyfamiliar
withthefundamentalsof.NET.However,a.NET
overviewisprovidedtoconciselyexplainseveralofthe
core.NETtechnologiesthatareessentialfordisturbed


programming,includingbuilding,versioning,and
deployingassemblies;garbagecollection;serialization;
andattribute-basedprogramming.
AbouttheAuthor
TomBarnabyisaninstructorandasoftwarearchitect
atIntertech,Inc.Asaninstructor,heisinconstant
contactwithfrontlinedevelopersfromaroundthe
world.Asasoftwarearchitect,headvisescompanies
onthedesignandimplementationoftheirITsystems.
Tomhasdevelopedavarietyofapplicationsranging
fromaproprietary4GL/databasesystemtoafully
distributedERPapplication.




Distributed.NETProgramminginC#
TOMBARNABY

Copyright©2002byTomBarnaby
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
ISBN(pbk):1-59059-039-2
PrintedandboundintheUnitedStatesofAmerica12345678910
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,weuse
thenamesonlyinaneditorialfashionandtothebenefitofthetrademark
owner,withnointentionofinfringementofthetrademark.
TechnicalReviewer:GordonWilmot
EditorialDirectors:DanAppleman,PeterBlackburn,GaryCornell,
JasonGilmore,KarenWatterson,JohnZukowski
ManagingEditor:GraceWong
ProjectManager:AlexaStuart
CopyEditor:AmiKnox
ProductionEditor:KariBrooks
Compositor:SusanGlinertStevens
Artist:CaraBrunk,BlueMudProductions
Indexer:ValerieRobbins


CoverDesigner:KurtKrames
ManufacturingManager:TomDebolski
MarketingManager:StephanieRodriguez

DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNew
York,Inc.,175FifthAvenue,NewYork,NY,10010andoutsidetheUnited
StatesbySpringer-VerlagGmbH&Co.KG,Tiergartenstr.17,69112
Heidelberg,Germany.
IntheUnitedStates,phone1-800-SPRINGER,email
<>,orvisit.
OutsidetheUnitedStates,fax+496221345229,email
<>,orvisit.
Forinformationontranslations,pleasecontactApressdirectlyat2560
9thStreet,Suite219,Berkeley,CA94710.
Phone510-549-5930,fax:510-549-5939,email<>,
orvisit.
Theinformationinthisbookisdistributedonan"asis"basis,without
warranty.Althougheveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthornorApressshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.
Thesourcecodeforthisbookisavailabletoreadersat
intheDownloadssection.
TomyMomandDad,whohadnoideawhattheywerestartingwhen
theyboughtmeaTI-99/4Acomputeralmost20yearsago.Ordidthey?
AbouttheAuthor


TomBarnabyisaninstructorandsoftwarearchitectatIntertech,Inc.,a
companydedicatedtoteachingtopprogrammershowtodevelop
enterprise-levelsoftware.Asaninstructor,heisinconstantcontactwith
developersfromaroundtheworldandknowstheproblemstheymust
solveandthequestionstheyhave.Asasoftwarearchitect,headvises
companiesonthedesignandimplementationoftheirITsystems.Before

becomingateacher,Tomdevelopedavarietyofapplicationsranging
fromaproprietary4GL/DatabasesystemonUnixtoafullydistributed
ERPapplicationonWindows.Inhissparetime,Tomenjoysplayingwith
hissonMax,watchingmovies,andplayingpowerchordsonhiselectric
guitarwiththeampvolumeturnedto11.
Acknowledgments
WritingabookisbyfarthehardestthingIhaveeverdone.Yetitwould
havebeencompletelyimpossibleifIdidn'thavethehelpandsupportof
thefollowingfolks:
ThankstoeveryoneatApress.GaryCornell,fortakingachanceonme,
acompleteunknownwishingtowriteaboutahottopic.Ami"DamnYer
Good"Knox,forbeingevenmoreanalyticalthanIinregardstowriting.
GraceWongandKariBrooksforkeepingthegreatwheelsofbook
productionchurningevenifIwasburning(out).Andahugethanksto
AlexaStuart,whosomehowkeptthisprojectrunningsmoothlyinspiteof
me.FinallythankstoPeterBlackburn.
Thankstomytechnicaleditor,GordonWilmot,whonotonlyprovided
greatfeedback,butalsoatremendousamountofencouragement.


ThankstoKellyKariforproofreadingseveralchapters.Butmore
importantly,thanksforactuallylaughingatmyattemptsathumor
scatteredthroughout.
ThankstoeveryoneatIntertech.Ifeelprivilegedtoworkforacompany
filledwithsuchtalentedanddedicatedindividuals.Thankstoallmy
cohorts,SteveClose(Javaistoast),GinaAccawi(XMLisjustabig
string),andAndrew"Gunnar"Sondgeroth(seeSteveClose)forproviding
achallenging,fun,andinvigoratingworkenvironment.Specialthanksto
AndrewTroelsenforcontributinganappendix,andwhose,um,unique
brandofencouragementultimatelyleadtothisbook.Finally,thanksto

TomSalonek,founderofIntertech,forsomehowtoleratingthebizarre
anticsofusadmittedprimadonnas.
ThankstoRabi,mycat,forkeepingmyshoulderswarmwhileIworked.
Finally,andmostimportantofall,many,manythankstomywifeTammy
andsonMax.Nobodysacrificedmoreforthesakeofthisbook.Iwillbe
forevergrateful.


Foreword
COMonawire,alsoknownasDCOM,wasagreatboontothe
distributedprogrammer.UnderthemodelofDCOM,aclientwasableto
interactwithCOMobjectslocatedliterallyanywhere,withoutrequiringa
changeofcodebase.UsingtheindirectionprovidedbyAppIDs,stubs,
proxies,andchannels,ourdistributedendeavorsinvolvedlittlemorethan
theuseofdeclarativetoolssuchasdcomcnfg.exeandtheComponent
Servicessnap-in.However,allwasnotwellintheworldofDCOM(or
COMforthatmatter).AlthoughtheclickingofcheckboxesmadeCOMbasedremotingappearquitesimpleonthesurface,wesufferedthrough
numerousregistryconflicts,alifetimeofpassinginterfacepointersby
reference,andthedreadedprospectofcrossingfirewalls.
JustasADO.NEThasnothingtodowithclassicADO,the.NET
RemotingstoryhasnothingtodowithclassicDCOM.Themostobvious
caseinpointisthefactthat.NETassembliesarenotregisteredwiththe
systemregistry.Giventhis,wehavenoAppID.WithoutanAppID,we
havenoRemoteServerNamevalue,whichmeansnoreferenceto
oleaut32.dllandthusnomoreCOM-basedstubandproxies.Inshort,
everythingweknewaboutinteractingwithtypesacrossthewirehas
changeddramatically.
Under.NET,weareprovidedwithdozensofnewremotingconstructs.
NotonlydoweneedtocontendwithnumerousTLAs(three-letter
acronyms)suchasWKO,CAO,andthelike,butwearealsorequiredto

becontentwithnewspinsonexistingideas(forexample,thedistinction
between"real"versus"transparent"proxies)aswellastheroleofXML
configurationfiles.
Manyprogrammerswhoarefacedwiththetaskoflearningthestoryof
.NETdistributedprogrammingturntoMSDN.Here,theyareconfronted
withnumerouscodeexamples,partialwhitepapers,anddiagramsthat
requirea21-inchmonitortoviewintheirentirety.Thisapproachisbound
toleadtofrustrationandadisjointedknowledgebase.Whatissorely
neededisapractical,approachable,andindepthtreatmentofhowallof
thesenewtechnologiesfittogetherinthecontextofanEnterprise
application.


Tom'slatestbook(theonecurrentlyinyourgrasp)providessucha
treatment.Here,youwillfindlogicalandclearexplanationsthat(surprise,
surprise)actuallyprovideinsighttotherichnessofthe.NETRemoting
layer.NotonlydoesTompoundoutthegorydetailsofthissuiteofnew
TLAs,buthealsoroundsoutyourunderstandingbyprovidingcoverage
ofnumerousrelatedEnterprise-centrictechnologiessuchasbuilding
configuredcomponents(a.k.a.COM+),.NETmessaging,Webservices,
andinteroperabilitywithclassicCOMtypes.
Foranumberofyearsnow,TomandIhaveworkedtogetherhereat
Intertech,Inc.().Ihavewitnessed
himteachnumerouscoursesonthetopicsofclassicCOMand.NET
(includinghisExpertDistributed.NETclass).Ihavealsohadthe
pleasuretoworkwithhimonnumerousdevelopmentefforts.Icanspeak
fromtheheartwhenIsayyouareingoodhands.
Enjoy!
AndrewTroelsen
PartnerandTrainer,Intertech,Inc.

Minneapolis,MN


AbouttheTechnicalReviewer

GordonWilmotisadirectorofICEnetwareLtd.,acompanyspecializing
inInternetandnetworkmanagementandmonitoringsoftware.Hehas
heldpositionsrangingfromsoftwareengineertosystemsarchitectand
hasbeendevelopingsoftwareusingMicrosoftproductsandarchitectures
forover20years.Overthistimehehasdesignedanddevelopedmany
productsandsystemsforvariousindustriessuchasfinance,
manufacturing,andtelecommunications.Allhissparetimeiseatenupby
makingcakes(badly)forhisthree-year-oldtwins,Charlotteand
Georgina,andbeingbeatencontinuouslybyhisseven-year-oldson,
Andrew,onthePS2.Whenhegrowsuphe'dstillliketobeanastronaut.


IntroductionandAFAQ(AnticipatedFrequently
AskedQuestions)
Thesubjectofdistributedprogrammingisvast.Toimplementdistributed
applicationsproperly,youmustunderstandeverythingfromlow-level
networkingdetailstohigh-levelarchitecturalissues..NETisabrandnew
platformdeservingofseveralthousandpagesofdocumentation.Sothe
challengeIfacedwhenwritingthisbookwasthis:howdoIcombine
thesetwoimmensesubjectsintoasingle,digestiblevolume?
Myanswer:Idon't.Inotherwords,Ihadtomakeassumptionsregarding
thelevelofexperienceofthereader,whichistoughgiventhat.NETis
suchanewtechnology.Evenharder,though,Ihadtomakedifficult
decisionsaboutwhatthebookwouldandwouldnotbe.OnafewissuesI
wasresolute.Thebookwouldnotbearegurgitationofdocumentation.

Thebookwouldnotbeathousand-pageboatanchorcoveringdozensof
subjectsandnoneofthemwell.
Ratherthanlistotherthingsthisbookisnot,however,Iwanttodiscuss
whatthisbookis.Ithinkofitasaguidedtourthroughthefundamental
technologiesyouusetobuilddistributedapplicationswith.NET,suchas
.NETRemoting,Webservices,serialization,COM+,andMSMQ.These
technologiesarethetoolswedevelopersusetocraftdistributed
applications.Andtheyarecomplexenoughinthemselvestowarrantindepthexamination.Thefocus,then,isontheuseofeachtechnologyand
theroleitplaysinadistributedapplication.Thinkofitaspullingeachtool
outofthebox,examiningit,andexperimentingwithittogetasenseof
theproblemsitcansolve.Likeanycraft,distributedprogrammingisbest
learnedbydoing,butwhereverpossibleIdiscusstheprosandconsof
usingonetooloveranother.
Inanattempttosettheproperexpectations(andtoheadoffsomeangry
e-mails),I'vecompiledthefollowinglistofanticipatedquestions.


WhoIsThisBookFor?
Sinceyoupulledthisbookofftheshelf,Iassumeyouareaprogrammer
whoisinterestedinusing.NETtechnologiestobuilddistributed
applications.IalsoassumeyouhaveagroundinginC#andobjectorientedprogramming.Anunderstandingof.NETbasicsisalsovery
helpful,butChapter2coversafewofthefundamentals.Most
importantly,Iassumeyouarewillingtoinvestsometimedownloading(or
typingin)andrunningtheexamples,lookingupdetailsinMSDN,and
sometimesreadingoveraparagraphacoupletimestointernalizethe
conceptspresented.Theseassumptionshavehelpedtokeepthisbook
downtoamanageablenumberofpages.


WhatDoINeedtoRuntheExamples?

Youcandownloadalmostallthecodepresentedinthebookfromthe
ApressWebsite().Ataminimum,torunthe
codeyouwillneedthefinalreleaseversionofthe.NETFramework,
whichyoucandownloadforfreefromMicrosoft
(Manyexamplesin
thebookcanbeimplementedandtestedusingnothingmorethanthe
compilersandtoolsprovidedinthe.NETFrameworkandatexteditor
suchasNotepad.However,IassumeVisualStudio.NETisthepreferred
developmenttool,andtheonlinecodeincludesVisualStudio.NET
solutionfiles.
Forlaterchaptersyouwillneedothersoftwaretoruntheexamples,
includingCOM+,IIS,andMSMQ.Theexamplesweredevelopedusing
WindowsXPProfessional,butIbelievetheywillalsorunonWindows
2000.


WhyIsn'tThereAnyReal-WorldCode?
Actually,thisbookisburstingwithreal-worldcode.Thatis,codethat
helpsyousolveeverydayproblemsyouwillexperiencewhilebuilding
distributedapplicationsin.NET.ButIknowwhatyoumean—Ihavenot
providedapizzadeliveryservice,oracontactsservice,oraworkingecommercesite.Itismyopinionthatthesetypesofexamplesare
overrated,especiallywhentherearesomanynewfundamentalconcepts
toimpart.Toomuchtimeandtoomanytreeswouldbespentmiredinthe
detailsofane-commercesystem,ratherthandiscussing(andlearning)
thetrulyessentialconcepts.Therefore,thecodeexamplesinthisbook
areshort,sweet,andtothepoint.


HowComeYouDon'tHaveTablesListingAllthe
Options/Methods/ParametersofEach

Tool/Class/Method?
Thisisatutorialbookfirst,ahow-tobooksecond,andareferencebook
last.Thedefinitive.NETreferencehasalreadybeenwritten;itiscalled
MSDN.IseenoreasontorepeatthefineworkMicrosofthasdoneto
documenteveryoptionofeverytool,everymethodofeveryclass,every
parameterofeverymethod,andsoon.Ido,however,seetheneedfora
bookthatleadsthereaderthroughalogicalprogressionoftopicswhile
clarifyingcomplexconcepts.Ialsowantedtoproduceabookthatwas
beach-bagfriendly—thatis,abookyoucouldcarryaroundinyour
briefcase,backpack,laptopcase,orbeachbagwithoutbreakingyour
back.Hopefully,thisbookmeetsthesegoals.


WhyDoIKeepGetting"FileNotFound"
ExceptionsWhenIRuntheExampleCode?
Someexampleprojectsinthisbookarefairlycomplex,requiringseveral
customdependentassemblies.Theseassemblieshavetobeinparticular
locationsfortheprojecttorun.Youmustreadandinternalizethe
assemblybindingprocessdocumentedinChapter2.Inparticular,note
theAssemblyBindingLogViewertoolexplainedin"Viewingthe
AssemblyBindingLog,"andtheassemblybindingflowchartin"Summary
oftheBindingProcess."Thesetwosectionsprovidetheinformationyou
needtodiagnosetheproblem.


What'sUpwiththeSpinalTapQuotes?
Inmyopinion,SpinalTapisthegreatestrockandrollbandever.Butdue
topoormanagement,interferinggirlfriends,andnumerousdrummers
mysteriouslydying,thebandslowlysunkintooblivionintheearly'80s.
ThewholesadaffairisdocumentedinthemovieThisIsSpinalTap,

wherethebandmembersoffermanypearlsofwisdomthatare
surprisinglyapplicabletotheworldofsoftwaredevelopment.Iwantedto
sharetheirprofoundinsightswithallmyreaders.
So,assumingyouhaven'tplacedthisbookbackontheshelf,let'sget
started!


Chapter1:TheEvolutionofDistributed
Programming


Highlights
"It'slike,howmuchmoreblackcanthisbe?andtheanswerisnone.
Nonemoreblack."
—NigelTufnel(ThisIsSpinalTap)speakingonthestateofsoftware
development.
Today,buzzwordslikeenterpriseprogramming,distributedprogramming,
n-tier,andscalabilityarefloatedinnearlyeveryproductannouncement.
Sobeforetacklingthenuancesofdistributeddevelopmentin.NET,this
chapterattemptstode-marketizesuchtermsbyapplyingrealmeaning
andcontexttotheseubiquitouswords.Also,whilethisbookisprimarilya
nuts-and-bolts"howto"guide,itisimportanttohaveaclear
understandingofwhyyoushoulddistributeapplicationsandhowto
designadistributedapplication.Tothisend,thischapteroffersfive
principlestohelpguideyourdistributeddevelopmentin.NETorany
otherplatform.
Finally,inordertodrivehometheprinciplesofdistributedprogramming,
thischaptertakesalightheartedlookatpastdistributeddevelopment
modelsandthereasonstheywerereplacedbynewmodels.Asyouwill
see,thisgoesalongwaytowardsexplainingwhyMicrosoftcreateda

newdevelopmentplatformcalled.NETtoreplaceCOM.


OverviewofDistributedProgramming
Whatisdistributedprogramming?Now,thereisaquestionfewdareto
ask.Thetermissocommontodaythatsomemaybeembarrassedto
questionitsmeaning.Restassuredthereisnoneedtobe.Iroutinelyask
mystudentstodefineit,andrarelydoIgetthesameanswer.
Distributedprogrammingischaracterizedbyseveraldistinctphysical
componentsworkingtogetherasasinglesystem.Here,"distinctphysical
components"couldmeanmultipleCPUsor,morecommonly,multiple
computersonanetwork.Youcanapplydistributedprogrammingtoa
widevarietyofproblems,frompredictingtheweathertopurchasinga
book.Atitsheart,thepremiseofdistributedprogrammingisthis:ifone
computercancompleteataskin5seconds,thenfivecomputersworking
togetherinparallelshouldcompletethetaskin1second.
Ofcourse,itisneverquitethateasy.Theproblemisthephrase"working
togetherinparallel."Itisdifficulttogetfivecomputersonanetworkto
cooperateefficiently.Infact,theapplicationsoftwaremustbespecifically
designedforthistobeeffective.Asananalogy,considerasinglehorse
pullingacarriage.Ahorseisapowerfulanimal,but,intermsofpower-toweightratios,anantismanytimesstronger(wewilljustassumeten
timesstronger).So,ifIgatherandharnessenoughantstoequalthe
massofthehorse,Icanmovetentimestheamountofmaterialinthe
carriage.Aperfectexampleofdistributingtheworkload,right?The
calculationsarereasonable,buthopefullyyouarechucklingatthe
ludicrousvisionofmillionsofantswithtinyharnessespullingtogether.

LayeringanApplication
Asdemonstratedwiththehorse-vs.-antanalogy,distributedcomputing
raisestheissueofcoordinatingtheworkofseveralcomputers.Thereis

alsotheissueofdecomposingtheapplicationintotasksthatcanbe
distributed.Luckily,hereyoucandrawonthelessonslearnedfrom
earlierapplications.Overtheyears,ithasbecomeclearthatmost
businessapplicationsconsistofthreeprimarysetsoflogic:presentation,
business,anddatasource.


Presentationlogic.Thisisthepartoftheapplicationthatthe
endusersusetoenterorders,lookupcustomerinformation,and
viewbusinessreports.Totheuser,thisistheapplication.
Businesslogic.Thisistheheartoftheapplicationandwhere
developersspendmostoftheirtimeandeffort.Itcontainsthe
businessrulesthatdefinethewaythebusinessisrun.For
example,businessrulesspecifywhencustomersreceive
discounts,howshippingcostsarecalculated,andwhat
informationisrequiredonanorder.
Datasourcelogic.Thisiswhereorders,customerinformation,
andotherfactsaresavedforfuturereference.Luckily,database
productssuchasSQLServerandOracletakecareofmostofthe
work.Butyoustillhavetodesignthedatalayoutandthequeries
youwillusetoretrievethedata.
Thefirstdesignpointofanynontrivialbusinessapplicationshouldbeto
partitionthesesetsoflogicintodistinctlayers.Inotherwords,youshould
notmixbusinesslogiccodewiththepresentationlogiccode.Donottake
thistomean,however,thateachlayermustrunonaseparatemachine,
orinseparateprocess.Instead,codefromonelayershouldonlyinteract
withthatinanotherlayerthroughawell-definedinterface.Typically,the
layersarephysicallyimplementedwithinseparatecodelibraries(DLLs).

TheFivePrinciplesofDistributedDesign

Layeringallowsyoutochangetheimplementationofonelayer,without
affectinganotherlayer.Italsoprovidestheflexibilitytophysically
separatethelayersinthefuture.However,astheupcomingsections
show,thedecisiontoexecuteeachlayerinaseparateprocessor
machineshouldnotbemadelightly.Ifyoudodecidetodistributethe
layer,youmustdesignitspecificallyfordistribution.Confusingtheissue
evenmoreisthefactthatsomeofthesedesigntacticscontradict
classicalobject-orientedprinciples.Tohelpclarifytheissues,thissection
describesseveralprinciplesyoucanusetoeffectivelydistributean
applicationandwhyyoushouldusethem.


Principle1:DistributeSparingly
Thismayseemlikeasurprisingprincipleforabookaboutdistributed
programming.However,thisprincipleisbasedonasimple,undeniable
factofcomputing:invokingamethodonanobjectinadifferentprocess
ishundredsoftimesslowerthandoingthesameonanin-processobject.
Movetheobjecttoanothermachineonanetwork,andthemethodcall
canbeanothertentimesslower.
Sowhenshouldyoudistribute?Thetriteanswerisonlywhenyouhave
to.Butyouareprobablylookingforalittlemoredetail,solet'sconsidera
fewexamples,startingwiththedatabaselayer.Typicallyanapplication's
databaserunsonaseparate,dedicatedserver—inotherwords,itis
distributedrelativetotheotherlayers.Thereareseveralgoodreasons
forthis:
Databasesoftwareiscomplicated,expensive,andtypically
requireshighpoweredhardware.Therefore,itisn'tcosteffective
todistributemanycopiesofthedatabasesoftware.
Adatabasecancontainandrelatedatasharedbymany
applications.Thisisonlypossible,however,ifeachapplication

serverisaccessingasingledatabaseserver,ratherthantheir
ownlocalcopy.
Databasesaredesignedtorunasaseparatephysicallayer.
Theyexposetheultimate"chunky"interface:theStructured
QueryLanguage(SQL).(SeePrinciple3fordetailsonchunky
interfaces.)
Therefore,thedecisiontodistributethedatasourcelogicistypically
madethemomentyoudecidetouseadatabase.However,thedecision
todistributethepresentationlogicisalittlemorecomplex.Firstofall,
unlessalltheapplicationuserswalkuptoacommonterminal(likean
ATM),thensomeaspectofthepresentationlayermustbedistributedto
eachuser.Thequestionishowmuch.Thetrendlately,ofcourse,isto
executethebulkofthelogicontheserverandsendsimpleHTMLto
clientWebbrowsers.Thisisactuallyinkeepingwiththeprincipleto


distributesparingly.However,italsorequireseachuserinteractionto
traveltotheserversothatitcangeneratetheappropriateresponse.
BeforetheproliferationoftheWeb,itwasmorecommontoexecutethe
entirepresentationlogiconeachclientmachine(inkeepingwithPrinciple
2).Thisprovidesfasterinteractionwiththeusersinceitminimizesround
tripstotheserver,butalsorequiresuserinterfaceupdatestobe
deployedthroughouttheuserbase.Intheend,thechoiceofwhichclient
youusehaslittletodowithdistributeddesignprinciples,andeverything
todowiththedesireduserexperienceanddeploymentissues.
Sothedatalogicalmostalwaysexecutesonaseparatecomputer,and
thepresentationlayerfrequentlydoes.Thatleavesuswiththebusiness
layer,andthemostcomplexsetofissues.Sometimes,thebusinesslayer
isdeployedtoeachclient.Othertimesitiskeptontheserver.Inmany
cases,thebusinesslayeritselfisdecomposedintotwoormore

components.Thosecomponentsrelatedtouserinterfaceinteractionare
deployedtotheclient,andthoserelatedtodataaccessareretainedon
theserver.Thisholdstothenextprinciple,whichistolocalizerelated
concerns.
Asyoucansee,youhavemanydistributionoptions.When,why,and
howyoudistributeisdrivenbyavarietyoffactors—manyofwhich
compete.Sothenextfewprinciplesofferfurtherguidelines.

Principle2:LocalizeRelatedConcerns
Ifyoudecideorareforcedtodistributeallorpartofthebusiness-logic
layer,thenyoushouldensurethatthosecomponentsthatfrequently
interactarekeptclosetogether.Inotherwords,youshouldlocalize
relatedconcerns.Forexample,considerthee-commerceapplication
showninFigure1-1.ThisapplicationseparatesCustomer,Product,
andShoppingCartcomponentsontodedicatedservers,ostensiblyto
allowparallelexecution.However,thesecomponentsneedtointeract
manytimeswhileaddingaproducttotheshoppingcart.Andeach
interactionincurstheoverheadofacross-networkmethodcall.
Therefore,thiscross-networkactivitywilleasilyeclipseanyparallel
processinggains.Multiplythisbyafewthousandsusers,andyouhavea


scenariothatcandevastateperformance.Relatingthistotheearlier
horseandcarriageanalogy,thisistheequivalentofharnessingeachleg
ofthehorseratherthantheentirehorse.

Figure1-1:HowNOTto
designadistributedapplication
Sohowcanyouleveragethepowerofdistributedprogramming,namely
parallelprocessing,whilestilllocalizingrelatedconcerns?Buyanother

horse.Thatis,duplicatetheentireapplicationandrunitonanother
dedicatedserver.Youcanuseloadbalancingtorouteeachclientrequest
toaparticularserver.ThisarchitectureisshowninFigure1-2.WebbasedapplicationsoftenusethismodelbyhostingtheidenticalWebsite
onseveralWebservers,asetupsometimesreferredtoasaWebfarm.


Figure1-2:Howtodistributeanapplication


×