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

2006 aw applying domain driven design and patterns wit

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 (4.59 MB, 923 trang )

ApplyingDomain-DrivenDesignandPatterns:With
ExamplesinC#and.NET,1/e
ByJimmyNilsson
...............................................
Publisher:AddisonWesleyProfessional
PubDate:May08,2006
PrintISBN-10:0-321-26820-2
PrintISBN-13:978-0-321-26820-4
Pages:576

TableofContents|Index

"[This]isabookaboutdesigninthe.NETworld,driveninanagilemannerandinfused
withtheproductsoftheenterprisepatternscommunity.[It]showsyouhowtobegin
applyingsuchthingsasTDD,objectrelationalmapping,andDDDto.NET
projects...techniquesthatmanydevelopersthinkarethekeytofuturesoftware
development....Asthetechnologygetsmorecapableandsophisticated,itbecomesmore
importanttounderstandhowtouseitwell.Thisbookisavaluablesteptowardadvancing
thatunderstanding."
MartinFowler,authorofRefactoringandPatternsofEnterpriseApplicationArchitecture

Patterns,Domain-DrivenDesign(DDD),andTest-DrivenDevelopment(TDD)enable
architectsanddeveloperstocreatesystemsthatarepowerful,robust,andmaintainable.
Now,there'sacomprehensive,practicalguidetoleveragingallthesetechniquesprimarily
inMicrosoft.NETenvironments,butthediscussionsarejustasusefulforJavadevelopers.
DrawingonseminalworkbyMartinFowler(PatternsofEnterpriseApplicationArchitecture)
andEricEvans(Domain-DrivenDesign),JimmyNilssonshowshowtocreatereal-world
architecturesforany.NETapplication.Nilssonilluminateseachprinciplewithclear,wellannotatedcodeexamplesbasedonC#1.1and2.0.Hisexamplesanddiscussionswillbe
valuablebothtoC#developersandthoseworkingwithother.NETlanguagesandany
databasesevenwithotherplatforms,suchasJ2EE.Coverageincludes
·Quickprimersonpatterns,TDD,andrefactoring


·Usingarchitecturaltechniquestoimprovesoftwarequality
·Usingdomainmodelstosupportbusinessrulesandvalidation
·ApplyingenterprisepatternstoprovidepersistencesupportviaNHibernate
·PlanningeffectivelyforthepresentationlayerandUItesting


·DesigningforDependencyInjection,AspectOrientation,andothernewparadigms


ApplyingDomain-DrivenDesignandPatterns:With
ExamplesinC#and.NET,1/e
ByJimmyNilsson
...............................................
Publisher:AddisonWesleyProfessional
PubDate:May08,2006
PrintISBN-10:0-321-26820-2
PrintISBN-13:978-0-321-26820-4
Pages:576

TableofContents|Index










































Copyright
PraiseforApplyingDomain-DrivenDesignandPatterns
AbouttheAuthor
Forewords
Preface:BridgingGaps
Acknowledgments
PartI:Background
Chapter1.ValuestoValue:OrEmbarrassingRamblingsWhenSelf-Reflecting
ontheLastFewYears
OverallValues
ArchitectureStylestoValue
ProcessIngredientstoValue
ContinuousIntegration
Don'tForgetAboutOperations
Summary
Chapter2.AHeadStartonPatterns
ALittleBitAboutPatterns
DesignPatterns
ArchitecturalPatterns
DesignPatternsforSpecificTypesofApplications
DomainPatterns
Summary
Chapter3.TDDandRefactoring



















































































Test-DrivenDevelopment(TDD)
MocksandStubs
Refactoring
Summary
PartII:ApplyingDDD
Chapter4.ANewDefaultArchitecture
TheBasisoftheNewDefaultArchitecture
AFirstSketch
MakingaFirstAttemptatHookingtheUItotheDomainModel
YetAnotherDimension
Summary
Chapter5.MovingFurtherwithDomain-DrivenDesign
RefiningtheDomainModelThroughSimpleTDDExperimentation
FluentInterface
Summary
Chapter6.PreparingforInfrastructure
POCOasaLifestyle

