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

Domain-Driven Design Quickly pdf

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 (1.25 MB, 106 trang )

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-DrivenDesign
Quickly
















©2006C4MediaInc.
Allrightsreserved.


C4Media, Publisher of InfoQ.com Enterprise Software Development
Community

PartoftheInfoQEnterpriseSoftwareDevelopmentseriesofbooks.

ForinformationororderingofthisorotherInfoQbooks,pleasecontact


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,scanningorotherwiseexceptas

permittedunderSections107or108ofthe1976UnitedStatesCopy-
rightAct,withouteitherthepriorwrittenpermissionofthePublisher.

Designations used by companies to distinguish their products are
often claimed as trademarks.Inallinstances where C4MEdia Inc. is
awareof a claim, the product names appear in initial Capital or ALL
CAPITALLETTERS.

Readers,however,shouldcontacttheappropriatecompaniesformore
completeinformationregardingtrademarksandregistration.

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,
courtesyof:EricEvans,DOMAIN-DRIVENDESIGN,Addison-Wesley,
EricEvans,2004.

ProductionCredits:
DDDSummaryby:AbelAvram
ManagingEditor:FloydMarinescu
Coverart:GeneSteffanson

Composition:LauraBrownandMelissaTessier
SpecialthankstoEricEvans.

LibraryofCongressCataloging-in-PublicationData:

ISBN:
978-1-4116-0925-9


PrintedintheUnitedStatesofAmerica

1098765321


Contents


WhatIsDomain-DrivenDesign 3
BuildingDomainKnowledge 8
TheUbiquitousLanguage 13
TheNeedforaCommonLanguage 13
CreatingtheUbiquitousLanguage 16
TheBuildingBlocksOfAModel-DrivenDesign 28
LayeredArchitecture 29
Entities 31

ValueObjects 34
Services 37
Modules 40
Aggregates 42
Factories 46
Repositories 51
RefactoringTowardDeeperInsight 57
ContinuousRefactoring 57
BringKeyConceptsIntoLight 59
PreservingModelIntegrity 67
BoundedContext 69
ContinuousIntegration 71

ContextMap 73
SharedKernel 75
Customer-Supplier 76
Conformist 79
AnticorruptionLayer 80
SeparateWays 83
OpenHostService 84
Distillation 85
DDDMattersToday:AninterviewwithEricEvans 91


 

Preface:WhyDDDQuickly?

firstheardaboutDomainDrivenDesignandmetEricEvansat
asmallgatheringofarchitectsatamountainsummitorganized
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
GregorHohpe.
The group seemed quite impressed with the vision of Domain
DrivenDesign,andwaseagertolearnmoreaboutit.Ialsogot
thefeelingthateveryonewishedthattheseconceptsweremore
mainstream.WhenInoticedhowEricusedthedomainmodelto

discusssolutionstosomeofthevarioustechnicalchallengesthe
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
waslostinthehypeofEJBandthecontainer/componentmodels
of 1999-2004. Luckily, shifts in technology and the collective
experiencesofthesoftwaredevelopmentcommunityaremoving

usbacktowardstraditionalobjectorientedparadigms.However,
thecommunityislackingaclearvisionforhowtoapplyobject
orientationonanenterprisescale,whichiswhyIthinkDDDis
important.
Unfortunately, outside of a small group of the most senior
architects,IperceivedthatveryfewpeoplewereawareofDDD,
whichiswhyInfoQcommissionedthewritingofthisbook.
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-sizedprintversion,thisvisioncanbecomemainstream.
Thisbookdoesnotintroduceanynewconcepts;itattemptsto
concisely summarize the essence of what DDD is, drawing
mostly Eric Evans’ original book on the subject, as well other
sourcessincepublishedsuchasJimmyNilsson’sApplyingDDD
andvariousDDDdiscussionforums.Thebookwillgiveyoua
crashcourseonthefundamentalsofDDD,butitisnosubstitute
forthe numerous examples and case studiesprovided in Eric’s
book or the hands-on examples provided in Jimmy’s book. I
highlyencourage youtoreadbothof these excellent works. In

themeantime,ifyouagreethatthecommunityneedsDDDtobe
part of our group consciousness, please let people know about
thisbookandEric’swork.
FloydMarinescu
Co-founder&ChiefEditorofInfoQ.com









1

Introduction

