Tải bản đầy đủ - 0 (trang)
Chapter 16. Developing and Testing the Domain Model

Chapter 16. Developing and Testing the Domain Model

Tải bản đầy đủ - 0trang

16.1TheDomainModelLayer

Thedomainmodellayerrepresentsanabstractionofthebusiness

applicationproblemspace.Itformalizestheknowledgediscoveredabout

aparticularsubjectareaofinteresttothebusiness,andprovidesthe

foundationforthebusinessapplications.Apowerfuldomainmodel

focusesattentionontheproblembeingsolvedandimproves

communicationamongdevelopersandusersofthesystem.Establishing

asoliddomainmodelprovidesafoundationforincrementaldevelopment

andevolutionofsoftwaresystemsthatmorecloselysupportcustomer

needs.

EricEvansdefinesthedomainmodellayerasthatwhich"servesto

captureknowledge,enhancecommunication,andprovideadirectpathto

implementationandmaintenanceoffunctionalsoftware"[Evans].A

domainmodelstructuresknowledgeaboutaparticularsubjectareawhile

abstractingawayextraneousdetail.Thebusinessvalueofyour

applicationisderivedfromthislayer.

Inaseminalpaper[Brooks],FredBrooksoncemadeadistinction

between"essence"and"accidents"insoftwareengineering.The

essenceofaproblemiswhatmakesitintrinsicallyinterestingorhard.

Thismaybefindingtherightformulaforcalculatingavalue,or

developinganalgorithmtosolveacomplexproblemefficiently.Accidents

ofimplementationstemfrominadequatelanguagesortools,orfroma

limitedunderstandingofthecapabilitiesofthetoolsandlanguagesyou

have.

WewanttohandledomaincomplexityseparatelyfromITcomplexityin

ordertofocusontheproblemdomainandnottheimplementation

domain.Inotherwords,youwanttobeabletoconcentrateonthe

essenceofyourbusinessproblem,andnotoverlyconcernyourselfwith

theaccidentsofaparticularimplementationtechnology.

Tothisend,thespecificpurposesofthedomainmodelare:



Torigorouslyandunambiguouslycapture,maintain,andevolve

knowledgeaboutthebusinessproblemdomain;

Toprovideacommon,sharedlanguagetoenhancecommunication

abouttheproblemsbeingsolved;

Toprovideasolidfoundationfortheimplementationand

maintenanceofsoftwarethatprovidestheintendedbusinessvalue.

Businessapplicationsareoftensubjecttomanydifferentdimensionsof

change.Therearechangesinhowtheapplicationshouldbeviewedto

supportdifferentstakeholderrolesandclientdevices.Therearechanges

inhowthedataisaccessedfromdatasources.Therearechangesinthe

runtimedeploymentarchitecturestosupportnonfunctional

characteristics,ortoenableintegrationwithotherapplications.Butmost

importantly,therearechangesinthemarketforcesthatdrivethe

businessprocessestheapplicationsareintendedtosupport.

Sincethedomainmodelrepresentsthatportionofthebusinessdomain

thatisautomatedand,therefore,constitutesthebusinessvalueofthe

application,andsinceitisoftensubjecttorapidchange,itisimportantto

buildtheapplicationinawaythatminimizescouplingwithother

applicationlayers.Thedomainmodelseparatesbusinesslogicfrom

viewsorpersistencemechanismssotheycanallvaryindependentfrom

eachother.Youneedtobeabletomodify,build,andtestquicklyto

enablechange.Separationofconcernsistheprimarymechanismfor

managingcomplexity,facilitatingreuse,andenablingchange.



16.1.1ServiceLayer

Thecontroller/mediatorlayerseparatesapplicationandbusinessdomain

logicandisusefulforimplementingcoordinatedapplicationlogic

involvingmultiple,looselycoupled,transactionaldomainmodelobjects.

Thecontroller/mediatorlayerisespeciallyusefulwhentheapplication

mustaccomplishsometaskorusecaseaccessedbymultipleclients.It



providesalayerforabstractingcommonuserinterfaceandapplication

controllerlogicthatcanbesharedacrossmanyuserinterface

implementations.

Thedomainmodelprovidesthefoundationfordevelopingtherestofthe

enterpriseapplication.However,itispossiblethatthesamedomain

modelmaybeusedformanypurposesinanapplication,orreusedin

differentapplications.Eachusesatisfiessomeaspectofthebusiness

