ATM Case Study, Part 1: Object-Oriented Design with The

ATM Case Study, Part 1: Object-Oriented Design with The

ATMCaseStudy,Part1: Object-Oriented Design with theUML 25

Actionspeakslouderthanwords butnot nearly as often. —Mark Twain

Always design athing by consideringitinits next larger context. —Eliel Saarinen

Oh,lifeisaglorious cycleof song. —Dorothy Parker

TheWrightbrothers’ design … allowedthemtosurvive long enough to learnhow to fly. —MichaelPotts

Objectives In this chapter you’ll learn:

■ Asimpleobject-oriented design methodology. ■ What arequirements document is. ■ To identify classes andclass attributes from a requirements document. ■ To identify objects’states, activities andoperationsfrom arequirements document. ■ To determine the collaborationsamong objects in asystem. ■ To work with theUML’s use case, class, state, activity, communication and sequence diagrams to graphically modelanobject- oriented system.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-2 Chapter 25 ATMCaseStudy,Part1:Object-Oriented Design with theUML

25.1 Introduction 25.6 IdentifyingObjects’Statesand 25.2 IntroductiontoObject-Oriented Activities Analysis andDesign 25.7 IdentifyingClass Operations 25.3 Examiningthe ATMRequirements 25.8 Indicating CollaborationAmong Document Objects 25.4 Identifyingthe Classesinthe ATM 25.9 Wrap-Up RequirementsDocument 25.5 IdentifyingClass Attributes

25.1 Introduction Now we begin theoptionalportion of ourobject-orienteddesign andimplementation case study. In this chapterand Chapter26, you’ll design andimplementanobject-orientedau- tomatedteller machine (ATM) softwaresystem.The case studyprovides youwithacon- cise, carefully paced,completedesign andimplementation experience. You’ll perform the stepsofanobject-orienteddesign (OOD) process using theUML whilerelating themto theobject-oriented conceptsdiscussed in Chapters 2–13. In this chapter, you’ll work with sixpopular typesofUML diagrams to graphicallyrepresent thedesign. In Chapter26, you’ll tune the design with inheritanceand polymorphism, then fully implementthe ATMinan850-line C++application (Section 26.4). This is not an exercise; rather,it’sanend-to-end learning experiencethatconcludes with adetailedwalkthrough of the complete C++code that implements ourdesign. It will acquaint youwith the kindsofsubstantialproblems encountered in industry. Thesechapterscan be studiedasacontinuousunit after you’ve completed theintro- duction to object-oriented programming in Chapters 2–13.Or, youcan pace thesections afterChapters 3–7, 9and 13.Eachsection of thecasestudy beginswithanote telling you thechapterafter which it canbecovered.

25.2 IntroductiontoObject-OrientedAnalysisand Design Whatifyou were askedtocreateasoftwaresystemtocontrol thousandsofautomatedtell- er machinesfor amajor bank ?Orsupposeyou were asked to work on ateamof1000soft- ware developers building thenextU.S.air trafficcontrol system. For projects so largeand complex, youcannotsimplysit down andstartwritingprograms. To createthe best solutions, youshould followaprocess for analyzing your project’s requirements (i.e.,determining what thesystemshould do) anddeveloping a design that satisfiesthem(i.e.,deciding how thesystemshould do it). Ideally,you’d go through this process andcarefully review thedesign (or haveyourdesign reviewed by othersoftware professionals) before writing anycode.Ifthis process involves analyzing anddesigning your systemfromanobject-oriented pointofview, it’s called an object-oriented analysis anddesign(OOAD)process.Analysisand design cansavemanyhours by helping youto avoid an ill-plannedsystem-developmentapproach that hastobeabandoned partofthe waythroughits implementation,possiblywasting considerabletime, moneyand effort. Smallproblems do notrequire an exhaustiveOOAD process.Itmay be sufficient to write pseudocode before youbegin writing C++code.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.3 Examiningthe ATMRequirements Document 25-3

As problemsand thegroups of people solving them increaseinsize,the methods of OOAD becomemore appropriate than pseudocode. Ideally,members of agroupshould agreeonastrictly definedprocessfor solving theirproblem andauniformway of commu- nicating theresults of that process to oneanother.Although many different OOAD pro- cesses exist, asinglegraphicallanguagefor communicating theresults of any OOAD process hascomeintowide use. This language, knownasthe UnifiedModeling Language (UML), wasdeveloped in themid-1990sunderthe initialdirection of threesoftware methodologists—Grady Booch, JamesRumbaugh andIvarJacobson.

25.3Examining the ATM Requirements Document [Note: This section canbestudied afterChapter3.] We begin ourdesign process by presenting a requirements document that specifiesthe ATMsystem’soverall purposeand what it must do. Throughoutthe case study, we refer to therequirements document to determinewhatfunctionality thesystemmustinclude.

Requirements Document Alocal bank intendstoinstallanewautomated teller machine(ATM) to allowusers (i.e., bank customers) to performbasic financialtransactions(Fig. 25.1). Each usercan have only oneaccount at thebank. ATMusers should be able to view their account balance, withdraw cash (i.e., take moneyout of an account)and depositfunds (i.e.,place moneyintoanaccount).

Please enter youraccountnumber:12345 Screen Enter yourPIN:54321

Take cash here Cash Dispenser

InserInsertdtdeposit envelopelope here here Deposit Slot

Fig.25.1 | Automatedtellermachineuser interface.

Theuserinterfaceofthe automatedteller machinecontains thefollowing hardware components: •ascreen that displays messages to theuser

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-4 Chapter 25 ATMCaseStudy,Part1:Object-Oriented Design with theUML

•akeypad that receives numeric inputfrom theuser •acash dispenser that dispenses cash to theuserand •adepositslotthatreceives depositenvelopes from theuser. Thecashdispenserbeginseachday loaded with 500$20 bills. [Note: Owingtothe limited scopeofthis case study, certainelements of theATM described here do notaccurately mimicthose of arealATM.For example, arealATM typicallycontains adevice that reads auser’s account number from an ATMcard, whereasthis ATMasksthe user to typean accountnumberusing thekeypad.Areal ATMalsousuallyprints areceipt at theend of asession, but alloutputfrom this ATMappears on thescreen.] Thebankwants youtodevelop softwaretoperform thefinancialtransactions initi- ated by bank customersthrough theATM. Thebankwillintegrate thesoftwarewiththe ATM’shardwareatalatertime. Thesoftwareshouldencapsulatethe functionalityofthe hardwaredevices(e.g.,cashdispenser,deposit slot)within software components,but it need notconcern itself with how thesedevicesperform theirduties.The ATMhardware hasnot been developedyet,soinstead of writing your softwaretorun on theATM,you should developafirstversion of thesoftwaretorun on apersonal computer. This version should usethe computer’smonitor to simulatethe ATM’sscreen,and the computer’s key- board to simulate theATM’s keypad. An ATMsession consists of authenticating auser(i.e., provingthe user’s identity) basedonanaccount number andpersonal identification number (PIN), followed by cre- ating andexecuting financial transactions. To authenticate auserand perform transac- tions, theATM must interact with thebank’saccount information database.[Note: A database is an organized collectionofdata storedonacomputer.]For each bank account , thedatabasestoresanaccountnumber,aPINand abalance indicating theamountof moneyinthe account.[Note: For simplicity, we assume that thebank planstobuild only oneATM, so we do notneedtoworry about multiple ATMs accessing this database at thesame time.Furthermore,weassumethatthe bank doesnot make any changes to theinformationin thedatabase while auserisaccessing theATM. Also,any business systemlikeanATM faces reasonably complicatedsecurityissuesthatgowell beyond the scopeofafirst- or second- semester computerscience course. We makethe simplifyingassumption,however,that thebanktruststhe ATMtoaccess andmanipulate theinformation in thedatabase without significant securitymeasures.] Upon firstapproachingthe ATM, theusershould experiencethe followingsequence of events (shown in Fig. 25.1): 1. Thescreen displaysawelcomemessage andprompts theusertoenteranaccount number. 2. Theuserenters afive-digit account number,using thekeypad. 3. Thescreen promptsthe user to enterthe PIN (personalidentification number) associatedwiththe specifiedaccount number. 4. Theuserenters afive-digit PIN, using the keypad. 5. If theuserenters avalid account number andthe correctPIN forthataccount, thescreen displaysthe mainmenu(Fig.25.2).Ifthe userenters an invalid ac- count number or an incorrect PIN, thescreen displaysanappropriate message, then theATM returnstoStep 1 to restartthe authentication process.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.3 Examiningthe ATMRequirements Document 25-5

Main menu: 1-View my balance 2-Withdraw cash 3-Deposit funds 4-Exit Enter achoice:

Take cash here

InserInserttddepositeposit envelopelope here here

Fig.25.2 | ATMmainmenu.

Afterthe ATMauthenticatesthe user,the mainmenu(Fig.25.2) displaysanum- beredoption foreachofthe threetypes of transactions:balance inquiry (option 1),with- drawal (option 2) anddeposit (option 3).The main menu also displaysanoption that allows theusertoexitthe system (option 4).The user then chooses either to perform a transaction (byentering1,2or 3) or to exit thesystem(by entering4). If theuserenters an invalid option,the screen displaysanerror message,thenredisplays to themainmenu. If theuserenters1to make abalance inquiry,the screen displaysthe user’s account balance.Todoso, theATM mustretrievethe balancefrom thebank’sdatabase. Thefollowing actionsoccurwhenthe user enters 2tomakeawithdrawal: 1. Thescreen displaysamenu (shown in Fig. 25.3)containingstandard withdrawal amounts: $20(option 1),$40 (option 2),$60 (option 3),$100(option 4) and $200 (option 5).The menu also contains an option to allowthe user to cancel thetransaction (option 6). 2. Theuserenters amenuselection (1–6)using thekeypad. 3. If thewithdrawal amount chosenisgreaterthanthe user’s account balance,the screen displays amessage stating thisand telling theusertochooseasmaller amount. TheATM then returns to Step 1.Ifthe withdrawalamount chosenisless than or equal to theuser’s account balance (i.e., an acceptable withdrawal amount), theATM proceedstoStep 4.Ifthe user chooses to cancelthe transaction (option 6),the ATMdisplaysthe main menu (Fig. 25.2)and waitsfor user input. 4. If thecashdispensercontains enough cash to satisfythe request, theATM pro- ceedstoStep 5.Otherwise,the screen displays amessage indicating theproblem andtelling theusertochooseasmallerwithdrawal amount.The ATMthen re- turnstoStep 1.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-6 Chapter 25 ATMCaseStudy,Part1:Object-Oriented Design with theUML

Withdrawal options: 1-$20 4-$100 2-$40 5-$200 3-$60 6-Cancel transaction Choose awithdrawal option (1-6):

Fig.25.3 | ATMwithdrawalmenu.

5. TheATM debits (i.e.,subtracts)the withdrawalamountfrom theuser’s account balance in the bank’s database. 6. Thecashdispenser dispenses thedesiredamountofmoney to theuser. 7. Thescreen displaysamessagereminding theusertotakethe money . Thefollowing actionsoccurwhenthe user enters 3(whilethe main menu is dis- played)tomakeadeposit: 1. Thescreen promptsthe usertoenteradepositamountortotype 0(zero) to can- celthe transaction. 2. Theuserenters adeposit amount or 0, using thekeypad. [Note: Thekeypad does notcontainadecimal pointoradollar sign,sothe user cannot type arealdollar amount (e.g., $1.25).Instead,the user mustenteradepositamountasanumber of cents(e.g.,125). TheATM then divides this number by 100toobtainanum- berrepresenting adollaramount(e.g.,125 ÷ 100=1.25).] 3. If theuserspecifiesadepositamount, theATM proceedstoStep 4.Ifthe user chooses to cancelthe transaction (byentering0), theATM displaysthe main menu (Fig.25.2) andwaits foruserinput. 4. Thescreen displays amessage telling theusertoinsertadepositenvelope intothe deposit slot. 5. If thedeposit slot receives adeposit envelope within twominutes, theATM cred- its(i.e.,adds)the deposit amount to the user’s account balance in thebank’sda- tabase. This moneyisnot immediatelyavailablefor withdrawal.The bank firstmust physically verifythe amount of cash in thedeposit envelope, andany checks in theen-

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.3 Examiningthe ATMRequirements Document 25-7

velopemust clear (i.e., money must be transferredfromthe check writer’s account to thecheck recipient’saccount). When eitherofthese eventsoccurs, thebankappropri- atelyupdatesthe user’sbalancestoredinits database.Thisoccurs independently of the ATMsystem. If thedeposit slot doesnot receiveadepositenvelopewithinthis time period, thescreen displaysamessagethatthe system hascanceled thetrans- action duetoinactivity. TheATM then displays themainmenuand waitsfor user input. Afterthe system successfully executes atransaction,the system should redisplay the main menu (Fig.25.2) so that theusercan performadditional transactions. If theuser chooses to exit thesystem(option 4),the screen should displayathank youmessage,then display thewelcomemessage forthe next user.

Analyzingthe ATMSystem Theprecedingstatement is asimplifiedexampleofarequirements document. Typically, such adocument is theresultofadetailed requirementsgathering process that mightin- cludeinterviewswithpotential usersofthe system andspecialistsinfields related to thesys- tem. For example, asystemsanalyst whoishiredtopreparearequirements document for banking software (e.g.,the ATMsystemdescribedhere) might interview financialexperts to gain abetterunderstanding of what thesoftwaremustdo. Theanalyst woulduse thein- formation gained to compile alistofsystem requirements to guide systemsdesigners. Theprocessofrequirements gathering is akey task of thefirststageofthe software lifecycle.The software lifecycle specifiesthe stages through which software evolvesfrom thetimeit’sfirst conceived to thetimeit’sretiredfrom use. Thesestagestypically include: analysis,design, implementation, testingand debugging, deployment,maintenance and retirement. Severalsoftwarelife-cyclemodels exist, each with itsown preferences andspec- ificationsfor when andhow oftensoftwareengineers should perform each of thesestages. Waterfallmodels perform each stageonceinsuccession, whereas iterative models may repeat oneormore stages severaltimes throughoutaproduct’s life cycle. Theanalysisstageofthe software life cyclefocusesondefining theproblem to be solved.Whendesigningany system,one must certainly solve theproblem right,but of equal importance,one must solvethe rightproblem.Systems analysts collect therequirements that indicate thespecific problemtosolve.Our requirementsdocument describes our ATMsysteminsufficient detailthatyou do not need to go through an extensive analysis stage—it hasbeendonefor you. To capture what aproposed system should do,developers oftenemploy atechnique knownasusecasemodeling.This processidentifiesthe usecases of thesystem, each of which represents adifferent capabilitythatthe system providestoits clients. For example, ATMs typically have severaluse cases, such as “ViewAccount Balance,” “Withdraw Cash,” “Deposit Funds,”“Transfer FundsBetween Accounts” and“BuyPostage Stamps.” ThesimplifiedATM systemwebuild in this case studyallowsonlythe firstthree of these usecases (Fig.25.4). Each usecasedescribesatypicalscenario in which theuserusesthe system.You’ve alreadyreaddescriptions of theATM system’suse casesinthe requirements document; the listsofsteps required to performeachtypeoftransaction (i.e.,balance inquiry,with- drawal and deposit) actuallydescribedthe threeuse casesofour ATM—“ViewAccount Balance,” “Withdraw Cash” and“DepositFunds.”

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-8 Chapter 25 ATMCaseStudy,Part1:Object-Oriented Design with theUML