oftware is an instrument created to help us deal with the
complexitiesofourmodernlife.Softwareisjustthemeanstoan
end, and usually that end is something very practical and real.
Forexample,weusesoftwareforairtrafficcontrol,andthisis
directlyrelatedtotheworldsurroundingus.Wewanttoflyfrom
one place to another, and we do that using sophisticated
machineries, so we create software to coordinate the flight of

thousandsofairplaneswhichhappentobeintheairatanytime.
Softwarehastobepracticalanduseful;otherwisewewouldnot
investsomuchtimeandresourcesintoitscreation.Thatmakes
itextremelyconnectedtoacertainaspectofourlives.Auseful
package of software cannot be decoupled from that sphere of
reality, the domain it is supposed to help us manage. On the
contrary,thesoftwareisdeeplyentangledwithit.
Softwaredesignisanart,andlikeanyartitcannotbetaughtand
learnedasaprecisescience,bymeansoftheoremsandformulas.
Wecandiscoverprinciplesandtechniquesusefultobeapplied
throughout the process of software creation, but we probably
won’teverbeabletoprovideanexactpathtofollowfromthe

real world need to the code module meant to serve that need.
Likeapictureorabuilding,asoftwareproductwillincludethe
personal touch of those who designed and developed it,
something of the charisma and flair (orthe lack of it)of those
whocontributedtoitsinceptionandgrowth.
There are different ways to approach software design. For the
last20years,thesoftwareindustryhasknownandusedseveral
methods to create its products, each with its advantages and
shortcomings.Thepurposeofthisbookisto focusonadesign
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
contributiontothissubjectmatterbywritingdowninonebook
much of the accumulated knowledge about domain-driven
design. For a more detailed presentation of this topic, we
recommendreadinghisbook“Domain-DrivenDesign: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
DomainDrivenDesigndiscussiongroupat:
/>This book is only an introduction to the topic, intended to
quicklygiveyouafundamental,butnotadetailedunderstanding
ofDomainDrivenDesign.We just wantto whet your appetite
forgoodsoftwaredesignwiththeprinciplesandguidelinesused
intheworldofdomain-drivendesign.

1


3


FreeOnlineVersion.
Supportthiswork,buytheprintcopy:
/>

WhatIsDomain-DrivenDesign

oftware development is most often applied to automating
processesthat exist in therealworld, or providingsolutions to
realbusinessproblems;Thebusinessprocessesbeingautomated
or real world problems that the software is the domain of the
software.Wemustunderstandfromthebeginningthatsoftware

isoriginatedfromanddeeplyrelatedtothisdomain.
Softwareismadeupofcode.Wemightbetemptedtospendtoo
much time with the code, and view the software as simply
objectsandmethods.
Consider car manufacturing as a metaphor. The workers
involved in auto manufacturing may specialize in producing
partsofthecar,butindoingsotheyoftenhavealimitedviewof
theentirecarmanufacturingprocess.Theystartviewingthecar
asahugecollectionofpartswhichneedtofittogether,butacar
ismuchmorethanthat.Agoodcarstartswithavision.Itstarts
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
designisnotallonpaper.Muchofitincludesdoingmodelsof
thecar,andtestingthemundercertainconditionstoseeifthey
work. The design is modified based on the testing results. The
carissenttoproductioneventually,andthepartsarecreatedand
assembledtogether.
S






Software development is similar. We can’t just sit down and
typecode.Wecandothat,anditworkswellfortrivialcases.
Butwecannotcreatecomplexsoftwarelikethat.
In order to create good software, you have to know what that
software is all about. You cannot create a banking software
systemunlessyouhaveagoodunderstandingofwhatbankingis
allabout,onemustunderstandthedomainofbanking.
Isitpossibletocreatecomplexbankingsoftwarewithoutgood
domainknowledge?Noway.Never.Whoknowsbanking?The
softwarearchitect?No.Hejustusesthebanktokeephismoney
safe and available when he needs them. The software analyst?

Notreally.Heknowstoanalyzeagiventopic,whenheisgiven
all the necessary ingredients. The developer? Forget it. Who
then?Thebankers,ofcourse.Thebankingsystemisverywell
understoodbythepeopleinside,bytheirspecialists.Theyknow
allthedetails,allthecatches,allthepossibleissues,alltherules.
Thisiswhereweshouldalwaysstart:thedomain.
When we begin a software project, we should focus on the
domainitisoperatingin.Theentirepurposeofthesoftwareisto
enhancea specific domain. To be ableto do that, the software
hastofitharmoniouslywiththedomainithasbeencreatedfor.
Otherwise it will introduce strain into the domain, provoking
malfunction,damage,andevenwreakchaos.