problem.Oftenthesedifferentpurposeswillrequireadifferent

perspectiveonthedomainmodel.Thiscouldbeassimpleasusing

differentnamesforthesameinformationorbehavior,orabstracting

lower-levelfunctionsintosomeotherbehaviormorefocusedona

particulardomain.

Youcantrytoincorporatethesefunctionalviewsintothedomainmodel

directly,butsometimesitisbettertofactorthemintoseparatepackages

andclasses.TheServiceLayerpattern[Fowler]isameansofproviding

multipleinterfacestothesamedomainmodeltobettersuitparticular

needs,views,orusecases.UsethispatterntoprovideAPIsforparticular

purposessothatthedomainmodeldoesnotbecomeovercomplicated

withdifferentfunctionalviews.Servicelayermethodsoftenmodel

specificusecasesorbusinessprocessesandcanrepresent

transactionalboundaries.Servicelayersaren'talwaysnecessary,but

theycanbeveryusefulwhenthesamedomainmodelisusedfor

differentpurposes.



16.1.2ApproachestoDomainModeling

Therearemanyapproachestoorganizingdomainlogic,including

processmodeling,functionaldecomposition,data-centereddesign,and

objectmodeling.Allareusefulindifferentcircumstances,butusingan

objectmodelforthedomainmodelhasmanyadvantages,evenfor

simpleproblems.

Functionaldecompositiondoesagoodjobcapturinganticipated

functions,butdoesnotcapturetheoveralldomaininamannerthat



facilitateschangingfunctionsoraddingunanticipatedfunctions.Thisis

becauseeachfunctionfocusesattentionononeparticularactivitythat

mustbeaccomplished.Indeed,oneofthemeasuresofsoftwarequality

ishighfunctionalcohesionandlowcoupling.However,it'softenhardto

seehowallthefunctionsfittogether.

Aswesaidearlier,enablingrapidchangeisoneoftheprimaryresultsof

agooddomainmodel.Functionaldecompositionoftenresultsin

duplicatedcodeandhighcouplingincalls/calledrelationships,plusit

spreadsstateandlogicthroughouttheapplicationandonlyhandlesone

dimensionofcomplexity(function).

Data-centereddesignsareusefulforsimpleCRUD(create,read,update,

delete)applicationssincetheyoftenallowrecordsetsobtainedfrom

relationaldatabasestobedisplayedandmanipulateddirectlybyuser

interfacecomponents.However,thistightlycouplesthepresentation,

domain,anddatastorelayersmakingitdifficulttochangeanyofthem.

ThismaybefineforsimpleCRUDapplicationsthataredata-centered,

stable,and/orshortlived.Itdoesn'tscalewelltocomplexdomains

becauseoftheincreasedcomplexityofhandlingaUI,domain,and

relationaldatabasethatareallmanagedtogether.Inaddition,anumber

ofusefulOOtechniquessuchasinheritance,strategies,andother

patternsthatcansimplifyapplicationdevelopmentandmaintenanceare

notdirectlysupportedbyrelationaltechnology;makingdevelopment

morechallenging.

Objectmodelingaddressesmanyoftheseissuesbyprovidingarich

languageforcapturingbroaddomainknowledge.Theprimaryadvantage

ofobjectmodelingresultsfromencapsulationofknowledgethrough

groupingbehaviorwiththestateitneeds.Thisreducescomplexityby

keepingcloselyrelatedstateandbehavioralknowledgetogether,avoids

duplication,andreducesdatacouplingbetweenobjects.Therearealso

manyapproachestodomainobjectmodelingfromsimpleintuitive

approachessuchasCRC(Class,Responsibility,andCollaborator)cards

allthewayuptotheRUP(RationalUnifiedProcess).Wewon'tcover

themallhere,butwewilltakealookatonesimpleapproachtodomain

modelingbasedonthenotionthatdomainmodelsaremoreoften

discoveredthandesigned.



Iterativedevelopmentbasedonexplorationwithyourcustomer,

implementing,mappingtothedatasourcelayer,andtestingproves

particularlyusefulfordevelopingcomplexdomainmodels.Thewhole

processisorientedaroundchangefromthebeginning.Whatfollowsisan

oversimplificationofwhatcanbeaverycomplextopic.However,we

havefounditusefulforcapturingawidevarietyofdomainmodels.Fora