DealingwithSaveScenarios
Let'sBuildtheFakeMechanism
DatabaseTesting
Querying
Summary
Chapter7.LettheRulesRule
CategorizationofRules
PrinciplesforRulesandTheirUsage
StartingtoCreateanAPI
RequirementsforaBasicRulesAPIRelatedtoPersistence
FocusonDomain-RelatedRules
ExtendingtheAPI
RefiningtheImplementation
BindingtothePersistenceAbstraction
GenericsandAnonymousMethodstotheRescue
WhatOthersHaveDone
Summary
PartIII:ApplyingPoEaa
Chapter8.InfrastructureforPersistence
RequirementsonthePersistenceInfrastructure
WheretoStoreData
Approach



















































































Classification
AnotherClassification:InfrastructurePatterns
Summary
Chapter9.PuttingNHibernateintoAction
WhyNHibernate?
AShortIntroductiontoNHibernate
RequirementsofthePersistenceInfrastructure
Classification
AnotherClassification:InfrastructurePatterns
NHibernateandDDD
Summary
PartIV:What'sNext?
Chapter10.DesignTechniquestoEmbrace
ContextIsKing
AnIntroductiontoSOA
InversionofControlandDependencyInjection
Aspect-OrientedProgramming(AOP)
Summary

Chapter11.FocusontheUI
APrepilogue
TheModel-View-ControllerPattern
Test-DrivingaWebForm
MappingandWrapping
Summary
Epilogue
PartV:Appendices
AppendixA.OtherDomainModelStyles
Object-OrientedDataModel,SmartServiceLayer,andDocuments
TheDatabaseModelIstheDomainModel
PragmatismandtheNontraditionalApproach
Summary
AppendixB.CatalogofDiscussedPatterns
AbstractFactory[GoFDesignPatterns]
Aggregate[EvansDDD]
BoundedContext[EvansDDD]
ChainofResponsibility[GoFDesignPatterns]
ClassTableInheritance[FowlerPoEAA]
Coarse-GrainedLock[FowlerPoEAA]
CollectingParameterPattern[BeckSBPP]




ConcreteTableInheritance[FowlerPoEAA]










































DataMapper[FowlerPoEAA]
DataTransferObjects[FowlerPoEAA]
Decorator[GoFDesignPatterns]
DependencyInjection
DomainModel[FowlerPoEAA]
EmbeddedValue[FowlerPoEAA]
Entity[EvansDDD]
Factory[EvansDDD]
FactoryMethod[GoFDesignPatterns]
ForeignKeyMapping[FowlerPoEAA]
GenerationGap[VlissidesPatternHatching]
IdentityField[FowlerPoEAA]
IdentityMap[FowlerPoEAA]
ImplicitLock[FowlerPoEAA]
LayerSupertype[FowlerPoEAA]
Layers[POSA]
LazyLoad[FowlerPoEAA]
MetadataMapping[FowlerPoEAA]
ModelViewController[FowlerPoEAA]
ModelViewPresenter[FowlerPoEAA2]
Notification[FowlerPoEAA2]
NullObject[WoolfNullObject]
OptimisticOfflineLock[FowlerPoEAA]
PartyArchetype[Arlow/NeustadtArchetypePatterns]

PessimisticOfflineLock[FowlerPoEAA]
PipesandFilters[POSA]
PresentationModel[FowlerPoEAA2]
Proxy[GoFDesignPatterns]
QueryObject[FowlerPoEAA]
Recordset[FowlerPoEAA]
Reflection[POSA]
Registry[FowlerPoEAA]
RemoteFaçade[FowlerPoEAA]
Repository[EvansDDD]
SeparatedPresentation[FowlerPoEAA2]
ServiceLayer[FowlerPoEAA]
ServiceLocator[Alur/Crupi/MalksCoreJ2EEPatterns]
Services[EvansDDD]

































































SingleTableInheritance[FowlerPoEAA]
Singleton[GoFDesignPatterns]
Specification[EvansDDD]
State[GoFDesignPatterns]
TableModule[FowlerPoEAA]
TemplateMethod[GoFDesignPatterns]
TransactionScript[FowlerPoEAA]
UnitofWork[FowlerPoEAA]
ValueObject[EvansDDD]
References


Index



Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsidetheUnitedStatespleasecontact:
InternationalSales