How can we make the software fit harmoniously with the
domain?Thebestwaytodoitistomakesoftwareareflectionof
thedomain.Softwareneedstoincorporatethecoreconceptsand
elementsofthedomain,andtopreciselyrealizetherelationships
betweenthem.Softwarehastomodelthedomain.
Somebodywithoutknowledgeofbankingshouldbeabletolearn
a lot just by reading the code in a domain model. This is
essential.Softwarewhichdoesnothaveitsrootsplanteddeeply
intothedomainwillnotreactwelltochangeovertime.
Sowestartwiththedomain.Thenwhat?Adomainissomething
of this world. It cannot just be taken and poured over the
K

NOW
Y
OUR
D
OMAIN
│5


keyboardintothecomputertobecomecode.Weneedtocreate
an abstraction of the domain. We learn a lot about a domain
whiletalkingwiththedomainexperts.Butthisrawknowledgeis
not going to be easily transformed into software constructs,

unlesswebuildanabstractionofit,ablueprintinourminds.In
the beginning, the blueprint always incomplete. But in time,
whileworkingonit,wemakeitbetter,anditbecomesmoreand
morecleartous.Whatisthisabstraction?Itisamodel,amodel
ofthedomain.AccordingtoEricEvans,adomainmodelisnota
particulardiagram;itistheideathatthediagramisintendedto
convey.Itisnotjusttheknowledgeinadomainexpert’shead;it
is a rigorously organized and selective abstraction of that
knowledge.Adiagramcanrepresentandcommunicateamodel,
ascancarefullywrittencode,ascananEnglishsentence.”
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
andmakelotsofreferencestothemodel.Theworldaroundusis
waytoomuchforourheadstohandle.Evenaspecificdomain
couldbemorethanahumanmindcanhandleatonetime.We
needtoorganizeinformation,tosystematizeit,todivideitupin
smallerpieces, to group those piecesintological modules, and
takeoneatatimeanddealwithit.Weevenneedtoleavesome
parts of the domain out. A domain contains just too much
informationtoincludeitallintothemodel.Andmuchofitisnot
even necessary to be considered. This is a challenge by itself.
Whatto keepandwhatto throw away? It’s part of the design,
thesoftwarecreationprocess.Thebankingsoftwarewillsurely

keeptrackofthecustomer’saddress,butitshouldnotcareabout
the customer’s eye color. That is an obvious case, but other
examplesmightnotbesoobvious.
A model is an essentialpart of software design. We need it in
order to be able to deal with complexity. All our thinking
processaboutthedomainissynthesizedintothismodel.That’s
good,butithastocomeoutofourhead.Itisnotveryusefulifit
remainsinthere,isit?Weneedtocommunicatethismodelwith
domainexperts,withfellowdesigners,andwithdevelopers.The





modelistheessenceofthesoftware,butweneedtocreateways
toexpressit,tocommunicateitwithothers.Wearenotalonein
this process, so we need to share knowledge and information,
and we need to do it well, precisely, completely, and without
ambiguity.Therearedifferentwaystodothat.Oneisgraphical:
diagrams,usecases,drawings,pictures,etc.Anotheriswriting.
We write down our vision about the domain. Another is
language. We can and we should create a language to
communicatespecificissuesaboutthedomain.Wewilldetailall
these later, but the main point is that we need to communicate
themodel.

When we have a model expressed, we can start doing code
design.Thisisdifferentfromsoftwaredesign.Softwaredesign
is like creating the architecture of a house, it’s about the big
picture.Ontheotherhand,codedesignisworkingonthedetails,
likethelocationofapaintingonacertainwall.Codedesignis
alsoveryimportant,butnotasfundamentalassoftwaredesign.
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
differentthingtoteardownonesideofthehouseinordertodo
it differently. Nonetheless the final product won’t be good
without good code design. Here code design patterns come

handy,andtheyshouldbeappliedwhennecessary.Goodcoding
techniqueshelptocreateclean,maintainablecode.
There are different approaches to software design. One is the
waterfall design method. This method involves a number of
stages.Thebusinessexpertsputupasetofrequirementswhich
arecommunicatedtothebusinessanalysts.Theanalystscreatea
modelbased on those requirements,and pass the results to the
developers,whostartcodingbasedonwhattheyhavereceived.
It’s a one way flow of knowledge. While this has been a
traditionalapproachinsoftwaredesign,andhasbeenusedwitha
certainlevelofsuccessovertheyears,ithasitsflawsandlimits.
Themainproblemisthatthereisnofeedbackfromtheanalysts