morecompletetreatmentofdomainmodeling,see[Evans].



16.1.3TheMini-MaxApproachtoDomain

Modeling

Startbyhavingyourcustomerstellyouastoryabouttheirbusinessor

yourendusersabouthowtheywanttouseyourapplication.Focuson

observable,existing,oranticipatedbusinessprocessesorfunctions,

scenarios,andusecases.Don'tworrytoomuchaboutdataatthis

pointthere'smoreknowledgeandvalueinthebusinessprocesses.Data

comeslaterasyoudeterminewhat'srequiredtoimplementthefunctions

thatsupportthebusiness'processes.Also,spendtimethinkingoutofthe

boxinordertodiscovernewbusinessopportunitiesandprocessesthat

supportthem.Youdon'twanttodevelopsomethingthecustomeralready

has.

Thebusinessprocessescanbecapturedintext,use-casescripts,

pseudocode,orUMLinteractionorcollaborationdiagrams.Atthisstage,

itisn'tnecessarytobetooformal.Youwanttofocusondiscovering

knowledgeaboutthedomain,notrequirementsormodelingtools.Awhite

boardisoftenthebestCASEtoolatthisstage.Avoidusingtoolsthat

focustheattentiononthecomputerortool,notthebusiness.Youalso

wanttobeabletoeasilyinteractwiththeparticipantsinthebusiness.

Thiscanbehardtodowhentheviewportisa1024x768screen.

Trytoidentifylogicalsubsetsofthebusinessdomainthataremoreor

lessindependentandusethisasaguidewhenyoupartitionthedomain

intoseparatepackagestomanagecomplexity.Thesepackagescanbe

UMLorJavapackages,foldersinthefilesystem,orsectionsina



document.Theimplementationdoesn'tmatteratthispoint.Thegoalisto

identifydifferentfunctionalareasinthedomainthatcanbehandledmore

orlessindependently.

Foreachdistinctbusinessprocessthatyouhavediscovered,identify

participatingobjectsandassignresponsibilities.Theobjectsareoften

identifiedbynounsinthedescriptionswhilethefunctionsareverbs

describingtheprocessing,butthisisonlyaguideline,notarule.Some

verbsmayultimatelybecomeserviceordomaincontrollerobjects.

Onegoodplacetofinddomainobjectsisinthecustomer'sorganization

charts.Departmentsandemployeesoftenhavewell-definedrolesand

responsibilitiessupportingbusinessobjectives.Thisisarichsourceof

domaininformationthatfocusesonthecustomer'scorevalueproposition

andtheresponsibilitiesofthekeystakeholders.Moreover,theplayers

andprocessesthatmakeupabusinessdomainrarelychange

independentofevolutionsintechnology.

Todayeverybusinesshascustomers,accounts,suppliers,andsoon;

yearsfromnowthatwillstillbetrue.Itislikelythatthemeanstoaccess

themandtheirabilitiestointeractwitheachothermorefluidlywillevolve

intime;however,thebasicbusinessrulesthatunderliethisinteraction

willremainprincipallyunchanged.Allthemorereasontofocusonthese

immutablefactsofdoingbusinessthanthetoolsandtechnologiesthat

supporttheirimplementation.

Examineeachresponsibilityanddeterminewhatotherinformationand

operationsarerequiredtosupportit.Asyoudiscovernewinformation

andbehavior,examineeachexistingdomainobjectstartingfrom

concreteexamples;avoidworryingtoomuchaboutabstractionor

generalizationsatthisearlystageandinsteadfocuswherethenew

knowledgebestfits.Ifitdoesn'tfitanywhere,createadomainobjectand

putitthere.Nametheobjectsbasedontheroletheyplayinthe

business,nothowtheyareimplementedintheapplicationordatabase.

Onceyouidentifyanobjectthatshouldownthenewinformationor

behavior,trytopushtheinformationorbehavioruptheclasshierarchyto

thehighestpointpossiblebyaskingthesamequestionabouteach

superclass.Wecallthisthemini-maxapproachtoclasshierarchydesign.



Itpushesinformationandbehavioruptheclasshierarchyashighasit

cangowithoutcompromisingcohesion.Thisresultsinashallowclass

hierarchythatminimizescouplingbetweenobjectsandmaximizesthe

behaviorofeachparticipatingobject.

Next,mapthedomainobjectstotheirunderlyingdatastorelayerinorder

