Tải bản đầy đủ - 0 (trang)
Appendix A. Other Domain Model Styles

Appendix A. Other Domain Model Styles

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

4. Concurrencyconflictdetectionisimportant.

It'salrighttouseoptimisticconcurrencycontrol.Thatis,it's

acceptedthatwhenauserisnotifiedafterheorshehas

donesomeworkandtriestosave,therewillbeaconflict

withaprevioussave.Onlyconflictsthatwillleadtoreal

inconsistenciesshouldbeconsideredasconflicts.Sothe

solutionneedstodecideontheversioningunitfor

customersandfororders.(Thiswillslightlyaffectsomeof

theotherfeatures.)

5. Acustomermaynotoweusmorethanacertainamountof

money.

Thelimitisspecificpercustomer.Wedefinethelimitwhen

thecustomerisaddedinitially,andwecanchangethe

amountlateron.It'sconsideredaninconsistencyifwehave

unpaidordersofatotalvalueofmorethanthelimit,butwe

allowthatinconsistencytohappeninonesituationandthat

isifauserdecreasesthelimit.Thentheuserthat

decreasesthelimitisnotified,butthesaveoperationis

allowed.However,it'snotallowedtoaddanorderor

changeanordersothatthelimitisexceeded.

6. Anordermaynothaveatotalvalueofmorethanone

millionSEK.

Thislimit(unlikethepreviousone)isasystem-widerule.