VisitusontheWeb:www.awprofessional.com


LibraryofCongressCataloging-in-PublicationData


Nilsson,Jimmy.
ApplyingdomaindrivendesignandpatternswithexamplesinC#and.NET/JimmyNilsson.
p.cm.
Includesbibliographicalreferences.
ISBN0-321-26820-2
1.Computersoftware-Development.2.C#(Computerprogramlanguage)3.Microsoft.NET.I.
QA76.76.D47N6452006
005.1--dc22
2006004371
Copyright©2006PearsonEducation,Inc.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
75ArlingtonStreet,Suite300
Boston,MA02116
Fax:(617)848-7047
TextprintedintheUnitedStatesonrecycledpaperatR.R.
DonnelleyinCrawfordsville,Indiana.
Firstprinting,May2006


Dedication
ToLotta,Tim,andLeo:thecentersofmyuniverse.



PraiseforApplyingDomain-Driven
DesignandPatterns
"Idon'tknowwhatitwasIprofessedtodoingbeforeI
hadaddedDomain-DrivenDesignandTest-Driven
Developmenttomytoolkit,butfrommypresent
perspective,I'mreticenttocallitanythingbutchaotic
hacking.Domain-DrivenDesignandTest-Driven
Developmentaretwoapproachesthathaveconsistently
guidedmetowardapracticalapplicationofsoftware
designprinciples,andbroughtmyprojectstofruitionwith
healthy,sustainablesoftware.Thisisabookthatputsits
moneywhereitsmouthisintermsofconcretely
communicatingAgilesoftwaredevelopmentpractice.It's
potentiallyoneofthemostimpactfulguidestosoftware
developmentsuccesspracticesyetofferedtothe.NET
softwaredevelopmentcommunity."
ScottBellware,MicrosoftMVPforC#,DDDandTDD
Blogger
"JimmyNilssondoeshisreadersagreatserviceby
showingthemhowtoapplythefoundationalprinciplesof
enterpriseapplicationdesignanddevelopmenttaughtby
Evans,Fowler,andotherthoughtleaders.Thebookuses
aworkedexamplenotonlytoexplain,butalsoto
demonstrateDomain-DrivenDesign,Patternsof
EnterpriseApplicationArchitecture,andTest-Driven
Development.Jimmy'sinsightandexperiencemake
readingitapleasure,andleavethereaderwiththe
certaintythattheyhavelearnedfromamaster

practitioner.Enterprisedeveloperslookingtomasterthese
principleswillfindthebookavaluableguide."
JackGreenfield,EnterpriseToolsarchitect,VisualStudio


TeamSystem,Microsoft
"Goodsoftwarearchitectsreservetherighttoget
smarter.Beyondthegoalofshippingtheircurrentsystem,
they'reonaquesttodiscoverbetterwaystodesignand
buildsoftware.Thisbookistravelogueofsortsinwhich
Jimmydocumentshisjourneythroughawiderangeof
patterns,practices,andtechnologies,explaininghowhis
thinkingaboutenterprisesystemshasevolvedalongthe
way.Ifyou'retravelingthesameroad,thisbookisagood
companion."
TimEwald,principalarchitectatFoliageSoftwareSystems
andauthorofTransactionalCOM+:BuildingScalable
Applications
"Thisbookdoesanexcellentjobatmakingtangiblethe
largebutveryimportantideasofDomain-DrivenDesign."
FloydMarinescu,authorofEJBDesignPatternsand
creatorofInfoQ.comandTheServerSide.com
"Understandingtheconceptsanddrivingforcesinthe
problemdomainisparamounttothesuccessofsoftware
development.JimmyNilssonhasdrawninspirationfrom
thepasttenyearsofstudiesintopatternsandDomainDrivenDesignaswellasrecordedhisownexperiences
fromconcretedevelopmentprojects.Thisbookcontains
compellingexamplesofhowtheorycanbetranslatedinto
practice.Itdemonstratestheauthor'sprofound
understandingofdesignchoicesandtrade-offsinvolvedin

object-orienteddevelopment."
AndersHessellund,ITUniversityofCopenhagen,Denmark
"Thisbooktacklesanareathatisachallengeformost
developersonthe.NETplatform.Asthepatternsand