View Account Balance

Withdraw Cash

User Deposit Funds

Fig.25.4 | Usecasediagram forthe ATMsystemfromthe User’s perspective.

UseCaseDiagrams We nowintroduce thefirstofseveralUML diagrams in ourATM case study. We create a usecasediagram to modelthe interactionsbetween asystem’sclients (in this case study, bank customers)and the system.The goalistoshow thekinds of interactionsusers have with asystemwithout providingthe details—theseare providedinother UMLdiagrams (which we presentthroughoutthe case study).Use case diagrams areoftenaccompanied by informal text that describes theuse casesinmore detail—like thetextthatappearsin therequirements document. Usecasediagrams areproduced duringthe analysis stageof thesoftwarelifecycle.Inlarger systems, usecasediagrams aresimplebut indispensable toolsthathelpsystemdesigners remain focusedonsatisfying the users’ needs. Figure 25.4 showsthe usecasediagramfor ourATM system. Thestick figure repre- sentsanactor,whichdefines therolesthatanexternalentity—such as apersonoranother system—plays when interacting with thesystem. For ourautomated tellermachine, the actorisaUser whocan view an account balance,withdrawcashand depositfunds from theATM. TheUserisnot an actualperson, butinstead comprises therolesthatareal person—whenplaying thepartofaUser—canplaywhile interactingwiththe ATM. Note that ause case diagramcan includemultipleactors. For example, theuse case diagram for arealbank’sATM system might also includeanactor named Administrator whorefills thecashdispensereachday. We identifythe actorinour system by examining the requirements document, which states,“ATMusers should be able to view theiraccount balance,withdraw cash and depositfunds.” So,the actorineachofthe threeuse casesisthe User whointeractswith theATM.Anexternalentity—arealperson—playsthe part of theUsertoperform finan- cial transactions.Figure25.4shows oneactor, whosename, User,appearsbelowthe actor in thediagram. TheUML models each usecaseasanoval connectedtoanactor with a solidline. Softwareengineers (more precisely,systems analysts)mustanalyze therequirements document or aset of usecases anddesign thesystembefore programmers implementit. Duringthe analysis stage, systemsanalystsfocusonunderstanding therequirementsdoc- umenttoproduce ahigh-level specification that describes what thesystemissupposedto do. Theoutputofthe design stage—a designspecification—shouldspecifyclearly how thesystem should be constructedtosatisfythese requirements. In thenextseveral sections, we perform thesteps of asimpleobject-orienteddesign (OOD) process on theATM

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.3 Examiningthe ATMRequirements Document 25-9 system to produce adesign specification containing acollection of UMLdiagrams and supportingtext. Recall that theUML is designed foruse with anyOOD process.Many such processes exist, thebestknown of which is theRationalUnified Process™ (RUP) developedbyRationalSoftwareCorporation (now adivision of IBM). RUPisarichpro- cessintendedfor designing“industrial strength”applications. For this case study, we presentour ownsimplifieddesign process.

Designingthe ATM System We now begin theATM system’s design.Asystem is aset of components that interactto solveaproblem.Toperform theATM system’s designatedtasks,our ATMsystemhas a user interface (Fig. 25.1), contains software that executes financial transactionsand inter- acts with adatabaseofbankaccount information. System structure describes thesystem’s objectsand their interrelationships. System behavior describes how thesystem changesas itsobjects interactwithone another. Everysystemhas both structureand behavior—de- signersmustspecifyboth. Thereare severaldistincttypes of system structures andbehav- iors. Forexample, theinteractionsamong objectsinthe system differfromthose between theuserand thesystem, yetbothconstitute aportion of thesystembehavior. TheUML 2specifies13diagramtypesfor documenting themodels of systems. Each models adistinctcharacteristicofasystem’s structureorbehavior—sixdiagramsrelateto system structure; theremainingseven relate to system behavior.Welisthereonlythe six typesofdiagrams used in ourcasestudy—oneofthese (classdiagrams)models system structure—theremainingfivemodelsystembehavior.Weoverview theremaining seven UMLdiagramtypes in Appendix G, UML2:Additional DiagramTypes. 1. Usecase diagrams,suchasthe oneinFig.25.4, modelthe interactionsbetween asystemand itsexternalentities(actors)interms of usecases (systemcapabilities, such as “ViewAccount Balance,”“WithdrawCash” and“DepositFunds”). 2. Classdiagrams,whichyou’llstudy in Section 25.4,model theclasses,or“build- ing blocks,”usedinasystem.Eachnounor“thing” described in therequirements document is acandidate to be aclass in thesystem(e.g.,“account,” “keypad”). Classdiagrams help us specifythe structural relationshipsbetween partsofthe system.For example, theATM system classdiagramwillspecifythatthe ATMis physicallycomposedofascreen,akeypad,acash dispenser andadepositslot. 3. Statemachine diagrams,whichyou’llstudyinSection 25.6,modelthe ways in which an object changesstate.Anobject’s state is indicatedbythe values of all theobject’sattributesatagiven time.Whenanobjectchanges state,thatobject maybehavedifferentlyinthe system.For example, aftervalidating auser’s PIN, theATM transitionsfromthe “user notauthenticated” state to the“user authen- ticated” state,atwhich point theATM allows theusertoperform financialtrans- actions(e.g.,viewaccount balance,withdrawcash, depositfunds). 4. Activity diagrams,which you’ll also studyinSection 25.6,modelanobject’s ac- tivity—the object’s workflow (sequence of events)during programexecution. An activity diagrammodels theactions theobjectperformsand specifiesthe orderin which it performsthese actions. For example,anactivitydiagramshowsthatthe ATMmustobtainthe balance of theuser’saccount (from thebank’saccount in- formation database) before thescreen candisplay thebalance to the user.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-10 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

5. Communication diagrams (called collaborationdiagrams in earlierversions of theUML)modelthe interactionsamong objects in asystem, with an emphasis on what interactionsoccur. You’ll learninSection 25.8thatthese diagrams show which objects must interacttoperform an ATMtransaction. Forexample, the ATMmustcommunicatewiththe bank’s account information database to re- trieve an accountbalance. 6. Sequencediagrams also modelthe interactions amongthe objectsinasystem, butunlikecommunication diagrams, they emphasize when interactionsoccur. You’ll learn in Section 25.8 that thesediagramshelpshow theorderinwhichin- teractions occurinexecuting afinancialtransaction.For example, thescreen prompts theusertoenterawithdrawal amountbefore cash is dispensed. In Section 25.4,wecontinuedesigning ourATM system by identifying the classes from therequirementsdocument. We accomplishthis by extracting keynouns andnoun phrasesfrom therequirements document. Usingthese classes, we developour firstdraft of theclass diagramthatmodels thestructure of ourATM system.

WebResources We’vecreated an extensiveUML Resource Center(www.deitel.com/UML/)thatcontains many linkstoadditional information,including introductions,tutorials,blogs,books, cer- tification,conferences, developertools, documentation, e-books, FAQs,forums,groups, UMLinC++,podcasts, security, tools, downloads,trainingcourses,videos andmore.

Self-ReviewExercises forSection 25.3 25.1 Supposeweenabled auserofour ATMsystem to transfermoney betweentwo bank ac- counts. Modify theuse case diagramofFig.25.4toreflect this change. 25.2 modelthe interactions amongobjects in asystemwithanemphasisonwhen these interactions occur. a) Class diagrams b) Sequence diagrams c) Communication diagrams d) Activity diagrams 25.3 Whichofthe following choiceslists stages of atypicalsoftware life cycleinsequentialorder? a) design,analysis,implementation, testing b) design,analysis,testing,implementation c) analysis,design, testing, implementation d) analysis,design, implementation, testing

25.4Identifyingthe Classesinthe ATM Requirements Document [Note: This section canbestudied afterChapter3.] Now we begin designingthe ATMsystemthatweintroducedinSection 25.3.Inthis sec- tion,weidentifythe classesthatare needed to buildthe ATMsystem by analyzing the nounsand noun phrasesthatappear in therequirementsdocument. We introduceUML classdiagrams to modelthe relationshipsbetween theseclasses.This is an importantfirst step in defining the structureofour system.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.4Identifying theClasses in theATM Requirements Document 25-11

Identifyingthe ClassesinaSystem We begin ourOOD process by identifying theclassesrequiredtobuild theATM system. We’lleventuallydescribe theseclasses using UMLclass diagrams andimplement these classesinC++.First,wereviewthe requirementsdocument of Section 25.3 andfindkey nounsand noun phrasestohelpusidentifyclasses that comprisethe ATMsystem. We maydecidethatsomeofthese nounsand noun phrasesare attributes of otherclasses in the system.Wemay also conclude that some of thenouns do not correspondtoparts of the system andthusshould not be modeledatall. Additional classesmay becomeapparent to us as we proceed through thedesignprocess. Figure 25.5 liststhe nounsand nounphrasesinthe requirements document. We list them from lefttoright in theorderinwhichtheyappear in therequirementsdocument. We list only thesingularform of each nounornounphrase.

Nouns andnoun phrasesinthe requirements document

bank money/fund account number ATM screen PIN user keypad bank database customer cash dispenser balanceinquiry transaction $20 bill /cash withdrawal account depositslot deposit balance depositenvelope

Fig.25.5 | Nounsand noun phrasesinthe requirements document.

We create classesonlyfor thenouns andnounphrases that have significance in the ATMsystem.Wedon’t need to model“bank”asaclass, because it’isnot apartofthe ATM system—the bank simplywants us to build theATM. “Customer” and“user”alsorepre- sent outsideentities—theyare importantbecause they interact with ourATM system, but we do notneed to modelthemasclasses in theATM software.Recallthatwemodeled an ATMuser(i.e.,abankcustomer) as theactor in theuse case diagramofFig.25.4. We do notmodel “$20 bill” or “deposit envelope”asclasses. Theseare physicalobjects in therealworld, buttheyare not part of what’s beingautomated. We canadequately rep- resent thepresence of billsinthe system using an attribute of theclass that models thecash dispenser. (Weassign attributes to classesinSection 25.5.) Forexample, thecashdispenser maintains acount of thenumberofbills it contains.The requirements document doesn’t sayanythingabout what thesystem should do with depositenvelopes afteritreceivesthem. We canassumethatacknowledgingthe receiptofanenvelope—anoperation performed by theclass that models thedeposit slot—issufficienttorepresent thepresenceofanenve- lope in thesystem.(We assign operations to classesinSection 25.7.) In oursimplifiedATM system,representingvarious amounts of “money,” including an account’s “balance,” as attributesofother classesseems most appropriate. Likewise,the nouns“account number”and “PIN” represent significant information in theATM system. They areimportant attributes of abankaccount. They do not,however,exhibit behaviors. Thus,wecan most appropriately modelthemasattributes of an account class. Though therequirements document frequently describes a“transaction”inageneral sense, we do notmodelthe broadnotion of afinancialtransaction at this time.Instead,

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-12 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML we modelthe threetypes of transactions(i.e.,“balanceinquiry,” “withdrawal”and “deposit”) as individual classes. Theseclasses possessspecific attributes needed forexe- cuting thetransactions they represent. For example, awithdrawalneeds to know the amount of moneythe user wants to withdraw. Abalance inquiry,however,doesnot require anyadditional data.Furthermore,the threetransaction classes exhibit unique behaviors.Awithdrawalincludes dispensing cash to theuser, whereasadepositinvolves receivingdeposit envelopesfrom theuser. In Section26.3, we “factorout”commonfeatures of alltransactions into ageneral “transaction” class using theobject-orientedconceptsofabstract classes andinheritance. We determinethe classes forour system basedonthe remaining nouns and noun phrasesfrom Fig. 25.5.Eachofthese refers to oneormore of thefollowing: •ATM •screen •keypad •cashdispenser •deposit slot •account •bankdatabase •balance inquiry •withdrawal •deposit Theelements of this list arelikelytobeclasses we’llneedtoimplementour system. We cannow modelthe classes in oursystembased on thelistwe’ve created.Wecap- italize classnames in thedesign process—a UMLconvention—aswe’ll do when we write theactual C++code that implements ourdesign. If thenameofaclasscontains more than oneword, we runthe words together andcapitalize thefirst letterofeachword (e.g., Mul- tipleWordName). Using this convention,wecreateclasses ATM, Screen, Keypad, CashDis- penser, DepositSlot, Account, BankDatabase, BalanceInquiry, Withdrawal and Deposit.Weconstruct oursystemusing allofthese classesasbuilding blocks. Beforewe begin building thesystem, however,wemust gain abetterunderstanding of how the classesrelatetoone another.

Modeling Classes TheUML enablesustomodel, via classdiagrams,the ATMsystem’sclasses andtheir in- terrelationships. Figure 25.6 represents class ATM.Eachclass is modeledasarectanglewith threecompartments. Thetop compartmentcontains thenameofthe class, centered hori- zontally andinboldface. Themiddle compartment contains the class’sattributes.(We dis- cuss attributes in Section 25.5 and Section 25.6.) Thebottomcompartment contains the class’soperations(discussedinSection 25.7).InFig. 25.6 themiddle andbottomcompart- ments areempty,becausewe’ve notyet determined this class’sattributes andoperations. Classdiagrams also show therelationshipsamong theclasses of thesystem. Figure 25.7 showshow ourclasses ATM and Withdrawal relate to oneanother. Forthe moment,wechoosetomodelonlythis subset of classesfor simplicity; we presentamore

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.4Identifying theClasses in theATM Requirements Document 25-13

Fig.25.6 | Representingaclass in theUML usingaclass diagram.

1 Executes 0..1 ATM Withdrawal currentTransaction

Fig.25.7 | Classdiagram showinganassociation amongclasses. completeclass diagramlater in this section. Notice that therectangles representing classes in this diagram arenot subdividedintocompartments.The UMLallowsthe suppression of class attributesand operationsinthis manner,whenappropriate,tocreatemore read- able diagrams.Suchadiagramissaidtobeanelideddiagram—one in which some infor- mation,suchasthe contentsofthe secondand third compartments,isnot modeled. We’ll placeinformation in thesecompartments in Section 25.5 andSection 25.7. In Fig. 25.7,the solidline that connectsthe twoclasses represents an association—a relationship betweenclasses.The numbersneareachend of theline are multiplicity values,whichindicate how many objectsofeachclass participateinthe association.Inthis case,following theline from oneend to theother revealsthat, at anygiven moment, one ATM object participates in an association with either zero or one Withdrawal objects—zero if thecurrentuserisnot currentlyperformingatransaction or hasrequested adifferent type of transaction, andone if the user hasrequested awithdrawal.The UMLcan model many typesofmultiplicity. Figure 25.8 listsand explains the multiplicitytypes.