tothebusinessexpertsorfromthedeveloperstotheanalysts.
K
NOW
Y
OUR
D
OMAIN
│7


AnotherapproachistheAgilemethodologies,suchasExtreme
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,particularlyin light of requirementschange. 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
youforeseesomeofthenegativesideeffectsormistakesofyour
design.AnotherproblemAgileattemptstosolveisthesocalled
“analysisparalysis”,withteammemberssoafraidofmakingany
designdecisionsthattheymakenoprogressatall.WhileAgile
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,thedevelopmentteamgetstolearn moreaboutthe
customerdomainandcanbetterproducesoftwarethatmeetsthe
customersneeds.
The Agile methods have their own problems and limitations;
theyadvocate simplicity, but everybody has their own view of
what that means. Also, continuous refactoring done by
developerswithoutsoliddesignprincipleswillproducecodethat
is hard to understand or change. And while the waterfall
approach may lead to over-engineering, the fear of over-
engineeringmayleadtoanotherfear:thefearofdoingadeep,

thoroughlythoughtoutdesign.
This book presents the principles of domain driven design,
which when applied can great increase any development
processesabilitytomodelandimplementthecomplexproblems
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
feedbackcomingfromthedevelopmentprocesswillenhancethe
design.






BuildingDomainKnowledge

Let’sconsiderthe exampleof anairplaneflight controlsystem
project,andhowdomainknowledgecanbebuilt.
Thousandsofplanesareintheairatagivenmomentalloverthe
planet. They are flying their own paths towards their
destinations,anditisquiteimportanttomakesuretheydonot
collideintheair.Wewon’ttrytoelaborateontheentiretraffic
control system, but on a smaller subset which is a flight

monitoringsystem.Theproposedprojectisamonitoringsystem
which tracks every flight over a certain area, determines if the
flight follows its supposed route or not, and if there is the
possibilityofacollision.
Wheredowestartfromasoftwaredevelopmentperspective?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.Butthecontrollersarenotsystemdesignersorsoftware
specialists. You can’t expect them to hand you a complete
descriptionoftheirproblemdomain.
The air traffic controllers have vast knowledge about their

domain,butinordertobeabletobuildupamodelyouneedto
extract essential information and generalize it. When you start
talkingtothem,youwillhearalotaboutaircraftstakingoff,and
landing, aircrafts in midair and the danger of collision, planes
waitingbeforebeingallowedtoland,etc.Tofindorderinthis
seemingly chaotic amount of information, we need to start
somewhere.
The controller and you agree that each aircraft has a departure
andadestinationairfield.Sowehaveanaircraft,adepartureand
adestination,asshowninthefigurebelow.
K
NOW

Y
OUR
D
OMAIN
│9



OK, the plane takes off from some place and touches down in
another.Butwhathappensintheair?Whatpathofflightdoesit
go?Actuallywearemoreinterestedinwhathappenswhileitis
airborn.Thecontrollersaysthateachplaneisassignedaflight

plan which is supposed to describe the entire air travel. While
hearingaboutaflightplan,youmaythinkinyourmindthatthis
is about the path followed by the plane while in the air. After
further discussion, you hear an interesting word: route. It
instantlycatchesyourattention,andforagoodreason.Theroute
contains an important concept of flight travel. That’s what
planesdowhileflying,theyfollowaroute.Itisobviousthatthe
departure and destination points of the aircraft are also the
startingandendingpointsoftheroute.So,insteadofassociating
the aircraft with the departure and destination points, it seems
more natural to associate it with a route, which in turn is
associatedwiththecorrespondingdepartureanddestination.

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,whichputtogetherconstitutesomesortofacrooked
linefromdeparturetodestination.Thelineissupposedtopass
through predetermined fixed points. So, a route can be
considered a series of consecutive fixes. At this point you no

longerseethedepartureanddestinationastheterminalpointsof
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
basedonthesediscoveriesare:
Thediagramshows another element, the fact that eachfix is a
point in space followed by the route, and it is expressed as a
threedimensionalpoint.Butwhenyoutalktothecontroller,you
willdiscoverthathedoesnotseeitthatway.Actuallyhesees
therouteastheprojectiononearthoftheplaneflight.Thefixes
are just points on Earth surface uniquely determined by their
latitudeandlongitude.Sothecorrectdiagramis:

Aircraft

Route

Fix

*

3DPoint

K
NOW

Y
OUR
D
OMAIN
│11



What is actually happening here? You and thedomain experts
are talking, you are exchanging knowledge. You start asking
questions, and they respond. While they do that, they dig
essentialconceptsoutof theairtrafficdomain.Thoseconcepts

maycomeoutunpolishedanddisorganized,butnonethelessthey
areessentialforunderstandingthedomain.Youneedtolearnas
much as possible about the domain from the experts. And by
puttingtherightquestions,andprocessingtheinformationinthe
rightway,youandtheexpertswillstarttosketchaviewofthe
domain, a domain model. This view is neither complete nor
correct,butitisthestartyouneed.Trytofigureouttheessential
conceptsofthedomain.
This is animportant 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

transformitintoausefulform.Atsomepoint,theymightwant
to create an early prototype to see how it works so far. While
doingthattheymayfindsomeissueswiththeirmodel,ortheir
approach, and may want to change the model. The
communicationisnotonlyoneway,fromthedomainexpertsto
thesoftwarearchitectandfurthertothedevelopers.Thereisalso
feedback, which helps create a better model, and aclearer and
more correct understanding of the domain. Domain experts
knowtheirareaofexpertisewell,buttheyorganizeandusetheir
knowledgeinaspecificway,whichisnotalwaysthebesttobe
implementedintoasoftwaresystem.Theanalyticalmindofthe
softwaredesignerhelpsunearthsomeofthekeyconceptsofthe

Aircraft

Route

Fix

*

2DPoint






domain during discussions with domain experts, and also help
constructastructureforfuturediscussionsaswewillseeinthe
next chapter. We, the software specialists (software architects
anddevelopers)andthedomainexperts,arecreatingthemodel
ofthedomaintogether,andthemodelistheplacewherethose
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
problemsinareallifedomain,soithastoblendperfectlywith
thedomain.

2

13

FreeOnlineVersion.
Supportthiswork,buytheprintcopy:
/>
TheUbiquitousLanguage

TheNeedforaCommonLanguage

hepreviouschaptermadethecasethatitisabsolutelynecessary

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
mindsfullofclasses,methods,algorithms,patterns,andtendto
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
thinkintermsofinheritance,polymorphism,OOP,etc.Andthey
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
evendatabases.Theyknowabouttheirspecificareaofexpertise.
Inthe airtrafficmonitoringexample,thedomainexpertsknow
about planes, about routes, altitudes, longitudes and latitudes,
theyknowaboutdeviancesfromthenormalroute, about plane
trajectories.Andtheytalkaboutthosethingsintheirownjargon,
which sometimes is not so straightforward to follow by an
outsider.
T






To overcome this difference in communication style, when we
buildthemodel,wemustcommunicatetoexchangeideasabout
the model, about the elements involved in the model, how we
connectthem,whatisrelevantandwhatisnot.Communication
atthis levelis paramount for the successof the project. If one
says something, and the other does not understand or, even
worse,understandssomethingelse,whatarethechancesforthe
projecttosucceed?
A project faces serious problems when team members don’t
share a common language for discussing the domain. Domain

expertsusetheirjargonwhiletechnicalteammembershavetheir
own language tuned for discussing the domain in terms of
design.
Theterminologyofday-to-daydiscussionsisdisconnectedfrom
the terminology embedded in the code (ultimately the most
important product of a software project). And even the same
personusesdifferentlanguageinspeechandinwriting,sothat
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
usedtolettheothersunderstandwhatsomeconceptsareabout.

Developers might try to explain some design patterns using a
layman’slanguage,andsometimeswithoutsuccess.Thedomain
expertswillstrivetobringhomesomeoftheirideasprobablyby
creating a new jargon. During this process communication
suffers,andthiskindoftranslationdoesnothelptheknowledge
buildingprocess.
We tend to use our own dialects during these design sessions,
but none of these dialects can be a common language because
noneserveseveryone’sneeds.
Wedefinitelyneedtospeakthesamelanguagewhenwemeetto
talkaboutthemodelandtodefineit.Whatlanguageisitgoing
to be? The developers’ language? The domain experts’