practicesarchitectwhoinitiatedanddrovetheefforts
aroundenterpriseguidancefor.NET,Iknowhow
importantthisareaisforourcustomers,andampainfully
awareofthegapsthatstillexistinourguidance.
"IwasthrilledtoseeJimmywouldbesharinghisinsights
basedonhisexperiencedoingDDDandTDD.Ibelieve
thistopiccanbebesttackledatthispointintimethrough
afocusonsimplicity,patterns,andawarenessofthe
socialaspectsofbuildingapplications.
"ItrustJimmy'sexperienceandknowledgeof.NET,and
haveenjoyedhisstyleofsharingconceptsandstories.I
canhardlyimaginesomeonebettersuitedtoexplainthis
topicontheplatformIworkoneveryday.
"IwilldefinitivelyrecommendJimmy'sbooktomy
customers,myteam,andotherMicrosoftengineers.
"Ultimately,Ihopethatourindustrycangetbetterat
expressingrichconceptsincode,andthatitgetsbetterat
thesocialprocessofarticulatingandevolvingshared
knowledge.TDDandDDDlietogetherattheheartofthis
path."
EdwardJezierski,architectofMicrosoftpatternsand
practices
"Jimmyhaswoventogetherbest-of-bread
techniquesDomain-DrivenDesign,Test-Driven

Development,refactoring,anddesignpatternsintoa
convincingalternativetotheData-DrivenDevelopment
stylethathasbeenthemainstayofMicrosoftapplications.
Thecoreofthebookbreatheslifeintothetechniques
advocatedinDomain-DrivenDesign;itisrelentlessly
practical,givesthereaderinsightintothethoughtprocess
thatunderliesapplyingproventechniquesand
technologies,and,likeallofJimmy'swork,isaneasyread


welldoneJimmy!"
ChristianCrowhurst,analystdeveloper
"I'vebeenworkingonajointprojectwithJimmyfor18
monthsnow.Jimmyreallylivesashepreaches.Inthis
bookhetellsyouhowheisworkinginpractice.Heuses
O/RMappingandNHibernatedailyandhealsoreallyuses
TDDtohelpunderstandanddistillthecustomer'sbusiness
logicandtomakesurethatheonlydeliverstested,highqualitycode.Justashedeliversahigh-qualitybook
containingtestedconceptstoyou.Enjoy."
DanByström,softwaredeveloper,www.visualdesign.se/blog
"ByshowinghowtoapplyDomain-DrivenDesignand
enterpriseapplicationpatterns,Jimmymakesadifficult
topicapproachableforalargeraudience.Thisbookhas
somethingfortheexperiencedarchitectandaspiring
patternimplementeralike.Infact,anydeveloperor
architectwhowantstoimprovethewayhe/shedesigns
andimplementssoftwaresolutionsshouldreadthisbook."
Per-OlaNilsson,headofdevelopmentandsoftware
architectforLuvit
"Constantlyabreastwiththelatesttrendsinsoftware

developmentbutneversweptawaybythehype,Jimmy
expertlyextractsthevalueandleavesthefluffbehind.
Alwayshumbleandwithbothhisearswideopen,heis
uniquelywellsuitedtoguideandenlightenthereader
usingthepracticalapplicabilityasthestandard,shunning
theivorytower.Jimmydoesn'tofferhishelpfromabove
heactuallymanagestoconvinceusthatwehavejust
learnedaboutthecuttingedgefromapeer."


MatsHelander,softwaredeveloper,
www.matshelander.com
"AswithJimmy'spreviousbook,thisbookisatrue
masterpiece:awell-laidoutbalancebetweenpragmatic
softwareengineeringanddeeptheory."
FransBouma,creatorofLLBLGenPro,
weblogs.asp.net/fbouma
"Withthisbookbeingbasedonsolidground,Jimmy
tacklestherealissuesinapplyingDomain-DrivenDesign
practices.Finallywehaveamanualtokeepusfrom
hittingthewallincopingwithever-increasingcomplexity
intomorrow'sdomainmodel-basedenterprise
applications."
PaulGielens,seniorconsultantforCapgemini,
weblogs.asp.net/pgielens
"Speakingfromexperience,combiningthesubstance
behindacronymssuchasDDD,DP,andTDDin.NETcan
leadtoveryefficientandadaptiveenterprisesoftware
architectures.Thisbookoutlineshow,andwhy,these
conceptstogethermakesuchapowerfulwhole.Hence,