Symbol Meaning

0 None 1 One m An integervalue 0..1 Zero or one m, n m or n m..n At least m,but notmorethan n * Anynonnegative integer(zero or more) 0..* Zero or more (identical to *) 1..* Oneormore

Fig.25.8 | Multiplicity types.

An association canbenamed.For example,the word Executes abovethe line con- nectingclasses ATM and Withdrawal in Fig. 25.7 indicatesthe name of that association. This part of thediagramreads “one object of class ATM executeszeroorone objects of class

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-14 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

Withdrawal.” Association namesare directional,asindicatedbythe filled arrowhead—so it wouldbeimproper,for example, to read thepreceding association from righttoleftas “zeroorone objectsofclass Withdrawal executeone objectofclass ATM.” Theword currentTransaction at the Withdrawal endofthe association line in Fig. 25.7 is a role name,whichidentifiesthe role the Withdrawal objectplays in itsrela- tionship with the ATM.Arolename adds meaningtoanassociationbetween classesbyiden- tifying the role aclass playsinthe contextofanassociation.Aclasscan play severalroles in thesame system. For example, in aschool personnelsystem, apersonmay play therole of “professor” when relating to students.The same person maytakeonthe roleof“col- league” when participating in arelationship with anotherprofessor, and“coach” when coachingstudent athletes.InFig.25.7, therolename currentTransaction indicatesthat the Withdrawal object participating in the Executes association with an objectofclass ATM represents thetransaction currentlybeing processed by theATM.Inother contexts,a Withdrawal object may takeonother roles (e.g., theprevioustransaction). Notice that we do not specifyarole name for the ATM endofthe Executes association.Role namesinclass diagrams areoftenomittedwhenthe meaning of an association is clear withoutthem. In additiontoindicating simple relationships, associationscan specifymorecomplex relationships, such as objects of oneclass being composed of objects of otherclasses.Con- siderareal-worldautomatedtellermachine. What“pieces”doesamanufacturer put together to buildaworking ATM? Ourrequirements document tells us that theATM is composed of ascreen,akeypad,acash dispenserand adeposit slot. In Fig. 25.9,the soliddiamonds attachedtothe associationlines of class ATM indicate that class ATM hasacomposition relationship with classes Screen, Keypad, CashDispenser and DepositSlot.Composition impliesawhole/partrelationship.The classthathas the composition symbol (the soliddiamond)onits endofthe associationline is thewhole (inthis case, ATM), andthe classesonthe otherend of theassociation linesare theparts—inthiscase, classes Screen, Keypad, CashDispenser and DepositSlot.The compositions in Fig. 25.9 indicate that an object of class ATM is formed from oneobjectofclass Screen,one object of class CashDispenser,one object of class Keypad andone object of class DepositSlot.The ATM hasascreen,akeypad,acash dispenserand adeposit slot.The has-a relationship definescomposition.(We’llsee in Section 26.3thatthe is-a relationship definesinheritance.)

11 11 DepositSlotCATM ashDispenser

Fig.25.9 | Classdiagram showingcomposition relationships.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.4Identifying theClasses in theATM Requirements Document 25-15

According to theUML specification,composition relationshipshavethe following properties: 1. Onlyone classinthe relationship canrepresent thewhole (i.e., thediamond can be placed on only oneend of theassociation line). Forexample, either thescreen is partofthe ATMorthe ATMispartofthe screen,but thescreen andthe ATM cannot both representthe wholeinthe relationship. 2. Theparts in acomposition relationship existonlyaslongasthe whole, andthe wholeisresponsible forcreating anddestroyingits parts. For example, theact of constructing an ATMincludes manufacturingits parts. Furthermore, if theATM is destroyed, itsscreen,keypad,cashdispenserand depositslotare also destroyed. 3. Apartmay belong to only onewhole at atime, although thepartmay be removed andattachedtoanotherwhole,whichthenassumes responsibility forthe part. Thesolid diamondsinour classdiagrams indicate composition relationshipsthatful- fill thesethree properties.Ifahas-a relationship does notsatisfyone or more of thesecri- teria,the UMLspecifiesthathollow diamondsbeattachedtothe ends of association lines to indicate aggregation—a weaker form of composition.For example, apersonalcom- puterand acomputermonitor participate in an aggregation relationship—the computer hasamonitor, butthe twoparts canexist independently, andthe same monitor can be attachedtomultiplecomputersatonce, thus violating the second andthirdproperties of composition. Figure 25.10showsaclassdiagramfor theATM system.This diagrammodels most of theclasses that we identified earlier in this section, as well as theassociationsbetween them that we caninfer from therequirements document. [Note: Classes BalanceInquiry and Deposit participateinassociationssimilar to thoseofclass Withdrawal,sowe’ve chosen to omit them from this diagram to keepitsimple. In Section 26.3,weexpandour class diagramtoincludeall theclasses in theATM system.] Figure 25.10presents agraphical modelofthe structureofthe ATMsystem. This classdiagramincludes classes BankDatabase and Account andseveralassociationsthat were notpresent in either Fig. 25.7 or Fig. 25.9.The class diagramshowsthatclass ATM hasaone-to-one relationship with class BankDatabase—one ATM objectauthenticates usersagainst one BankDatabase object.InFig.25.10,wealsomodelthe fact that the bank’s database contains information aboutmanyaccounts—oneobjectofclass BankDa- tabase participatesinacomposition relationship with zero or more objectsofclass Account.Recallfrom Fig. 25.8 that themultiplicityvalue 0..* at the Account endofthe association between class BankDatabase andclass Account indicatesthatzeroormore objectsofclass Account take part in theassociation.Class BankDatabase hasaone-to- many relationship with class Account—the BankDatabase contains many Accounts. Sim- ilarly,class Account hasamany-to-one relationship with class BankDatabase—there can be many Accountscontainedinthe BankDatabase.[Note: Recallfrom Fig. 25.8 that the multiplicityvalue *isidenticalto0..*.Weinclude 0..* in ourclass diagrams forclarity.] Figure 25.10alsoindicatesthatifthe user is performingawithdrawal, “one objectof class Withdrawal accesses/modifiesanaccount balance through oneobjectofclass Bank- Database.” We could have createdanassociation directly between class Withdrawal and class Account.The requirements document, however,statesthatthe “ATM must interact with thebank’saccount information database” to perform transactions.Abank account

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-16 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

1 111 Keypad CashDispenser

1 DepositSlot Screen

1111 0..1 0..10..1 Executes ATM Withdrawal 1 0..1 1 0..1 Authenticates user against 1

BankDatabase 1 Accesses/modifies an account balance through 1 Contains 0..*

Fig.25.10 | Classdiagram forthe ATMsystemmodel. contains sensitiveinformation,and systemsengineers mustalways considerthe security of personal data when designingasystem.Thus, only the BankDatabase canaccessand manipulate an account directly.All otherparts of thesystem must interactwiththe data- base to retrieve or update account information (e.g., an account balance). Theclass diagram in Fig. 25.10alsomodels associationsbetween class Withdrawal andclasses Screen, CashDispenser and Keypad.Awithdrawaltransaction includes prompting theusertochooseawithdrawalamount and receivingnumeric input. These actionsrequire theuse of thescreenand thekeypad, respectively.Furthermore, dispensing cash to theuserrequiresaccess to thecashdispenser. Classes BalanceInquiry and Deposit,though notshowninFig.25.10,takepartin several associationswiththe otherclasses of theATM system.Likeclass Withdrawal,each of theseclasses associateswithclasses ATM and BankDatabase.Anobjectofclass Balan- ceInquiry also associateswithanobjectofclass Screen to display thebalance of an accounttothe user.Class Deposit associateswithclasses Screen, Keypad and Deposit- Slot.Likewithdrawals,deposit transactions require useofthe screen andthe keypadto display promptsand receiveinput,respectively.Toreceivedeposit envelopes, an object of class Deposit accesses thedeposit slot. We’venow identifiedthe classesinour ATMsystem(although we maydiscover others as we proceed with thedesign andimplementation). In Section 25.5,wedetermine theattributesfor each of theseclasses,and in Section 25.6,weuse theseattributes to examine howthe system changesovertime. In Section 25.7,wedetermine theoperations of theclasses in oursystem.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Self-ReviewExercisesfor Section 25.4 25-17

Self-ReviewExercises forSection 25.4 25.4 Supposewehaveaclass Car that represents acar.Think of some of thedifferent pieces that amanufacturerwouldput together to produceawholecar.Createaclassdiagram (similar to Fig. 25.9) that models some of the compositionrelationships of class Car. 25.5 Supposewehaveaclass File that representsanelectronicdocumentinastand-alone,non- networkedcomputerrepresented by class Computer.Whatsortofassociationexistsbetween class Computer and class File? a) Class Computer hasaone-to-one relationship with class File. b) Class Computer hasamany-to-one relationshipwith class File. c) Class Computer hasaone-to-many relationshipwith class File. d) Class Computer hasamany-to-many relationship with class File. 25.6 Statewhether the followingstatementistrue or false,and if false,explain why: AUML dia- graminwhich aclass’s second andthird compartments arenot modeledissaidtobeanelided diagram. 25.7 Modify theclass diagramofFig.25.10 to includeclass Deposit insteadofclass Withdrawal.

25.5IdentifyingClass Attributes [Note: This section canbestudied afterChapter4.] In Section 25.4,webegan the first stageofanobject-orienteddesign (OOD) forour ATM system—analyzing therequirements document andidentifying the classesneededtoim- plementthe system.Welistedthe nouns and noun phrases in the requirements document andidentifiedaseparateclass foreachone that plays asignificant role in theATM system. We then modeledthe classesand their relationshipsinaUMLclass diagram(Fig.25.10). Classeshaveattributes(data) and operations (behaviors).Class attributesare imple- mented in C++programs as data members, andclass operationsare implementedas member functions.Inthis section, we determinemanyofthe attributesneededinthe ATMsystem.InSection 25.6,weexamine how theseattributes representanobject’sstate. In Section 25.7,wedetermine classoperations.

IdentifyingAttributes Consider theattributesofsomereal-worldobjects:Aperson’s attributes includeheight, weight andwhether thepersonisleft-handed,right-handedorambidextrous. Aradio’sattri- butesincludeits station setting,its volume setting and itsAMorFMsetting.Acar’sattri- butesinclude itsspeedometer andodometer readings,the amount of gasinits tank and what gear it’s in. Apersonal computer’sattributes includeits manufacturer (e.g., Dell,HP, Apple or IBM),typeofscreen(e.g.,LCD or CRT), mainmemorysize andharddisksize. We canidentifymanyattributes of theclasses in oursystembylookingfor descriptive words andphrasesinthe requirements document. Foreachone we find that playsasig- nificantrole in theATM system,wecreateanattribute andassign it to oneormore of the classesidentifiedinSection 25.4.Wealsocreateattributestorepresent anyadditional data that aclass mayneed,assuchneeds becomeapparentthroughoutthe designprocess. Figure 25.11lists thewords or phrasesfromthe requirements document that describe each class. We formed this list by reading therequirementsdocument andidentifying any words or phrasesthatrefer to characteristics of theclasses in thesystem. For example,the requirements document describes thesteps takentoobtaina“withdrawal amount,” so we list “amount”nexttoclass Withdrawal.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-18 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

Figure 25.11leads us to create oneattribute of class ATM.Class ATM maintains infor- mation aboutthe state of theATM. Thephrase “userisauthenticated” describes astate of theATM (weintroduce statesinSection 25.6), so we include userAuthenticated as a Boolean attribute (i.e., an attributethathas avalue of either true or false). TheUML Boolean type is equivalent to the bool type in C++. This attributeindicateswhether the ATMhas successfullyauthenticatedthe current user—userAuthenticated must be true forthe system to allowthe user to perform transactions andaccess accountinformation. This attribute helpsensurethe securityofthe data in thesystem.

Class Descriptivewords andphrases

ATM user is authenticated BalanceInquiry account number Withdrawal account number amount Deposit account number amount BankDatabase [nodescriptivewords or phrases] Account account number PIN balance Screen [nodescriptivewords or phrases] Keypad [nodescriptivewords or phrases] CashDispenser begins each dayloaded with 500 $20 bills DepositSlot [nodescriptivewords or phrases]

Fig.25.11 | Descriptivewords andphrases from the ATMrequirements.

Classes BalanceInquiry, Withdrawal and Deposit shareone attribute. Each transac- tion involvesan“account number”thatcorrespondstothe account of theusermakingthe transaction.Weassign an integerattribute accountNumber to each transaction classto identifythe account to which an object of theclass applies. Descriptive words andphrasesinthe requirements document also suggest some dif- ferencesinthe attributes requiredbyeachtransaction class. Therequirements document indicatesthattowithdraw cash or depositfunds,users must enteraspecific “amount” of moneytobewithdrawn or deposited, respectively.Thus, we assign to classes Withdrawal and Deposit an attribute amount to store thevalue suppliedbythe user.The amountsof moneyrelatedtoawithdrawal andadepositare defining characteristics of thesetransac- tionsthatthe system requiresfor them to takeplace.Class BalanceInquiry,however, needsnoadditional data to perform itstask—it requiresonlyanaccount number to indi- cate theaccount whosebalance should be retrieved. Class Account hasseveral attributes. Therequirements document statesthateachbank accounthas an “accountnumber”and “PIN,”whichthe systemuses foridentifyingaccounts

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.5 Identifying ClassAttributes 25-19 andauthenticating users. We assign to class Account twointegerattributes: accountNumber and pin .The requirements document also specifiesthatanaccount maintains a“balance” of theamount of moneyinthe accountand that moneythe userdepositsdoesnot become availablefor awithdrawal untilthe bank verifiesthe amount of cash in thedeposit envelope, and any checksinthe envelope clear. An account muststill recordthe amount of moneythat auserdeposits, however.Therefore,wedecidethatanaccount should representabalance usingtwo attributesofUML type Double: availableBalance and totalBalance.Attribute availableBalance tracks theamount of moneythatausercan withdraw from theaccount. Attribute totalBalance refers to thetotal amount of moneythatthe userhas “ondeposit” (i.e.,the amount of moneyavailable,plusthe amount waitingtobeverifiedorcleared). For example, suppose an ATMuserdeposits$50.00into an empty account. The totalBalance attribute wouldincreaseto$50.00torecordthe deposit, but the availableBalance would remainat$0. [Note: We assume that thebankupdates the availableBalance attributeof an Account soon afterthe ATMtransaction occurs, in response to confirming that $50 worthofcashorcheckswas found in thedeposit envelope.Weassumethatthisupdate occursthrough atransaction that abankemployee performsusing some pieceofbanksoft- ware otherthanthe ATM. Thus, we do notdiscuss this transaction in ourcasestudy.] Class CashDispenser hasone attribute.The requirements document statesthatthe cash dispenser “begins each dayloadedwith500 $20bills.” Thecashdispensermustkeep trackofthe number of bills it contains to determinewhether enough cash is on handto satisfywithdrawal requests. We assign to class CashDispenser an integer attribute count, which is initially setto500. For real problemsinindustry,there is no guaranteethatrequirementsspecifications will be rich enough andprecise enough forthe object-oriented systemsdesigner to deter- mine allthe attributes or even allthe classes.The need foradditional (or fewer) classes, attributesand behaviors may becomeclear as thedesign process proceeds. As we progress through this case study, we toowillcontinuetoadd,modifyand delete information about theclasses in oursystem.