tosupportpersistence.Thisisthesubjectoftherestofthischapter.

Doingthisearlyensuresthedomainmodelisconsistentwiththe(often

existing)datasourceslayerearlyinthedevelopmentcycle,avoiding

potentialbigsurpriseslater.

Don'tletexistingdatabasesdictatethedomainmodel.Theymaybeout

ofdate,ordesignedtosolveadifferentproblem.Getthedatabase

administratorsinvolvedindiscoveringthedomainmodel;theywilloften

knowthedataverywell.Youcantrytogetthemtoupdatetheschemato

betterfitwiththedomainmodel,butthismaybeverydifficulttodo.

Instead,youcanusethedatamappinglayertoallowthedomainmodel

andrelationalschematoevolvemoreindependently.

Finally,takethebusinessfunctionsyoustartedwithandthatwereused

todefinethedomainlayer,andthenturnthemintotestcasestorun

againstthenewlyimplementedsubsetofthedomainmodel.This

validatesthedomainmodelbasedontheoriginalrequirements.

Afteryou'vecompletedthesesteps,iterate.Doincrementaldevelopment

drivenbytestcasesthatmatchanticipatedfunctions,scenarios,anduse

casesthatwereusedtodevelopthemodel.Duringeachdevelopment

iteration,trytoimplementspecificfunctionsthatwereidentifiedas

systemrequirements.Refactorasneededtoincorporatenewknowledge.

Implementthedomainmodelfirstandthenmapittoapersistentstore.

Theoriginalfunctionalrequirementsareimplementedastestcasesthat

canbeusedtoensurethedomainmodelactuallysolvestheintended

problems.Thisprovidescompletefeedbackbetweenrequirements,

domainmodel,andtestingearlyandofteninthedevelopmentlifecycle,

ensuringtheextendedteamunderstandsthebusinessproblemasitis

discoveredandevolves.Keepinmindacustomeroftendoesn'tknow

preciselywhatshewantsuntilyoushowhersomethingthatisn'tit.



Continuousanditerativerefinementofthedomainmodelthroughthefull

lifecyclecanavoidmoreunpleasantsurprises,missedexpectations,and

unsatisfiedcustomers.



16.1.4IssueswithDomainModeling

Therearesomeissueswithdomainmodelingthatshouldbetakeninto

consideration.Oneofthemostsignificantisthatstakeholdersoftencan't

discerntheiroriginalbusinessprocessorusecases;they'rehiddenina

webofcollaboratingobjects.Thisisahardissuetoaddresscompletely,

buttherearesomethingsthatcanhelp.

First,presentingmoreabstractviewsofthedomainmodelusingUML

usecase,interaction,andcollaborationdiagramscanfocusattentionon

theessenceofthedomainmodel.Ifyou'reworkingattheprogramming

level,usingagoodprogramdevelopmentenvironmentcanmake

navigatingthedomainmodelimplementationsimpleandeasy,makingit

easiertofigureouthowthingsrelateandhowwelltheimplementation

matchesyourinitialdesignthoughts.TheJavadevelopmenttoolsin

WSADarestellarinthisregard.Youcanprettymuchputthecursorover

anythingandgethoverHelpshowingitsspecificationorJavaDocif

available.PressF3toimmediatelyopenitsdefinition.

Youcanselectinterfacesandmethodsandseehowtheyareusedor

wheretheyareimplementedtofindouthowtoimplementorcustomize

them.SearchisbasedonJavasemantics,notjuststrings,andis

extremelyfast.Anothertechniqueistoputbreakpointsatinteresting

pointsintheapplicationandthenrunitundercontrolofthedebugger.

Whenthebreakpointisreached,thestacktraceinthedebugperspective

willtellyouhowyougotthere,effectivelyaviewofaprocessinstance.

Justdouble-clickonanyentryinthestacktracetoviewtheJavasource

atthatpoint.Then,singlesteptoseewhereyoumightgonext.

Thereareevenapplicationsthatcanintrospecttheinformationcollected

bytheapplicationprofilingtoolsandrecreatetheoriginalprocess

models.Wewon'tcoverthosehere,buttoolslikeRationalXDE



Professionalcanbeusefulinthisregard.

Anotherproblemisthatdeveloperscanfindithardtorealizeknownand

anticipatedfunctionsinanobjectmodel.Thisrequiresakindofabstract

thinkingandasemanticshiftthatsomepeoplefinddifficult.Youstartout

