•
•
•
•
•
•
TableofContents
Index
Reviews
ReaderReviews
Errata
Academic
Better,Faster,LighterJava
ByJustinGehtland,BruceA.Tate
Publisher :O'Reilly
PubDate :June2004
ISBN :0596006764
Pages :250
InBetter,Faster,LighterJavaauthorsBruce
TateandJustinGehtlandarguethattheold
heavyweightarchitectures,suchasWebLogic,
JBoss,andWebSphere,areunwieldy,
complicated,andcontributetoslowand
buggyapplicationcode.Asanalternative,the
authorspresenttwo"lightweight"open
sourcearchitectures,HibernateandSpring,
thatcanhelpyoucreateenterprise
applicationsthatareeasiertomaintain,
write,anddebug,andareultimatelymuch
faster.
•
•
•
•
•
•
TableofContents
Index
Reviews
ReaderReviews
Errata
Academic
Better,Faster,LighterJava
ByJustinGehtland,BruceA.Tate
Publisher :O'Reilly
PubDate :June2004
ISBN :0596006764
Pages :250
Copyright
Preface
WhoShouldReadThisBook?
OrganizationofThisBook
ConventionsUsedinThisBook
Acknowledgments
CommentsandQuestions
Chapter1.TheInevitableBloat
Section1.1.BloatDrivers
Section1.2.Options
Section1.3.FivePrinciplesforFightingtheBloat
Section1.4.Summary
Chapter2.KeepItSimple
Section2.1.TheValueofSimplicity
Section2.2.ProcessandSimplicity
Section2.3.YourSafetyNet
Section2.4.Summary
Chapter3.DoOneThing,andDoItWell
Section3.1.UnderstandingtheProblem
Section3.2.DistillingtheProblem
Section3.3.LayeringYourArchitecture
Section3.5.Summary
Section3.4.RefactoringtoReduceCoupling
Chapter4.StriveforTransparency
Section4.1.BenefitsofTransparency
Section4.2.Who'sinControl?
Section4.3.AlternativestoTransparency
Section4.5.InjectingCode
Section4.7.AdvancedTopics
Section4.4.Reflection
Section4.6.GeneratingCode
Section4.8.Summary
Chapter5.YouAreWhatYouEat
Section5.1.GoldenHammers
Section5.2.UnderstandingtheBigPicture
Section5.3.ConsideringTechnicalRequirements
Section5.4.Summary
Chapter6.AllowforExtension
Section6.1.TheBasicsofExtension
Section6.2.ToolsforExtension
Section6.3.Plug-InModels
Section6.5.Summary
Section6.4.WhoIstheCustomer?
Chapter7.Hibernate
Section7.1.TheLie
Section7.2.WhatIsHibernate?
Section7.3.UsingYourPersistentModel
Section7.5.Summary
Section7.4.EvaluatingHibernate
Chapter8.Spring
Section8.1.WhatIsSpring?
Section8.2.PetStore:ACounter-Example
Section8.3.TheDomainModel
Section8.4.AddingPersistence
Section8.6.Summary
Section8.5.Presentation
Chapter9.SimpleSpider
Section9.1.WhatIstheSpider?
Section9.2.ExaminingtheRequirements
Section9.3.PlanningforDevelopment
Section9.5.TheConfigurationService
Section9.7.TheSearchService
Section9.9.TheWebServiceInterface
Section9.4.TheDesign
Section9.6.TheCrawler/IndexerService
Section9.8.TheConsoleInterface
Section9.10.ExtendingtheSpider
Chapter10.ExtendingjPetStore
Section10.1.ABriefLookattheExistingSearchFeature
Section10.2.ReplacingtheController
Section10.3.TheUserInterface(JSP)
Section10.5.MakingUseoftheConfigurationService
Section10.7.Summary
Section10.4.SettingUptheIndexer
Section10.6.AddingHibernate
Chapter11.WhereDoWeGofromHere?
Section11.1.Technology
Section11.2.Process
Section11.3.Challenges
Section11.4.Conclusion
Chapter12.Bibliography
Section12.1.Books
Section12.2.ReferencedInternetSources
Section12.3.HelpfulInternetSources
Section12.4.OtherReferences
Colophon
Index
Copyright©2004O'ReillyMedia,Inc.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'ReillyMediabooksmaybepurchasedforeducational,
business,orsalespromotionaluse.Onlineeditionsarealso
availableformosttitles().Formore
information,contactourcorporate/institutionalsales
department:(800)998-9938or
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
TheJavaSeries,Better,Faster,LighterJava,theimageofa
hummingbird,andrelatedtradedressaretrademarksof
O'ReillyMedia,Inc.
Java™andallJava-basedtrademarksandlogosaretrademarks
orregisteredtrademarksofSunMicrosystems,Inc.,inthe
UnitedStatesandothercountries.Manyofthedesignations
usedbymanufacturersandsellerstodistinguishtheirproducts
areclaimedastrademarks.Wherethosedesignationsappearin
thisbook,andO'ReillyMedia,Inc.wasawareofatrademark
claim,thedesignationshavebeenprintedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
Preface
In2001,IwaswithSteveDaniel,arespectedkayaker.Wewere
atBullCreekaftertorrentialrains,staringattherapidthatwe
laternamedBores.Theleftsideoftherapidhadwater,butwe
wantednopartofit.WewereheretoruntheV,aviolentsixfootdropwithundercutledgesontheright,apotentialkeeper
hydraulicontheleft,andaboilingtoweroffoamsevenfeet
highinthemiddle.Ididn'tseeacleanroute.Stevefavored
stayingrightandcrankinghardtotheleftafterthedropto
avoidtheundercutledge.Iwasleaningleft,whereI'dhavea
trickysetup,andwhereitwouldbetoughtoidentifymyline,
butIfeltthatIcouldfinditandjumpoverthehydraulicafter
makingadiceymoveatthetop.Webothdismissedthelinein
themiddle.Neitherofusthoughtwecouldkeepourboats
uprightafterrunningthedropandhittingthetower,whichwe
calledahaystackbecauseofitsshape.Neitherofuswashappy
withourintendedline,sowestoodthereandstared.
Thenafunnythinghappened.Alittleboy,maybe11yearsold,
cameoverwitha$10inflatableraft.Heshoveditintothemain
current,andwithoutpaddle,lifejacket,helmet,oranyskill
whatsoever,hejumpedrightin.Heshowedabsolutelynofear.
Thestreampredictablytookhimwheremostofthewaterwas
going,rightintothe"towerofpower."Thehorizontalforceof
thewatershothimthroughbeforethetowercouldbudgehim
aninch.Webothlaughedhysterically.Heshouldhavebeen
dead,buthemadeitusinganapproachthatmoreexperienced
kayakerswouldneverhaveconsidered.Wehadourline.
In2004,Iwentwith60kidstoMexicotobuildhousesforthe
poor.I'ddonelightconstructionofthiskindbefore,andwe'd
alwaysusedportablecementmixerstodothefoundationwork.
Thisgrouppreferredanothermethod.They'dpourallofthe
ingredientsonthegroundcement,gravel,andsand.We'dmix
upthepileswithshovels,shapeitlikeavolcano,andthenpour
waterinthemiddle.Thewaterwouldsoakin,andwe'dstirit
upsomemore,andthenshovelthefreshcementwherewe
wantedit.Theworkwasutterlyexhausting.Ilatertoldthe
projectdirectorthatheneededcementmixers;theywould
havesavedalotofbackbreakingeffort.
Heaskedmehowtomaintainthemixers.Ididn'tknow.He
askedwherehemightstorethem.Icouldn'ttellhim.Hethen
askedhowhemighttransportthemtothesites,becausemost
groupstendedtobringvansandnotpickuptrucks.Ifinallygot
thepicture.Hedidn'tusecementmixersbecausetheywerenot
therighttoolforthejobforremotesitesinMexico.Theymight
saveahalfadayofconstructioneffort,buttheyaddedjustas
muchormoreworktospareusthateffort.Thetradeoff,once
fullyunderstood,notonlyfailedonapurecostbasis,but
wouldn'tworkatallgiventheavailableresources.
In2003,IworkedwithanITdepartmenttosimplifytheir
design.TheyusedamultilayeredEJBarchitecturebecausethey
believedthatitwouldgivethembetterscalabilityandprotect
theirdatabaseintegritythroughsophisticatedtransactions.
Aftermuchdeliberation,wewentfromfivelogicaltierstotwo,
completelyremovedtheEJBsessionandentitybeans,and
deployedonTomcatratherthanWebLogicorJBoss.Thenew
architecturewassimpler,faster,andmuchmorereliable.
Itneverceasestoamazemehowoftenthesimplestanswer
turnsouttobethebestone.Ifyou'reliketheaverageJ2EE
developer,youprobablythinkyoucouldusealittledoseof
simplicityaboutnow.Javacomplexityisgrowingfarbeyondour
capabilitytocomprehend.XMLisbecomingmuchmore
sophisticated,andbeingpressedintoservicewheresimple
parsedtextwouldeasilysuffice.TheEJBarchitectureis
everywhere,whetherit'swarrantedornot.Webserviceshave
grownfromasimpleideaandthreemajorAPIstoamassof
complex,overdonestandards.Ifearthattheymayalsobe
forcedintothemainstream.Icallthistendency"thebloat."
Further,somanyofusaretrainedtolookforsolutionsthat
matchourpredeterminedcomplicatednotionsthatwedon't
recognizesimplesolutionsunlesstheyhitusintheface.Aswe
staredownintothecreekatthesimpledatabaseproblem,it
becomesablobofEJB.Theinterfacesbecomewebservices.
Thistransformationhappenstodifferentdevelopersatdifferent
times,butmostenterprisedeveloperseventuallysuccumb.The
solutionsyouseematchthetechniquesyou'velearned,evenif
they'reinappropriate;you'vebeentrainedtolookbeyondthe
simplesolutionsthatarestaringyouintheface.
Javaisinadangerousplacerightnow,becausetherealdrivers,
bigvendorslikeSun,BEA,Oracle,andIBM,areallmotivatedto
buildlayeruponlayerofsophisticatedabstractions,tokeep
raisingthebarandstayonestepaheadofthecompetition.It's
notenoughtosellaplainservletcontaineranymore.Tomcatis
alreadyfillingthatniche.ManyfearthatJBosswillfillasimilar
roleasaJ2EEapplicationserverkiller.So,thebigboysinnovate
andbuildmorecomplex,feature-richservers.That'sgoodifthe
serversalsodelivervaluethatwe,thecustomers,canleverage.
Moreandmore,though,customerscan'tkeepup.Thenewstuff
istoohard.Itforcesustoknowtoomuch.AtypicalJ2EE
developerhastounderstandrelationaldatabases,theJava
programminglanguages,EJBabstractions,JNDIforservices,
JTAfortransactions,JCAanddatasourcesforconnection
management,XMLfordatarepresentation,Strutsfor
abstractinguserinterfaceMVCdesigns,andsoon.Then,she's
gottolearnawholesetofdesignpatternstoworkaroundholes
intheJ2EEspecification.Tomakethingsworse,sheneedsto
keepaneyeonthefutureandatleastkeeptabsonemerging
technologieslikeJavaServerFacesandwebservicesthatcould
explodeatanymoment.
Totopitoff,itappearsthatweareapproachinganevent
horizonofsorts,whereprogrammersaregoingtospendmore
timewritingcodetosupporttheirchosenframeworksthanto
solvetheiractualproblems.It'sjustlikewiththecementmixers
inMexico:isitworthittosaveyourselffromspendingtime
writingdatabasetransactionsifyouhavetospend50%ofyour
timewritingcodesupportingCMP?
Developmentprocessesasweknowthemarealsogrowingout
ofcontrol.Nohumanwithatraditionalapplicationbudgetcan
concentrateondeliveringbeautifulobjectinteractiondiagrams,
classdiagrams,andsophisticatedusecasesandstillhave
enoughtimetocreateworkingcode.Wespendasmuchor
moretimeonaprojectonartifactsthatwillneveraffectthe
program'sperformance,reliability,orstability.Asrequirements
inevitablychangeduetoincreasingcompetitivepressures,
theseartifactsmustalsochange,andwefindthatratherthan
aidingus,theseartifactsturnintoaball,tiedtoarope,withthe
otherendforminganever-tighteningnoosearoundournecks.
There'sabetterway.
Afewindependentdevelopersaretryingtorethinkenterprise
development,andbuildingtoolsthataremoreappropriatefor
thejob.GavinKing,creatorofHibernate,isbuildinga
persistenceframeworkthatdoesitsjobwithaminimalAPIand
getsoutoftheway.RodJohnson,creatorofSpring,isbuilding
acontainerthat'snotinvasiveorheavyorcomplicated.They
arenotattemptingtobuildontheincreasinglyprecariousJ2EE
stack.They'rediggingthroughthemucktofindamoresolid
foundation.Inshort,I'mnottryingtostartarevolution.It's
alreadystarted.
That'sthesubjectofthisbook.IrecommendthatwereimaginewhatJ2EEcouldandshouldbe,andmovebackdown
toabasewherewecanapplyrealunderstandingandbasic
principlestobuildsimplerapplications.Ifyou'restaringatthe
rapids,lookingatsolutionsyou'vebeentaughtwillworkbutyou
stilldon'tquiteseehowtogetfrompointAtopointBwithout
realpainit'stimetorethinkwhatyou'redoing.It'stimetoget
beyondtheorthodoxapproachestosoftwaredevelopmentand
focusonmakingcomplextaskssimple.Ifyouembracethe
fundamentalphilosophiesinthisbook,you'llspendmoretime
onwhat'simportant.You'llbuildsimplersolutions.Whenyou're
done,you'llfindthatyourJavaisbetter,faster,andlighter.
WhoShouldReadThisBook?
Thisbookisn'tforuber-programmerswhoalreadyhaveallthe
answers.IfyouthinkthatJ2EEdoeseverythingthatyouneedit
todoandyoucanmakeitsing,thisbookisnotforyou.Believe
me,therearealreadyenoughbooksoutthereforyou.
Ifyou'vealreadycrackedthecodeforsimplicityandflexibility,
I'mprobablynotgoingtoteachyoutoomuchthat'snew.The
frameworksIholdupasexampleshavebeenaroundfor
yearsalthoughincredibly,peopleareonlynowstartingtowrite
aboutthem.ThetechniquesIshowwillprobablyseemlike
commonsensetoyou.I'lltakeyourmoney,butyou'llprobably
beleftwantingwhenyou'redone.
Thisbookisforthefrustratedmasses.It'sintendedforthose
intermediate-to-advanceddeveloperswithsomerealexperience
withJavawhoarelookingforanswerstothespiraling
complexity.I'llintroduceyoutosomeideaswithpowerand
bite.Iknowthatyouwon'treadaphonebook.Youhaven'tgot
time,soI'llkeepitshort.I'lltrytoshowyoutechniqueswith
realexamplesthatwillhelpyoudothingsbetterthanyoudid
before.
OrganizationofThisBook
Thisbookconsistsof11chaptersandaBibliography:
Chapter1,TheInevitableBloat
ThischapterhighlightstheproblemsinherentinthelargescaleenterpriseJavaframeworksthatmostprogrammers
workwithtoday.Iwillcovernotonlywhat'swrongwith
thesebloatedframeworks,buthowtheygotthatway.
Finally,Iwilllayoutthecoreprincipleswe'llcoverinthe
restofthebook.
Chapter2,KeepItSimple
Manyprogrammersfallintothesametrap,believingthat
themorecomplicatedtheircode,thebetteritmustbe.In
fact,simplicityisthehallmarkofawell-writtenapplication.
Thischapterdefinestheprincipleofsimplicity,while
drawingadistinctionbetweensimpleandsimplistic.Iwill
alsoexaminethetoolsandprocessesthathelpyouachieve
simplicity,likeJUnit,Ant,andAgiledevelopment.
Chapter3,DoOneThing,andDoItWell
Programmersneedtoresisttheurgetosolvehuge
problemsallatonce.Codethattriestodotoomuchisoften
tooentangledtobereadable,muchlessmaintainable.This
chaptertracesthepathfrombeingpresentedwitha
problem,totrulyunderstandingtheproblemandits
requirements,tofinallysolvingtheproblemthrough
multiple,simple,andtargetedlayers.Itfinallydescribes
howtodesignyourlayerstoavoidunnecessarycoupling.
Chapter4,StriveforTransparency
Theprogrammingcommunityhastriedforyearstosolve
theproblemofcross-cuttingconcerns.Genericservices,like
loggingordatabasepersistence,arenecessaryformost
applicationsbuthavelittletodowiththeactualproblem
domain.Thischapterexaminesthemethodsforproviding
thesekindsofserviceswithoutunnecessarilyaffectingthe
codethatsolvesyourbusinessproblemthatis,howtosolve
themtransparently.Thetwomainmethodsweexamineare
reflectionandcodegeneration.
Chapter5,YouAreWhatYouEat
Everychoiceoftechnologyorvendoryoumakeisan
embodimentofrisk.WhenyouchoosetouseJava,orlog4j,
orJBoss,orStruts,youarehitchingyourselftotheir
wagon.Thischapterexaminessomeofthereasonswe
choosecertaintechnologiesforourprojects,some
traditionalchoicesthatthemarketplacehasmade(andwhy
theymayhavebeenpoorchoices),andsomestrategiesfor
makingtherightdecisionsforyourproject.
Chapter6,AllowforExtension
Yousimplycannotknoweveryusetowhichyour
applicationwillbeputwhenyouwriteit.Anyapplication
thatisworththeeffortputintoitwillhavealifeoutsidethe
imaginationofitsauthors.Yourapplicationneedstoallow
forextensionafteritsreleasetotheworld.Thischapter
examinesthetechniquesforprovidingextensionpoints,
frominterfacesandinheritancetoconfigurationandthe
plug-inmodel.
Chapter7,Hibernate
Hibernateisanopensourcepersistenceframeworkthat
providestransparentobject-to-relationalmapping.Itisa
straightforwardandsimpleimplementationthatfocuseson
thejobofpersistingyourdomainobjectssothattheycanin
turnfocusonsolvingthebusinessproblemsathand.
Chapter8,Spring
Springisanopensourceapplicationserviceprovider
frameworkonwhichtodeployenterpriseapplications.It
hasasimple,lightweightcontainerforyourobjects,and
providesaccesstoavarietyofcoreJ2EEservices.However,
itdoessowithoutalltheheavyrequirementsofstandard
J2EEframeworks,andwithnointrusionintothedesignof
yourdomainobjects.
Chapter9,SimpleSpider
Buildingontheprinciplesthisbookespouses,thischapter
examinestheconstructionofasampleapplication,the
SimpleSpider.Thisapplicationprovidesindexingandsearch
capabilitiesforawebsitebycrawlingitspages,indexing
themwithLucene,andprovidingmultipleinterfacesfor
searchingtheresults.
Chapter10,ExtendingjPetStore
HavingbuilttheSimpleSpider,wenowexaminehoweasyit
istoextendanapplication(thejPetstoresamplefrom
Chapter8)ifyoufollowtheprinciplesinthisbook.We
replacetheexistingjPetstoresearchfeaturewiththeSimple
Spider,thenreplacethepersistencelayerwithHibernate.
Chapter11,WhereDoWeGofromHere?
Finally,thischapterlooksaheadtowhatiscomingonthe
horizon,newtrendsandtechnologiesthatarehereorjust
aroundthecorner,andhowtheideasinthisbookarepart
ofachanginglandscapeinenterpriseJavadevelopment.
Bibliography
Containsalistingofresourcesandreferences.
ConventionsUsedinThisBook
Thisbookisbytwoauthors,butwithonevoice.Thestories
comefromthereal-lifeexperiencesofBruceandJustin.In
everywherebutthisparagraph,we'vecombinedourvoices,so
thatwedon'tconfuseyou.Don'tworry.Webothagreeabout
everythingthatyouseehere.
Thefollowingtypographicalconventionsareusedinthisbook:
Italic
Usedforfilenames,directories,emphasis,andfirstuseofa
technicalterm.
Constantwidth
Usedincodeexamplesandforclassnames,method
names,andobjects.
Constantwidthitalic
Indicatesanitemthatshouldbereplacedwithanactual
valueinyourprogram.
Constantwidthbold
Usedforuserinputintextandinexamplesshowingboth
inputandoutput.Alsousedforemphasisincode,andin
ordertoindicateablockoftextincludedinanannotated
call-out.
CommentsandQuestions
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(international/local)
(707)829-0104(fax)
Thereisawebpageforthisbook,whichlistserrata,examples,
oranyadditionalinformation.Youcanaccessthispageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:
Forinformationaboutbooks,conferences,ResourceCenters,
andtheO'ReillyNetwork,seetheO'Reillywebsiteat:
Acknowledgments
ThisbookhasbeenarealpleasuretowriteandIhopethat
translatestosomethingthat'sajoyforyoutoread.Thenames
onthecoverarenecessarilyonlyasmallpartofthetotalteam
effortthatittooktoproducethisbook.Itwouldbeimpossible
tothankeverypersonthatcontributed,butIfeeltheobligation
totry.
BothBruceandJustinwouldliketothankMichaelLoukidesfor
hisgentleencouragement,experttouch,andsteadyhand.At
times,itmayhaveseemedlikethisbookwouldwriteitself,but
don'tunderestimateyourimpactonit.Thanksforgivingusthe
freedomtodosomethingunique,andthegentleguidanceand
leadershipwhenthebookrequiredit.Wealsogreatly
appreciateouroutstandingtechnicalreviewers,includingStuart
Holloway,AndyHunt,DaveThomas,andGlennVanderburg.We
respecteachofyoudeeply.It'strulyanhonortohavesucha
combinedbrain-trustreviewourbook.SpecialthanksgotoRod
Johnsonforhisquickresponseandthoroughattentionwhile
editingtheSpringchapter.I'mastoundedbywhathe's
accomplished.
Manyheartfeltthanksalsogototheproductionandmarketing
teamsatO'Reilly,includingDavidChufordoingwhateverit
takestospeedtheprojectalong,RobertRomanoforhiswork
onthegraphics,DanielH.Steinbergforkeepingusinfrontof
hiscommunity,ColleenGormanforherexperienced,delicate
editing,andKyleHartforhertirelesspromotion.
Thisbookisaboutlighter,fastertechnologiesanditrelies
heavilyontheopinionsandworkofsomepioneers.Thanksto
thefolksatIntelliJ,foruseofafantasticIDE.Weuseditto
createmanyoftheexamplesinthisbook.ThankstoTed
Neward,forhishelpinunderstandingJSR175,andforhis
uniqueperspective.Ted,youscareme,onlyinagoodway
(sometimes).ForhisworkonSpring,wethankagainRod
Johnson.Thanksalsotothosewhocontributedtotheopen
sourceJPetstoreexamples,includingClintonBeganforhis
originalJPetstore,whichformedthefoundationforSpring's
version,andJuergenHoeller'sworktoportthatexampleto
Spring.GavinKingandcrewwethankforafantastic
persistenceframework.Yourremarkableaccomplishmentsare
rewritingJavahistoryintheareaoftransparentpersistence.We
alsowouldliketothankDougCuttingandtheentireLucene
maintenanceteamfortheirworkonthatexcellentproduct.
DaveThomasandMikeClarkareJavaleadersintheareasof
test-drivendevelopmentanddecoupleddesigns.Thankstoboth
forprovidingcredibleexamplesforthisbook.
BruceA.Tate
IwouldliketopersonallythankJayZimmermanforgivingmea
soapboxforthiscriticalmessage.Asamentor,you'vetaught
mehowtorunasmallbusiness,you'vetrustedmewithyour
customers,andyou'vebeenajovialfriendontheroad.Thanks
gotoMaciejforhelpingtogettheballrollingandforhelp
outliningthisbook.ThanksalsogotoMikeClarkforyourideas
onunittesting,andyourfriendship.Mostimportantly,Ithank
myfamily.YouareallthereasonthatIwrite.ThankstoKayla
andJuliaforyoursmiles,kisses,andhugswhenIamdown;to
mygreatestloveMaggie,foryourinspirationand
understanding;andmostofallConnie,for32yearsofloving
thosewhohavebeentheclosesttome.Connie,thisbookisfor
you.
JustinGehtland
IwouldliketopersonallythankStuartHallowayforbeing
preternaturallybusyallthetime.I'dalsoliketosaythanksto
TedNeward,KevinJones,andErikHatcherforforminga
gravitationalwellpullingmetowardsJava.Mostly,I'dliketo
thankmywifeLisaanddaughterZoe,whoprovetome
constantlythatworkisn'teverything.Someday,perhaps,I'll
writeabookyou'dbothliketoread.
Chapter1.TheInevitableBloat
Javadevelopmentisincrisis.ThoughJava'smarketsharehas
beensteadilygrowing,allisnotwell.I'veseenenterpriseJava
developmenteffortsfailwithincreasingregularity.Evenmore
alarmingisthatfewerandfewerpeoplearesurprisedwhen
thingsdogowrong.Developmentisgettingsocumbersome
andcomplexthatit'sthreateningtocollapseunderitsown
weight.Typicalapplicationsusetoomanydesignpatterns,too
muchXML,andtoomanyEnterpriseJavaBeans.Andtoomany
beansleadstowhatI'llcallthebloat.
1.1BloatDrivers
I'llillustratethebloatbycomparingitwiththefamousLewis
andClarkexpedition.Theystartedwithahuge,heavilyloaded
55-footkeelboat.Keelboatswerewelldesignedfortraversing
massiveriversliketheMissouriandtheMississippi,butquickly
boggeddownwhentheexpeditionneededtonavigateand
portagethetighter,trickierriversoutWest.LewisandClark
adaptedtheirstrategy;theymovedfromthekeelboatsto
canoes,andeventuallytohorseback.Tothrive,weallmustdo
thesame.Javahasnotalwaysbeenhard,anditdoesn'thave
tobetoday.Youmustonceagaindiscoverthelighter,nimbler
vesselsthatcangetyouwhereyouneedtogo.Ifthemassive,
unwieldyframeworkshinderyou,thendon'tbeafraidtobeach
them.Tousetherightboat,you'vegottoquitdrivingthebloat.
Overtime,mostsuccessfulframeworks,languages,and
librarieseventuallysuccumbtobloat.Expansiondoesnot
happenrandomlypowerfulforcescompelevolution.Youdon't
havetoacceptmypremiseblindly.I'vegotplentyofanecdotal
evidence.Inthischapter,I'llshowyoumanyexamplesofthe
bloatinapplications,languages,libraries,frameworks,
middleware,andevenintheoperatingsystemitself.
1.1.1EnterpriseMega-Frameworks
Javadeveloperslivewithapainfulreality:hugeenterprise
frameworksareenvogue.Thatmightbegoodnewstoyouif
you'reamongthe10%ofJavadeveloperswhoareworkingon
thehardestproblems,andyourapplicationshappentofitthose
enterpriseframeworksperfectly.Therestofusarestuckwith
excruciatingcomplexityforlittleornobenefit.SuccessfulJ2EE
vendorslistentothemarket:
Vendorscanchargemega-dollarsformega-frameworks.
Sellingsoftwaremeanspresentingtheillusionofvalue.Big
companieshavedeeppockets,sovendorsbuildproducts
thattheycanselltothebigboys.
It'shardtocompetewithothermega-frameworksifyou
don'tsupportthesamefeatures.Faceit.Softwarebuyers
respondtomarketingtallysheetslikePavlov'sdogs
respondedtothedinnerbell.
Collaborationcanincreasebloat.Wheneveryougetmultiple
agendasdrivingasoftwarevision,yougetsoftwarethat
supportsmultipleagendas,oftenwithunintended
consequences.That'swhywehavetwodramatically
differenttypesofEJB.Theprocesssatisfiedtwo
dramaticallydifferentagendas.
Youcanalmostwatcheachnewenterpriseframeworksuccumb
tothebloat,likechickensbeingfattenedformarket.Initsfirst
incarnation,XMLwasslightlytedious,butitprovided
tremendouspower.Intruth,XMLinitsfirstiterationdidalmost
everythingthatmostdevelopersneededitto.Withthe
additionsofXMLSchemaandtheincreaseduseofnamespaces,
XMLisdramaticallymorecumbersomethaneverbefore.True,
Schemaandnamespacesmakeiteasiertomanageandmerge
massivetypes.Unfortunately,once-simplewebservicesare
takingasimilarpath.
Butnoneofthoseframeworksapproachthereputationthat
EnterpriseJavaBeans(EJB)hasachievedforbloat.EJB
container-managedpersistence(CMP)istheposterchildfor
tightcoupling,obscuredevelopmentmodels,integrated
concerns,andsheerweightthatareallcharacteristicofthe
bloat(Figure1-1).