Modeling Attributes Theclass diagraminFig. 25.12lists some of theattributes forthe classes in oursystem— thedescriptive words andphrasesinFig.25.11 helped us identifythese attributes.For simplicity, Fig. 25.12doesnot show theassociationsamong classes—weshowed thesein Fig. 25.10. This is acommonpracticeofsystems designerswhendesigns arebeing devel- oped.Recallfrom Section 25.4 that in theUML,aclass’s attributes areplacedinthe mid- dle compartment of theclass’s rectangle. We list each attribute’snameand type separated by acolon (:), followed in some casesbyanequal sign (=)and an initialvalue. Considerthe userAuthenticated attribute of class ATM:

userAuthenticated :Boolean=false This attribute declaration contains threepiecesofinformation aboutthe attribute.The at- tribute name is userAuthenticated.The attribute type is Boolean.InC++,anattribute canberepresentedbyafundamental type,suchasbool, int or double,oraclasstype. We’vechosentomodel only primitive-type attributesinFig.25.12—wediscuss therea- soning behindthis decision shortly.[Note: Figure 25.12lists UML data typesfor theat- tributes.Whenweimplementthe system,we’ll associate theUML types Boolean, Integer and Double with theC++ fundamental types bool, int and double,respectively.]

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-20 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

ATM Account userAuthenticated :Boolean =false accountNumber :Integer pin :Integer availableBalance :Double totalBalance :Double BalanceInquiry accountNumber :Integer Screen

Withdrawal accountNumber :Integer amount :Double Keypad

Deposit accountNumber :Integer CashDispenser amount :Double count :Integer =500

BankDatabase DepositSlot

Fig. 25.12 | Classes with attributes.

We canalsoindicateaninitial value foranattribute. The userAuthenticated attri- bute in class ATM hasaninitialvalue of false.This indicatesthatthe system initially does notconsiderthe user to be authenticated. If an attribute hasnoinitial valuespecified, only itsnameand type (separatedbyacolon) areshown.For example, the accountNumber attri- bute of class BalanceInquiry is an Integer.Hereweshow no initialvalue,because the valueofthis attribute is anumber that we do notyet know—it will be determined at exe- cution time basedonthe account number enteredbythe currentATM user. Figure 25.12doesnot include anyattributes forclasses Screen, Keypad and DepositSlot.These areimportantcomponents of oursystem, forwhichour design process simply hasnot yetrevealed anyattributes. We maystill discover some,however, in theremaining design phases or when we implementthese classesinC++.This is per- fectly normal forthe iterativeprocessofsoftwareengineering. Software EngineeringObservation25.1 At theearly stages in the design process,classes oftenlackattributes (and operations). Such classesshould not be eliminated,however, because attributes (and operations)may become evident in the laterphasesofdesignand implementation.

Figure 25.12alsodoesnot include attributes forclass BankDatabase.Recallthatattri- butescan be representedbyeitherfundamentaltypes or class types. We’vechosento

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Self-ReviewExercisesfor Section 25.5 25-21 includeonlyfundamental-typeattributesinthe class diagraminFig.25.12 (and in similar classdiagrams throughoutthe case study).Aclass-typeattributeismodeledmore clearly as an association (in particular, acomposition)between the classwiththe attributeand the classofthe object of which theattributeisaninstance. Forexample, theclass diagramin Fig. 25.10indicatesthatclass BankDatabase participates in acomposition relationship with zero or more Account objects. From this composition,wecan determinethatwhen we implementthe ATMsysteminC++,we’ll be required to createanattribute of class BankDatabase to holdzero or more Account objects. Similarly,we’ll assign attributes to class ATM that correspond to itscomposition relationshipswithclasses Screen, Keypad, CashDispenser and DepositSlot.These composition-based attributes wouldberedun- dant if modeledinFig.25.12,because thecompositionsmodeledinFig. 25.10already convey thefactthatthe database contains information aboutzeroormore accountsand that an ATMiscomposed of ascreen,keypad,cashdispenserand depositslot. Software developers typically modelthese whole/part relationshipsascompositionsratherthanas attributesrequiredtoimplement therelationships. Theclass diagraminFig. 25.12provides asolid basisfor thestructure of ourmodel, butthe diagramisnot complete. In Section 25.6,weidentifythe statesand activities of theobjects in themodel, andinSection 25.7 we identify theoperations that theobjects perform.Aswepresent more of theUML andobject-orienteddesign, we’ll continueto strengthenthe structureofour model. Self-ReviewExercises forSection 25.5 25.8 We typically identify theattributes of the classesinour system by analyzingthe in therequirementsdocument. a) nounsand noun phrases b) descriptivewords and phrases c) verbsand verb phrases d) Allofthe above. 25.9 Whichofthe followingisnot an attributeofanairplane? a) length b) wingspan c) fly d) numberofseats 25.10 Describethe meaning of thefollowing attributedeclaration of class CashDispenser in the classdiagram in Fig. 25.12: count :Integer=500 25.6IdentifyingObjects’Statesand Activities [Note: This section canbestudied afterChapter5.] In Section 25.5,weidentifiedmanyofthe class attributes needed to implementthe ATM system andaddedthemtothe classdiagraminFig.25.12.Inthis section, we show how theseattributesrepresent an object’s state.Weidentify some keystatesthatour objectsmay occupy anddiscuss howobjects change state in response to various events occurring in the system.Wealsodiscuss theworkflow,oractivities,thatobjects perform in theATM sys- tem. We presentthe activitiesofBalanceInquiry and Withdrawal transaction objectsin this section, as they representtwo of thekey activities in theATM system.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-22 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

StateMachine Diagrams Each object in asystemgoesthrough aseriesofdiscrete states.Anobject’scurrentstateis indicatedbythe values of theobject’sattributes at agiven time. Statemachine diagrams (commonlycalled statediagrams)modelkey states of an object andshow underwhatcir- cumstancesthe object changesstate.Unlikethe class diagrams presentedinearliercase studysections,whichfocusedprimarilyonthe structure of thesystem,state diagrams mod- el some of the behavior of thesystem. Figure 25.13isasimplestatediagramthatmodels some of thestates of an objectof class ATM.The UML represents each state in astate diagramasaroundedrectangle with thenameofthe state placed inside it.Asolidcircle with an attachedstick arrowheaddes- ignatesthe initialstate.Recallthatwemodeledthis stateinformation as the Boolean attri- bute userAuthenticated in theclass diagramofFig. 25.12. This attribute is initializedto false,orthe “Usernot authenticated” state, according to thestatediagram.

bank database authenticates user

User notauthenticated User authenticated user exits system

Fig.25.13 | Statediagram forthe ATM object.

Thearrowswithstick arrowheadsindicate transitions betweenstates.Anobjectcan transition from onestate to anotherinresponse to various events that occurinthe system. Thenameordescription of theevent thatcauses atransition is writtennearthe linethat corresponds to thetransition.For example,the ATM objectchangesfrom the“User not authenticated” statetothe “Userauthenticated” state after thedatabase authenticatesthe user.Recallfrom therequirementsdocument that thedatabaseauthenticatesauser by comparingthe account number andPIN enteredbythe user with thoseofthe corre- spondingaccount in thedatabase. If thedatabaseindicates that theuserhas enteredavalid accountnumberand thecorrectPIN, the ATM objecttransitions to the“User authenti- cated” stateand changes its userAuthenticated attributetoavalue of true.Whenthe user exitsthe systembychoosing the“exit”option from themainmenu, the ATM object returnstothe “Usernot authenticated” stateinpreparation forthe next ATMuser. Software EngineeringObservation25.2 Software designers do not generally create statediagramsshowingevery possiblestate and statetransitionfor allattributes—there aresimplytoo many of them.State diagrams typically show onlythe most important or complexstatesand statetransitions.

Activity Diagrams Like astate diagram, an activity diagrammodels aspectsofsystem behavior.Unlikeastate diagram, an activitydiagrammodels an object’s workflow (sequenceofevents)during pro- gramexecution. An activity diagrammodels theactions theobjectwillperform andin what order. RecallthatweusedUML activity diagramstoillustratethe flow of control for thecontrol statements presentedinChapters4and 5. Figure 25.14models theactions involvedinexecuting a BalanceInquiry transaction. We assume that a BalanceInquiry objecthas been initializedand assigned avalid account

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.6 IdentifyingObjects’States andActivities 25-23 number (thatofthe current user), so theobjectknows which balance to retrieve.The dia- gramincludes theactions that occurafterthe user selectsabalance inquiry from themain menu andbefore theATM returns theusertothe main menu—a BalanceInquiry object doesnot perform or initiate theseactions,sowedonot modelthemhere. Thediagram beginswithretrieving the availablebalance of theuser’s account from thedatabase. Next, the BalanceInquiry retrievesthe totalbalance of theaccount.Finally,the transaction dis- playsthe balancesonthe screen.This action completes theexecution of thetransaction.

getavailable balance of user’s account from database

gettotal balance of user’s account from database

displaybalances on screen

Fig.25.14 | Activity diagramfor a BalanceInquiry transaction.

TheUML represents an action in an activity diagramasanaction state modeledbya rectanglewithits leftand right sidesreplacedbyarcs curvingoutward. Each action state contains an action expression—for example, “get available balance of user’s account from database”—that specifiesanaction to be performed.Anarrow with astick arrowhead con- nectstwo action states,indicating theorderinwhichthe actionsrepresented by theaction states occur. Thesolid circle (atthe topofFig. 25.14) represents theactivity’sinitial state—thebeginning of theworkflow before theobjectperformsthe modeledactions.In this case,the transaction firstexecutesthe “get available balance of user’s account from database”action expression.Second, thetransaction retrievesthe totalbalance.Finally,the transaction displays both balancesonthe screen.The solidcircleenclosedinanopencircle (atthe bottomofFig. 25.14) represents thefinal state—theend of theworkflow afterthe object performsthe modeledactions. Figure25.15 showsanactivitydiagramfor a Withdrawal transaction. We assume that a Withdrawal object hasbeenassignedavalidaccount number.Wedonot modelthe user selecting awithdrawalfrom themainmenuorthe ATMreturning the user to themain menu becausethese arenot actionsperformed by a Withdrawal object.The transaction firstdisplays amenuofstandardwithdrawal amounts (Fig.25.3) andanoption to cancel thetransaction. Thetransaction then inputsamenu selection from theuser. Theactivity flow nowarrives at adecisionsymbol. This pointdeterminesthe next action basedonthe associatedguardconditions. If theusercancels thetransaction, thesystem displaysan appropriate message. Next,the cancellation flow reachesamerge symbol,where this activityflowjoins thetransaction’s otherpossibleactivityflows (which we discuss shortly).

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-24 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

displaymenu of withdrawal amounts and option to cancel

input the menu selection

[user canceled transaction] displaycancel message [user selected an amount]

setamount attribute

[amount >available balance] displayerror message [amount <= available balance]

test whether sufficient cash is available in cash dispenser

[insufficient cash available] displayerror message [sufficient cash available]

interact with database to debit amount from user’s account

dispense cash

instruct user to take cash

[cash notdispensed and user did notcancel]

[cash dispensed or user canceled transaction]

Fig. 25.15 | Activity diagramfor a Withdrawal transaction.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Self-ReviewExercisesfor Section 25.6 25-25

Amerge canhave any number of incomingtransition arrows, but only one outgoingtran- sition arrow.The decision at thebottomofthe diagramdetermineswhether thetransac- tion should repeatfrom thebeginning.Whenthe user hascanceledthe transaction, the guardcondition “cashdispensed or user canceled transaction” is true,socontrol transi- tionstothe activity’s finalstate. If theuserselects awithdrawalamountfrom themenu, the transaction sets amount (anattributeofclass Withdrawal originallymodeledinFig.25.12)tothe valuechosenby theuser. Thetransaction next gets theavailable balance of theuser’saccount (i.e.,the availableBalance attribute of theuser’s Account object)fromthe database.The activity flow then arrives at anotherdecision. If therequested withdrawalamount exceedsthe user’s availablebalance,the system displaysanappropriate error messageinforming the user of theproblem. Control then merges with theother activity flowsbefore reachingthe decisionatthe bottomofthe diagram. Theguard decision “cashnot dispensedand user did notcancel” is true,sothe activityflowreturns to the topofthe diagram, andthe trans- action prompts theusertoinput anew amount. If therequested withdrawal amount is less than or equal to theuser’savailablebalance, the transaction testswhether thecashdispenserhas enough cash to satisfythe withdrawal request. If it does not, thetransaction displaysanappropriate errormessage andpasses throughthe mergebeforereachingthe finaldecision.Cashwas notdispensed, so theactivity flow returns to thebeginning of theactivitydiagram, andthe transaction prompts theuser to chooseanewamount. If sufficient cash is available,the transaction interactswiththe data- base to debitthe withdrawalamount from theuser’s account(i.e.,subtractthe amount from both the availableBalance and totalBalance attributesofthe user’s Account object). The transaction then dispensesthe desiredamountofcashand instructsthe user to takethe cash that is dispensed. Themainflowofactivitynextmergeswiththe twoerrorflows andthe can- cellationflow. In this case,cashwas dispensed, so theactivityflowreachesthe final state. We’vetaken the first stepsinmodeling theATM system’s behavior andhaveshown how an object’sattributes participateinthe object’s activities.InSection 25.7,weinvesti- gate theoperationsofour classes to create amore completemodel of thesystem’sbehavior.

Self-ReviewExercises forSection 25.6 25.11 Statewhether thefollowing statementistrue or false,and if false,explain why: Statedia- gramsmodel structural aspects of asystem. 25.12 An activity diagrammodelsthe that an object performs and theorder in which it performs them. a) actions b) attributes c) states d) statetransitions 25.13 Basedonthe requirements document,createanactivitydiagram for adeposit transaction.