followingaspecificsequenceofstepsinafunction,butthenhaveto

abstractdomainknowledgeaboutnotonlythatfunction,butalltheother

partsofthedomainitinteractswith.Abstractingmeaningoutofsimple

stepsinaparticularfunctionrequiresathoroughknowledgeofthe

domain,somethingmanyprogrammersdon'thave.Oneapproachto

addressingthisproblemisthroughpair-programmingwhereteam

memberswhohaveafunctionalworldviewarepairedwithsomeoneelse

whocandealeffectivelywithOOabstractions,resultinginabetter

domainmodelthaneithercouldhavecreatedbythemselves.

Richdomainmodelscantakelongertobuildandcostmoreintheirinitial

development.However,theycanreduceoverallcostwhenapplications

arechangedorextended.Itishardtoachieveabalancebetweenthese

conflictinggoals,especiallywhenyourcustomerdoesn'tknowwhat

unanticipatedfunctionstheteamisgoingtocomeupwith,andisn't

willingtopayfortheincreaseddevelopmentcosts.Youcanalwaysstart

outwithasimple,limiteddomainmodelwithlotsoffunctioncalls

implementingthesystembehavior.Then,astheapplicationgetsmore

complicated,usetheknowledgeobtaineduptothatpointtohelpdevelop

abetterdomainmodelforsubsequentreleases.Thiscanresultinalotof

refactoringandredeveloping,butitmightbebetterthanother

alternatives.

ThereisalsoincreasedriskiftheteamisnotexperiencedinOO

development.Inthiscaseitmaybeusefultohireconsultantsto

participateinpair-programmingteamstohelpmentorthedevelopment

team.Thisisoftencheaperandfasterthansendingthedevelopersoffto

anumberofclassessincetheylearnthetechniqueswhileworkingwith

anexperttosolvetheprobleminthecontextoftheirownbusiness

insteadofgeneralprogrammingexercises.Itmayseemcostlyinthe

shortterm;however,onegoodmentorcanboosttheproductivityofa

largergroupmorethanenoughtooffsettheadditionalcost(ifnot,they

arenotagoodmentor,intheauthors'sharedopinion).



16.2TheDataMappingLayer

Thislayerprovidesthepersistentdatafromatechnology-specificdata

storeforthedomainlayer,whichinturnprovidesthisdatainamore

naturalandaccessibleformatforotherdomainobjects.Thesedata

sourcescouldbeanythingexistingapplications,faỗadesencapsulating

existingapplications,objectdatabases,real-timesensors.Butveryoften

thedatasourcelayerisarelationaldatabase.

Thedatamappinglayeristhegatewaythatmapsbetweenthedomain

layerandthedatasourceslayer.InChapter7,wedevelopedavery

simplemodelandpersistedthedomainobjectsinarelationaldatabase

usingtheActiveRecordpattern.Thisworkswellforsimpleobjectmodels

thatcloselymatchtablesinthedatabase.Butthepatterndoesn'tscale

wellformorecomplexdomainlayers,primarilybecausethedomain

modelisresponsibleforthemapping,whichresultsintightercoupling

betweenthedomainanddatasourcelayer.Thiscouplinglimitsdata

miningflexibilityandinhibitschangeinboththedomainmodeland

databaseschema.

Largerdomainmodelswillbepermeatedwithmappingcodethroughout

itsmanydomainobjects,makingithardertomaintainasdomainmodel

andrelationalschemaschangeduetorefactoringandschemamigration.

Also,thiscouplingmakesitdifficulttotestthedomainmodelwithouta

database.

Twoimportantprinciplesofsoftwaredevelopmentareencapsulationand

separationofconcerns.Thistypicallymeansfactoringoutthethingsthat

changesotheycanbeimplementedindependentlyandclientsdon'tneed

tobeawareof,ordependenton,implementationdetails.Thisenables

reuseandisolateschangetominimizemaintenanceoverhead.The

encapsulationofpersistingdataisacommonexampleofmanaging

variability.Therearenumerousdifferentobjectmodelstopersistand

waystopersistthemusingmanydifferentdatabasetechnologiesoreven

thesametechnology.Sowhenmappingbetweenthedomainanddata

sourcelayers,wewanttodefineinterfacesthatareindependentofthe



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 16. Developing and Testing the Domain Model

Tải bản đầy đủ ngay(0 tr)

×