language?Somethinginbetween?
C
REATE
A

L
ANGUAGE
│15


A core principle of domain-driven design is to use a language
basedonthemodel.Sincethemodelisthecommonground,the

placewherethesoftwaremeetsthedomain,it isappropriateto
useitasthebuildinggroundforthislanguage.
Usethemodelasthebackboneof alanguage.Requestthatthe
team use the language consistently in all communications, and
alsoin the code.Whilesharing knowledge and hammeringout
the model, the team uses speech, writing and diagrams. Make
surethislanguageappearsconsistentlyinallthecommunication
forms used bythe team; for this reason, the language is called
theUbiquitousLanguage.
The Ubiquitous Language connects all the parts of the design,
andcreatesthepremiseforthedesignteamto functionwell.It
takesweeksandevenmonthsforlargescaleprojectdesignsto

takeshape.Theteammembersdiscoverthatsomeoftheinitial
conceptswereincorrectorinappropriatelyused,ortheydiscover
newelementsofthedesignwhichneedtobeconsideredandfit
into the overall design. All this is not possible without a
commonlanguage.
Languagesdonotappearovernight.Ittakeshardworkandalot
offocustomakesurethatthekeyelementsofthelanguageare
brought to light. We need to find those key concepts which
definethedomainandthedesign,andfindcorrespondingwords
forthem,andstartusingthem.Someofthemareeasilyspotted,
butsomeareharder.
Iron out difficulties by experimenting with alternative

expressions,whichreflectalternativemodels.Thenrefactorthe
code,renamingclasses,methods,andmodulestoconformtothe
new model. Resolve confusion over terms in conversation, in
just the way we come to agree on the meaning of ordinary
words.
Buildingalanguagelikethathasaclearoutcome:themodeland
the language are strongly interconnected with one another. A
changeinthelanguageshouldbecomeachangetothemodel.





Domain experts should object to terms or structures that are
awkward or inadequate to convey domain understanding. If
domainexpertscannotunderstandsomethinginthemodelorthe
language,thenitismostlikelythatthereissomethingiswrong
with it. On the other hand, developers should watch for
ambiguityorinconsistencythatwilltendtoappearindesign.

CreatingtheUbiquitousLanguage

Howcanwe start buildingalanguage?  Hereis a hypothetical
dialogbetweenasoftwaredeveloperandadomainexpertinthe
airtrafficmonitoringproject.Watchoutforthewordsappearing

inboldface.
Developer:Wewanttomonitorairtraffic.Wheredowestart?
Expert:Let’sstartwiththebasics.Allthistrafficismadeupof
planes.Eachplanetakesofffromadepartureplace,andlands
atadestinationplace.
Developer:That’seasy.Whenitflies,theplanecanjustchoose
anyairpaththepilotslike?Isituptothemtodecidewhichway
theyshouldgo,aslongastheyreachdestination?
Expert: Oh, no. The pilots receive a route they must follow.
Andtheyshouldstayonthatrouteascloseaspossible.
Developer:I’mthinkingofthisrouteasa3Dpathintheair.If
we use a Cartesian system of coordinates, then the route is

simplyaseriesof3Dpoints.
Expert: I don’t think so. We don’t see route that way. The
routeisactuallytheprojectiononthegroundoftheexpectedair
pathoftheairplane.Theroutegoesthroughaseriesofpointson
thegrounddeterminedbytheirlatitudeandlongitude.
C
REATE
A

L
ANGUAGE
│17



Developer: OK, then let’s call each of those points a fix,
becauseit’safixedpointofEarth’ssurface.Andwe’llusethen
aseriesof2Dpointstodescribethepath.And,bytheway,the
departure and destination are just fixes. We should not
consider them as separate concepts. The route reaches
destinationasitreachesanyotherfix.Theplanemustfollowthe
route,but doesthatmeanthatitcanflyashighoraslowasit
likes?
Expert:No.Thealtitudethatanairplaneistohaveatacertain
momentisalsoestablishedintheflightplan.

Developer:Flightplan?Whatisthat?
Expert:Beforeleavingtheairport,thepilotsreceiveadetailed
flight plan which includes all sorts of information about the
flight: the route, cruise altitude, the cruise speed, the type of
airplane,eveninformationaboutthecrewmembers.
Developer:Hmm,theflightplanseemsprettyimportanttome.
Let’sincludeitintothemodel.

Aircraft FlightPlan Route
Fix
2DPoint

×