Domain-Driven Design Quickly
FREE ONLINE EDITION
(non-printable free online version)
If you like the book, please support
the author and InfoQ by
purchasing the printed book:
(only
$22.95
)
Brought to you
Courtesy of
This book is distributed for free on InfoQ.com, if
you have received this book from any other
source then please support the author and the
publisher by registering on InfoQ.com.
Visit the homepage for this book at:
/>design-quickly
Domain-DrivenDesign
Quickly
©2006C4MediaInc.
Allrightsreserved.
C4Media, Publisher of InfoQ.com Enterprise Software Development
Community
PartoftheInfoQEnterpriseSoftwareDevelopmentseriesofbooks.
ForinformationororderingofthisorotherInfoQbooks,pleasecontact
No part of this publication may be reproduced, stored in a retrieval
system or transmitted in any form or by any means, electronical,
mechanical,photocopying,recording,scanningorotherwiseexceptas
permittedunderSections107or108ofthe1976UnitedStatesCopy-
rightAct,withouteitherthepriorwrittenpermissionofthePublisher.
Designations used by companies to distinguish their products are
often claimed as trademarks.Inallinstances where C4MEdia Inc. is
awareof a claim, the product names appear in initial Capital or ALL
CAPITALLETTERS.
Readers,however,shouldcontacttheappropriatecompaniesformore
completeinformationregardingtrademarksandregistration.
Some of the diagrams used in this book were reproduced with
permission, under Creative Commons License, courtesy of: Eric
Evans, DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans,
2004.
Cover page image republished under Creative Commons License,
courtesyof:EricEvans,DOMAIN-DRIVENDESIGN,Addison-Wesley,
EricEvans,2004.
ProductionCredits:
DDDSummaryby:AbelAvram
ManagingEditor:FloydMarinescu
Coverart:GeneSteffanson
Composition:LauraBrownandMelissaTessier
SpecialthankstoEricEvans.
LibraryofCongressCataloging-in-PublicationData:
ISBN:
978-1-4116-0925-9
PrintedintheUnitedStatesofAmerica
1098765321
Contents
WhatIsDomain-DrivenDesign 3
BuildingDomainKnowledge 8
TheUbiquitousLanguage 13
TheNeedforaCommonLanguage 13
CreatingtheUbiquitousLanguage 16
TheBuildingBlocksOfAModel-DrivenDesign 28
LayeredArchitecture 29
Entities 31
ValueObjects 34
Services 37
Modules 40
Aggregates 42
Factories 46
Repositories 51
RefactoringTowardDeeperInsight 57
ContinuousRefactoring 57
BringKeyConceptsIntoLight 59
PreservingModelIntegrity 67
BoundedContext 69
ContinuousIntegration 71
ContextMap 73
SharedKernel 75
Customer-Supplier 76
Conformist 79
AnticorruptionLayer 80
SeparateWays 83
OpenHostService 84
Distillation 85
DDDMattersToday:AninterviewwithEricEvans 91
Preface:WhyDDDQuickly?
firstheardaboutDomainDrivenDesignandmetEricEvansat
asmallgatheringofarchitectsatamountainsummitorganized
by Bruce Eckel in the summer of 2005. The summit was
attended by a number of people I respect, including Martin
Fowler, Rod Johnson, Cameron Purdy, Randy Stafford, and
GregorHohpe.
The group seemed quite impressed with the vision of Domain
DrivenDesign,andwaseagertolearnmoreaboutit.Ialsogot
thefeelingthateveryonewishedthattheseconceptsweremore
mainstream.WhenInoticedhowEricusedthedomainmodelto
discusssolutionstosomeofthevarioustechnicalchallengesthe
group discussed, and how much emphasis he placed on the
business domain instead of technology-specific hype, I knew
right away that this vision is one that the community sorely
needed.
We, in the enterprise development community, especially the
web development community, have been tainted by years of
hype that took us away from proper object oriented software
development. In the Java community, good domain modeling
waslostinthehypeofEJBandthecontainer/componentmodels
of 1999-2004. Luckily, shifts in technology and the collective
experiencesofthesoftwaredevelopmentcommunityaremoving
usbacktowardstraditionalobjectorientedparadigms.However,
thecommunityislackingaclearvisionforhowtoapplyobject
orientationonanenterprisescale,whichiswhyIthinkDDDis
important.
Unfortunately, outside of a small group of the most senior
architects,IperceivedthatveryfewpeoplewereawareofDDD,
whichiswhyInfoQcommissionedthewritingofthisbook.
I
It is my hope that by publishing a short, quickly-readable
summary and introduction to the fundamentals of DDD and
making it freely downloadable on InfoQ with an inexpensive
pocket-sizedprintversion,thisvisioncanbecomemainstream.
Thisbookdoesnotintroduceanynewconcepts;itattemptsto
concisely summarize the essence of what DDD is, drawing
mostly Eric Evans’ original book on the subject, as well other
sourcessincepublishedsuchasJimmyNilsson’sApplyingDDD
andvariousDDDdiscussionforums.Thebookwillgiveyoua
crashcourseonthefundamentalsofDDD,butitisnosubstitute
forthe numerous examples and case studiesprovided in Eric’s
book or the hands-on examples provided in Jimmy’s book. I
highlyencourage youtoreadbothof these excellent works. In
themeantime,ifyouagreethatthecommunityneedsDDDtobe
part of our group consciousness, please let people know about
thisbookandEric’swork.
FloydMarinescu
Co-founder&ChiefEditorofInfoQ.com
1
Introduction
oftware is an instrument created to help us deal with the
complexitiesofourmodernlife.Softwareisjustthemeanstoan
end, and usually that end is something very practical and real.
Forexample,weusesoftwareforairtrafficcontrol,andthisis
directlyrelatedtotheworldsurroundingus.Wewanttoflyfrom
one place to another, and we do that using sophisticated
machineries, so we create software to coordinate the flight of
thousandsofairplaneswhichhappentobeintheairatanytime.
Softwarehastobepracticalanduseful;otherwisewewouldnot
investsomuchtimeandresourcesintoitscreation.Thatmakes
itextremelyconnectedtoacertainaspectofourlives.Auseful
package of software cannot be decoupled from that sphere of
reality, the domain it is supposed to help us manage. On the
contrary,thesoftwareisdeeplyentangledwithit.
Softwaredesignisanart,andlikeanyartitcannotbetaughtand
learnedasaprecisescience,bymeansoftheoremsandformulas.
Wecandiscoverprinciplesandtechniquesusefultobeapplied
throughout the process of software creation, but we probably
won’teverbeabletoprovideanexactpathtofollowfromthe
real world need to the code module meant to serve that need.
Likeapictureorabuilding,asoftwareproductwillincludethe
personal touch of those who designed and developed it,
something of the charisma and flair (orthe lack of it)of those
whocontributedtoitsinceptionandgrowth.
There are different ways to approach software design. For the
last20years,thesoftwareindustryhasknownandusedseveral
methods to create its products, each with its advantages and
shortcomings.Thepurposeofthisbookisto focusonadesign
S
method which has emerged and evolved over the last two
decades, but has crystallized more clearly during the last few
years: domain-driven design. Eric Evans has made a great
contributiontothissubjectmatterbywritingdowninonebook
much of the accumulated knowledge about domain-driven
design. For a more detailed presentation of this topic, we
recommendreadinghisbook“Domain-DrivenDesign:Tackling
Complexity in the Heart of Software”, published by Addison-
Wesley,ISBN:0-321-12521-5.
Many valuable insights can also be learned by following the
DomainDrivenDesigndiscussiongroupat:
/>This book is only an introduction to the topic, intended to
quicklygiveyouafundamental,butnotadetailedunderstanding
ofDomainDrivenDesign.We just wantto whet your appetite
forgoodsoftwaredesignwiththeprinciplesandguidelinesused
intheworldofdomain-drivendesign.
1
3
FreeOnlineVersion.
Supportthiswork,buytheprintcopy:
/>
WhatIsDomain-DrivenDesign
oftware development is most often applied to automating
processesthat exist in therealworld, or providingsolutions to
realbusinessproblems;Thebusinessprocessesbeingautomated
or real world problems that the software is the domain of the
software.Wemustunderstandfromthebeginningthatsoftware
isoriginatedfromanddeeplyrelatedtothisdomain.
Softwareismadeupofcode.Wemightbetemptedtospendtoo
much time with the code, and view the software as simply
objectsandmethods.
Consider car manufacturing as a metaphor. The workers
involved in auto manufacturing may specialize in producing
partsofthecar,butindoingsotheyoftenhavealimitedviewof
theentirecarmanufacturingprocess.Theystartviewingthecar
asahugecollectionofpartswhichneedtofittogether,butacar
ismuchmorethanthat.Agoodcarstartswithavision.Itstarts
with carefully written specifications. And it continues with
design. Lots and lots of design. Months, maybe years of time
spent on design, changing and refining it until it reaches
perfection, until it reflects the original vision. The processing
designisnotallonpaper.Muchofitincludesdoingmodelsof
thecar,andtestingthemundercertainconditionstoseeifthey
work. The design is modified based on the testing results. The
carissenttoproductioneventually,andthepartsarecreatedand
assembledtogether.
S
Software development is similar. We can’t just sit down and
typecode.Wecandothat,anditworkswellfortrivialcases.
Butwecannotcreatecomplexsoftwarelikethat.
In order to create good software, you have to know what that
software is all about. You cannot create a banking software
systemunlessyouhaveagoodunderstandingofwhatbankingis
allabout,onemustunderstandthedomainofbanking.
Isitpossibletocreatecomplexbankingsoftwarewithoutgood
domainknowledge?Noway.Never.Whoknowsbanking?The
softwarearchitect?No.Hejustusesthebanktokeephismoney
safe and available when he needs them. The software analyst?
Notreally.Heknowstoanalyzeagiventopic,whenheisgiven
all the necessary ingredients. The developer? Forget it. Who
then?Thebankers,ofcourse.Thebankingsystemisverywell
understoodbythepeopleinside,bytheirspecialists.Theyknow
allthedetails,allthecatches,allthepossibleissues,alltherules.
Thisiswhereweshouldalwaysstart:thedomain.
When we begin a software project, we should focus on the
domainitisoperatingin.Theentirepurposeofthesoftwareisto
enhancea specific domain. To be ableto do that, the software
hastofitharmoniouslywiththedomainithasbeencreatedfor.
Otherwise it will introduce strain into the domain, provoking
malfunction,damage,andevenwreakchaos.
How can we make the software fit harmoniously with the
domain?Thebestwaytodoitistomakesoftwareareflectionof
thedomain.Softwareneedstoincorporatethecoreconceptsand
elementsofthedomain,andtopreciselyrealizetherelationships
betweenthem.Softwarehastomodelthedomain.
Somebodywithoutknowledgeofbankingshouldbeabletolearn
a lot just by reading the code in a domain model. This is
essential.Softwarewhichdoesnothaveitsrootsplanteddeeply
intothedomainwillnotreactwelltochangeovertime.
Sowestartwiththedomain.Thenwhat?Adomainissomething
of this world. It cannot just be taken and poured over the
K
NOW
Y
OUR
D
OMAIN
│5
keyboardintothecomputertobecomecode.Weneedtocreate
an abstraction of the domain. We learn a lot about a domain
whiletalkingwiththedomainexperts.Butthisrawknowledgeis
not going to be easily transformed into software constructs,
unlesswebuildanabstractionofit,ablueprintinourminds.In
the beginning, the blueprint always incomplete. But in time,
whileworkingonit,wemakeitbetter,anditbecomesmoreand
morecleartous.Whatisthisabstraction?Itisamodel,amodel
ofthedomain.AccordingtoEricEvans,adomainmodelisnota
particulardiagram;itistheideathatthediagramisintendedto
convey.Itisnotjusttheknowledgeinadomainexpert’shead;it
is a rigorously organized and selective abstraction of that
knowledge.Adiagramcanrepresentandcommunicateamodel,
ascancarefullywrittencode,ascananEnglishsentence.”
The model is our internal representation of the target domain,
and it is very necessary throughout the design and the
development process. During the design process we remember
andmakelotsofreferencestothemodel.Theworldaroundusis
waytoomuchforourheadstohandle.Evenaspecificdomain
couldbemorethanahumanmindcanhandleatonetime.We
needtoorganizeinformation,tosystematizeit,todivideitupin
smallerpieces, to group those piecesintological modules, and
takeoneatatimeanddealwithit.Weevenneedtoleavesome
parts of the domain out. A domain contains just too much
informationtoincludeitallintothemodel.Andmuchofitisnot
even necessary to be considered. This is a challenge by itself.
Whatto keepandwhatto throw away? It’s part of the design,
thesoftwarecreationprocess.Thebankingsoftwarewillsurely
keeptrackofthecustomer’saddress,butitshouldnotcareabout
the customer’s eye color. That is an obvious case, but other
examplesmightnotbesoobvious.
A model is an essentialpart of software design. We need it in
order to be able to deal with complexity. All our thinking
processaboutthedomainissynthesizedintothismodel.That’s
good,butithastocomeoutofourhead.Itisnotveryusefulifit
remainsinthere,isit?Weneedtocommunicatethismodelwith
domainexperts,withfellowdesigners,andwithdevelopers.The
modelistheessenceofthesoftware,butweneedtocreateways
toexpressit,tocommunicateitwithothers.Wearenotalonein
this process, so we need to share knowledge and information,
and we need to do it well, precisely, completely, and without
ambiguity.Therearedifferentwaystodothat.Oneisgraphical:
diagrams,usecases,drawings,pictures,etc.Anotheriswriting.
We write down our vision about the domain. Another is
language. We can and we should create a language to
communicatespecificissuesaboutthedomain.Wewilldetailall
these later, but the main point is that we need to communicate
themodel.
When we have a model expressed, we can start doing code
design.Thisisdifferentfromsoftwaredesign.Softwaredesign
is like creating the architecture of a house, it’s about the big
picture.Ontheotherhand,codedesignisworkingonthedetails,
likethelocationofapaintingonacertainwall.Codedesignis
alsoveryimportant,butnotasfundamentalassoftwaredesign.
A code design mistake is usually more easily corrected, while
software design errors are a lot more costly to repair. It’s one
thing to move a painting more to the left, and a completely
differentthingtoteardownonesideofthehouseinordertodo
it differently. Nonetheless the final product won’t be good
without good code design. Here code design patterns come
handy,andtheyshouldbeappliedwhennecessary.Goodcoding
techniqueshelptocreateclean,maintainablecode.
There are different approaches to software design. One is the
waterfall design method. This method involves a number of
stages.Thebusinessexpertsputupasetofrequirementswhich
arecommunicatedtothebusinessanalysts.Theanalystscreatea
modelbased on those requirements,and pass the results to the
developers,whostartcodingbasedonwhattheyhavereceived.
It’s a one way flow of knowledge. While this has been a
traditionalapproachinsoftwaredesign,andhasbeenusedwitha
certainlevelofsuccessovertheyears,ithasitsflawsandlimits.
Themainproblemisthatthereisnofeedbackfromtheanalysts
tothebusinessexpertsorfromthedeveloperstotheanalysts.
K
NOW
Y
OUR
D
OMAIN
│7
AnotherapproachistheAgilemethodologies,suchasExtreme
Programming (XP). These methodologies are a collective
movement against the waterfall approach, resulting from the
difficulties of trying to come up with all the requirements
upfront,particularlyin light of requirementschange. It’s really
hard to create a complete model which covers all aspects of a
domain upfront. It takes a lot of thinking, and often you just
cannot see all the issues involved from the beginning, nor can
youforeseesomeofthenegativesideeffectsormistakesofyour
design.AnotherproblemAgileattemptstosolveisthesocalled
“analysisparalysis”,withteammemberssoafraidofmakingany
designdecisionsthattheymakenoprogressatall.WhileAgile
advocates recognize the importance of design decision, they
resist upfront design. Instead they employ a great deal of
implementation flexibility, and through iterative development
with continuous business stakeholder participation and a lot of
refactoring,thedevelopmentteamgetstolearn moreaboutthe
customerdomainandcanbetterproducesoftwarethatmeetsthe
customersneeds.
The Agile methods have their own problems and limitations;
theyadvocate simplicity, but everybody has their own view of
what that means. Also, continuous refactoring done by
developerswithoutsoliddesignprincipleswillproducecodethat
is hard to understand or change. And while the waterfall
approach may lead to over-engineering, the fear of over-
engineeringmayleadtoanotherfear:thefearofdoingadeep,
thoroughlythoughtoutdesign.
This book presents the principles of domain driven design,
which when applied can great increase any development
processesabilitytomodelandimplementthecomplexproblems
in the domain in a maintainable way. Domain Driven Design
combines design and development practice, and shows how
design and development can work together to create a better
solution. Good design will accelerate the development, while
feedbackcomingfromthedevelopmentprocesswillenhancethe
design.
BuildingDomainKnowledge
Let’sconsiderthe exampleof anairplaneflight controlsystem
project,andhowdomainknowledgecanbebuilt.
Thousandsofplanesareintheairatagivenmomentalloverthe
planet. They are flying their own paths towards their
destinations,anditisquiteimportanttomakesuretheydonot
collideintheair.Wewon’ttrytoelaborateontheentiretraffic
control system, but on a smaller subset which is a flight
monitoringsystem.Theproposedprojectisamonitoringsystem
which tracks every flight over a certain area, determines if the
flight follows its supposed route or not, and if there is the
possibilityofacollision.
Wheredowestartfromasoftwaredevelopmentperspective?Iin
the previous section we said that we should start by
understanding the domain, which in this case is air traffic
monitoring. Air traffic controllers are the specialists of this
domain.Butthecontrollersarenotsystemdesignersorsoftware
specialists. You can’t expect them to hand you a complete
descriptionoftheirproblemdomain.
The air traffic controllers have vast knowledge about their
domain,butinordertobeabletobuildupamodelyouneedto
extract essential information and generalize it. When you start
talkingtothem,youwillhearalotaboutaircraftstakingoff,and
landing, aircrafts in midair and the danger of collision, planes
waitingbeforebeingallowedtoland,etc.Tofindorderinthis
seemingly chaotic amount of information, we need to start
somewhere.
The controller and you agree that each aircraft has a departure
andadestinationairfield.Sowehaveanaircraft,adepartureand
adestination,asshowninthefigurebelow.
K
NOW
Y
OUR
D
OMAIN
│9
OK, the plane takes off from some place and touches down in
another.Butwhathappensintheair?Whatpathofflightdoesit
go?Actuallywearemoreinterestedinwhathappenswhileitis
airborn.Thecontrollersaysthateachplaneisassignedaflight
plan which is supposed to describe the entire air travel. While
hearingaboutaflightplan,youmaythinkinyourmindthatthis
is about the path followed by the plane while in the air. After
further discussion, you hear an interesting word: route. It
instantlycatchesyourattention,andforagoodreason.Theroute
contains an important concept of flight travel. That’s what
planesdowhileflying,theyfollowaroute.Itisobviousthatthe
departure and destination points of the aircraft are also the
startingandendingpointsoftheroute.So,insteadofassociating
the aircraft with the departure and destination points, it seems
more natural to associate it with a route, which in turn is
associatedwiththecorrespondingdepartureanddestination.
Aircraft
Departure
Destination
Aircraft
Route
Departure
Destination
Talking with the controller about the routes airplanes follow,
you discover that actually the route is made up of small
segments,whichputtogetherconstitutesomesortofacrooked
linefromdeparturetodestination.Thelineissupposedtopass
through predetermined fixed points. So, a route can be
considered a series of consecutive fixes. At this point you no
longerseethedepartureanddestinationastheterminalpointsof
the route, but just another two of those fixes. This is probably
quite different from how the controller sees them, but it is a
necessary abstraction which helps later. The resulting changes
basedonthesediscoveriesare:
Thediagramshows another element, the fact that eachfix is a
point in space followed by the route, and it is expressed as a
threedimensionalpoint.Butwhenyoutalktothecontroller,you
willdiscoverthathedoesnotseeitthatway.Actuallyhesees
therouteastheprojectiononearthoftheplaneflight.Thefixes
are just points on Earth surface uniquely determined by their
latitudeandlongitude.Sothecorrectdiagramis:
Aircraft
Route
Fix
*
3DPoint
K
NOW
Y
OUR
D
OMAIN
│11
What is actually happening here? You and thedomain experts
are talking, you are exchanging knowledge. You start asking
questions, and they respond. While they do that, they dig
essentialconceptsoutof theairtrafficdomain.Thoseconcepts
maycomeoutunpolishedanddisorganized,butnonethelessthey
areessentialforunderstandingthedomain.Youneedtolearnas
much as possible about the domain from the experts. And by
puttingtherightquestions,andprocessingtheinformationinthe
rightway,youandtheexpertswillstarttosketchaviewofthe
domain, a domain model. This view is neither complete nor
correct,butitisthestartyouneed.Trytofigureouttheessential
conceptsofthedomain.
This is animportant part of the design. Usually there are long
discussions between software architects or developers and the
domain experts. The software specialists want to extract
knowledge from the domain experts, and they also have to
transformitintoausefulform.Atsomepoint,theymightwant
to create an early prototype to see how it works so far. While
doingthattheymayfindsomeissueswiththeirmodel,ortheir
approach, and may want to change the model. The
communicationisnotonlyoneway,fromthedomainexpertsto
thesoftwarearchitectandfurthertothedevelopers.Thereisalso
feedback, which helps create a better model, and aclearer and
more correct understanding of the domain. Domain experts
knowtheirareaofexpertisewell,buttheyorganizeandusetheir
knowledgeinaspecificway,whichisnotalwaysthebesttobe
implementedintoasoftwaresystem.Theanalyticalmindofthe
softwaredesignerhelpsunearthsomeofthekeyconceptsofthe
Aircraft
Route
Fix
*
2DPoint
domain during discussions with domain experts, and also help
constructastructureforfuturediscussionsaswewillseeinthe
next chapter. We, the software specialists (software architects
anddevelopers)andthedomainexperts,arecreatingthemodel
ofthedomaintogether,andthemodelistheplacewherethose
two areas of expertise meet. This might seem like a very time
consuming process, and it is, but this is how it should be,
because in the end the software’s purpose is to solve business
problemsinareallifedomain,soithastoblendperfectlywith
thedomain.
2
13
FreeOnlineVersion.
Supportthiswork,buytheprintcopy:
/>
TheUbiquitousLanguage
TheNeedforaCommonLanguage
hepreviouschaptermadethecasethatitisabsolutelynecessary
to develop a model of the domain by having the the software
specialists work with the domain experts; however, that
approach usually has some initial difficulties due to a
fundamental communication barrier. The developers have their
mindsfullofclasses,methods,algorithms,patterns,andtendto
always make a match between a real life concept and a
programming artifact. They want to see what object classes to
create and what relationships to model between them. They
thinkintermsofinheritance,polymorphism,OOP,etc.Andthey
talk like that all the time. And it is normal for them to do so.
Developers will be developers. But the domain experts usually
know nothing about any of that. They have no idea about
software libraries, frameworks, persistence, in many case not
evendatabases.Theyknowabouttheirspecificareaofexpertise.
Inthe airtrafficmonitoringexample,thedomainexpertsknow
about planes, about routes, altitudes, longitudes and latitudes,
theyknowaboutdeviancesfromthenormalroute, about plane
trajectories.Andtheytalkaboutthosethingsintheirownjargon,
which sometimes is not so straightforward to follow by an
outsider.
T
To overcome this difference in communication style, when we
buildthemodel,wemustcommunicatetoexchangeideasabout
the model, about the elements involved in the model, how we
connectthem,whatisrelevantandwhatisnot.Communication
atthis levelis paramount for the successof the project. If one
says something, and the other does not understand or, even
worse,understandssomethingelse,whatarethechancesforthe
projecttosucceed?
A project faces serious problems when team members don’t
share a common language for discussing the domain. Domain
expertsusetheirjargonwhiletechnicalteammembershavetheir
own language tuned for discussing the domain in terms of
design.
Theterminologyofday-to-daydiscussionsisdisconnectedfrom
the terminology embedded in the code (ultimately the most
important product of a software project). And even the same
personusesdifferentlanguageinspeechandinwriting,sothat
the most incisive expressions of the domain often emerge in a
transient form that is never captured in the code or even in
writing.
During these sessions of communication, translation is often
usedtolettheothersunderstandwhatsomeconceptsareabout.
Developers might try to explain some design patterns using a
layman’slanguage,andsometimeswithoutsuccess.Thedomain
expertswillstrivetobringhomesomeoftheirideasprobablyby
creating a new jargon. During this process communication
suffers,andthiskindoftranslationdoesnothelptheknowledge
buildingprocess.
We tend to use our own dialects during these design sessions,
but none of these dialects can be a common language because
noneserveseveryone’sneeds.
Wedefinitelyneedtospeakthesamelanguagewhenwemeetto
talkaboutthemodelandtodefineit.Whatlanguageisitgoing
to be? The developers’ language? The domain experts’
language?Somethinginbetween?
C
REATE
A
L
ANGUAGE
│15
A core principle of domain-driven design is to use a language
basedonthemodel.Sincethemodelisthecommonground,the
placewherethesoftwaremeetsthedomain,it isappropriateto
useitasthebuildinggroundforthislanguage.
Usethemodelasthebackboneof alanguage.Requestthatthe
team use the language consistently in all communications, and
alsoin the code.Whilesharing knowledge and hammeringout
the model, the team uses speech, writing and diagrams. Make
surethislanguageappearsconsistentlyinallthecommunication
forms used bythe team; for this reason, the language is called
theUbiquitousLanguage.
The Ubiquitous Language connects all the parts of the design,
andcreatesthepremiseforthedesignteamto functionwell.It
takesweeksandevenmonthsforlargescaleprojectdesignsto
takeshape.Theteammembersdiscoverthatsomeoftheinitial
conceptswereincorrectorinappropriatelyused,ortheydiscover
newelementsofthedesignwhichneedtobeconsideredandfit
into the overall design. All this is not possible without a
commonlanguage.
Languagesdonotappearovernight.Ittakeshardworkandalot
offocustomakesurethatthekeyelementsofthelanguageare
brought to light. We need to find those key concepts which
definethedomainandthedesign,andfindcorrespondingwords
forthem,andstartusingthem.Someofthemareeasilyspotted,
butsomeareharder.
Iron out difficulties by experimenting with alternative
expressions,whichreflectalternativemodels.Thenrefactorthe
code,renamingclasses,methods,andmodulestoconformtothe
new model. Resolve confusion over terms in conversation, in
just the way we come to agree on the meaning of ordinary
words.
Buildingalanguagelikethathasaclearoutcome:themodeland
the language are strongly interconnected with one another. A
changeinthelanguageshouldbecomeachangetothemodel.
Domain experts should object to terms or structures that are
awkward or inadequate to convey domain understanding. If
domainexpertscannotunderstandsomethinginthemodelorthe
language,thenitismostlikelythatthereissomethingiswrong
with it. On the other hand, developers should watch for
ambiguityorinconsistencythatwilltendtoappearindesign.
CreatingtheUbiquitousLanguage
Howcanwe start buildingalanguage? Hereis a hypothetical
dialogbetweenasoftwaredeveloperandadomainexpertinthe
airtrafficmonitoringproject.Watchoutforthewordsappearing
inboldface.
Developer:Wewanttomonitorairtraffic.Wheredowestart?
Expert:Let’sstartwiththebasics.Allthistrafficismadeupof
planes.Eachplanetakesofffromadepartureplace,andlands
atadestinationplace.
Developer:That’seasy.Whenitflies,theplanecanjustchoose
anyairpaththepilotslike?Isituptothemtodecidewhichway
theyshouldgo,aslongastheyreachdestination?
Expert: Oh, no. The pilots receive a route they must follow.
Andtheyshouldstayonthatrouteascloseaspossible.
Developer:I’mthinkingofthisrouteasa3Dpathintheair.If
we use a Cartesian system of coordinates, then the route is
simplyaseriesof3Dpoints.
Expert: I don’t think so. We don’t see route that way. The
routeisactuallytheprojectiononthegroundoftheexpectedair
pathoftheairplane.Theroutegoesthroughaseriesofpointson
thegrounddeterminedbytheirlatitudeandlongitude.
C
REATE
A
L
ANGUAGE
│17
Developer: OK, then let’s call each of those points a fix,
becauseit’safixedpointofEarth’ssurface.Andwe’llusethen
aseriesof2Dpointstodescribethepath.And,bytheway,the
departure and destination are just fixes. We should not
consider them as separate concepts. The route reaches
destinationasitreachesanyotherfix.Theplanemustfollowthe
route,but doesthatmeanthatitcanflyashighoraslowasit
likes?
Expert:No.Thealtitudethatanairplaneistohaveatacertain
momentisalsoestablishedintheflightplan.
Developer:Flightplan?Whatisthat?
Expert:Beforeleavingtheairport,thepilotsreceiveadetailed
flight plan which includes all sorts of information about the
flight: the route, cruise altitude, the cruise speed, the type of
airplane,eveninformationaboutthecrewmembers.
Developer:Hmm,theflightplanseemsprettyimportanttome.
Let’sincludeitintothemodel.
Aircraft FlightPlan Route
Fix
2DPoint