Upload
saravanakumarnm
View
225
Download
0
Embed Size (px)
Citation preview
8/11/2019 Pattern Summaries Under Creative Commons
1/40
Domain-Driven Design
Pattern Summaries
Excerpted from Domain-Driven Design: Tackling Complexity in the
Heart of Software, y Eric Evans, !ddison-"esley #$$%&
This doc'ment is distri'ted 'nder the Creative Commons Deed: !ttri'tion#&$&
(o' are free:
to copy, distri'te, display, and perform the work
to make derivative works
to make commercial 'se of the work
)nder the following conditions: !ttri'tion
You must give the original author credit with the following attribution:
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans,
!!"#
*or any re'se or distri'tion, yo' m'st make clear to others the license terms of
this work&
!ny of these conditions can e waived if yo' get permission from the copyright
holder&
*or the f'll text of the license, see the following we sites:
http:++creativecommons&org+licenses+y+#&$+
http:++creativecommons&org+licenses+y+#&$+legalcode
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
http://creativecommons.org/licenses/by/2.0/http://creativecommons.org/licenses/by/2.0/http://creativecommons.org/licenses/by/2.0/legalcodehttp://creativecommons.org/licenses/by/2.0/http://creativecommons.org/licenses/by/2.0/legalcode8/11/2019 Pattern Summaries Under Creative Commons
2/40
Part %
Putting the &odel 'o Wor(
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
3/40
UBIQUITOUSLANGUAGE
To create a supple, knowledge-rich design calls for a versatile, shared team language, and a lively
experimentation with language that seldom happens on software projects.
! proect faces serio's prolems when its lang'age is fract'red& Domain experts 'se their argon while
technical team memers have their own lang'age t'ned for disc'ssing the domain in terms of design&
The terminology of day-to-day disc'ssions is disconnected from the terminology emedded in the code'ltimately the most important prod'ct of a software proect.& !nd even the same person 'ses different
lang'age in speech and in writing, so that the most incisive expressions of the domain often emerge in a
transient form that is never capt'red in the code or even in writing&
Translation l'nts comm'nication and makes knowledge cr'nching anemic&(et none of these dialects can e a common lang'age eca'se none serves all needs&
Therefore:
)se the model as the bac(bone of a language# $ommit the team to e*ercising that language
relentlessly in all communication within the team and in the code# )se the same language in
diagrams, writing, and es+ecially s+eech#
%ron out difficulties by e*+erimenting with alternative e*+ressions, which reflect alternative
models# 'hen refactor the code, renaming classes, methods, and modules to conform to the new
model# esolve confusion over terms in conversation, in ust the way we come to agree on the
meaning of ordinary words#
ecogni.e that a change in the language is a change to the model#
Domain e*+erts should obect to terms or structures that are aw(ward or inade/uate to convey
domain understanding0 develo+ers should watch for ambiguity or inconsistency that will tri+ u+
design#
With a )1%2)%'3)S4A56)A6E, the model is not ust a design artifact# %t becomes integral to
everything the develo+ers and domain e*+erts do together#
!lso,
Play with the model as you tal( about the system# Describe scenarios out loud using the elements
and interactions of the model, combining conce+ts in ways allowed by the model# 7ind easier ways
to say what you need to say, and then ta(e those new ideas bac( down to the diagrams and code#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
4/40
MODEL-DRIVENDESIGN
Tightly relating the code to an underlying model gives the code meaning and makes the model relevant.
/f the design, or some central part of it, does not map to the domain model, that model is of little val'e,
and the correctness of the software is s'spect& !t the same time, complex mappings etween modelsand design f'nctions are diffic'lt to 'nderstand and, in practice, impossile to maintain as the design
changes& ! deadly divide opens etween analysis and design so that insight gained in each of those
activities does not feed into the other&
Therefore,
Design a +ortion of the software system to reflect the domain model in a very literal way, so that
ma++ing is obvious# evisit the model and modify it to be im+lemented more naturally insoftware, even as you see( to ma(e it reflect dee+er insight into the domain# Demand a single
model that serves both +ur+oses well, in addition to su++orting a fluent )1%2)%'3)S4A56)A6E#
Draw from the model the terminology used in the design and the basic assignment of
res+onsibilities# 'he code becomes an e*+ression of the model, so a change to the code may be a
change to the model# %ts effect must ri++le through the rest of the +roect8s activities accordingly#
'o tie the im+lementation slavishly to a model usually re/uires software develo+ment tools and
languages that su++ort a modeling +aradigm, such as obect-oriented +rogramming#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
5/40
HANDS-ONMODELERS
/f the people who write the code do not feel responsile for the model, or don0t 'nderstand how to makethe model work for an application, then the model has nothing to do with the software& /f developersdon0t reali1e that changing code changes the model, then their refactoring will weaken the model rather
than strengthen it& 2eanwhile, when a modeler is separated from the implementation process, he or she
never ac3'ires, or 3'ickly loses, a feel for the constraints of implementation& The asic constraint of24DE5-D6/7E8DES/98that the model s'pports an effective implementation and astracts key insightsinto the domainis half-gone, and the res'lting models will e impractical& *inally, the knowledge and
skills of experienced designers won0t e transferred to other developers if the division of laor prevents
the kind of collaoration that conveys the s'tleties of coding a 24DE5-D6/7E8DES/98&
Therefore,
Any technical +erson contributing to the model must s+end some time touching the code,
whatever +rimary role he or she +lays on the +roect# Anyone res+onsible for changing code must
learn to e*+ress a model through the code# Every develo+er must be involved in some level of
discussion about the model and have contact with domain e*+erts# 'hose who contribute in
different ways must consciously engage those who touch the code in a dynamic e*change of model
ideas through the )1%2)%'3)S4A56)A6E#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
6/40
Part %%
1uilding 1loc(s of a &3DE4-D%9E5DES%65
These patterns cast widely held est practices of oect-oriented design in the light of domain-drivendesign& They g'ide decisions to clarify the model and to keep the model and implementation aligned
with each other, each reinforcing the other0s effectiveness& Caref'l crafting the details of individ'al
model elements gives developers a steady platform from which to apply the modeling approaches of
;arts /// and /7&
encapsulate with
MODEL-DRIVEN
DESIGN
ep!ess "#$el with
is#late $#"ain with
encapsulate with
ENTITIES
VALUE OBJECTS
LAYEREDARCHITECTURE
AGGREGATES
REPOSITORIES
act as !##t #%
SMART UI
X
FACTORIES
encapsulate with
ep!ess "#$el with
encapsulate with
"utuall& eclusi'e
ch#ices
access with
"aintain inte(!it& with
access withSERVICES
ep!ess "#$el with
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
7/40
LA)EREDAR*HITE*TURE
Applicatio
D
o!ai
I"#a$t#%ct%#&
U$
It"ac&
/n an oect-oriented program, )/, dataase, and other s'pport code often gets written directly into the'siness oects& !dditional 'siness logic is emedded in the ehavior of )/ widgets and dataase
scripts& This happens eca'se it is the easiest way to make things work, in the short r'n&
"hen the domain-related code is diff'sed thro'gh s'ch a large amo'nt of other code, it ecomes
extremely diffic'lt to see and to reason ao't& S'perficial changes to the )/ can act'ally change'siness logic& To change a 'siness r'le may re3'ire metic'lo's tracing of )/ code, dataase code, or
other program elements& /mplementing coherent, model-driven oects ecomes impractical& !'tomated
testing is awkward& "ith all the technologies and logic involved in each activity, a program m'st e
kept very simple or it ecomes impossile to 'nderstand&
Therefore,
Partition a com+le* +rogram into 4AYES# Develo+ a design within each 4AYEthat is cohesive
and that de+ends only on the layers below# 7ollow standard architectural +atterns to +rovideloose cou+ling to the layers above# $oncentrate all the code related to the domain model in one
layer and isolate it from the user interface, a++lication, and infrastructure code# 'he domain
obects, free of the res+onsibility of dis+laying themselves, storing themselves, managing
a++lication tas(s, and so forth, can be focused on e*+ressing the domain model# 'his allows a
model to evolve to be rich enough and clear enough to ca+ture essential business (nowledge and
+ut it to wor(#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
8/40
ENTITIES+A,AREEREN*EOB.E*TS/
Many objects are not fundamentally defined by their attributes, but rather by a thread of continuity and
identity.
Some oects are not defined primarily y their attri'tes& They represent a thread of identity that r'ns
thro'gh time and often across distinct representations& Sometimes s'ch an oect m'st e matched with
another oect even tho'gh attri'tes differ& !n oect m'st e disting'ished from other oects eventho'gh they might have the same attri'tes& 2istaken identity can lead to data corr'ption&
Therefore,
When an obect is distinguished by its identity, rather than its attributes, ma(e this +rimary to its
definition in the model# ee+ the class definition sim+le and focused on life cycle continuity and
identity# Define a means of distinguishing each obect regardless of its form or history# 1e alert to
re/uirements that call for matching obects by attributes# Define an o+eration that is guaranteed
to +roduce a uni/ue result for each obect, +ossibly by attaching a symbol that is guaranteed
uni/ue# 'his means of identification may come from the outside, or it may be an arbitrary
identifier created by and for the system, but it must corres+ond to the identity distinctions in the
model# 'he model must define what it meansto be the same thing#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
9/40
VALUEOB.E*TS
Many objects have no conceptual identity. These objects describe some characteristic of a thing.
Tracking the identity of E8T/T/ESis essential, 't attaching identity to other oects can h'rt system
performance, add analytical work, and m'ddle the model y making all oects look the same&Software design is a constant attle with complexity& "e m'st make distinctions so that special
handling is applied only where necessary&
However, if we think of this category of oect as 'st the asence of identity, we haven0t added m'ch to
o'r toolox or voca'lary& /n fact, these oects have characteristics of their own, and their ownsignificance to the model& These are the objects that describe things.
Therefore:
When you care only about the attributes of an element of the model, classify it as a 9A4)E31;E$'#
&a(e it e*+ress the meaning of the attributes it conveys and give it related functionality# 'reat the
9A4)E31;E$'as immutable# Don8t give it any identity and avoid the design com+le*ities
necessary to maintain E5'%'%ES#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
10/40
SERVI*ES
Sometimes, it just isnt a thing.
Some concepts from the domain aren0t nat'ral to model as oects& *orcing the re3'ired domain
f'nctionality to e the responsiility of an E8T/T(or 7!5)Eeither distorts the definition of a model-
ased oect or adds meaningless artificial oects&
Therefore:
When a significant +rocess or transformation in the domain is not a natural res+onsibility of an
E5'%'Yor 9A4)E31;E$', add an o+eration to the model as a standalone interface declared as aSE9%$E# Define the interface in terms of the language of the model and ma(e sure the o+eration
name is +art of the )1%2)%'3)S4A56)A6E# &a(e the SE9%$Estateless#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
11/40
MODULES+A,A 0A*,AGES/
Everyone 'ses 24D)5ES, 't few treat them as a f'll-fledged part of the model& Code gets roken downinto all sorts of categories, from aspects of the technical architect're to developers0 work assignments&Even developers who refactor a lot tend to content themselves with 24D)5ESconceived early in the
proect&
/t is a tr'ism that there sho'ld e low co'pling etween 24D)5ESand high cohesion within them&
Explanations of co'pling and cohesion tend to make them so'nd like technical metrics, to e 'dgedmechanically ased on the distri'tions of associations and interactions& (et it isn0t 'st code eing
divided into 24D)5ES, 't concepts& There is a limit to how many things a person can think ao't at
once hence low co'pling.& /ncoherent fragments of ideas are as hard to 'nderstand as an
'ndifferentiated so'p of ideas hence high cohesion.&
Therefore,
$hoose &3D)4ESthat tell the story of the system and contain a cohesive set of conce+ts# 'his
often yields low cou+ling between modules, but if it doesn8t loo( for a way to change the model to
disentangle the conce+ts, or an overloo(ed conce+t that might be the basis of a &3D)4Ethat
would bring the elements together in a meaningful way# See( low cou+ling in the sense of conce+ts
that can be understood and reasoned about inde+endently of each other# efine the model until it
+artitions according to high-level domain conce+ts and the corres+onding code is decou+led as
well#
6ive the &3D)4ESnames that become +art of the )1%2)%'3)S4A56)A6E# &3D)4ESand their
names should reflect insight into the domain#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
12/40
AGGREGATES
/t is diffic'lt to g'arantee the consistency of changes to oects in a model with complex associations&
/nvariants need to e maintained that apply to closely related gro'ps of oects, not 'st discrete oects&(et ca'tio's locking schemes ca'se m'ltiple 'sers to interfere pointlessly with each other and make a
system 'n'sale&
Therefore:
$luster the E5'%'%ESand 9A4)E31;E$'Sinto A66E6A'ESand define boundaries around each#
$hoose one E5'%'Yto be the root of each A66E6A'E, and control all access to the obects inside
the boundary through the root# Allow e*ternal obects to hold references to the root only#
'ransient references to internal members can be +assed out for use within a single o+eration only#
1ecause the root controls access, it cannot be blindsided by changes to the internals# 'his
arrangement ma(es it +ractical to enforce all invariants for obects in the A66E6A'Eand for the
A66E6A'Eas a whole in any state change#
!"ote# Many such schemes are possible. This section of the book describes one particular set of rules in
detail.$
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
13/40
A*TORIES
%hen creation of an object, or an entire&''()'&T), becomes complicated or reveals too much of the
internal structure,*&+T()Sprovide encapsulation.
Creation of an oect can e a maor operation in itself, 't complex assemly operations do not fit the
responsiility of the created oects& Comining s'ch responsiilities can prod'ce 'ngainly designs that
are hard to 'nderstand& 2aking the client direct constr'ction m'ddies the design of the client, reachesencaps'lation of the assemled oect or !996E9!TE, and overly co'ples the client to the
implementation of the created oect&
Therefore,Shift the res+onsibility for creating instances of com+le* obects and A66E6A'ESto a se+arate
obect, which may itself have no res+onsibility in the domain model but is still +art of the domain
design# Provide an interface that enca+sulates all com+le* assembly and that does not re/uire the
client to reference the concrete classes of the obects being instantiated# $reate entire
A66E6A'ESas a +iece, enforcing their invariants#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
14/40
RE0OSITORIES
! client needs a practical means of ac3'iring references to preexisting domain oects& /f the
infrastr'ct're makes it easy to do so, the developers of the client may add more traversale associations,m'ddling the model& 4n the other hand, they may 'se 3'eries to p'll the exact data they need from the
dataase, or to p'll a few specific oects rather than navigating from !996E9!TEroots& Domain logic
moves into 3'eries and client code, and the E8T/T/ESand 7!5)E4
8/11/2019 Pattern Summaries Under Creative Commons
15/40
Part %%%
efactoring 'oward Dee+er %nsight
)sing a proven set of asic 'ilding locks along with consistent lang'age rings some sanity to the
development effort& This leaves the challenge of act'allyfindingan incisive model, one that capt'res
s'tle concerns of the domain experts and can drive a practical design& ! model that slo'ghs off thes'perficial and capt'res the essential is a deep model& This sho'ld make the software more in t'ne with
the way the domain experts think and more responsive to the 'ser0s needs&
Traditionally, refactoring is descried in terms of code transformations with technical motivations&
6efactoring can also e motivated y an insight into the domain and a corresponding refinement of themodel or its expression in code&
Sophisticated domain models are seldom developed except thro'gh an iterative process of refactoring,
incl'ding close involvement of the domain experts with developers interested in learning ao't the
domain&
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
16/40
Supple Desi(n
To have a proect accelerate as development proceedsrather than get weighed down y its own legacy
demands a design that is a pleas're to work with, inviting to change& ! s'pple design&
S'pple design is the complement to deep modeling&
Developers play two roles, each of which m'st e served y the design& The same person might well
play oth roleseven switch ack and forth in min'tes't the relationship to the code is differentnonetheless& 4ne role is the developer of a client, who weaves the domain oects into the application
code or other domain layer code, 'tili1ing capailities of the design& ! s'pple design reveals a deep
'nderlying model that makes its potential clear& The client developer can flexily 'se a minimal set of
loosely co'pled concepts to express a range of scenarios in the domain& Design elements fit together ina nat'ral way with a res'lt that is predictale, clearly characteri1ed, and ro'st&
E3'ally important, the design m'st serve the developer working to change it& To e open to change, a
design m'st e easy to 'nderstand, revealing thatsame'nderlying model that the client developer is
drawing on& /t m'st follow the conto'rs of a deep model of the domain, so most changes end thedesign at flexile points& The effects of its code m'st e transparently ovio's, so the conse3'ences of a
change will e easy to anticipate&
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
17/40
Ma'i( B&)a*io# O+*io%$
INTENTION-REVEALINGINTERA*ES
/f a developer m'st consider the implementation of a component in order to 'se it, the val'e of
encaps'lation is lost& /f someone other than the original developer m'st infer the p'rpose of an oect oroperation ased on its implementation, that new developer may infer a p'rpose that the operation or
class f'lfills only y chance& /f that was not the intent, the code may work for the moment, 't the
concept'al asis of the design will have een corr'pted, and the two developers will e working at
cross-p'rposes&
Therefore,
5ame classes and o+erations to describe their effect and +ur+ose, without reference to the means
by which they do what they +romise# 'his relieves the client develo+er of the need to understandthe internals# 'hese names should conform to the )1%2)%'3)S4A56)A6Eso that team members
can /uic(ly infer their meaning# Write a test for a behavior before creating it, to force your
thin(ing into client develo+er mode#
SIDE-EE*T-REEUN*TIONS
/nteractions of m'ltiple r'les or compositions of calc'lations ecome extremely diffic'lt to predict& The
developer calling an operation m'st 'nderstand its implementation and the implementation of all itsdelegations in order to anticipate the res'lt& The 'sef'lness of any astraction of interfaces is limited if
the developers are forced to pierce the veil& "itho't safely predictale astractions, the developers m'st
limit the cominatory explosion, placing a low ceiling on the richness of ehavior that is feasile to
'ild&
Therefore:
Place as much of the logic of the +rogram as +ossible into functions, o+erations that return results
with no observable side effects# Strictly segregate commands
8/11/2019 Pattern Summaries Under Creative Commons
18/40
ASSERTIONS
"hen the side effects of operations are only defined implicitly y their implementation, designs with a
lot of delegation ecome a tangle of ca'se and effect& The only way to 'nderstand a program is to traceexec'tion thro'gh ranching paths& The val'e of encaps'lation is lost& The necessity of tracing concrete
exec'tion defeats astraction&
Therefore,
State +ost-conditions of o+erations and invariants of classes and A66E6A'ES# %f ASSE'%35S
cannot be coded directly in your +rogramming language, write automated unit tests for them#
Write them into documentation or diagrams where it fits the style of the +roect8s develo+ment
+rocess#
See( models with coherent sets of conce+ts, which lead a develo+er to infer the intended
ASSE'%35S, accelerating the learning curve and reducing the ris( of contradictory code#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
19/40
R&,%ci( Co$t o" C)a(&
*ON*E0TUAL*ONTOURS
Sometimes people chop functionality fine to allow flexible combination. Sometimes they lump it large to
encapsulate complexity. Sometimes they seek a consistent granularity, making all classes andoperations to a similar scale. These are oversimplifications that dont work well as general rules. ut
they are motivated by a basic set of problems.
"hen elements of a model or design are emedded in a monolithic constr'ct, their f'nctionality getsd'plicated& The external interface doesn0t say everything a client might care ao't& Their meaning is
hard to 'nderstand, eca'se different concepts are mixed together&
4n the other hand, reaking down classes and methods can pointlessly complicate the client, forcing
client oects to 'nderstand how tiny pieces fit together& "orse, a concept can e lost completely& Halfof a 'rani'm atom is not 'rani'm& !nd of co'rse, it isn0t 'st grain si1e that co'nts, 't 'st where the
grain r'ns&
Therefore:
Decom+ose design elements
8/11/2019 Pattern Summaries Under Creative Commons
20/40
STANDALONE*LASSES
Even within a 24D)5E, the diffic'lty of interpreting a design increases wildly as dependencies areadded& This adds to mental overload, limiting the design complexity a developer can handle& /mplicitconcepts contri'te to this load even more than explicit references&
4ow cou+ling is fundamental to obect design# When you can, go all the way# Eliminate allother
conce+ts from the +icture# 'hen the class will be com+letely self-contained and can be studied and
understood alone# Every such self-contained class significantly eases the burden of understanding
a &3D)4E#
*LOSUREOO0ERATIONS
2ost interesting oects end 'p doing things that can0t e characteri1ed y primitives alone&
Therefore:
Where it fits, define an o+eration whose return ty+e is the same as the ty+e of its argument
8/11/2019 Pattern Summaries Under Creative Commons
21/40
D&cla#ati*& D&$i(There can e no real g'arantees in handwritten software& To name 'st one way of evading !SSE6T/48S,code co'ld have additional side effects that were not specifically excl'ded& 8o matter how 24DE5-
D6/7E8o'r design is, we still end 'p writing proced'res to prod'ce the effect of the concept'alinteractions& !nd we spend so m'ch of o'r time writing oilerplate code that doesn0t really add any
meaning orehavior& /8TE8T/48-6E7E!5/89/8TE6*!CESand the other patterns in this chapter help, 'tthey can never give conventional oect-oriented programs formal rigor&
These are some of the motivations ehind declarative design& This term means many things to many
people, 't 's'ally it indicates a way to write a program, or some part of a program, as a kind of
exec'tale specification& ! very precise description of properties act'ally controls the software& /n its
vario's forms, this co'ld e done thro'gh a reflection mechanism or at compile time thro'gh codegeneration prod'cing conventional code a'tomatically, ased on the declaration.& This approach allows
another developer to take the declaration at face val'e& /t is an asol'te g'arantee&
2any declarative approaches can e corr'pted if the developers ypass them intentionally or
'nintentionally& This is likely when the system is diffic'lt to 'se or overly restrictive& Everyone has to
follow the r'les of the framework in order to get the enefits of a declarative program&&
A D&cla#ati*& Stl& o" D&$i(4nce yo'r design has /8TE8T/48-6E7E!5/89/8TE6*!CES, S/DE-E**ECT-*6EE*)8CT/48S, and!SSE6T/48S, yo' are edging into declarative territory& 2any of the enefits of declarative design are
otained once yo' have cominale elements that comm'nicate their meaning, and have characteri1ed
or ovio's effects, or no oservale effects at all&
! s'pple design can make it possile for the client code to 'se a declarativestyleof design& To
ill'strate, the next section will ring together some of the patterns in this chapter to make theS;EC/*/C!T/48more s'pple and declarative&
D#a.i( o E$ta+li$)&, Fo#!ali$!$
Creating a tight concept'al framework from scratch is something yo' can0t do every day& Sometimesyo' discover and refine one of these over the co'rse of the life of a proect&
8/11/2019 Pattern Summaries Under Creative Commons
22/40
Part %9
Strategic Design
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
23/40
Maintainin( M#$el Inte(!it&
CONTEXTMAP
#'e!lap allie$ c#ntets th!#u(h
#'e!lap unilate!all& as
supp#!t "ultiple
clients th!#u(h
%#!"ali1e as
CONTINUOUS
INTEGRATION
CUSTOMER/
SUPPLIER
TEAMS
CONFORMIST
OPEN HOST
SERVICE
SEPARATE
0AYS
PUBLISHED
LANGUAGE
SHARED
1ERNEL
!elate allie$ c#ntets as
%!ee tea"s t# (#
ANTICORRUPTION
LAYER
t!anslate an$ insulate
unilate!all& with
BOUNDED
CONTEXT
2eep "#$el uni%ie$ 3&
assess4#'e!'iew
!elati#nships with
UBI2UITOUS
LANGUAGE
na"es
ente!
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
24/40
BOUNDED*ONTE5T
2'ltiple models are in play on any large proect& (et when code ased on distinct models is comined,
software ecomes 'ggy, 'nreliale, and diffic'lt to 'nderstand& Comm'nication among team memers
ecomes conf'sed& /t is often 'nclear in what context a model sho'ld note applied&
Therefore:
E*+licitly define the conte*t within which a model a++lies# E*+licitly set boundaries in terms of
team organi.ation, usage within s+ecific +arts of the a++lication, and +hysical manifestations such
as code bases and database schemas# ee+ the model strictly consistent within these bounds, but
don8t be distracted or confused by issues outside#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
25/40
*ONTINUOUSINTEGRATION
nce a/"6)6+"T)7Thas been defined, we must keep it sound.
"hen a n'mer of people are working in the same
8/11/2019 Pattern Summaries Under Creative Commons
26/40
*ONTE5TMA0
Mo,&l i Cot&3t
Mo,&l i Cot&3t
T#a$latio
Map
&n individual/"6)6+"T)7Tleaves some problems in the absence of a global view. The context ofother models may still be vague and in flux.
;eople on other teams won0t e very aware of the context o'nds and will 'nknowingly make changesthat l'r the edges or complicate the interconnections& "hen connections m'st e made etween
different contexts, they tend to leed into each other&
Therefore:
%dentify each model in +lay on the +roect and define its 13)5DED$35'E>'# 'his includes the
im+licit models of non-obect-oriented subsystems# 5ame each 13)5DED$35'E>', and ma(e the
names +art of the )1%2)%'3)S4A56)A6E#Describe the +oints of contact between the models, outlining e*+licit translation for any
communication and highlighting any sharing#
&a+ the existingterrain# 'a(e u+ transformations later#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
27/40
SHARED,ERNEL
T!anslati#n
Map
$)a#&,
%hen functional integration is limited, the overhead of +"T"//S"T)'(&T"may be deemed too
high. This may especially be true when the teams do not have the skill or the political organi8ation tomaintain continuous integration, or when a single team is simply too big and unwieldy. So separate
/"6)6+"T)7TSmight be defined and multiple teams formed.
)ncoordinated teams working on closely related applications can go racing forward for a while, 't
what they prod'ce may not fit together& They can end 'p spending more on translation layers and
retrofitting than they wo'ld have onC48T/8)4)S
/8TE96!T/48
in the first place, meanwhiled'plicating effort and losing the enefits of a common )
8/11/2019 Pattern Summaries Under Creative Commons
28/40
subsystems commonly serve very different user communities, with different jobs, where different modelsmay be useful. The tool set may also be different, meaning that program code cannot be shared.
The freewheeling development of the 'pstream team can e cramped if the downstream team has veto
power over changes, or if proced'res for re3'esting changes are too c'mersome& The 'pstream teammay even e inhiited, worried ao't reaking the downstream system& 2eanwhile, the downstream
team can e helpless, at the mercy of 'pstream priorities&
Therefore:
Establish a clear customer?su++lier relationshi+ between the two teams# %n +lanning sessions,
ma(e the downstream team +lay the customer role to the u+stream team# 5egotiate and budget
tas(s for downstream re/uirements so that everyone understands the commitment and schedule#
;ointly develo+ automated acce+tance tests that will validate the interface e*+ected# Add these
tests to the u+stream team8s test suite, to be run as +art of its continuous integration# 'his testing
will free the u+stream team to ma(e changes without fear of side effects downstream#
*ONORMIST
"hen two development teams have an 'pstream+downstream relationship in which the 'pstream has nomotivation to provide for the downstream team0s needs, the downstream team is helpless& !ltr'ism may
motivate 'pstream developers to make promises, 't they are 'nlikely to e f'lfilled& 'Sby slavishly adhering to the
model of the u+stream team# Although this cram+s the style of the downstream designers and
+robably does not yield the ideal model for the a++lication, choosing $3573&%'Yenormously
sim+lifies integration# Also, you will share a )1%2)%'3)S4A56)A6Ewith your su++lier team# 'he
su++lier is in the driver8s seat, so it is good to ma(e communication easy for them# Altruism may
be sufficient to get them to share information with you#
ANTI*ORRU0TIONLA)ER
"ew systems almost always have to be integrated with legacy or other systems, which have their own
models. %hen control or communication is not ade5uate to pull off a S:&()6;)(")1or+/STM)(
8/11/2019 Pattern Summaries Under Creative Commons
29/40
"hen a new system is eing 'ilt that m'st have a large interface with another, the diffic'lty of relating
the two models can event'ally overwhelm the intent of the new model altogether, ca'sing it to e
modified to resemle the other system0s model, in an ad hoc fashion& The models of legacy systems are's'ally weak, and even the exception that is well developed may not fit the needs of the c'rrent proect&
(et there may e a lot of val'e in the integration, and sometimes it is an asol'te re3'irement&
Therefore:
$reate an isolating layer to +rovide clients with functionality in terms of their own domain model#
'he layer tal(s to the other system through its e*isting interface, re/uiring little or no
modification to the other system# %nternally, the layer translates in both directions as necessary
between the two models#
SE0ARATE6A)S
%e must be ruthless when it comes to defining re5uirements. f two sets of functionality have nosignificant relationship, they can be completely cut loose from each other.
/ntegration is always expensive, and sometimes the enefit is small&
Therefore:
Declare a 13)5DED$35'E>'to have no connection to the others at all, allowing develo+ers to
find sim+le, s+eciali.ed solutions within this small sco+e#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
30/40
O0ENHOSTSERVI*E
Typically for each/"6)6+"T)7T, you will define a translation layer for each component withwhich you have to integrate that is outside the +"T)7T. %here integration is one-off, this approach ofinserting a translation layer for each external system avoids corruption of the models with a minimum
of cost. ut when you find your subsystem in high demand, you may need a more flexible approach.
"hen a s'system has to e integrated with many others, c'stomi1ing a translator for each can og
down the team& There is more and more to maintain, and more and more to worry ao't when changes
are made&
Therefore:
Define a +rotocol that gives access to your subsystem as a set of SE9%$ES# 3+en the +rotocol so
that all who need to integrate with you can use it# Enhance and e*+and the +rotocol to handle newintegration re/uirements, e*ce+t when a single team has idiosyncratic needs# 'hen, use a one-off
translator to augment the +rotocol for that s+ecial case so that the shared +rotocol can stay sim+le
and coherent#
0UBLISHEDLANGUAGE
The translation between the models of two /"6)6+"T)7TSre5uires a common language.
Direct translation to and from the existing domain models may not e a good sol'tion& Those models
may e overly complex or poorly factored& They are proaly 'ndoc'mented& /f one is 'sed as a data
interchange lang'age, it essentially ecomes fro1en and cannot respond to new development needs&
Therefore:
)se a well-documented shared language that can e*+ress the necessary domain information as a
common medium of communication, translating as necessary into and out of that language#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
31/40
Distillati#n
James Clerk Maxwell,A T!eatise #n Elect!icit& an$
Ma(netis", 1873
These four equations, along with the definitions of theirterms and the bod of mathemati!s the rest on, ex"ress theentiret of !lassi!al nineteenth#!entur ele!tromagnetism$
How do yo' foc's on yo'r central prolem and keep from drowning in a sea of side iss'esB6istillationis the process of separating the components of a mixt're to extract the essence in a form
that makes it more val'ale and 'sef'l& ! model is a distillation of knowledge& "ith every refactoring to
deeper insight, we astract some cr'cial aspect of domain knowledge and priorities& 8ow, stepping ack
for a strategic view, this chapter looks at ways to disting'ish road swaths of the model and distill thedomain model as a whole&
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
32/40
*OREDOMAIN
/n designing a large system, there are so many contri'ting components, all complicated and all
asol'tely necessary to s'ccess, that the essence of the domain model, the real 'siness asset, can e
osc'red and neglected&
The harsh reality is that not all parts of the design are going to e e3'ally refined& ;riorities m'st e set&To make the domain model an asset, the critical core of that model has to e sleek and f'lly leveraged to
create application f'nctionality&
8/11/2019 Pattern Summaries Under Creative Commons
33/40
GENERI*SUBDOMAINS
Some parts of the model add complexity witho't capt'ring or comm'nicating speciali1ed knowledge&!nything extraneo's makes the C46ED42!/8harder to discern and 'nderstand& The model clogs 'pwith general principles everyone knows or details that elong to specialties which are not yo'r primary
foc's 't play a s'pporting role& (et, however generic, these other elements are essential to the
f'nctioning of the system and the f'll expression of the model&
Therefore:
%dentify cohesive subdomains that are not the motivation for your +roect# 7actor out generic
models of these subdomains and +lace them in se+arate &3D)4ES# 4eave no trace of your
s+ecialties in them#
3nce they have been se+arated, give their continuing develo+ment lower +riority than the $3E
D3&A%5, and avoid assigning your core develo+ers to the tas(s
8/11/2019 Pattern Summaries Under Creative Commons
34/40
HIGHLIGHTED*ORE
&6M&"2S"ST&T)M)"Tidentifies the +()6M&"in broad terms, but it leaves the identificationof the specific +()model elements up to the vagaries of individual interpretation. /nless there is anexceptionally high level of communication on the team, the 2S"ST&T)M)"Talone will have little
impact.
Even tho'gh team memers may know roadly what constit'tes the C46ED42!/8, different people
won0t pick o't 3'ite the same elements, and even the same person won0t e consistent from one day to
the next& The mental laor of constantly filtering the model to identify the key parts asors
concentration etter spent on design thinking, and it re3'ires comprehensive knowledge of the model&The C46ED42!/8m'st e made easier to see&
Significant str'ct'ral changes to the code are the ideal way of identifying the C46ED42!/8, 't they
are not always practical in the short term& /n fact, s'ch maor code changes are diffic'lt to 'ndertake
witho't the very view the team is lacking&
Therefore as one form of H/9H5/9HTEDC46E.:
Write a very brief document P
suggests#
!ltho'gh the 7/S/48ST!TE2E8Tand H/9H5/9HTEDC46Einform and g'ide, they do not act'ally modifythe model or the code itself& ;artitioning 9E8E6/CS)
8/11/2019 Pattern Summaries Under Creative Commons
35/40
*OHESIVEME*HANISMS
Comp'tations sometimes reach a level of complexity that egins to loat the design& The concept'al
>what? is swamped y the mechanistic >how&? ! large n'mer of methods that provide algorithms forresolving the prolem osc're the methods that express the prolem&
Therefore:
Partition a conce+tually $3CES%9E&E$CA5%S&into a se+arate lightweight framewor(#
Particularly watch for formalisms or well-documented categories of algorithms# E*+ose the
ca+abilities of the framewor( with an %5'E5'%35-E9EA4%56%5'E7A$E# 5ow the other elements
of the domain can focus on e*+ressing the +roblem
8/11/2019 Pattern Summaries Under Creative Commons
36/40
SEGREGATED*ORE
Elements in the model may partially serve the C46ED42!/8and partially play s'pporting roles& C46Eelements may e tightly co'pled to generic ones& The concept'al cohesion of the C46Emay not estrong or visile& !ll this cl'tter and entanglement chokes the C46E& Designers can0t clearly see the
most important relationships, leading to a weak design&
Therefore:
efactor the model to se+arate the $3Econce+ts from su++orting +layers
8/11/2019 Pattern Summaries Under Creative Commons
37/40
La!(e-Scale St!uctu!e
Thousands of people worked independently to create the &6S 0uilt.
/n a large system witho't any overarching principle that allows elements to e interpreted in terms of
their role in patterns that span the whole design, developers cannot see the forest for the trees."e need
to e ale to 'nderstand the role of an individ'al part in the whole witho't delving into the details of thewhole&
& >large-scale structure? is a language that lets you discuss and understand the system in broad
strokes.! set of high-level concepts or r'les, or oth, estalishes a pattern of design for an entire
system& This organi1ing principle can g'ide design as well as aid 'nderstanding& /t helps coordinateindependent work eca'se there is a shared concept of the ig pict're: how the roles of vario's parts
shape the whole&
Devise a +attern of rules or roles and relationshi+s that will s+an the entire system and that allows
some understanding of each +art8s +lace in the whole@even without detailed (nowledge of the
+art8s res+onsibility#
EVOLVINGORDER
Design free-for-alls prod'ce systems no one can make sense of as a whole, and they are very diffic'lt to
maintain&
8/11/2019 Pattern Summaries Under Creative Commons
38/40
S)STEMMETA0HOR
Metaphorical thinking is pervasive in software development, especially with models. ut the )xtreme=rogramming practice of >metaphor? has come to mean a particular way of using a metaphor to bringorder to the development of a whole system.
Software designs tend to e very astract and hard to grasp& Developers and 'sers alike need tangile
ways to 'nderstand the system and share a view of the system as a whole&
Therefore:
When a concrete analogy to the system emerges that ca+tures the imagination of team members
and seems to lead thin(ing in a useful direction, ado+t it as a large-scale structure# 3rgani.e the
design around this meta+hor and absorb it into the )1%2)%'3)S4A56)A6E# 'he SYS'E&
&E'APC3should both facilitate communication about the system and guide develo+ment of it#
'his increases consistency in different +arts of the system, +otentially even across different
13)5DED$35'E>'S# 1ut because all meta+hors are ine*act, continually ree*amine the meta+hor
for overe*tension or ina+tness, and be ready to dro+ it if it gets in the way#
RES0ONSIBILIT)LA)ERS
Throughout this book, individual objects have been assigned narrow sets of related responsibilities.
(esponsibility-driven design also applies to larger scales.
"hen each individ'al oect has handcrafted responsiilities, there are no g'idelines, no 'niformity,
and no aility to handle large swaths of the domain together& To give coherence to a large model, it is
'sef'l to impose some str'ct're on the assignment of those responsiilities&
Therefore:
4oo( at the conce+tual de+endencies in your model and the varying rates and sources of change
of different +arts of your domain# %f you identify natural strata in the domain, cast them as broad
abstract res+onsibilities# 'hese res+onsibilities should tell a story of the high-level +ur+ose and
design of your system# efactor the model so that the res+onsibilities of each domain obect,
A66E6A'E, and &3D)4Efit neatly within the res+onsibility of one layer#
Eric Evans,DOMAIN-DRIVEN DESIGN, Addison-Wesley, Eric Evans, !!"#
$reative $ommons Deed: Attribution #!
8/11/2019 Pattern Summaries Under Creative Commons
39/40
,NO6LEDGELEVEL
Ope!ati#nal Le'el
,n#wle$(e Le'el
Thin( T&pe
Thin(
Beha'i#!al
St!ate(&
S#"e
,n#wle(e
& group of objects that describe how another group of objects should behave !from Martin *owlers%eb site, www.martinfowler.com$
/n an application in which the roles and relationships etween E8T/T/ESvary in different sit'ations,complexity can explode& 8either f'lly general models nor highly c'stomi1ed ones serve the 'sers0
needs& 4ects end 'p with references to other types to cover a variety of cases, or with attri'tes that
are 'sed in different ways in different sit'ations& Classes that have the same data and ehavior may
m'ltiply 'st to accommodate different assemly r'les&
Therefore:
$reate a distinct set of obects that can be used to describe and constrain the structure and
behavior of the basic model# ee+ these concerns se+arate as two levels,B one very concrete, the
other reflecting rules and (nowledge that a user or su+er-user is able to customi.e#
0LUGGABLE*OM0ONENTRAME6OR,
pportunities arise in a very mature model that is deep and distilled. &=1/''&1)+M=")"T*(&M)%(;usually only comes into play after a few applications have already been implemented in thesame domain.
"hen a variety of applications have to interoperate, all ased on the same astractions 't designed
independently, translations etween m'ltiple
8/11/2019 Pattern Summaries Under Creative Commons
40/40
a++lication to use those com+onents, so long as it o+erates strictly through the interfaces of the
A1S'A$'$3E#