25.7IdentifyingClass Operations [Note: This section canbestudied afterChapter6.] In Sections 25.4–25.6, we performed thefirstfew stepsinthe object-oriented design of ourATM system.InSection 25.4,weidentifiedthe classes that we’llneed to implement

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-26 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML andwecreated ourfirst classdiagram. In Section 25.5,wedescribed some attributes of our classes.InSection 25.6,weexaminedobjectstates andmodeledobjectstate transitions andactivities. Now,wedetermine some of theclass operations (or behaviors)neededto implementthe ATMsystem.

IdentifyingOperations An operation is aservice that objectsofaclass provide to clientsofthe class.Considerthe operations of some real-worldobjects.Aradio’s operationsinclude setting itsstation and volume (typically invokedbyaperson adjusting theradio’s controls).Acar’soperations include accelerating (invoked by thedriver pressing the acceleratorpedal), decelerating (invoked by thedriver pressing the brakepedal or releasing thegas pedal), turningand shifting gears. Softwareobjects canoffer operationsaswell—forexample, asoftware graphics object might offeroperationsfor drawing acircle, drawing aline,drawing a squareand thelike. Aspreadsheet softwareobjectmight offer operations like printingthe spreadsheet,totaling theelements in arow or columnand graphing information in the spreadsheet as abar chart or piechart. We canderivemanyofthe operations of each classbyexaminingthe keyverbs and verb phrasesinthe requirements document.Wethenrelate each of thesetoparticular classesinour system (Fig. 25.16).The verb phrasesinFig.25.16 help us determinethe operations of each class.

Class Verbsand verb phrases

ATM executes financial transactions BalanceInquiry [none in therequirements document] Withdrawal [none in therequirements document] Deposit [none in therequirements document] BankDatabase authenticates auser, retrievesanaccountbalance, credits adeposit amount to an account, debits awithdrawalamount from an account Account retrievesanaccountbalance, creditsadepositamount to an account, debits awithdrawalamount from an account Screen displays amessage to theuser Keypad receives numeric inputfromthe user CashDispenser dispensescash,indicates whether it contains enoughcashtosatisfy a withdrawal request DepositSlot receives adeposit envelope

Fig.25.16 | Verbsand verb phrasesfor each classinthe ATMsystem.

Modeling Operations To identifyoperations,weexamine the verb phraseslistedfor each classinFig.25.16.The “executesfinancialtransactions”phrase associatedwithclass ATM impliesthatclass ATM in- structstransactions to execute.Therefore, classes BalanceInquiry, Withdrawal and De- posit each need an operation to provide this servicetothe ATM. We placethisoperation

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.7Identifying ClassOperations 25-27

(which we’venamed execute)inthe thirdcompartment of thethree transaction classesin theupdatedclass diagramofFig. 25.17. DuringanATM session,the ATM objectwillin- voke the execute operation of each transaction objecttotellittoexecute.

ATM Account userAuthenticated :Boolean =false accountNumber :Integer pin :Integer availableBalance :Double totalBalance :Double BalanceInquiry validatePIN() :Boolean accountNumber :Integer getAvailableBalance() :Double execute() getTotalBalance() :Double credit() debit() Withdrawal

accountNumber :Integer Screen amount :Double execute() displayMessage()

Deposit Keypad accountNumber :Integer amount :Double execute() getInput() :Integer

BankDatabase CashDispenser count :Integer =500 authenticateUser() :Boolean dispenseCash() getAvailableBalance() :Double isSufficientCashAvailable() :Boolean getTotalBalance() :Double credit() DepositSlot debit()

isEnvelopeReceived() :Boolean

Fig.25.17 | Classesinthe ATMsystemwithattributesand operations.

TheUML represents operations (whichare implementedasmemberfunctionsin C++) by listing theoperation name,followedbyacomma-separated list of parameters in parentheses, acolon andthe returntype: operationName( parameter1, parameter2, …, parameterN ):return type Each parameterinthe comma-separatedparameterlistconsists of aparametername, fol- lowedbyacolon andthe parametertype: parameterName : parameterType Forthe moment,wedonot list theoperations’parameters—we’ll identifyand model theparametersofsomeofthe operations shortly.For some,wedonot yetknowthe return

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-28 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML types, so we also omit them from thediagram.These omissionsare perfectlynormalatthis point. As ourdesign andimplementation proceed,we’ll addthe remaining return types.

Operations of Class BankDatabase and Class Account Figure 25.16 liststhe phrase “authenticatesauser”nexttoclass BankDatabase—the database is theobjectthatcontains theaccountinformation necessary to determinewhether theac- count number andPIN enteredbyausermatchthoseofanaccountheldatthe bank.There- fore,class BankDatabase needsanoperation that providesanauthentication servicetothe ATM. We placethe operation authenticateUser in thethirdcompartment of class Bank- Database (Fig. 25.17).However,anobjectofclass Account,not class BankDatabase,stores theaccount number andPIN that mustbeaccessed to authenticate auser, so class Account mustprovide aservice to validate aPIN obtainedthrough user input against aPIN stored in an Account object.Therefore,weadd a validatePIN operation to class Account.Wespecify return type Boolean forthe authenticateUser and validatePIN operations. Each opera- tion returns avalue indicatingeitherthatthe operation wassuccessful in performing itstask (i.e.,areturnvalue of true)orthatitwas not(i.e.,areturnvalue of false). Figure 25.16lists several additional verb phrasesfor class BankDatabase:“retrieves an accountbalance,” “credits adeposit amount to an account” and “debitsawithdrawal amount from an account.” Like “authenticatesauser,” theseremainingphrasesrefer to services that thedatabasemustprovide to theATM,because thedatabaseholds allthe accountdata used to authenticate auserand perform ATMtransactions.However,objects of class Account actually perform theoperationstowhichthese phrasesrefer.Thus, we assign an operation to both class BankDatabase andclass Account to correspondtoeach of thesephrases. Recallfrom Section 25.4 that, becauseabank account contains sensitive information,wedonot allowthe ATMtoaccessaccountsdirectly.The databaseactsasan intermediary betweenthe ATMand the account data,thuspreventing unauthorized access .Aswe’ll seeinSection 25.8,class ATM invokesthe operationsofclass BankDatabase, each of which in turn invokes theoperation with thesamenameinclass Account. Thephrase “retrieves an account balance”suggeststhatclasses BankDatabase and Account each need a getBalance operation.However,recallthatwecreated twoattributes in class Account to representabalance—availableBalance and totalBalance.Abalance inquiry requires access to both balance attributessothatitcan display them to theuser, butawithdrawalneeds to check only thevalue of availableBalance.Toallow objectsin thesystemtoobtaineachbalance attributeindividually,weadd operations getAvail- ableBalance and getTotalBalance to thethirdcompartment of classes BankDatabase and Account (Fig. 25.17).WespecifyareturntypeofDouble foreachofthese operations, becausethe balance attributes which they retrieve areoftype Double. Thephrases “creditsadepositamounttoanaccount”and “debitsawithdrawal amount fromanaccount”indicate that classes BankDatabase and Account mustperform operations to update an account during adeposit andwithdrawal,respectively. We there- fore assign credit and debit operations to classes BankDatabase and Account.You may recall that crediting an account (asinadeposit) adds an amountonlytothe totalBalance attribute.Debiting an account (asinawithdrawal),onthe otherhand,subtracts the amount frombothbalance attributes.Wehidethese implementation detailsinside class Account.This is agood example of encapsulation andinformation hiding. If this were arealATM system, classes BankDatabase and Account wouldalsoprovide aset of operationstoallowanother bankingsystemtoupdate auser’s account balance after

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.7Identifying ClassOperations 25-29 either confirming or rejecting allorpartofadeposit. Operation confirmDepositAmount, forexample,would addanamount to the availableBalance attribute, thus making depositedfunds availablefor withdrawal. Operation rejectDepositAmount wouldsub- tractanamountfromthe totalBalance attribute to indicate that aspecifiedamount, which hadrecently been depositedthrough theATM andadded to the totalBalance,was notfound in thedeposit envelope.The bank wouldinvokethis operation after deter- mining either that theuserfailed to includethe correct amountofcash or that anychecks did not clear(i.e,they“bounced”). While addingthese operations wouldmakeour system more complete, we do notinclude them in ourclass diagrams or ourimplementation becausetheyare beyond the scopeofthe case study.

Operations of Class Screen Class Screen “displays amessage to theuser” at varioustimes in an ATMsession. Allvisual outputoccurs through thescreen of theATM.The requirementsdocument describes many typesofmessages(e.g.,awelcomemessage,anerror message, athank youmessage) that thescreen displaystothe user.The requirements document also indicatesthatthe screen displays promptsand menustothe user.However,aprompt is really just amessage describingwhatthe user should input next, and amenuisessentially atypeofprompt con- sistingofaseries of messages (i.e.,menuoptions) displayed consecutively.Therefore, rath- er than assign class Screen an individualoperation to display each type of message, prompt andmenu, we simplycreate oneoperation that candisplay anymessage specifiedbyapa- rameter. We placethis operation (displayMessage)inthe thirdcompartment of class Screen in ourclass diagram(Fig.25.17). We do not worry aboutthe parameterofthis operation at this time—wemodelthe parameter laterinthis section.

Operations of Class Keypad From thephrase “receivesnumeric input from theuser” listedbyclass Keypad in Fig. 25.16, we concludethatclass Keypad should performagetInput operation. Because theATM’s keypad,unlikeacomputerkeyboard, containsonlythe numbers0–9, we specifythatthis operation returnsaninteger value.Recallfromthe requirements document that in different situationsthe user mayberequiredtoenteradifferenttype of number (e.g., an account number,aPIN, thenumberofamenu option,adepositamountasanumber of cents). Class Keypad simplyobtains anumeric valuefor aclientofthe class—it does not determine whetherthe value meetsany specific criteria.Any classthatusesthisoperation must verify that theuserenters appropriate numbers,and if not,display error messages viaclass Screen). [Note: Whenweimplementthe system,wesimulate theATM’skeypad with a computerkeyboard, andfor simplicityweassumethatthe user doesnot enternonnumeric inputusing keys on thecomputerkeyboardthatdonot appear on theATM’s keypad.]

Operations of Class CashDispenser and Class DepositSlot Figure 25.16lists “dispenses cash”for class CashDispenser.Therefore,wecreate opera- tion dispenseCash andlistitunder class CashDispenser in Fig. 25.17. Class CashDis- penser also “indicates whetheritcontains enough cash to satisfyawithdrawalrequest.” Thus,weinclude isSufficientCashAvailable,anoperation that returnsavalueofUML type Boolean,inclass CashDispenser.Figure25.16 also lists“receives adeposit envelope” forclass DepositSlot.The depositslotmustindicate whetheritreceivedanenvelope,so we placeanoperation isEnvelopeReceived,which returnsaBoolean value, in thethird

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-30 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML compartment of class DepositSlot.[Note: Arealhardwaredeposit slot wouldmostlikely send theATM asignaltoindicate that an envelope wasreceived. We simulatethis behav- ior,however,withanoperation in class DepositSlot that class ATM caninvoketofindout whetherthe deposit slot received an envelope.]

Operations of Class ATM We do not list anyoperationsfor class ATM at this time.Weare notyet aware of anyservices thatclass ATM provides to otherclasses in thesystem. Whenweimplementthe system with C++code,however,operations of this class, andadditional operations of theother classes in thesystem, may emerge.

Identifyingand Modeling OperationParameters So far, we’venot been concernedwiththe parameters of ouroperations—we’ve attempted to gain only abasic understanding of theoperations of each class. Let’snow takeacloser look at some operation parameters. We identifyanoperation’s parametersbyexamining what data theoperation requirestoperform itsassigned task. Considerthe authenticateUser operation of class BankDatabase.Toauthenticate a user,this operation mustknowthe account number andPIN supplied by theuser. Thus we specifythatoperation authenticateUser takesinteger parameters userAccountNumber and userPIN,whichthe operation must compare to theaccount number andPIN of an Account objectinthe database.Weprefixthese parameternames with “user”toavoid con- fusion betweenthe operation’s parameter namesand the attribute namesthatbelongto class Account.Welistthese parameters in theclass diagraminFig.25.18 that models only class BankDatabase.[Note: It’s perfectlynormal to modelonlyone classinaclassdiagram. In this case,weare most concernedwithexaminingthe parameters of this one classinpar- ticular, so we omit theother classes.Inclass diagrams laterinthe case study, in which parameters arenolongerthe focusofour attention, we omit theparameters to save space. Remember,however,thatthe operationslistedinthese diagramsstill have parameters.] Recall that theUML models each parameter in an operation’s comma-separated parameter list by listingthe parameter name, followed by acolon andthe parametertype (inUML notation). Figure 25.18thusspecifiesthatoperation authenticateUser takes two parameters—userAccountNumber and userPIN,bothoftype Integer.Whenwe implementthe system in C++, we’ll representthese parameterswith int values.

BankDatabase

authenticateUser( userAccountNumber :Integer,userPIN :Integer ):Boolean getAvailableBalance( userAccountNumber :Integer ):Double getTotalBalance( userAccountNumber :Integer ):Double credit( userAccountNumber :Integer,amount :Double ) debit( userAccountNumber :Integer,amount :Double )

Fig.25.18 | Class BankDatabase withoperation parameters.

Class BankDatabase operations getAvailableBalance, getTotalBalance, credit and debit also each require a userAccountNumber parameter to identify theaccount to

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.7Identifying ClassOperations 25-31 which thedatabase must applythe operations, so we includethese parameters in theclass diagramofFig. 25.18. In addition,operations credit and debit each require a Double parameter amount to specifythe amount of moneytobecredited or debited, respectively. Theclass diagraminFig. 25.19models theparameters of class Account’s operations. Operation validatePIN requiresonlyauserPIN parameter,whichcontains the user-spec- ifiedPIN to be comparedwiththe PINassociatedwiththe account.Liketheir counter- partsinclass BankDatabase,operations credit and debit in class Account each require a Double parameter amount that indicatesthe amountofmoney involvedinthe operation. Operations getAvailableBalance and getTotalBalance in class Account require no additional data to perform theirtasks.Class Account’s operations do not require an accountnumberparameter—each of theseoperations canbeinvoked only on aspecific Account object, so including aparameter to specifyanAccount is unnecessary.

Account accountNumber :Integer pin :Integer availableBalance :Double totalBalance :Double validatePIN( userPIN: Integer) :Boolean getAvailableBalance() :Double getTotalBalance() :Double credit( amount :Double ) debit( amount :Double )

Fig.25.19 | Class Account withoperation parameters.

Figure 25.20models class Screen with aparameter specifiedfor operation display- Message.This operation requiresonlyaString parameter message that indicatesthe text to be displayed.Recallthatthe parametertypeslistedinour classdiagrams areinUML notation,sothe String type listed in Fig. 25.20referstothe UMLtype.Whenweimple- ment thesysteminC++,we’ll in factuse aC++ string objecttorepresent thisparameter.