thereaderisgivenaninvaluableshortcuttosuccessful
enterprisesoftwarearchitectures,makingitamustread
foranydeveloperofsuch."
MartinRosén-Lidholm,softwarearchitectforExense
Healthcare
"Doyouwanttobuildahigh-qualityenterprisesystem
withobjectorientationandarelationaldatabase?Don't
missthisone.JimmyshowsyouhowTest-Driven
Developmentcanbethedrivingforcethroughoutthe
wholeproject.HeshowshowtomaptheOOdesigntothe


database,astepoftentreatedverybrieflyinliterature,
whichalonemakesthebookworththemoney.Thereare
alsoplentyofdesigntipsanddiscussionssoyoucan
followhisreasoning."
IngemarLundberg,passionatesoftwaredeveloper,
www.ingolundberg.com
"Thisimportantandtimelybookisamustreadforanyone
wantingtogetintoDomain-DrivenDesigninC#."
GregoryYoung,MicrosoftMVPforC#,independent
consultant
"Thisbookdealswithseveralimportantconceptsusedin
modernsoftwaredevelopment,suchasTest-Driven
Development,refactoring,patterns,andofcourse,
Domain-DrivenDesign.JimmyNilssonwritesaboutthese
thingsinaveryconversationaltone,andyoualmostget
thefeelingthatheisactuallysittingnexttoyou,showing
youhisexamplesandhavingaconversationaboutthe
prosandconsofdifferentsolutionswithyoupersonally."

NiclasNilsson,softwaredeveloperandeducatorfor
Activa;notabrothertoJimmy,notevenrelated
"ThisbookdoesanexcellentjobofbringingDomainDrivenDesign(DDD)intopracticalcontextbybridgingthe
gapsbetweendifferentabstractionlevelsstartingfromthe
businessperspectivedowntothesystemlevel.Thebook
isidealforsoftwarearchitectsanddevelopersbecauseit
iswritteninawaythatallowsittobeusedasaprimeror
reference.Theauthorexcelsinpresentingallaspectsof
DDDinawaythatisnotonlyeducationalbutalsofunto
read."
GuntherLenz,programmanagerandauthor


"Notsoverylongago,Ibloggedaboutmyoverallfeeling
thatasarchitectswemaybefailingtoprovideenough
guidancefordeveloperstosortthroughthehundredsof
differentwaystobuildsoftware.Therearemanyideasout
therethatareexcellentbythemselvesandcomewith
perfectlywell-reasonedjustifications,workingexamples,
andanimpassionedcommunityofbelievers.Veryfewof
themcanbeusedbythemselvestobuildapplications,
muchlesssystemsofapplicationsandservices.This
leavesituptodeveloperstofindwaystoputthe
individualideastogetherintoapplications.Thisisalways
muchharderinrealitythantheproponentsofany
particularapproach,liketothinkabout.Developers,on
theotherhand,needtogetsomeworkdoneandoften
don'tcaretowadethroughallthiseverytimetheystarta
newapplication.Thisistrueevenwhentheyaretruly
interestedinthepotentialgainsofnewapproachesor

ideas.Jimmy'sbookispointeddirectlyatthisproblem.
Howdoyouapplysomeofthegreatideasthathavecome
forwardinthelastfewyearstoreal,livedevelopment?I
thinkthisbookdoesagreatjobofbothexplainingthe
underlyingideaswithenoughdetailtomakethem
practicalandputtingthegroupofideastogetherinaway
thatwillhelpdevelopersseeapathfromstarttoend.
Domain-DrivenDesign,Test-DrivenDevelopment,
DependencyInjection,persistence,andmanyother
practicalissuesarecovered.Afterreadingthisbook,I
thinkareaderwillreallybeabletotaketheseimportant
ideasandusethemtogethereffectively.Consideringthe
greatvalueoftheindividualideaspresented,butthe
limitednumbersofexamplesofpeoplereallyusingthem,
thisworkrepresentsagreatwinforusall.Ihighly
recommendit."
PhilipNelson,chiefscientistforPAi,
xcskiwinn.org/community/blogs/panmanphil/default.aspx