(SEKistheSwedishcurrency,butthat'snotimportant.)

7. Eachorderandcustomershouldhaveauniqueanduserfriendlynumber.

Gapsintheseriesareacceptable.

8. BeforeanewcustomerisconsideredOK,hisorhercredit

willbecheckedwithacreditinstitute.

Thatis,thelimitdiscussedpreviouslythatisdefinedfora



customerwillbecheckedtoseeifit'sreasonable.

9. Anordermusthaveacustomer;anorderlinemusthavean

order.

Theremustnotbeanyorderswithanundefinedcustomer.

Thesamegoesfororderlines,theymustbelongtoan

order.

10. Savinganorderanditslinesshouldbeatomic.

Tobehonest,I'mnotactuallysurethatthisfeatureis

necessary.Itmightbealrightiftheorderiscreatedfirst

andtheorderlinesareaddedlateron,butIwanttherule

tobelikethissothatwehaveafeaturerequestrelatedto

transactionalprotection.

11. Ordershaveanacceptancestatusthatischangedbythe

user.

Thisstatuscanbechangedbyusersbetweendifferent

values(suchastoapproved/disapproved).Tootherstatus

values,thechangeisdoneimplicitlybyothermethodsin

theDomainModel.

FirstupisMatsHelanderwiththevariationhecalls"Objectorienteddatamodel,smartservicelayer,anddocuments."Here

goes.



Object-OrientedDataModel,SmartServiceLayer,and

Documents



ByMatsHelander

Sometimes,duringdarkwinternights,Irecallfaintlywhatlife

waslikeinthedaysbeforetheDomainModel.Itisattimeslike

thosethatIpouralittlecognacintomyhotchocolateand

throwanextralogonthefire.

Theevolutionofthearchitectureinmyapplications,finally

leadinguptotheuseoftheDomainModel,followedapattern

somereadersmayfeelfamiliarwith.I'mgoingtooutlinethis

evolutionquickly,asithelpsputmycurrentapproachforusing

theDomainModelintocontext.



IntheBeginning

Istartedoutwritingclient-serverapplicationswhereallthe

applicationcodewasstuffedintotheclient,whichwouldtalk

directlytothedatabase.WhenIstartedwritingWeb

applications,theyconsistedofASPpageswithallthe

applicationcodeinthemincludingthecodeforcallingthe

database.

Becausetheresultofthistypeofapplicationarchitectureis,

withoutexception,ahorrificmesswhenevertheapplication

growsbeyondthecomplexityofa"HelloWorld"example,Isoon

learnedtofactoroutmostofthecodefromthepresentation

layerandtoputitinaBusinessLogicLayer(BLL)instead.

Immediately,theapplicationsbecameeasiertodevelop,more

maintainable,andasabonustheBLLcouldbemadereusable



betweendifferentpresentationlayers.Itshouldalsobenoted

thatinthosedays,itcouldmakeabigdifferencetothe

performanceandscalabilityofaWebapplicationtohavethe

bulkofitscodecompiledinacomponent.

Thenextstepwastoliftoutallthecoderesponsiblefor

communicatingwiththedatabasefromtheBLLandputitina

layerofitsown,theDataAccessLayer(DAL).IrecallthatIwas

slightlysurprisedtoseethattheDALwasoftensubstantially

largerthantheBLLmeaningmoreofmyapplicationlogicdealt

withdatabasecommunicationthanwithactualbusinesslogic.

Atthistime,IwasalmostatthepointwheretheDomainModel

wouldenterintotheequation.ThePLwouldtalktotheBLLthat

wouldtalktotheDALthatwouldtalktothedatabase.However,

alldatafromthedatabasewaspassedaroundtheapplicationin

theformofRecordsets,thein-memoryrepresentationofrows

inthedatabase(seeFigureA-1).



FigureA-1.Classic,pre-DomainModellayered

applicationarchitecture



Sometimes,workingwiththedatainitsrelationalformisjust

whatyouwant,andinthosecasesthearchitecturedescribed

earlierstillfitsthebillnicely.But,asIwasbecomingawareof,

relationaldatastructuresaren'talwaysidealforthebusiness

logictoworkwith.



Object-OrientationandRelationalData



Structures

FromsomeworkIhaddonewithanobject-orienteddatabase

fromComputerAssociatescalledJasmine,Ihadcometo

understandthatanobject-orienteddatastructurewasquite

oftenaloteasiertoworkwithwhendevelopingthebusiness

logicthanthecorrespondingrelationalstructure.

Relationshipsbetweenentitiesaresimpler,foronething.Inthe

caseofmany-to-manyrelationships,thisisespeciallyso,

becausetherelationaldatastructurerequiresanadditional

tablewhereasnoadditionalclassisrequiredintheobjectorienteddatastructure.

Collectionpropertiesareanothercasewhereanadditionaltable

isusedintherelationalmodelbutnoextraclassisrequiredin

theobject-orienteddatastructure.Furthermore,object-oriented

datastructuresaretypesafeandsupportinheritance.



TheDomainModelandObject-Relational

Mapping

TheproblemwasthatOOdatabasesweren'tthatcommon.

MostprojectsIencounteredstillrevolvedaroundtherelational

database.ThisiswhereObject-RelationalMappingenteredthe

picture.

WhatObject-RelationalMappingdoesistoletyoutakean

object-orienteddatastructureandmapittothetablesina

relationaldatabase.Theadvantageisthatyouwillbeableto

workwithyourobject-orienteddatastructureasifworkingwith

anOOdatabaselikeJasmine,whileinrealityyou'restillusinga

relationaldatabasetostoreallyourdata.

Furthermore,youcanaddbusinesslogictotheclassesofthe



object-orienteddatastructureintheformofbusinessmethods.

Asyoumayhaveguessed,theobject-orienteddatastructure

withbusinessmethodsthatI'mtalkingaboutisthat'srightthe

DomainModel.

BylearningaboutObject-RelationalMappingIcouldfinallytake

thesteptowardincludingtheDomainModelinmyapplication

architecture.InsertedbetweentheBLLandtheDAL,the

DomainModelLayernowallowedmybusinesslogictowork

withanobject-orienteddatastructure(seeFigureA-2).



FigureA-2.Updated,layeredapplication

architectureincludingDomainModel



ThismeantthataBLLmethodthathadpreviouslybeenworking

withaRecordsetcontainingarowfromtheEmployeestablewould

nowinsteadworkwithanEmployeeDomainModelclass.Igained

typesafety,andthecodebecameshorterandeasiertoreadnot

tomentionthatIcouldnavigatemydatastructureduring

developmentusingMicrosoft'sIntelliSensefeature!

Eversince,I'vebeenadevoteduseroftheDomainModelandI

haven'tlookedbackexceptduringthosecold,darkwinter

nights.

AsImentioned,anotheradvantagewiththeDomainModelis

thatitletsyoudistributeyourbusinesslogicovertheDomain

Modelclasses.I'veexperimentedalotwithwheretoputmy

businesslogic.I'veshiftedbetweenputtingmostofitinthe



BusinessLogicLayertoputtingmostofitintheDomainModel

Layerandbackagain.



ServiceLayer

I'vealsocometopreferthetermServiceLayer[FowlerPoEAA]

toBusinessLogicLayer,asitbettercoverswhatI'mdoingat

timeswhenmostofmybusinesslogicisintheDomainModel

Layer.WhenmostofmybusinesslogicisintheServiceLayerI

seenoreasontoswitchbacktothetermBusinessLogicLayer,

thoughIsometimesrefertoitasa"thick"ServiceLayerto

distinguishitfromamoreconventionallythinServiceLayer.

ThesedaysIalmostalwaysputmostofthebusinesslogicina

"thick"ServiceLayer.WhilesomeOOpuristsmightarguethat

structureandbehaviorshouldbecombined,everysooftenI

finditpracticaltokeepthebusinesslogic-relatedbehaviorin

theServiceLayer.

Themainreasonforthisisthatinmyexperience,business

rulesgoverningthebehavioroftheDomainModelwillusually

changeatadifferentpace,andatdifferenttimes,fromthe

rulesgoverningthestructureoftheDomainModel.Another

reasonisthatiteasilyletsyoureusetheDomainModelunder

differentsetsofbusinessrules.

Normally,theonlybusinessmethodsIwouldputontheDomain

ModelobjectsthemselvesareonesthatIbelieveare

fundamentalenoughtobevalidunderanysetofbusinessrules

andareprobablygoingtochangeatthesametimeandpaceas

thestructureoftheDomainModel.

WithmostofmybusinesslogicintheServiceLayer,the

applicationarchitectureisnicelypreparedforthestepintothe

worldofSOA.ButbeforewegothereandtakealookathowI

wouldtackleJimmy'sexampleapplication,I'djustliketostress



anotherparticularbenefitofthisapproach.



CombiningThings

AsImentionedearlier,theobject-orienteddatastructure

offeredbytheDomainModelisn'ttheperfectfitforevery

operationyou'llwanttoperform.Therearereasonswhy

relationaldatabasesarestillsopopularandwhymanypeople

prefertouseObject-RelationalMappingbeforegoingwithan

actualOOdatabase.Formanytasks,therelationaldata

structureandtheset-basedoperationsofferedbySQLarethe

perfectfit.

Inthesecases,slappingmethodsontotheDomainModel

objectsthatwillactuallybeperformingset-basedoperations

directlyontherelationaldatastructuresmaynotseemlikea

verynaturalwaytogo.

Incontrast,lettingServiceLayermethodsthataccessthe

databasedirectly(orviatheDAL)co-existsidebysidewith

methodsthatoperateontheDomainModelisnostretchatall.

ConvertingaServiceLayermethodfromusingoneapproachto

theotherisalsoeasilyaccomplished.

Inshort,I'mfreetoimplementeachServiceLayermethodasI

seefit,bypassingtheDomainModelLayerwhereitisnotuseful

aswellastakingfulladvantageofitwhereitisuseful(which,in

myexperience,happenstobequiteoften).



Jimmy'sApplicationandSOA

Havingsaidthat,let'sreturntoJimmy'sapplicationandthe

bravenewworldofSOA.SofarIhaveonlyreallydescribed

whatmyapplicationarchitecturelookslikeontheserver,which



maybeenoughforaWebapplication,butnowwe'regoingto

dealwithaRichClient,andI'dliketofocusonapplication

serversasavariationtotherestofthebook.

Incaseswherealot,ifnotall,ofthebusinesslogichasbeen

distributedovertheDomainModel,atemptingapproachisto

trytoexportbothdataandbehaviorpackagedtogetherinthis

waytotheRichClientbygivingitaccesstotheDomainModel.

WiththearchitectureI'musing,wheremostofthebehavioris

foundintheServiceLayer,amorenaturalapproachisto

exposethebehaviorandthedataseparately.

Concretely,theServiceLayeriscomplementedwithaWeb

Servicefaỗade(atypeoftheRemoteFaỗadepattern[Fowler

PoEAA]),whichisjustathinlayerforexposingthebusiness

logicmethodsintheServiceLayerasWebServices.TheRich

ClientcommunicateswiththeserverbycallingtheWeb

Services,exchangingXMLdocumentscontainingserialized

DomainModelobjects.

Forourexampleapplication,thismeansthateachtimetheRich

ClientneedsnewinformationitwillcallaWebServiceonthe

serverthatwillreturntheinformationintheformofanXML

document.Tobeginwith,let'stakethecaseoflistingcustomers

matchingafilter.

IwouldbeginbycreatingaGetCustomersByFilter()ServiceLayer

methodimplementingtheactualfiltering.TheServiceLayer

methodwouldtakethefilterargumentsandreturnthe

matchingDomainModelobjects.ThenI'dadda

GetCustomersByFilter()WebServiceexposingtheServiceLayer

methodtotheRichClient.

TheWebServiceacceptsthesamefilterargumentsandpasses

themoninacalltotheServiceLayermethod.TheDomain

ModelobjectsreturnedbytheServiceLayermethodwouldthen

beserializedtoanXMLdocumentthatwouldfinallybereturned

bytheWebService.TheRichClientcanthenusethe



informationintheXMLdocumenttodisplaythelistof

customerstotheuser(seeFigureA-3).



FigureA-3.RichClientApplicationServerlayered

applicationarchitectureincludingDomainModel



ItiscompletelyuptotheRichClientapplicationdevelopersif

theywanttocreateaclient-sideDomainModelthattheycanfill

withthedatafromtheXMLdocument.Theymayalsodecideto

storetheinformationforofflineuse.Onewayistojustsavethe

XMLdocumentstodisk.Anotheristopersisttheclient-side

DomainModelstoanofflinedatabaseontheclientmachine.

Notethattheeventualclient-sideDomainModeldoesn'thaveto

matchtheDomainModelontheserver.Accordingly,ifthe

client-sideDomainModelispersistedtoanofflinedatabase,the

client-sidedatabasewillpresumablyfollowthedesignofthe

client-sideDomainModelandthusdoesn'thavetolooklikethe

server-sidedatabase.



Note

Oneimportantdifferenceregardingtheschemaof

theserver-sidedatabaseandtheclient-side

databaseisthatifaserver-sidedatabasetableuses

automaticallyincreasingidentityfields,the

correspondingclient-sidedatabasetablenormally

shouldn't.



Saythatanewemployeeiscreatedontheserver.

AsanewrowisinsertedintheEmployeestableitis

automaticallygivenavalueinitsauto-increasingID

column.Theemployeeisthenserializedandsentto

theclient,whichfillsaclient-sideDomainModelwith

thedataandstoresitintheclient-sidedatabasefor

offlineuse.

Thenewrowintheclient-sideEmployeestableshould

notbeassignedwithanewIDtheIDthatwas

assignedtotheemployeeintheserver-side

databaseshouldbeused.Thismeansthatthe

propertiesfortheIDcolumnsmaybedifferenton

theclientandtheserver.



ThepointhereisthatthedevelopersoftheRichClient

applicationarefreetodecidewhetherornottheywanttousea

DomainModelatall,andiftheywantonetheyarefreeto

designitastheyseefit.Thecommunicationbetweenclientand

serveris100%document-oriented,andnoassumptionsabout

theDomainModelsoneithersidearemadebytheother.

Forexample,maybetheRichClientcallsWebServicesofmany

differentcompanies,allcapableofreturninglistsofcustomers

butallwithslightlydifferentfieldsintheirXMLdocuments.One

waytodealwiththiswouldbetocreatea"superset"client-side

CustomerDomainModelobjectwithpropertiesforallthedifferent

fieldsthatwerereturnedfromallthecompaniescalled.

Next,wewanttheuseroftheRichClientapplicationtobeable

tolookattheordersbelongingtoaparticularcustomer.The

uniqueIDofeachcustomerwasofcourseincludedintheXML

documentreturnedbythefirstWebService,soweknowtheID

ofthecustomerinwhichwe'reinterested.



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

Appendix A. Other Domain Model Styles

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

×