displayMessage( message:String )

Fig.25.20 | Class Screen withoperation parameters.

Theclass diagraminFig.25.21 specifiesthatoperation dispenseCash of class Cash- Dispenser takesaDouble parameter amount to indicate theamountofcash(in dollars)to be dispensed. Operation isSufficientCashAvailable also takesaDouble parameter amount to indicate theamountofcash in question. We do notdiscuss parameters foroperation execute of classes BalanceInquiry, Withdrawal and Deposit,operation getInput of class Keypad andoperation isEnvelope- Received of class DepositSlot.Atthis point in ourdesign process, we cannot determine

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-32 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

CashDispenser count :Integer =500 dispenseCash(amount :Double ) isSufficientCashAvailable( amount :Double ):Boolean

Fig.25.21 | Class CashDispenser with operationparameters. whetherthese operations require additional data to perform theirtasks,soweleave their parameterlists empty. As we progress through thecasestudy,wemay decide to addparam- eterstothese operations. In this section, we’vedeterminedmanyofthe operations performed by theclasses in theATM system.We’ve identifiedthe parametersand return typesofsomeofthe opera- tions. As we continue ourdesign process,the number of operationsbelonging to each class mayvary—we might find that newoperations areneeded or that some currentoperations areunnecessary—andwemight determinethatsomeofour class operations need addi- tional parameters anddifferent return types.

Self-ReviewExercises forSection 25.7 25.14 Whichofthe followingisnot abehavior? a) readingdatafromafile b) printing output c) text output d) obtaininginput from theuser 25.15 If youwere to addtothe ATMsystem an operationthatreturnsthe amount attributeofclass Withdrawal,how and wherewouldyou specifythisoperation in theclass diagramofFig.25.17? 25.16 Describethe meaning of thefollowing operation listingthatmight appear in aclass diagram for an object-oriented design of acalculator:

add( x:Integer, y:Integer ):Integer

25.8IndicatingCollaborationAmong Objects [Note: This section canbestudied afterChapter7.] In this section, we concentrate on thecollaborations(interactions) amongobjects in our ATMsystem. When twoobjects communicatewitheachother to accomplishatask,they aresaidtocollaborate—theydothis by invoking oneanother’s operations.Acollabora- tion consistsofanobjectofone classsending a message to an objectofanotherclass.Mes- sagesare sent in C++via member-function calls. In Section 25.7,wedeterminedmanyofthe operations of thesystem’sclasses.Next, we concentrate on the messages thatinvokethese operations.Toidentifythe collabora- tions, we return to therequirements document in Section 25.3.Recallthatthis document specifiesthe rangeofactivitiesthatoccurduringanATM session (e.g., authenticating a user,performingtransactions). Thesteps used to describehow thesystemmustperform each of thesetasks areour firstindication of thecollaborationsinour system.Aswepro- ceedthrough this andthe remaining sections, we maydiscover additional collaborations.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.8Indicating Collaboration AmongObjects 25-33

Identifyingthe Collaborations in aSystem We identify thecollaborationsinthe systembycarefully reading therequirementsdocu- ment sections that specifywhatthe ATMshould do to authenticate auserand to perform each transaction type. Foreachaction or step described,wedecidewhichobjects in our system must interacttoachievethe desired result.Weidentifyone object as the sending object (i.e., theobjectthatsends themessage)and anotherasthe receivingobject (i.e., the object that offers that operation to clientsofthe class).Wethenselectone of thereceiving object’s operations(identifiedinSection 25.7)thatmust be invoked by thesending object to produce theproper behavior. For example, theATM displaysawelcomemessage when idle. We know that an object of class Screen displaysamessagetothe user viaits dis- playMessage operation. Thus,wedecidethatthe system candisplay awelcomemessage by employingacollaboration betweenthe ATM andthe Screen in which the ATM sendsa displayMessage messagetothe Screen by invoking the displayMessage operation of class Screen.[Note: To avoid repeating thephrase “an objectofclass…,”werefer to each object simply by using itsclass name preceded by an article(“a,” “an”or“the”)—forex- ample, “the ATM”referstoanobjectofclass ATM.] Figure 25.22lists thecollaborationsthatcan be derivedfromthe requirements docu- ment.For each sending object,welistthe collaborationsinthe orderinwhichtheyare discussed in therequirements document.Welisteachcollaboration involving aunique sender,message andrecipient only once,eventhoughthe collaboration mayoccurseveral timesduringanATM session. For example,the firstrow in Fig. 25.22indicatesthatthe ATM collaborateswiththe Screen whenever the ATM needstodisplay amessage to theuser.

to an object An object of class… sends themessage… of class…

ATM displayMessage Screen getInput Keypad authenticateUser BankDatabase execute BalanceInquiry execute Withdrawal execute Deposit BalanceInquiry getAvailableBalance BankDatabase getTotalBalance BankDatabase displayMessage Screen Withdrawal displayMessage Screen getInput Keypad getAvailableBalance BankDatabase isSufficientCashAvailable CashDispenser debit BankDatabase dispenseCash CashDispenser Deposit displayMessage Screen getInput Keypad isEnvelopeReceived DepositSlot credit BankDatabase

Fig. 25.22 | Collaborationsinthe ATMsystem. (Part1of 2.)

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-34 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

BankDatabase validatePIN Account getAvailableBalance Account getTotalBalance Account debit Account credit Account

Fig. 25.22 | Collaborationsinthe ATMsystem. (Part2of 2.)

Let’sconsiderthe collaborationsinFig.25.22.Beforeallowingauser to perform any transactions,the ATMmustpromptthe user to enteranaccount number,thentoenter a PIN. It accomplisheseachofthese tasksbysending a displayMessage messagetothe Screen.Bothofthese actionsrefer to thesame collaboration between the ATM andthe Screen,which is alreadylistedinFig.25.22.The ATM obtains input in response to a prompt by sending a getInput messagetothe Keypad.Next, theATM must determine whetherthe user-specifiedaccount number andPIN matchthose of an accountinthe database.Itdoessobysending an authenticateUser messagetothe BankDatabase.Recall that the BankDatabase cannotauthenticate auserdirectly—only theuser’s Account (i.e., the Account that contains the account number specifiedbythe user)can access theuser’s PIN to authenticate theuser. Figure 25.22therefore listsacollaboration in which the BankDatabase sendsavalidatePIN messagetoanAccount. Afterthe user is authenticated, the ATM displays themainmenubysending aseries of displayMessage messagestothe Screen andobtains input containing amenuselection by sendingagetInput message to the Keypad.We’ve alreadyaccounted forthese collabora- tions. Afterthe userchoosesatype of transactiontoperform,the ATM executesthe transac- tion by sendinganexecute message to an objectofthe appropriate transactionclass (i.e., a BalanceInquiry,aWithdrawal or a Deposit). For example, if theuserchoosestoper- form abalance inquiry, the ATM sendsanexecute message to a BalanceInquiry. Furtherexamination of therequirementsdocument revealsthe collaborations involved in executing each transaction type.ABalanceInquiry retrievesthe amount of moneyavailable in theuser’s account by sending a getAvailableBalance messagetothe BankDatabase,whichrespondsbysending a getAvailableBalance messagetothe user’s Account.Similarly,the BalanceInquiry retrievesthe amount of moneyondeposit by sendingagetTotalBalance messagetothe BankDatabase,whichsends thesame message to theuser’s Account.Todisplay both measures of theuser’sbalance at thesame time,the BalanceInquiry sendsadisplayMessage messagetothe Screen. A Withdrawal sendsthe Screen several displayMessage messages to display amenu of standard withdrawalamounts (i.e.,$20,$40,$60,$100, $200). The Withdrawal sends the Keypad a getInput messagetoobtainthe user’s menu selection, then determines whetherthe requestedwithdrawal amountislessthanorequal to theuser’s accountbal- ance.The Withdrawal canobtainthe amount of moneyavailable in theaccount by sendingthe BankDatabase a getAvailableBalance message. The Withdrawal then tests whetherthe cash dispenser contains enough cash by sendingthe CashDispenser an isSufficientCashAvailable message. A Withdrawal sendsthe BankDatabase a debit

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.8Indicating Collaboration AmongObjects 25-35 messagetodecreasethe user’s account balance.The BankDatabase sendsthe same message to theappropriate Account.Recallthatdebitingfunds from an Account decreases both the totalBalance andthe availableBalance.Todispense therequested amountofcash, the Withdrawal sendsthe CashDispenser a dispenseCash message. Finally, the Withdrawal sendsadisplayMessage messagetothe Screen,instructing theusertotakethe cash. A Deposit responds to an execute messagefirstbysending a displayMessage mes- sage to the Screen to prompt theuserfor adeposit amount. The Deposit sendsaget- Input messagetothe Keypad to obtain theuser’s input. The Deposit then sendsa displayMessage message to the Screen to tell theusertoinsertadeposit envelope.To determinewhether thedeposit slot received an incoming depositenvelope, the Deposit sendsanisEnvelopeReceived messagetothe DepositSlot.The Deposit updatesthe user’s account by sending a credit messagetothe BankDatabase,whichsubsequently sendsacredit messagetothe user’s Account.Recallthatcrediting funds to an Account increases the totalBalance butnot the availableBalance.

InteractionDiagrams Now that we’veidentifiedpossiblecollaborationsbetween theobjects in ourATM system, let’s graphically modelthese interactionsusing theUML.Several types of interaction di- agrams modelthe behavior of asystembyshowing how objectsinteractwithone another. The communication diagram emphasizeswhichobjects participate in collaborations. [Note: Communication diagrams were called collaborationdiagrams in earlierversionsof theUML.] Like thecommunication diagram,the sequencediagram showscollaborations amongobjects,but it emphasizes when messages aresentbetween objects over time.

CommunicationDiagrams Figure 25.23shows acommunication diagramthatmodels the ATM executing a BalanceInquiry.Objects aremodeledinthe UMLasrectangles containing namesinthe form objectName :ClassName.Inthis example, which involvesonlyone objectofeach type,wedisregard theobjectnameand listonlyacolon followedbythe class name.[Note: Specifying the name of each objectinacommunication diagram is recommended when modeling multipleobjects of thesametype.] Communicating objects areconnectedwith solidlines,and messages arepassedbetween objectsalong theselinesinthe direction shownbyarrows. Thenameofthe message, which appearsnexttothe arrow,isthe name of an operation (i.e.,amember function)belonging to the receivingobject— think of the name as aservice thatthe receivingobjectprovides to sending objects (its“clients”).

execute() :ATM :BalanceInquiry

Fig.25.23 | Communicationdiagram of theATM executingabalance inquiry.

Thesolid filled arrow in Fig. 25.23represents amessage—or synchronous call—in theUML andafunctioncallinC++.This arrowindicatesthatthe flow of control is from thesending object (the ATM)tothe receivingobject(aBalanceInquiry). Sincethisisasyn- chronouscall, thesending object maynot send anothermessage,ordoanythingatall, until the receiving object processesthe message andreturns control to thesending object—the sender just

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-36 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML waits. For example,inFig.25.23,the ATM calls member function execute of a BalanceIn- quiry andmay notsendanothermessage until execute hasfinishedand returnscontrol to the ATM.[Note: If this were an asynchronous call,representedbyastick arrowhead,the sendingobjectwould nothave to wait forthe receivingobjecttoreturncontrol—it would continuesending additional messages immediately following the asynchronouscall. Asyn- chronouscalls oftencan be implementedinC++ using platform-specific librariesprovided with your compiler. Suchtechniques arebeyondthe scopeofthis book.]

Sequence of MessagesinaCommunicationDiagram Figure 25.24showsacommunication diagramthatmodelsthe interactionsamong objects in thesystem when an object of class BalanceInquiry executes.Weassume that theobject’s accountNumber attribute contains the accountnumberofthe current user.The collabora- tionsinFig.25.24 begin afterthe ATM sendsanexecute messagetoaBalanceInquiry (i.e., theinteraction modeledinFig.25.23). Thenumbertothe left of amessage name indicates theorderinwhichthe messageispassed. The sequenceofmessages in acommunication diagramprogressesinnumerical orderfrom leasttogreatest.Inthisdiagram,the number- ing starts with message 1 andendswithmessage 3.The BalanceInquiry firstsends a getAvailableBalance messagetothe BankDatabase (message 1), then sendsagetTotal- Balance message to the BankDatabase (message 2). Within theparentheses following a messagename, we canspecifyacomma-separatedlistofthe namesofthe parameters sent with themessage (i.e.,arguments in aC++ function call)—the BalanceInquiry passesat- tribute accountNumber with itsmessagestothe BankDatabase to indicatewhich Account’s balance information to retrieve.Recallfrom Fig. 25.18thatoperations getAvailableBal- ance and getTotalBalance of class BankDatabase each require aparametertoidentifyan account.The BalanceInquiry next displaysthe availableBalance andthe totalBalance to theuserbypassing a displayMessage message to the Screen (message 3)thatincludes aparameterindicating the message to be displayed.

3: displayMessage( message)

:BalanceInquiry

1: getAvailableBalance( accountNumber ) 2: getTotalBalance( accountNumber )

:BankDatabase :Account

1.1: getAvailableBalance() 2.1: getTotalBalance()

Fig.25.24 | Communicationdiagram forexecuting abalance inquiry.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25.8Indicating Collaboration AmongObjects 25-37