"Takingtheleapfromadata-centricmindsettothe
deeperrealizationofOOPfoundinDomain-DrivenDesign,
Test-DrivenDevelopment,object/relationalpersistence,
andotherAgilemethodsandpatternscanbeanarduous
anddisorientingundertakingfortheuninitiated.
"Withapatient,pragmatic,andmentoringstyle,Jimmy
takesthereaderalongfortheleap,exploringtheissues
andtheoptions,givingsoundadvicealongtheway.This
bookshowsyouhowtointegratethevariousmethodsand
patternsintoafullycoherentapproachtodesigningand

creatingsuperblymaintainable.Netsoftware."
GeorgeHicks,seniordeveloperforPropertyWorks
"Ifyouhaveeverreadhisblog,youalreadyknowthat
JimmyNilssonlikestochallengeestablished'truths'inthe
.NETcommunity,lookingforbetterwaystodesign
software.Heacknowledgesthatsoftwaredesignishard,
andthatone-size-fits-allsolutionsdonotwork;prosand
conshavetobebalancedincontextoftheproblemat
handbeforerulingawinner.Forbuildingtestableand
maintainablesoftwarewithcomplexbusiness
requirements,JimmychoosestouseDomain-Driven
Design,andhebringsalongatoolboxofprovenand
establishedprinciples,patterns,andpracticestocarryit
out.Jimmy'sinformalwritingstyleanduseofexamples
andTest-DrivenDevelopmentmakethisbookvery
approachable,especiallyconsideringallthegroundthatis
covered.BecauseheisontopoftheDDDstuff,Jimmy
(andfriends)bringsyoudistilledknowledgeon,and
referencesto,manyofthemostvaluabletechniquesand
resourceswithinsoftwaredevelopmenttoday.Ibelieve
thisbooktobeavaluableguidetoapplyingDDD,andfor
developerswhowanttoimprovetheirgeneraldesign
skills."


AndreasBrink,softwaredeveloper
"InApplyingDomain-DrivenDesignandPatterns,Jimmy
Nilssonstrengthenshispositionasanauthorityonapplied
softwarearchitecture.Withaniceblendofhispersonal
thoughtsonthesubjects,Jimmytakesthereaderona

tourthroughmostofthemodernmust-knowdesign
techniques,leavingnothinguntouched.Jimmyshowshow
toimplementthethoughtsofother,moretheoretical
thoughtleadersinanappealingandeasytofollow
structure.IamcertainthatApplyingDomain-Driven
DesignandPatternswillbecomeamandatorytitleinthe
enterprisebookshelf."
MikaelFreidlitz,vicepresidentofContentandKnowledge
ProgramsatIASA
"Domain-DrivenDesignisanimportanttechniquethatcan
helpproducequalitybusinessapplicationsthatevolvewith
theneedsofthebusiness.Inanidealworld,practicing
DDDwouldbeaboutOOdesignbutinreality,the
technologiesweworkwithimposenumerousconstraints.
"Thisbooktacklesthatchallengeheadon,bridgingthe
gapbetweenDDDconceptsandtheactionoftranslating
themintopracticeonthe.NETplatform.Jimmynotonly
hasadeepunderstandingofDDDandenterprise
technologies,buthaslearnedmanylessonsfromhis
extensiveindustryexperience,andtakesarefreshingly
pragmaticapproach.Thisisavaluablebook."
RodJohnson,founderofSpringFramework,CEOof
Interface21
"Thisisagreatbook.Ittakesyouonahands-on
informativetravelintheworldofDomain-DrivenDesign.
Agreatnumberofimportantissuesarediscussed,


explained,andshowninrelevantcontexts.Thesewillgive
youagreatfoundationwhenyouareworkingwithyour

ownDomainModel-basedsystem.Boththeactual
developmenttechniquesaswellaspracticalworkmethods
(asincorporationofTest-DrivenDevelopment)are
discussed."
Trond-EirikKolloen,softwarearchitectanddeveloper
"Canwefocusonthehouseprojectsnow?"
Lotta,wife
"Aaa,dee,dee,dee,pee..."(Swedishpronunciationofthe
bookabbreviation)
Leo,son,fouryearsold
"Dad,doyoureallythinksomeonewillreadit?"
Tim,son,eightyearsold