Figure 25.24models twoadditional messages passing from the BankDatabase to an Account (message 1.1 andmessage 2.1). To provide the ATM with thetwo balancesofthe user’s Account (asrequestedbymessages 1 and 2), the BankDatabase must passa getAvailableBalance andagetTotalBalance messagetothe user’s Account.Messages passed within thehandling of anothermessage arecalled nested messages.The UMLrec- ommendsusing adecimal numbering scheme to indicate nested messages.For example, message 1.1 is thefirst messagenestedinmessage 1—the BankDatabase passes a get- AvailableBalance messagewhile processing BankDatabase’s messageofthe same name. [Note: If the BankDatabase needed to pass asecondnestedmessage whileprocessing mes- sage 1,the second message wouldbenumbered 1.2.] Amessage maybepassedonlywhen allthe nested messages from thepreviousmessage have been passed—e.g.,the BalanceIn- quiry passes message 3 only aftermessages 2 and 2.1 have been passed, in that order. Thenestednumberingscheme used in communication diagrams helpsclarify pre- ciselywhenand in what contexteachmessage is passed. For example, if we numbered the messages in Fig. 25.24using aflatnumberingscheme (i.e., 1, 2, 3, 4, 5), someonelooking at thediagrammight not be able to determinethat BankDatabase passesthe getAvailableBalance message(message 1.1)toanAccount during the BankDatabase’s processing of message 1,asopposedtoafter completing theprocessing of message 1.The nested decimalnumbers makeitclear that thesecond getAvailableBalance message (message 1.1)ispassedtoanAccount within thehandling of thefirst getAvailableBal- ance message(message 1)bythe BankDatabase. Sequence Diagrams Communication diagrams emphasize theparticipantsincollaborationsbut modeltheir timing abit awkwardly.Asequence diagram helpsmodelthe timing of collaborations more clearly.Figure25.25 showsasequence diagram modeling thesequenceofinterac- tionsthatoccurwhenaWithdrawal executes.The dottedline extending down from an object’s rectangleisthatobject’s lifeline,whichrepresentsthe progression of time.Actions typically occuralong an object’s lifeline in chronological order from toptobottom—an ac- tion near thetop typically happens before onenearthe bottom. Messagepassing in sequence diagrams is similartomessage passing in communica- tion diagrams.Asolidarrow with afilled arrowhead extendingfrom thesending object to thereceivingobjectrepresentsamessagebetween twoobjects.The arrowheadpointstoan activation on thereceivingobject’slifeline.Anactivation,shownasathin vertical rect- angle, indicatesthatanobjectisexecuting. When an object returnscontrol,areturnmes- sage,representedasadashed line with astick arrowhead,extends from theactivation of theobjectreturning control to theactivation of theobjectthatinitially sent the message. To eliminate clutter, we omit thereturn-messagearrows—theUML allows this practice to make diagrams more readable. Like communication diagrams,sequence diagrams can indicate messageparameters betweenthe parentheses following amessage name. Thesequence of messages in Fig. 25.25beginswhenaWithdrawal prompts theuser to chooseawithdrawal amount by sending a displayMessage messagetothe Screen.The Withdrawal then sendsagetInput messagetothe Keypad,whichobtains input from the user.We’ve alreadymodeledthe controllogic involved in a Withdrawal in theactivitydia- gramofFig. 25.15, so we do notshow this logic in thesequence diagram of Fig.25.25. Instead, we modelthe best-case scenario in which thebalance of theuser’s account is greaterthanorequal to thechosenwithdrawal amount, andthe cash dispenser contains a

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-38 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

:Withdrawal :Keypad :Account

:Screen :BankDatabase :CashDispenser

displayMessage( message)

getAvailableBalance( accountNumber ) getAvailableBalance()

isSufficientCashAvailable( amount )

debit( accountNumber,amount ) debit( amount )

dispenseCash( amount )

Fig.25.25 | Sequencediagram that models a Withdrawal executing. sufficient amount of cash to satisfythe request. For information on how to modelcontrol logic in asequence diagram, please refertothe webresourcesatthe endofSection 25.3. Afterobtaining awithdrawalamount,the Withdrawal sendsagetAvailableBalance messagetothe BankDatabase,whichinturnsends a getAvailableBalance messagetothe user’s Account.Assumingthatthe user’s account hasenoughmoney available to permit thetransaction,the Withdrawal next sendsanisSufficientCashAvailable messageto the CashDispenser.Assumingthatthere is enough cash available, the Withdrawal decreases thebalance of theuser’saccount (i.e.,boththe totalBalance andthe avail- ableBalance)bysending a debit messagetothe BankDatabase.The BankDatabase responds by sending a debit message to theuser’s Account.Finally,the Withdrawal sends a dispenseCash messagetothe CashDispenser andadisplayMessage messagetothe Screen,telling theusertoremovethe cash from themachine.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Self-ReviewExercisesfor Section 25.8 25-39

We’veidentifiedthe collaborationsamong theATM system’s objects andmodeled some of them using UMLinteraction diagrams—bothcommunication diagramsand sequence diagrams. In Section 26.2, we enhance thestructure of ourmodeltocompletea preliminary object-oriented design,thenweimplement theATM system in C++. Self-ReviewExercises forSection 25.8 25.17 A(n) consists of an object of one classsending amessage to an objectofanother class. a) association b) aggregation c) collaboration d) composition 25.18 Whichformofinteraction diagramemphasizes what collaborations occur?Which form em- phasizes when collaborations occur? 25.19 Create asequencediagram that models theinteractions amongobjectsinthe ATMsystem that occurwhenaDeposit executes successfully, and explain thesequenceofmessagesmodeled by thediagram. 25.9Wrap-Up In this chapter, youlearned how to work from adetailedrequirements document to de- velopanobject-oriented design.You worked with sixpopular typesofUML diagrams to graphicallymodelanobject-orientedautomated teller machine softwaresystem. In Section 26.3,wetunethe design using inheritance,thencompletelyimplementthe design in an 850-line C++application.

AnswerstoSelf-Review Exercises 25.1 Figure 25.26 shows ause case diagram foramodified version of ourATM system that alsoallows userstotransfermoney betweenaccounts. 25.2 b. 25.3 d.

Deposit Funds

User Transfer Funds Between Accounts

Fig. 25.26 | Usecasediagram foramodifiedversion of ourATM system that also allows userstotransfermoney betweenaccounts.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-40 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

25.4 [Note: Answersmay vary.] Figure 25.27presentsaclassdiagram that showssomeofthe compositionrelationships of aclass Car. 25.5 c. [Note: In acomputer network, this relationship could be many-to-many.] 25.6 True. 25.7 Figure25.28 presents an ATM classdiagram includingclass Deposit insteadofclass With- drawal.Notethat Deposit does not access CashDispenser,but does access DepositSlot.

151 1 SteeringWheel Car SeatBelt

Fig.25.27 | Classdiagram showingcompositionrelationships of aclass Car.

1 1 1 Keypad CashDispenser

1 DepositSlot Screen 1 1 1

1111 0..1 0..10..1 Executes ATM Deposit 0..1 1 0..1 Authenticates user against 1

BankDatabase Accesses/modifies an account balance through 1 Contains 0..*

Fig. 25.28 | Class diagram forthe ATMsystemmodel includingclass Deposit.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. Answers to Self-ReviewExercises 25-41

25.8 b. 25.9 c. Fly is an operationorbehaviorofanairplane,not an attribute. 25.10 This indicates that count is an Integer with an initialvalue of 500.Thisattribute keeps trackofthe numberofbills availableinthe CashDispenser at any giventime. 25.11 False. Statediagramsmodel some of thebehaviorofasystem. 25.12 a. 25.13 Figure25.29’s activity diagrammodelsthe actions that occurafter theuserchooses thede- positoptionfromthe main menu and before theATM returnsthe usertothe main menu. Recall that part of receiving adeposit amount from theuserinvolves convertinganintegernumberofcents to adollaramount.Also recall that creditingadepositamounttoanaccount involves increasing onlythe totalBalance attributeofthe user’s Account object. Thebankupdates the availableBal-

prompt user to enter adeposit amount or cancel

receiveinput from user

[usercanceledtransaction]

[userentered an amount]

displaycancel message setamount attribute

instruct user to insertdeposit envelope

attempt to receivedeposit envelope

[deposit envelope notreceived] [deposit envelope received]

interact with database displayerror message to credit amount to user’s account

Fig. 25.29 | Activity diagramfor a Deposit transaction.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved. 25-42 Chapter25ATM Case Study,Part1:Object-Oriented Designwiththe UML

ance attributeofthe user’s Account objectonlyafter confirmingthe amount of cash in thedeposit envelope and after theenclosedchecksclear—thisoccursindependently of theATM system. 25.14 c. 25.15 To specify an operationthatretrievesthe amount attributeofclass Withdrawal,the following operation would be placed in theoperation (i.e., third) compartmentofclass Withdrawal: getAmount( ):Double

25.16 This is an operationnamed add that takesintegers x and y as parameters and returnsanin- tegervalue. 25.17 c. 25.18 Communication diagrams emphasize what collaborations occur. Sequence diagrams em- phasize when collaborations occur. 25.19 Figure 25.30presents asequence diagramthatmodelsthe interactions between objectsthat occurwhenaDeposit executes successfully. A Deposit firstsends a displayMessage messagetothe Screen to askthe user to enter adeposit amount.Next, it sendsagetInput messagetothe Keypad to receive inputfromthe user. Then, it instructsthe user to insert adeposit envelope by sendinga displayMessage messagetothe Screen.Itthen sendsanisEnvelopeReceived messagetothe Depos- itSlot to confirm that the deposit envelope hasbeen received.Finally,itincreasesthe totalBalance attribute(butnot the availableBalance attribute) of theuser’s Account by sendingacredit message to the BankDatabase.The BankDatabase respondsbysendingthe same messagetothe user’s Account.

:Deposit :Keypad :BankDatabase

:Screen :DepositSlot :Account

isEnvelopeReceived()

credit( accountNumber,amount ) credit( amount )

Fig.25.30 | Sequencediagram that models a Deposit executing.

© 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

design-an-atm.md

Latest commit, file metadata and controls, design an atm, let's design an atm..

We'll cover the following:

System Requirements

How atm works, use case diagram, class diagram, activity diagrams, sequence diagram.

An automated teller machine (ATM) is an electronic telecommunications instrument that provides the clients of a financial institution with access to financial transactions in a public space without the need for a cashier or bank teller. ATMs are necessary as not all the bank branches are open every day of the week, and some customers may not be in a position to visit a bank each time they want to withdraw or deposit money.

ATM

The main components of the ATM that will affect interactions between the ATM and its users are:

  • Card reader: to read the users’ ATM cards.
  • Keypad: to enter information into the ATM e.g. PIN. cards.
  • Screen: to display messages to the users.
  • Cash dispenser: for dispensing cash.
  • Deposit slot: For users to deposit cash or checks.
  • Printer: for printing receipts.
  • Communication/Network Infrastructure: it is assumed that the ATM has a communication infrastructure to communicate with the bank upon any transaction or activity.

The user can have two types of accounts: 1) Checking, and 2) Savings, and should be able to perform the following five transactions on the ATM:

  • Balance inquiry: To see the amount of funds in each account.
  • Deposit cash: To deposit cash.
  • Deposit check: To deposit checks.
  • Withdraw cash: To withdraw money from their checking account.
  • Transfer funds: To transfer funds to another account.

The ATM will be managed by an operator, who operates the ATM and refills it with cash and receipts. The ATM will serve one customer at a time and should not shut down while serving. To begin a transaction in the ATM, the user should insert their ATM card, which will contain their account information. Then, the user should enter their Personal Identification Number (PIN) for authentication. The ATM will send the user’s information to the bank for authentication; without authentication, the user cannot perform any transaction/service.

The user’s ATM card will be kept in the ATM until the user ends a session. For example, the user can end a session at any time by pressing the cancel button, and the ATM Card will be ejected. The ATM will maintain an internal log of transactions that contains information about hardware failures; this log will be used by the ATM operator to resolve any issues.

  • Identify the system user through their PIN.
  • In the case of depositing checks, the amount of the check will not be added instantly to the user account; it is subject to manual verification and bank approval.
  • It is assumed that the bank manager will have access to the ATM’s system information stored in the bank database.
  • It is assumed that user deposits will not be added to their account immediately because it will be subject to verification by the bank.
  • It is assumed the ATM card is the main player when it comes to security; users will authenticate themselves with their debit card and security pin.

Here are the actors of the ATM system and their use cases:

Operator: The operator will be responsible for the following operations:

  • Turning the ATM ON/OFF using the designated Key-Switch.
  • Refilling the ATM with cash.
  • Refilling the ATM’s printer with receipts.
  • Refilling the ATM’s printer with INK.
  • Take out deposited cash and checks.

Customer: The ATM customer can perform the following operations:

  • Balance inquiry: the user can view his/her account balance.
  • Cash withdrawal: the user can withdraw a certain amount of cash.
  • Deposit funds: the user can deposit cash or checks.
  • Transfer funds: the user can transfer funds to other accounts.

Bank Manager: The Bank Manager can perform the following operations:

  • Generate a report to check total deposits.
  • Generate a report to check total withdrawals.
  • Print total deposits/withdrawal reports.
  • Checks the remaining cash in the ATM.

Here is the use case diagram of our ATM system:

Here are the main classes of the ATM System:

  • ATM: The main part of the system for which this software has been designed. It has attributes like ‘atmID’ to distinguish it from other available ATMs, and ‘location’ which defines the physical address of the ATM.
  • CardReader: To encapsulate the ATM’s card reader used for user authentication.
  • CashDispenser: To encapsulate the ATM component which will dispense cash.
  • Keypad: The user will use the ATM’s keypad to enter their PIN or amounts.
  • Screen: Users will be shown all messages on the screen and they will select different transactions by touching the screen.
  • Printer: To print receipts.
  • DepositSlot: User can deposit checks or cash through the deposit slot.
  • Bank: To encapsulate the bank which ownns the ATM. The bank will hold all the account information and the ATM will communicate with the bank to perform customer transactions.
  • Account: We’ll have two types of accounts in the system: 1)Checking and 2)Saving.
  • Customer: This class will encapsulate the ATM’s customer. It will have the customer’s basic information like name, email, etc.
  • Card: Encapsulating the ATM card that the customer will use to authenticate themselves. Each customer can have one card.
  • Transaction: Encapsulating all transactions that the customer can perform on the ATM, like BalanceInquiry, Deposit, Withdraw, etc.

ATM Class Diagram

Customer authentication: Following is the activity diagram for a customer authenticating themselves to perform an ATM transaction:

Cash withdraw: Following is the activity diagram for a user withdrawing cash:

Deposit check: Following is the activity diagram for the customer depositing a check:

Fund transfer: Following is the activity diagram for a user transferring funds to another account:

ATM Fund Transfer Activity Diagram

Here is the sequence diagram for balance inquiry transaction:

Here is the skeleton code for the classes defined above:

Enums and Constants: Here are the required enums, data types, and constants:

Customer, Card, and Account: “Customer” encapsulates the ATM user, “Card” the ATM card, and “Account” can be of two types: checking and savings:

Bank, ATM, CashDispenser, Keypad, Screen, Printer and DepositSlot: The ATM will have different components like keypad, screen, etc.

Transaction and its subclasses: Customers can perform different transactions on the ATM, these classes encapsulate them:

SlidePlayer

  • My presentations

Auth with social network:

Download presentation

We think you have liked this presentation. If you wish to download it, please recommend it to your friends in any social system. Share buttons are a little bit lower. Thank you!

Presentation is loading. Please wait.

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

Chapter 12 ATM Case Study, Part 1: Object-Oriented Design with the UML

Published by Bethany Cameron Modified over 9 years ago

Similar presentations

Presentation on theme: "Chapter 12 ATM Case Study, Part 1: Object-Oriented Design with the UML"— Presentation transcript:

Chapter 12 ATM Case Study, Part 1: Object-Oriented Design with the UML

GCSE ICT By the end of this session, you will be able to: Explain main features of ATM machines Identify features of credit cards, debit cards, smart cards.

atm case study part 1 object oriented design with the uml

Chapter 4: Requirements Engineering

atm case study part 1 object oriented design with the uml

From use cases to classes (in UML). A use case for writing use cases Use case: writing a use case Actors: analyst, client(s) Client identifies and write.

atm case study part 1 object oriented design with the uml

Use Case Diagrams Damian Gordon.

atm case study part 1 object oriented design with the uml

Use Case & Use Case Diagram

atm case study part 1 object oriented design with the uml

1 Object-oriented design Part 2: OO tools & UML. 2 CRC cards Design tool & method for discovering classes, responsibilities, & relationships Record on.

atm case study part 1 object oriented design with the uml

Chapter 25 ATM Case Study, Part 1: Object-Oriented Design with the UML

atm case study part 1 object oriented design with the uml

Introduction to Software Testing Chapter 2.6 Graph Coverage for Use Cases Paul Ammann & Jeff Offutt

atm case study part 1 object oriented design with the uml

9/10/2004Use Case Workshop 1 CSC480 Software Engineering Workshop 1 Requirements Modeling.

atm case study part 1 object oriented design with the uml

UML and Systems Analysis MIS3502: Application Integration and Evaluation David Schuff

atm case study part 1 object oriented design with the uml

Sequence Diagrams. Introduction A Sequence diagram depicts the sequence of actions that occur in a system. The invocation of methods in each object, and.

atm case study part 1 object oriented design with the uml

Paul Deitel, CEO Deitel & Associates, Inc.. Contact Information  Paul Deitel, CEO  Deitel & Associates, Inc.  Twitter:  Facebook:

atm case study part 1 object oriented design with the uml

1 Classes. 2 Finding classes w Choosing classes is first step in defining essence of problem w If you can recognize an abstraction, you’ve found a candidate.

atm case study part 1 object oriented design with the uml

Lecture 9 Object-Oriented Analysis

atm case study part 1 object oriented design with the uml

ATM User Interface Design. Requirements A bank customer is able to access his or her account using an automatic teller machine. To be able to use an ATM.

atm case study part 1 object oriented design with the uml

Tutorial 2. What is a UML Use Case Diagram? Use case diagrams model the functionality of a system using actors and use cases. Use cases are services or.

atm case study part 1 object oriented design with the uml

Interaction Diagrams Activity Diagram State Machine Diagram

atm case study part 1 object oriented design with the uml

 2009 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.

atm case study part 1 object oriented design with the uml

January Ron McFadyen1 Ch 9. Use-case model: drawing System Sequence Diagrams Elaboration Iteration 1: a simple cash-only success scenario of.

About project

© 2024 SlidePlayer.com Inc. All rights reserved.

atm case study part 1 object oriented design with the uml

Snapsolve any problem by taking a picture. Try it in the Numerade app?

C++ How to Program

Paul deitel, harvey deitel, atm case study, part i: object-oriented design with the uml - all with video answers.

Chapter Questions

Suppose we enabled a user of our ATM system to transfer money between two bank ac- counts. Modify the use case diagram of Fig. 25.4 to reflect this change.

Jennifer Stoner

__________model the interactions among objects in a system with an emphasis on when these interactions occur. a) Class diagrams b) Sequence diagrams c) Communication diagrams d) Activity diagrams

Which of the following choices lists stages of a typical software life cycle in sequential order? a) design, analysis, implementation, testing b) design, analysis, testing, implementation c) analysis, design, testing, implementation d) analysis, design, implementation, testing

Ernest Castorena

Suppose we have a class Car that represents a car. Think of some of the different pieces that a manufacturer would put together to produce a whole car. Create a class diagram (similar to Fig. 25.9) that models some of the composition relationships of class Car.

Donald Albin

Suppose we have a class File that represents an electronic document in a stand-alone, non- networked computer represented by class Computer. What sort of association exists between class Computer and class File? a) Class Computer has a one-to-one relationship with class File. b) Class Computer has a many-to-one relationship with class File. c) Class Computer has a one-to-many relationship with class File. d) Class Computer has a many-to-many relationship with class File.

Foster Wisusik

State whether the following statement is true or false, and if false, explain why: A UML diagram in which a class’s second and third compartments are not modeled is said to be an elided diagram.

Ashley High

Modify the class diagram of Fig. 25.10 to include class Deposit instead of class Withdrawal.

Grant Castaneda

We typically identify the attributes of the classes in our system by analyzing the _________ in the requirements document. a) nouns and noun phrases b) descriptive words and phrases c) verbs and verb phrases d) All of the above.

Asma Venkitta

Which of the following is not an attribute of an airplane? a) length b) wingspan c) fly d) number of seats

Liuxi Sun

Describe the meaning of the following attribute declaration of class CashDispenser in the class diagram in Fig. 25.12: count : Integer = 500

Bryan Valdivia

State whether the following statement is true or false, and if false, explain why: State diagrams model structural aspects of a system.

An activity diagram models the __________ that an object performs and the order in which it performs them. a) actions b) attributes c) states d) state transitions

Preeti Kumari

Based on the requirements document, create an activity diagram for a deposit transaction.

Oluwadamilola Ameobi

Which of the following is not a behavior? a) reading data from a file b) printing output c) text output d) obtaining input from the user

Zack Spears

If you wereto add to the ATM system an operation that returns the amount attribute of class Withdrawal, how and where would you specify this operation in the class diagram of Fig. 25.17?

Pragya Ahuja

Describethe meaning of thefollowing operation listing that might appear in a class diagram for an object-oriented design of a calculator: add( x : Integer, y : Integer ) : Integer

A(n) _________ consists of an object of one class sending a messageto an object of another class. a) association b) aggregation c) collaboration d) composition

Aditya Sood

Which form of interaction diagram emphasizes what collaborations occur? Which form emphasizes when collaborations occur?

Create a sequence diagram that models the interactions among objects in the ATM system that occur when a Deposit executes successfully, and explain the sequence of messages modeled by the diagram.

Suzanne W.

Java™ for Programmers: Deitel Developer Series, Second Edition by Paul Deitel - Deitel & Associates, Inc., Harvey Deitel - Deitel & Associates, Inc.

Get full access to Java™ for Programmers: Deitel Developer Series, Second Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Chapter 12. ATM Case Study, Part 1: Object-Oriented Design with the UML

Action speaks louder than words but not nearly as often.

— Mark Twain

Always design a thing by considering it in its next larger context.

— Eliel Saarinen

Oh, life is a glorious cycle of song.

— Dorothy Parker

The Wright brothers’ design ... allowed them to survive long enough to learn how to fly.

— Michael Potts

In this chapter you’ll learn:

• A simple object-oriented design methodology.

• What a requirements document is.

• To identify classes and class attributes from a requirements document.

• To identify objects’ states, activities and operations from a requirements document.

• To determine the collaborations among objects in a system.

• To work with ...

Get Java™ for Programmers: Deitel Developer Series, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

atm case study part 1 object oriented design with the uml

COMMENTS

  1. PDF ATM Case Study, Part 1: Object-Oriented Design with the UML

    33_6 Chapter 33 ATM Case Study, Part 1: Object-Oriented Design with the UML 1. The screen prompts the user to enter a depo sit amount or type 0 (zero) to cancel. 2. The user enters a deposit amou nt or 0 using the keypad. [Note: The keypad does not contain a decimal point or a dollar sign, so the user cannot type a real dollar amount (e.g., $27 ...

  2. PDF Object-OrientedDesignwith 25 theUML

    25-12 Chapter25ATMCaseStudy,Part1:Object-OrientedDesignwiththe UML we modelthe threetypes of transactions(i.e.,"balanceinquiry," "withdrawal"and "deposit") as individual classes. Theseclasses possessspecific attributes needed forexe- cuting thetransactions they represent.

  3. 25. ATM Case Study, Part 1: Object-Oriented Design with the UML

    25. ATM Case Study, Part 1: Object-Oriented Design with the UML Objectives In this chapter you'll: Learn a simple object-oriented design methodology. Learn what a requirements document is. Identify classes … - Selection from C# 6 for Programmers, Sixth Edition [Book]

  4. PDF ATM Case Study Part 1

    The user enters a deposit amount or 0 using the keypad. If the user specifies a deposit amount, the ATM proceeds to Step 4. If the user chooses to cancel the transaction (by entering 0), the ATM displays the main menu and waits for user input. The screen displays a message telling the user to insert a deposit envelope.

  5. Chapter 25 ATM Case Study, Part 1: Object-Oriented Design with the UML

    25.2 Introduction to Object-Oriented Analysis and Design In this chapter, you'll work with six popular types of UML diagrams to graphically represent the design. In Chapter 26, you'll tune the design with inheritance, then fully implement the ATM in an 850-line C++ application (Section 26.4). This is not an exercise; rather, it's an end-to-end learning experience that concludes with a ...

  6. ATM Case Study, Part 1: Object-Oriented Design with The

    ATMCaseStudy,Part1: Object-Oriented Design with theUML 25. Actionspeakslouderthanwords butnot nearly as often. —Mark Twain. Always design athing by consideringitinits next larger context.

  7. grokking-the-object-oriented-design-interview/object-oriented-design

    The main components of the ATM that will affect interactions between the ATM and its users are: Card reader: to read the users' ATM cards. Keypad: to enter information into the ATM e.g. PIN. cards. Screen: to display messages to the users. Cash dispenser: for dispensing cash. Deposit slot: For users to deposit cash or checks. Printer: for printing receipts. ...

  8. PPT ATM Case Study, Part 1: Object-Oriented Design with the UML

    This part of the diagram reads "one object of class ATM executes zero or one objects of class Withdrawal." Association names are directional, as indicated by the filled arrowhead. * 03/20/17 * In Fig. 12.9, the solid diamonds attached to the ATM class's association lines indicate that ATM has a composition relationship with classes Screen ...

  9. PDF Object-Oriented Analysis, Design and Implementation Case Study Part I

    In Chapters 12-13, you design and implement an object-oriented automated teller machine (ATM) software system. Concise, carefully paced, complete design and implementation experience. Perform the steps of an object-oriented design (OOD) process using the UML Sections 12.2--12.7 and 13.2-13.3 Relate these steps to the object-oriented ...

  10. PDF ATM Case Study, Part 1: Object-Oriented Design with the UML

    25_4 Chapter 25 ATM Case Study, Part 1: Object-Oriented Design with the UML † a keypad that receives numeric input from the user † a cash dispenser that dispenses cash to the user and † a deposit slot that receives deposit envelopes from the user. The cash dispenser begins each day loaded with 500 $20 bills. [Note: Owing to the limited

  11. ATM Case Study, Part 1: Object-Oriented Design With The UML

    11_atmCaseStudy - Free download as Powerpoint Presentation (.ppt), PDF File (.pdf), Text File (.txt) or view presentation slides online. The document describes requirements for an ATM system. It identifies several key classes needed to model the system, including ATM, screen, keypad, cash dispenser, deposit slot, account, bank database, and classes for each transaction type (balance inquiry ...

  12. Chapter 12 ATM Case Study, Part 1: Object-Oriented Design with the UML

    Chapter 25 ATM Case Study, Part 1: Object-Oriented Design with the UML Introduction to Software Testing Chapter 2.6 Graph Coverage for Use Cases Paul Ammann & Jeff Offutt 9/10/2004Use Case Workshop 1 CSC480 Software Engineering Workshop 1 Requirements Modeling.

  13. Chapter 12

    ATM Case Study 1, Object-Oriented Design with the UML atm case study, part design with the uml 12 action speaks louder than words but not nearly as often. twain. Skip to document. University; High School. Books; Discovery. ... ATM Case Study 1, Object-Oriented Design with the UML. Module. Object Oriented Software Design and Java Programming (04 ...

  14. Chapter 25, ATM Case Study, Part I: Object-Oriented Design with the UML

    Video answers for all textbook questions of chapter 25, ATM Case Study, Part I: Object-Oriented Design with the UML, C++ How to Program by Numerade ... ATM Case Study, Part I: Object-Oriented Design with the UML - all with Video Answers. Educators. Chapter Questions. 01:04. Problem 1

  15. 25. ATM Case Study, Part 1: Object-Oriented Design with the UML

    25. ATM Case Study, Part 1: Object-Oriented Design with the UML Action speaks louder than words but not nearly as often. —Mark Twain Objectives In this chapter you'll: Learn a … - Selection from C++ How to Program, Ninth Edition [Book]

  16. ATM

    State pattern UML diagram. Context class stores a reference to the concrete state class which does the state related work.; State inter­face declares the state-spe­cif­ic meth­ods.; Con­crete ...

  17. Case study ATM

    25-4 Chapter 25 ATM Case Study, Part 1: Object-Oriented Design with the UML. a keypad that receives numeric input from the user; a cash dispenser that dispenses cash to the user and; a deposit slot that receives deposit envelopes from the user. The cash dispenser begins each day loaded with 500 $20 bills.

  18. 25. ATM Case Study, Part 1: Object-Oriented Design with the UML

    O'Reilly members experience books, live events, courses curated by job role, and more from O'Reilly and nearly 200 top publishers. 25. ATM Case Study, Part 1: Object-Oriented Design with the UML Objectives In this chapter you'll learn: A simple object-oriented design methodology. What a requirements document is.

  19. PDF ATM Case Study, Part 2: Implementing an OO Design in C#

    26 ATM Case Study, Part 2: Implementing an OO Design in C# Objectives In this chapter you'll: Incorporate inheritance into the design of the ATM. Incorporate polymorphism into the design of the ATM. Fully implement in C# the UML-based object-oriented design of the ATM software. Study a detailed code walkthrough of the ATM software system that explains the implementation issues.

  20. ATM Design Exercise

    25-8 Chapter 25 ATM Case Study, Part 1: Object-Oriented Design with the UML. Use Case Diagrams We now introduce the first of several UML diagrams in our ATM case study. We create a use case diagram to model the interactions between a system's clients (in this case study, bank customers) and the system.

  21. 33 ATM Case Study, Part 1: Object-Oriented Design with the UML

    33 ATM Case Study, Part 1: Object-Oriented Design with the UML Objectives. In this chapter you'll learn: A simple object-oriented design methodology. What a requirements document is. To identify classes and class attributes from a requirements document. To identify objects' states, activities and operations from a requirements document.

  22. 12 ATM Case Study, Part 1: Object-Oriented Design with the UML

    12 ATM Case Study, Part 1: Object-Oriented Design with the UML Action speaks louder than words but not nearly as often. —Mark Twain Always design a thing by considering it … - Selection from Java How to Program (early objects), 9/e [Book] ... Part 1: Object-Oriented Design with the UML. Action speaks louder than words but not nearly as often.

  23. Chapter 12. ATM Case Study, Part 1: Object-Oriented Design with the UML

    ATM Case Study, Part 1: Object-Oriented Design with the UML Action speaks louder than words but not nearly as often. —Mark Twain Always design a thing by … - Selection from Java™ for Programmers: Deitel Developer Series, Second Edition [Book]