AbouttheAuthor
JimmyNilssonownsandrunstheSwedishconsulting
companyJNSKAB.Hehaswrittennumeroustechnicalarticles
andtwobooks.Hehasalsobeentrainingandspeakingat
conferences,butaboveeverythingelse,heisadeveloperwith
almost20yearsofexperience(www.jnsk.se/weblog/).




Forewords
Buildingenterprisesoftwareisrarelyeasy.Althoughwehavea
plethoraoftoolsandframeworkstomakeiteasier,westillhave
tofigureouthowtousethesetoolswell.Therearelotsof
approachesyoucantake,butthetrickisknowingwhichoneto
useinspecificsituationshardlyeverdoesoneapproachworkin

allcases.Overthelastfewyearsthere'sgrownupacommunity
ofpeoplelookingtocaptureapproachestodesignenterprise
applicationsanddocumentthemintheformofpatterns(Ikeep
anoverviewwithlinksat
/>Peopleinvolvedinthiseffort,suchasme,trytofindcommon
approachesanddescribehowtodothemwellandwhenthey
areapplicable.Theresultingworkisprettywideranging,and
thatcanleadtotoomuchchoiceforthereader.
WhenIstartedwritingPatternsofEnterpriseApplication
Architecture(Addison-Wesley,2002),Ilookedforthiskindof
designadviceintheMicrosoftworld.Istruggledtofindmuchof
anything,butonerarebookthattackledtheterritorywas
Jimmy'searlierbook.Ilikedhisinformalwritingstyleand
eagernesstodigintoconceptsthatmanyothersskimmedover.
Soit'sfittingthatJimmydecidedtotakemanyoftheideas
frommeandtheothersintheenterprisepatternscommunity
andshowhowyoucanapplytheminwriting.NETapplications.
Thefocusofthisenterprisepatternscommunityisdocumenting
gooddesigns,butanotherthreadrunsthroughus.Wearealso
bigfansofagilemethods,embracingtechniquessuchasTestDrivenDevelopment(TDD)andrefactoring.SoJimmyalso
broughttheseideasintothisbook.Manypeoplethinkthat
pattern-people'sfocusondesignandTDD'sfocusonevolution
areatodds.Thehugeoverlapbetweenpattern-peopleand
TDDersshowsthisisn'ttrue,andJimmyhasweavedbothof


thesethreadsintothisbook.
Theresultisabookaboutdesigninthe.NETworld,driveninan
agilemannerandinfusedwiththeproductsoftheenterprise
patternscommunity.It'sabookthatshowsyouhowtobegin

applyingsuchthingsasTDD,object-relationalmapping,and
domain-drivendesignto.NETprojects.Ifyouhaven'tyetcome
acrosstheseconcepts,you'llfindthatthisbookisan
introductiontotechniquesthatmanydevelopersthinkarethe
keyforfuturesoftwaredevelopment.Ifyouarefamiliarwith
theseideas,thebookwillhelpyoupassthoseideasontoyour
colleagues.
ManypeoplefeeltheMicrosoftcommunityhasnotbeenasgood
asothersinpropagatinggooddesignadviceforenterprise
applications.Asthetechnologybecomesmorecapableand
sophisticated,itbecomesmoreimportanttounderstandhowto
useitwell.Thisbookisavaluablestepinadvancingthat
understanding.
MartinFowler

ThebestwaytolearnhowtodoDomain-DrivenDesign(DDD)
istositdownnexttoafriendly,patient,experienced
practitionerandworkthroughproblemstogether,step-by-step.
Thatiswhatreadingthisbookislike.
Thisbookdoesnotpushanewgrandscheme.Itunaffectedly
reportsononeexpertpractitioner'suseofandcombinationof
thecurrentpracticeshehasbeendrawnto.
JimmyNilssonreiterateswhatmanyofushavebeensaying:
thatseveralcurrentlytrendytopicsspecifically,DDD,Patternsof
EnterpriseApplicationArchitecture(PoEAA),andTest-Driven
Development(TDD)arenotalternativestoeachother,butare
mutuallyreinforcingelementsofsuccessfuldevelopment.


Furthermore,allthreeoftheseareharderthantheylookat

first.Theyrequireextensiveknowledgeoverawiderange.This
bookdoesspendsometimeadvocatingtheseapproaches,but
mostlyitfocusesonthedetailsofhowtomakethemwork.
Effectivedesignisnotjustabunchoftechniquestobelearned
byrote;itisawayofthinking.AsJimmydivesintoanexample
hegivesusalittlewindowintohismind.Henotonlyshowshis
solutionandexplainsit,heletsusseehowhegotthere.
WhenIamdesigningsomething,dozensofconsiderationsflit
throughmymind.IftheyarefactorsI'vedealtwithoften,they
passsoquicklyIambarelyconsciousofthem.Iftheyarein
areaswhereIhavelessconfidence,Idwellonthemmore.I
presumethisistypicalofdesigners,butitisdifficultto
communicatetoanotherperson.AsJimmywalksthroughhis
examples,itisasifhewereslowingthisprocessdowntoan
observablepace.Ateverylittlejuncture,threeorfour
alternativespresentthemselvesandgetweighedandrejected
infavoroftheoneheeventuallychooses.
Forexample,wewantmodelobjectsthatareimplementedfree
ofentanglementwiththepersistencetechnology.Sowhatare
eightways(eight!)thatapersistenceframeworkcanforceyou
tocontaminatetheimplementationofadomainobject?What
considerationswouldleadyoutocompromiseonsomeofthese
points?Whatdothecurrentlypopularframeworks,including
the.NETplatform,impose?
Jimmythinkspragmatically.Hedrawsonhisexperienceto
makeadesignchoicethatwilllikelytakehimtowardthegoal,
adheringtothedeeperdesignprinciple,ratherthanthechoice
thatlooksthemostlikeatextbookexample.Andallofhis
decisionsareprovisional.
ThefirstdesignprincipleJimmyholdsinfrontofhimselfisthe

fundamentalgoalofDDD:adesignthatreflectsdeep
understandingofthebusinessproblemathandinaformthat


allowsadaptationtonewwrinkles.Sowhysomuchdiscussion
oftechnicalframeworkandarchitecture?
Itisacommonmisperception,perhapsanaturalone,thatsuch
apriorityonthedomaindemandslesstechnicaltalentandskill.
Wouldthatthisweretrue.Itwouldnotbequitesodifficultto
becomeacompetentdomaindesigner.Ironically,torenderclear
andusefuldomainconceptsinsoftware,tokeepthemfrom
beingsuffocatedundertechnicalclutter,requiresparticularly
deftuseoftechnology.Myobservationisthatthosewiththe
greatestmasteryoftechnologyandarchitecturalprinciples
oftenknowhowtokeeptechnologyinitsplaceandareamong
themosteffectivedomainmodelers.
Idonotrefertotheknowledgeofeveryquirkofcomplextools,
buttothemasteryofthesortofknowledgelaidoutinMartin
Fowler'sPoEAA,becausenaïveapplicationoftechnology
paradoxicallymakesthattechnologymoreintrusiveintothe
application.
Formanypeoplethisbookwillfillingapsofhowtoimplement
expressiveobjectmodelsinpractice.Ipickedupanumberof
usefulwaysofthinkingthroughtheapplicationoftechnical
frameworks,andIespeciallyfirmedupmyunderstandingof
someparticularsofdoingDDDina.NETsetting.
Inadditiontotechnicalarchitecture,Jimmyspendsagreatdeal
oftimeonhowtowritetests.TDDcomplementsDDDina
differentway.Intheabsenceofafocusonrefininganever
moreusefulmodel,TDDispronetofragmentedapplications,

whereasingle-mindedattackononefeatureatatimeleadsto
anunextendablesystem.Acomprehensivetestsuiteactually
allowssuchateamtocontinuemakingprogresslongerthan
wouldbepossiblewithoutit,butthisisjustthebasestvalueof
TDD.
Atitsbest,thetestsuiteisthelaboratoryforthedomainmodel
andatechnicalexpressionoftheubiquitouslanguage.Testsof


×