Chapter Twelve Object-Oriented Software Developmentfbeedle.com/mercer/36-8ch12.pdfChapter Twelve...

40
435 Chapter Twelve Object-Oriented Software Development Analysis and Design Summing Up You have seen several class definitions, modified some classes, implemented class member functions (in programming projects for Chapters 6 through 11), and per- haps completely implemented a few classes (in programming project 8H, “The el- evator Class”; 10K, “The stats Class”; or 11E, “The set Class”). All of these previ- ous activities relate to the implementation of classes. Coming Up This chapter discusses another facet of the object-oriented paradigm—the analysis and design of a system with objects as the main building blocks. You will study an object-oriented software development strategy in the context of a real-world problem—building a jukebox system for a campus student center. The analysis in this chapter will help the programming team design the class defi- nitions and implement the member functions in Chapter 13. After studying this chapter, you will be able to * identify classes that model a solution to a problem * assign responsibilities to classes * use Component/Responsibility/Helper cards to aid analysis and design * understand the need for analysis and design before implementation Analysis and design projects to reinforce object-oriented development

Transcript of Chapter Twelve Object-Oriented Software Developmentfbeedle.com/mercer/36-8ch12.pdfChapter Twelve...

435

Chapter Twelve

Object-Oriented SoftwareDevelopment

Analysis and Design

Summing UpYou have seen several class definitions, modified some classes, implemented classmember functions (in programming projects for Chapters 6 through 11), and per-haps completely implemented a few classes (in programming project 8H, “The el-evator Class”; 10K, “The stats Class”; or 11E, “The set Class”). All of these previ-ous activities relate to the implementation of classes.

Coming UpThis chapter discusses another facet of the object-oriented paradigm—the analysisand design of a system with objects as the main building blocks.

You will study an object-oriented software development strategy in the contextof a real-world problem—building a jukebox system for a campus student center.The analysis in this chapter will help the programming team design the class defi-nitions and implement the member functions in Chapter 13. After studying thischapter, you will be able to

* identify classes that model a solution to a problem* assign responsibilities to classes* use Component/Responsibility/Helper cards to aid analysis and design* understand the need for analysis and design before implementation

Analysis and design projects to reinforce object-oriented development

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

436

12.1 Object-Oriented AnalysisSo far, we have only considered individual classes and some low-level design issues,such as where the data members should go in a C++ class, why constructors areneeded, and member function implementations. However, before individual classesare designed and implemented, they are first recognized as part of some larger soft-ware system.

This section introduces an object-oriented design (OOD) methodology in thecontext of a real-world problem—the cashless jukebox. The strategy is based on theresponsibility-driven design methodology of Wirfs-Brock, Wilkerson, and Wiener[Wirfs-Brock 90].

Another major component of object-oriented software development is the Com-ponent/Responsibility/Collaborator (CRC) card introduced by Kent Beck and WardCunningham [Beck/Cunningham 89]. This simple and effective tool consists of a setof 3-by-5-inch index cards. CRC cards were first used to help people understandobject technology. Developers employ them to develop large-scale, object-orientedsystems. Because the word collaborator has caused confusion, CRC cards will hence-forth be referred to as Component/Responsibility/Helper (CRH) cards.

The first step in object-oriented analysis involves identification of the key ab-stractions—the major classes. The system is modeled as a set of classes, each withits own responsibilities. You will see how team members “become” an object throughrole playing. Playing the roles of the objects helps the team identify the responsibili-ties of each while determining the relationships between them. Role playing helpsthe team understand the problem, model a solution, and iron out the rough spotsearly in development, when it is relatively cheap and easy to do so.

Self-CheckTo warm up to an object-oriented view of systems, first answer each of thefollowing “Pre-Check” questions. Look at the answer for each before goingon to the next. These “Pre-Check” questions are intended to get you tounderstand the essentials of planning the design of some larger systems.

437

12.1 OBJECT-ORIENTED ANALYSIS

12-1 On one piece of paper, sketch the design of a small one-branch banksuch that someone unfamiliar with the system would understandthe major components, the key purpose of each, and any interactionbetween those components.

12-2 On one piece of paper, sketch the design of a small one-branchlibrary such that someone unfamiliar with the system wouldunderstand the major components, the key purpose of each, and anyinteraction between those components.

12.1.1 The Problem SpecificationIn the spring of 1997, the author suggested building a CD music jukebox using a200-capacity compact-disc player. Sophomore Ed Slatt, a computer engineering ma-jor, guaranteed that he would figure some way to control that CD player from acomputer. By the end of the semester, Ed had a prototype infrared remote (IR) unitworking. He used a circuit design that Chris Dodge has made available on the Web.1

His IRDEV class and some assembler code were wrapped up in a cdPlayer class. Thisallowed messages like these that play the fifth track on the CD in the third tray of aseven-disc CD player:

// Construct an object that can send signals to a real CD playercdPlayer myCdPlayer;

// Play the fifth track in the third tray of the physical CD playermyCdPlayer.play(3, 5);

Ed then went on to pursue his computer engineering degree.In the fall of 1997, several students asked the same author to provide an honors

option for the first course in the computer science major. They decided to build thejukebox. The events you are about to read are based on this true story. The followingproblem statement begins the project:

1. At the time of this writing, Chris Dodge has the information located at this URL: http://http://http://http://http://wwwwwwwwwwwwwww.ee.ee.ee.ee.ee.w.w.w.w.washington.edu/eeca/circuits/PCIR/Washington.edu/eeca/circuits/PCIR/Washington.edu/eeca/circuits/PCIR/Washington.edu/eeca/circuits/PCIR/Washington.edu/eeca/circuits/PCIR/Welcomeelcomeelcomeelcomeelcome.html.html.html.html.html

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

438

PROBLEM STATEMENT FOR THE CASHLESS JUKEBOX

The Student Affairs office has decided to put some new-found activity fee funds toward

a music jukebox in the student center. The jukebox will allow a student to play indi-

vidual songs. No money will be required. Instead, a student will swipe a magnetic stu-

dent ID card through a card reader. Students will each be allowed to play up to 1,500

minutes worth of “free” jukebox music in their academic careers at the school, but never

more than two selections on any given date. A student may select a CD from the avail-

able collection of CDs and then an individual song from that CD. Students may not play

entire CDs.

This project is now assigned to a team that includes Blaine, Director of StudentAffairs. Blaine is playing the role of the domain expert—the person who knows aboutstudent policies. His office is in the student center, not far from where the jukeboxmight be installed. Blaine also represents the client—the one with the money. Theteam will also have an object expert—Chelsea—to help guide the team though this,their first try at object-oriented software development. Chelsea’s experience andknowledge of object-oriented design heuristics will likely help the team make betterdesign decisions. The team has two chemical engineering majors—Jessica and Ja-son—who are taking an honors option in the middle of a first programming course.Also on the team are Matt, a computer engineering major, and Steve, an engineeringscience major, who are both taking the introductory course. The team also has Charlie,a second-year computer science major who promised to help Matt implement thejukebox (see Chapter 13). Charlie has more programming experience than any ofthe other team members. The team is completed by Misty, who is deciding between amath or a computer science career.

At the first meeting, the team decides to hammer out an idea of what this cash-less jukebox should be able to do. During analysis, the team will be concerned withwhat the system must do. The team will not worry too much over the how. Duringanalysis, the terminology and activities relate to those who requested the software.The analysts should be able to communicate their thoughts with those who requestedthe software. The analyst must also

* work with the clients to refine requirements* challenge the requirements* probe for missing information

439

12.1.2 The Goal of the Analysis PhaseThe goal of the analysis phase is to create an abstract model in the vocabulary of theclient (the Student Affairs office, in this case). This can be accomplished by way ofthe following three-step strategy:

1. Identify classes that model (shape) the system as a natural and sensibleset of abstractions.

2. Determine the purpose, or main responsibility, of each class. The respon-sibilities of a class are what an instance of the class must be able to do(member functions) and what it must know about itself (data members).

3. Determine the helper classes for each. To help complete its responsibili-ties, a class typically delegates responsibility to one or more other ob-jects. These are called helpers.

Before the team begins to analyze the problem, Chelsea tells them that soft-ware developers do not immediately find all classes. It is also unlikely that all re-sponsibilities will be discovered in the first pass. Some of the helper classes mayalso be missed. It is perfectly acceptable to change the list and names of the classesthat shape the solution as the problem is considered over time. Also, new classesmay be required when moving into the design and implementation phases.

For now, don’t worry about creating the perfect model. There are many falsestarts. And because analysis sometimes recognizes uncertainty in a problem state-ment, there may be some new concerns that need to be settled. The team will betrying to understand the requested software system at the level of those requestingthe software.

Also realize that there is rarely one true correct best design. Relax. Tell yourselfnow that all designs are valid. So don’t be afraid to make mistakes. It is much easierto change things during analysis and design than after the system has been de-ployed.

12.1.3 Identification of Classes that Model the SolutionThe first goal, or deliverable, in object-oriented software development is a set ofclasses that potentially model the system. Each class will be assigned its majorresponsibility.

One simple tool for getting started is to write down all the reasonable nounsand noun phrases in the problem statement. Consider these as potential classesrepresenting part of the solution. You may also record potential classes even if they

12.1 OBJECT-ORIENTED ANALYSIS

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

440

were not written as nouns in the problem statement. For example, someone on theteam with expertise in the problem area may suggest useful classes due to his or herunderstanding of the domain—in this case, students and music. Potential classesmay come from words that are spoken while describing the system or questioningthe problem statement. In summary, useful classes for modeling the system maycome from sources such as these:

* the problem statement* an understanding of the problem domain (knowledge of the system that the

problem statement may have missed or taken for granted)* the words floating around in the air during analysis of the problem

And while considering potential classes, consider the following object-oriented de-sign heuristic:

OBJECT-ORIENTED DESIGN HEURISTIC 12.1 (RIEL’S 3.6)

Model the real world whenever possible.

This design heuristic leads to more understandable software. It not only helps dur-ing analysis, but also during maintenance when someone unfamiliar with the systemmust fix a bug, add an enhancement, or update the software to match real-worldchanges.

The team established the following list of noun phrases from the problem state-ment (redundant entries were not recorded).

NOUN PHRASES—ALL NOUNS IN THE PROBLEM STATEMENT

Student Affairs office minutes student ID card student

activity fee funds date academic careers money

music jukebox card reader student center CD

collection of CDs selection jukebox music song

The noun phrases of a problem statement fall into three categories that indicatetheir potential viability as classes to model a solution.

1. somewhat sure

2. not sure

3. should not be considered—irrelevant or has the propensity to muddle

There are many guidelines intended to help us discover useful classes. Oneguideline has already been used above—eliminate redundant entries. There was no

441

useful purpose for writing down “student” three times, for example. Only considerthe noun phrases that have meaning in the realm of the system. The activity feefunds provide the money to pay for the jukebox; however, that money will not be partof the design.

The following set of noun phrases represents a first attempt to identify the keyabstractions in the problem statement (irrelevant nouns omitted).

POTENTIAL CLASSES—A FIRST PASS AT FINDING KEY ABSTRACTIONS

Somewhat Sure Not Sure

jukebox activity fee funds

student money

song jukebox music

card reader date

student ID card

CD

collection of CDs

Self-Check12-3 Write a list of potential classes after reading the following problem

statement: (Note: This problem specification will be used in laterself-check questions.)

The college library has requested a system that supports a smallset of library operations. Students may borrow books, return thoseborrowed books, and pay fees. The late fee and due date have beenestablished as follows:

Late Fee Borrowing Period

Books: $0.50 per day 14 days

The due date is set when a borrowed item is checked out. A studentmay borrow only seven books. Any student with seven bookschecked out may not borrow anything more.

The team considers each potential class in more detail for help in understand-ing the system.

12.1 OBJECT-ORIENTED ANALYSIS

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

442

12.1.3.1 Jukebox? YES, coordinates all activities

The programmers on the team feel that jukeBox seems an appropriate name for theclass that will be responsible for coordinating activities such as handling requestsfrom the users of this system. There might be one instance of jukeBox in the pro-gram that gets things going and keeps things going.

12.1.3.2 Student? YES, maintains student information

It is suggested that a class named student will prove itself a useful abstraction formodeling the users. After all, students will be involved in playing music. Chelseaadvises the team to distinguish between the human version of the student thatapproaches the jukebox with a student ID card and the software model of that stu-dent stored inside the computer. A friendly argument ensues. Although no one seemsto recognize it at first, the confusion is due to the name student. Steve suggests thatthe team employ the name “user” to indicate the physical student that uses thejukebox. The programmers agree to keep student as the name of the class thatmodels that physical real-world user. student is the software equivalent of “user.”

12.1.3.3 Song? NO; Track? YES, one of the tracks on a CD

Because students are allowed a certain amount of play time in minutes, it appearsthat song would be a useful class. Each song object should know its playing time inminutes and seconds along with its title. Jason and Jessica see this as an instance ofthe State Object pattern they learned about earlier in their first computer sciencecourse.

Matt changes the subject by claiming that there are some CDs that put twosongs into one track. Other CDs have some blank air time at the end. Blaine ob-serves, “Rock and roll has changed since I was young.” He can’t believe what he ishearing. Additionally, Charlie relates that he has a Beethoven CD where one “song”(symphony, actually) is distributed over several tracks. Each track is a movement—the first movement, the second movement, and so on.

Chelsea indicates that the team can better communicate the design if the nameis changed to track. The user will select a track from a CD. That sounds better.

12.1.3.4 Card reader? YES, the object used to read the magnetic student ID cards

The card reader is one of several physical objects in the cashless jukebox. Should itbe a class? No one is sure. Ed suggests that magnetic card readers are easy to comeby. It may be a useful abstraction. After a quick check on the Web, Jessica produces

443

this picture of a combination keyboard and magnetic card reader to solidify theconcept of a card reader.

FIGURE 12.1. Magnetic card reader keyboard

Picture courtesy of B & C Data Systems, Gorham, Maine

Although the physical card reader exists, it will still be useful to have a soft-ware abstraction for this physical entity—analogous to the user/student relation-ship. The team decides to use the class name cardReader for the object that getsinput from magnetic ID cards.

12.1.3.5 Student ID card? NO, the object inserted into the magnetic card reader

The student ID card is one of several physical objects in the cashless jukebox. How-ever, the team decides it is “outside” the system. Although it allows students to gainaccess to the jukebox, it need not be modeled. It is already done. Every student hasa student ID card.

Chelsea congratulates the team as she tells them about a widely accepted ob-ject-oriented design heuristic:

OBJECT-ORIENTED DESIGN HEURISTIC 12.2

Eliminate classes that are outside the system.

According to Arthur Riel [Riel 95], the hallmark of such a class is one whose onlyimportance to the system is the data contained in it. While the student identifica-tion number might be of great importance, the system should not care whether theID number was read from a swiped magnetic ID card, typed in at the keyboard, or “ifa squirrel arrived carrying it in his mouth.”

12.1.3.6 CD? YES, each CD object stores a collection of tracks

Someone on the team doesn’t agree that CD should be a key abstraction. Jason, oneof the computer science majors, chimes in and suggests, “This is not a problem, I can

12.1 OBJECT-ORIENTED ANALYSIS

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

444

visualize a CD object as a vector of tracks.” Blaine asks, “What is a vector?” Chelseatries to rectify unfamiliar and differing terminology with some anthropomorphicobject-speak: “A CD is responsible for knowing what tracks it has.” Blaine complainsthat Chelsea is trying to give human qualities to the CD. Jessica responds that thisis precisely what anthropomorphism means. She also heard in her CmpSc class thatgiving human qualities to objects happens quite often during object-oriented soft-ware development. It really helps.

Steve still has a problem with the singularity of a CD and a song: “Certainly thesystem must maintain many CD objects, each of which may store many songs. Howcan we talk about just one class when there are many songs on so many CDs?” Jasonretorts that one class is used to create many instances, or objects. And right now, theteam should concentrate on identifying classes to model the real-world componentsthat are part of a jukebox.

Steve agrees that there should be more than one CD for students to choose.Jason relates how they have just learned about two different container classes forstoring collections of objects—vectors and bags. “Bags and vectors?” wonders Blaine.Jessica tells Blaine that he needn’t worry about these implementation details andreminds Jason that the programming team can choose the appropriate containerclass later. Instead, Jessica introduces the notion of a class that is responsible forstoring all the CDs. Steve asks if we could rename this cdCollection. The teamunanimously approves.

12.1.3.7 Collection of CDs? YES, all CDs that could be listened to

Jason is thinking that behind the public interface of the cdCollection class, thedata members may include a vector of CD objects and the number of CDs physicallystored in the CD player. Matt suggests that someone will have to make sure thesoftware version is always in sync with the physical CD collection. Chelsea encour-ages the team to postpone these implementation details for now.

12.1.4 Any Other Classes?Steve and Matt launch into a discussion about who is allowed to play a track.Shouldn’t a collection of students also be maintained? Jason agrees, but he com-plains it may be difficult to keep a collection of all valid students. Should the juke-

445

box allow anyone in the world with a magnetic ID card to play a track? How mightthe system prevent unauthorized access? It appears certain that some part of thecashless jukebox will have to maintain a collection of students. Although the nounphrase “collection of students” does not exist in the problem statement, Jessica saysthat it helps her to think of a studentCollection class that is responsible for main-taining the time credit available for each student. Chelsea recommends the team gowith their instincts and add a studentCollection class to the design.

12.1.4.1 studentCollection stores a list of students who could select songs

Of the original set of potential classes, all but one survived the first cut at modelingthe system. Two new key abstractions (classes) were added. One is for storing thecollection of CDs. The other maintains the list of students who are allowed to use thejukebox. However, an uneasy feeling pervades the team. Misty thinks there is some-thing missing. The team reviews the classes. Ed suggests that there must be someobject that actually plays the selected song.

Jessica suggests a solution. The team could purchase an old jukebox and modifyit to allow card swipes. However, this would not prevent students from playing morethan two songs on any given date. Ed says that a computer could be hooked up to thejukebox. Then the computer would be responsible for reading student ID cards andsending play messages to the physical jukebox. The physical jukebox has the re-sponsibility of selecting the physical CD and playing the correct track. Commer-cially available jukeboxes do this. Ed states that another major advantage derivesfrom the fact that jukeboxes also have built-in stereo systems. This could save money.Blaine reminds Steve that the student center already has a potent stereo system.Any money saved on this project could be funneled back into other student projects.So, as is done in the world of business, a decision must be made that relates to thebottom line.

Chelsea investigates on the Internet and finds a place to purchase a CD juke-box that holds 50 CDs. It looks very cool. However, it lists for $4,500. And this doesnot include the CDs. However, according to the Wurlitzer Jukebox Co. representa-tive, they could probably modify their jukebox to allow magnetic ID card input.

12.1 OBJECT-ORIENTED ANALYSIS

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

446

FIGURE 12.2. The Wurlitzer “One More Time” CD Jukebox

Picture courtesy of Wurlitzer Jukebox Co., Pittsburgh, Pennsylvania

The team considers cost alternatives. Matt informs the team that the computerdepartment has some personal computer components sitting around gathering dust.He suggests that for little or no money, he could put together a computer capable ofimplementing the appropriate classes. A card reader keyboard would have to bepurchased no matter what.

Charlie suggests that a computer could be connected to a 200- or 300-disc CDplayer. The CD player in turn could easily be connected to the existing student cen-ter stereo system. Chelsea reminds the team, “Ed already did this.” The team con-siders adding another object to model the system—a compact-disc player.

12.1.4.2 cdPlayer plays any track from any CD

The compact-disc player is yet another physical object in the cashless jukebox. Butshould it be a class? After all, several electronic stereo manufacturers already imple-ment this physical device. Chelsea suggests the team try to understand the systemusing a common vocabulary. A CD player appears to be a very important part of thesolution. The implementation would come later. The team decides to have a cdPlayerclass to represent the responsibilities of this “real” object—analogous to the student

447

and cardReader classes, which represent other real objects. The actual CD player hasnot been purchased yet. Jessica pulls a picture off the Web to help bring a more con-crete feel to these abstractions.

FIGURE 12.3. Sony CDP-CX200 CD player

Picture courtesy of Sony Electronics Inc.

Now that the team has added a cdPlayer class, Misty suggests the team con-sider a stereo system class.

The stereo system certainly is part of the entire system. It is yet another one ofthose essential physical components. Chelsea asserts that we could consider thestereo system as part of the cashless jukebox. Its major responsibility is to take theoutput from the CD player and produce audible sounds at the right treble, bass, andvolume settings. However, it is reasonable to set boundaries around the system un-der development. The team decides that sending a song selection message to cdPlayerrepresents such a boundary. The prebuilt electronic components will then take overand perform their well-defined responsibilities. Chelsea excitedly shouts out, “Thisis reuse!” The cdPlayer class is the interface to the music-generating part of thissystem. The team agrees that the stereo system is on the other side of the CD player,well outside the system being designed.

12.1.4.3 Stereo system? NO, amplifies the music

The team feels as though they have captured many key abstractions for this appli-cation. They have the beginning of a framework for analyzing the problem in moredetail. There is a sense that the primary responsibility of each class has been recog-nized—or at least implied. Chelsea suggests that the class names be documentedalong with their major responsibilities.

Before splitting for pizza, the team documents the classes discovered duringanalysis with a sketch that includes

1. the class names

2. the primary responsibility of each class

12.1 OBJECT-ORIENTED ANALYSIS

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

448

3. arrows indicating possible message sends to helper classes

4. the boundaries of the software abstractions under development

FIGURE 12.4. Analysis sketch of major classes that model a cashless jukebox (subject to change)

CD

cdCollectionStores all CDs that can be played

track

studentCollectionStores valid students

Plays a songcdPlayer

Coordinates activitiesjukeBox

Gets student IDcardReader student

Chelsea congratulates the team again. The design looks good. Out of the origi-nal eight noun phrases, one was eliminated (student ID card). The studentCollectionclass was discovered as the result of someone knowing something about collectionsof data and the necessity for searching for a particular student. Chelsea reports thatsuch changes are typical. Writing the noun phrases is a tool to help find classes thateffectively model the solution. It doesn’t mean all nouns must become classes. Itdoesn’t pretend to find them all. Charlie suggests that some of these classes maynever even get implemented. Chelsea says that other new classes may be discoveredas the team proceeds with role playing.

Self-Check12-4 Reconsider the key abstractions (classes) for representing the

college library. (See Self-Check 12-3.) Draw a picture like Figure12.4 above that does the following:

1. lists all the classes that reasonably model the system

2. lists the major responsibility of each class

3. marks the boundary of the system—it’s okay to show entitiesthat are outside the system

449

12.2 Role Playing and CRH Card DevelopmentThe primary responsibility of each class has now been identified. The team will nowset about the task of identifying and recording other responsibilities. Responsibil-ity-driven design emphasizes identifying responsibilities and assigning those re-sponsibilities to the most appropriate class. Chelsea, the object expert, suggests thatthe team should often ask questions like this:

* What is this class responsible for?* What class is responsible for a particular action (member function) or spe-

cific knowledge (data member)?The team will also be identifying helpers. These are classes that one class needs

to help carry out its responsibility. The object-oriented approach views the runningsolution as a collection of objects in which each object does its own thing for the goodof the whole. There should not be any all-powerful class that does everything.

The team should try to answer questions such as: What are the other responsi-bilities needed to model the solution? Which class should take on this particularresponsibility? and What classes help another class fulfill its responsibility? Re-sponsibilities convey the purpose of a class and its role in the system. These ques-tions are more easily addressed if the team remembers that each instance of a classwill be responsible for

1. the knowledge that any object of the class must maintain, and

2. the actions that any object of the class can perform.

The team should always be prepared to ask these two questions:

1. What should any object of the class know (knowledge)?

2. What should any object of the class be able to do (action)?

“It’s that anthropomorphism thing again,” moans Blaine, the domain expert fromthe Student Affairs office.

Assigning a responsibility to a class means that every instance of that class willhave the same responsibility. This is true when there are many instances of theclass. There will be many CD and student objects for example. It is also true whenthere may be only one instance of the class—jukeBox and cdCollection for ex-ample. Later on, during design and implementation, the actions may become publicmember functions of a class. The knowledge may become data members.

The responsibilities may be identified from several sources such as:* the problem statement (specification)

12.2 ROLE PLAYING AND CRH CARD DEVELOPMENT

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

450

* the classes* the ideas that float around the room, especially during role playing

These responsibilities must eventually be assigned to the appropriate class, eitherto the classes already identified or to new classes if necessary. For example, whoseresponsibility is it to play one particular song? This responsibility might be sharedbetween several classes. jukeBox may send a message to studentCollection to findout whether or not a user may select a song. jukeBox cannot do this by itself—itneeds help from studentCollection and student. In situations like this, when classA needs the help of class B, class B is said to be a helper of class A.

The object expert suggests that the team begin to assign responsibilities to classesusing the simple tool of role playing. During role playing, each team member as-sumes the role of a class to see what happens when a certain situation arises; forexample, what happens when a certain student wants to select a certain track. Butbefore this is done, the object expert suggests that the team use another simple low-cost tool for capturing the decisions made during role playing.

12.2.1 CRH CardsAt this point, Chelsea writes the heading “Class:” at the top of a 3-by-5-inch indexcard. Under this, she also writes the column headings “Responsibilities:” and“Helpers:”. Immediately, an inexpensive index card has metamorphosed into aComponent/Responsibility/Helper (CRH) card. A CRH card records a class name,the responsibilities of the class, and the other classes required to help the classfulfill those responsibilities—the helpers. Here is an example CRH card with somepossible responsibilities and helpers as it may appear much later in the softwaredevelopment phase.

FIGURE 12.5. CRH card showing what cdCollection might develop into

Class: cdCollection

Responsibilities:

know all CDs

retrieve a CD

addNewCD(CD aCD, int trayNumber)

removeCD(int trayNumber)

CD getCD(int trayNumber)

Helpers:

vector of CDs

451

Although this CRH card for the cdCollection class contains return types andarguments, CRH cards typically list only the member function names (action re-sponsibilities). Conversely, the CRH card might well indeed say “know all CDs”(knowledge responsibility). Knowledge responsibilities may later get turned intoprivate data members such as vector<CD> my_cds;.

The responsibilities are what the object must be able to do and what the objectmust know. These responsibilities are written down on the front of the card underthe heading “Responsibilities:”. However, the previous CRH card represents designdecisions yet to be made. It is only a preview of what it might look like.

Some CRH card practitioners use the backs of the CRH cards for recordingdifferent types of information. Chelsea suggests the team write down the class namealong with its major responsibility on the back of the 3-by-5-inch index cards. Hereis the result, using the design shown earlier.

FIGURE 12.6

jukeBox: The object in the system responsible for coordinating activities

CD: Something that holds many tracks

cdPlayer: Plays any track

studentCollection: Stores all students who could potentially play songs

cdCollection: Stores all CDs with tracks that could be played

student: Someone who can make selections

track: Stores information about one track (title, play length)

cardReader: Reads information from a magnetic student ID card to identify the user

Each team member takes one or two of these CRH cards to “become” the class.The holder of each card will play the role of that class.

12.2.2 Role PlayingEach team member has now assumed the role of at least one class (one team mem-ber could role play several classes if necessary). Chelsea suggests that the team roleplay a scenario to see how one instance of a class could interact with instances ofother classes. Jessica wants to know, “What is a scenario?” Chelsea responds, “A

12.2 ROLE PLAYING AND CRH CARD DEVELOPMENT

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

452

scenario is the answer to the question, What happens when . . . ?” Steve suggests theteam role play the following scenario.

12.2.2.1 Scenario 1: “What happens when a student wants to select a track?”

The first thing to do is decide which object begins the scenario. Each team memberlooks on his or her CRH card to see who will start. The team member playing therole of jukeBox states, “I’m playing the role of the object responsible for coordinatingactivities, so I guess I’ll start.”

jukeBox: I’m playing the role of the jukebox so I’ll start this scenario. Hey cardReader,has a user swiped a card?

cardReader: No.

jukeBox: Hmmm. Okay, cardReader, has a student swiped a card?

cardReader: No.

jukeBox: Hey, how often do I have to do this? I suppose I’ll have to wait for a user.

The object expert suggests that Jason (jukeBox) add a waitForUser responsibility tohis card.

jukeBox: Okay, I’m waiting for a user. Waiting, waiting, waiting . . .

cardReader: Okay, jukeBox, a user just swiped a card. Here is all the information onthat magnetic strip ID card.

jukeBox: Thanks, cardReader, but I don’t know what to do with all of this stuff.Which part of the input uniquely identifies the student?

The team wonders what information is recorded on a magnetic student identifi-cation card. Is there a name, a student ID number, the amount of money left in thestudent’s food service balance, an address? Since no one knows for sure, perhapscardReader could take on the responsibility for getting the unique student identifi-cation number of the user holding the magnetic card just swiped.

cardReader: Okay, I’ll add getStudentID to my list of responsibilities.

jukeBox: Thanks, cardReader. By the way, although I first believed you weren’t nec-essary as a class, I do believe so now. You not only communicate with the physi-cal card reader, you also have access to the entire student ID card so you canreturn the information I seek—the student ID number. You just made my life

453

simpler. I don’t need to know what kind of physical card reader is out there, nordo I have to know details such as the format of the magnetic card being swiped.Now that I have the student ID number, I need to verify that the user can selecta song.

studentCollection: Well, since it is my responsibility to store the collection of stu-dent objects, let me check to see if there is a student here with that ID. Yes, hereis the student object associated with the student ID number you passed to me.I will add a responsibility to the front of my CRH card: getStudent.

jukeBox: Now that I know the user is valid, I suppose we should let the user select asong, I mean track. Okay, whose responsibility is it to maintain the list of alltracks on all CDs?

cdCollection: That’s me! What do you want?

jukeBox: I’d like the collection of all CDs.

cdCollection: Well, all you have to do is ask. I’ve been here all along.

jukeBox: Okay, I now know I always have access to cdCollection. What do I do withyou now?

There is a pause. No one knows. Should jukeBox display the CD choices to theuser and then, based on the CD selection, show the tracks? This would mean thatjukeBox will have much more to do (Jason and Jessica are thinking about all thoseloops). Chelsea suggests that it seems like some other object should be responsiblefor getting this information from the user. jukeBox coordinates activities; it can del-egate authority to other classes. It does not have to do everything.

Chelsea points out that there are many object-oriented designers who use thefollowing design heuristic when confronted with similar design decisions:

OBJECT-ORIENTED DESIGN HEURISTIC 12.3

Avoid all-powerful (omnipotent) classes.

It is undesirable to have a class that does everything, or even too much. The by-product of assigning too much responsibility is a complicated class that can be diffi-cult to implement and maintain after deployment into the student center. Chelseadescribes another related object-oriented design heuristic that helps software devel-opers attain well-designed object-oriented systems:

12.2 ROLE PLAYING AND CRH CARD DEVELOPMENT

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

454

OBJECT-ORIENTED DESIGN HEURISTIC 12.4 (RIEL’S 3.1)

Distribute system intelligence among the classes as evenly as possible. The top-level

classes in a design should share the work uniformly.

Chelsea encourages the team to try to evenly distribute the work amongst theanalysis classes that are currently being role played. The benefit is a more easilyunderstood system. The design will be more easily communicated to the client andthe programmers that will implement the design. It will be more easily understoodwhen the inevitable bugs have to be fixed or enhancements are to be made.

jukeBox: Let me summarize: I won’t try to get the user’s track selection. I know thatI will somehow have access to the CD collection, but what has to happen now?What should I do next to get the track?

Chelsea offers a suggestion: “A good object-oriented system has objects that delegateresponsibilities to other objects. This is not about producing lazy objects. This isabout understandable systems. Some other object could get the user selection.” “Butwho?” asks Jason.

Chelsea proposes that to keep things simple, it might be appropriate to add anew class to interface with the user. The major responsibility would be getTrack.The team’s computer engineer, Matt, and the computer science major Charlie, whoare now quite familiar with interactive input and output, suggest that with a newtrackSelector class, jukeBox need not worry about how to get output to and inputfrom the user. It could come from the keyboard; from a touch screen; or through agraphical user interface for the Mac, a graphical user interface for a WinTel ma-chine, a graphical user interface for a Unix or Linux system, or whatever. The jukeBoxrole player suggests backing up one step and finishing the current scenario with anew trackSelector class, which has the major responsibility of communicating withthe user. trackSelector will get the user’s selection.

12.2.2.2 trackSelector, a new class added to get student selections

jukeBox: Okay, I now have access to the collection of all CDs. I’ll pass it totrackSelector. You tell me what track the user wants to hear.

trackSelector: Okay, I’ll offer the options to the user and let him or her decide. Hey,what options are there? I’m in control here, but I still don’t know how to get theuser’s selection.

455

cdCollection: I hold the collection of CDs, so it seems like I should have some mecha-nism to allow access to the CDs and all tracks on the CDs. Then you could lookat every CD in my collection and show the artist and title, perhaps by artistname in alphabetic order. Once the CD is selected, you could iterate over all thetracks available on that CD.

CD: I think I can help. Those knowledge responsibilities are listed on my CRH card(know all tracks). However, I don’t know how to reveal individual tracks. I willadd that responsibility: “allow references to individual tracks.”

“Yes, you could have a vector of tracks that are accessible with the subscriptoperator,” asserts Jason. Chelsea warns Jason to avoid tying in implementation de-tails at this point. He can decide later. For now it seems cdCollection must allowreferences to individual CDs and each CD must allow references to individual tracks.“Do you both have that responsibility on your individual CRH cards?” she asks.

cdCollection: No, I’ll add the responsibility of allowing access to all CDs now. Infact, it seems like I will have to be able to add new CDs and delete others as themusic in the physical CD jukebox changes. So I’ll also add addCD and removeCD.

CD: I didn’t list those responsibilities either, but I’ll add them now. And in addition toknowing my play time, I could also be responsible for knowing my CD numberand my track locations. This is all cdPlayer would need to know in order to playany track.

trackSelector: Look, you guys, if you are done for now, I’d like to just say that I canget the track selected by the user. Let’s continue the scenario. Okay, jukeBox,here is the track selected by the user. I’ll write the responsibility getTrack onmy CRH card.

jukeBox: Thanks, trackSelector. Now I need to determine whether or not the cur-rent student can play the selected track. Who is responsible for knowing theplay time of any track?

track: It seems like I should be responsible for knowing the duration of my track.For example, it might take 3 minutes and 34 seconds to be completely played.I’ll add the operation “know play time” to my CRH card along with the respon-sibility to know the CD number and what track number I am.

“Whoooooaaaaa, this is confusing!” proclaims Blaine, the domain expert. “Whydoes jukeBox need to know the duration of the track?” Jessica suggests that some

12.2 ROLE PLAYING AND CRH CARD DEVELOPMENT

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

456

object must be made responsible for determining whether or not this particularstudent can play this particular song. Chelsea suggests that the team continue roleplaying until this scenario reaches some logical conclusion.

jukeBox: Okay, now I should check to make sure the student is able to select thistrack before telling cdPlayer to play it. I seem to remember I cannot simplyplay a track without checking on a few things. I know the current student andthe selected track. What do I do now?

The team has stalled. They wonder what must be done next. Why did jukeBoxneed to know the student in the first place? Misty reminds the team that jukeboxplay time is reserved for this school’s valid students only. Therefore jukeBox had toask studentCollection to validate the user first. Well actually, studentCollectionhas that responsibility. The verification was done earlier in this scenario (even if itis not exactly clear yet how it was done). Additionally, as stated in the problemstatement, a student must have enough time credit, and may not play more thantwo tracks on the same date. The role player of track has an idea. He suggests thatthe jukebox ask the track for its play time.

12.2.2.3 Alternative 1

jukeBox: So tell me, track, how many minutes and seconds do you require to beplayed?

track: 3 minutes and 34 seconds.

jukeBox: student, do you have at least 3 minutes and 34 seconds credit?

student: I’ll be responsible for maintaining my remaining time credit (he adds thisto his CRH card), so I can answer that. Yes, I have enough credit.

jukeBox: student, have you played fewer than two tracks on this date?

student: Yes, I have not played two tracks today.

jukeBox: Okay, now we can play the track. Here it is, cdPlayer.

cdPlayer: Okay, jukeBox, I would be willing to tell the physical CD player to playthis track. Actually, I have no idea how I am going to do that, but I’ll write aplayTrack responsibility on my CRH card for now as long as you send me thetrack to be played during a playTrack message.

This scenario has now reached a logical conclusion. However, the team feelsthat jukeBox already has enough responsibilities. “Why should I have to figure outif the student can play the selected track?” asks the member role playing jukeBox.

457

Chelsea suggests that they follow their instincts and try to distribute system intel-ligence as evenly as possible—a principle of good object-oriented design. Anotherheuristic for good design is avoid all-powerful classes. This suggests that in a gooddesign, jukeBox might not be the best class for determining whether or not a stu-dent can play a track. Perhaps some other class should have that responsibility. Theperson playing student thinks it is appropriate to let the student object be respon-sible for figuring out if its human equivalent is allowed to play the selected track.

12.2.2.4 Alternative 2

jukeBox: student, can you play this track?

student: I feel as though I should be responsible for maintaining my own time credit.It seems appropriate that I should also know how many tracks I’ve played to-day. So I should be able to do some simple calculations to give you the answeryou seek. Yes, jukeBox, I can play the track you sent me. I’ll add these responsi-bilities to my CRH card:* know how much time credit I have left* know how many tracks I’ve played on this date* respond to a message like student::canSelect(currentTrack)

The team wonders which alternative is better. One way to assess the design isto ask what feels better. Alternative 2 feels better somehow. Wouldn’t it be nice ifthere were some object-oriented design heuristics to make us feel better about feel-ing better?

Well, it turns out that the first alternative has a higher degree of coupling,which means more messages are sent from jukeBox to student. There were twodifferent messages versus the single message of the second alternative (canSelect).Chelsea adds this heuristic to the repertoire:

OBJECT-ORIENTED DESIGN HEURISTIC 12.5

Minimize the number of messages between a class and its helper.

Additionally, the second alternative has better cohesion. This means that the twoknowledge responsibilities necessary to answer a canSelect message are closelyrelated.

THE RESPONSIBILITIES OF EACH student

1. know how much time credit I have

2. know how many tracks I’ve played on this date

12.2 ROLE PLAYING AND CRH CARD DEVELOPMENT

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

458

Additionally, the first alternative requires jukeBox to know about the internalstate of the track and the internal state of student. This is a violation of Object-Oriented Design Heuristic 6.1, “All data should be hidden within its class.” In con-clusion, the second alternative delegates responsibility to the more appropriate class.

Chelsea (the object expert) verifies that the team member holding the studentcard should add canSelect as a responsibility. The team feels this scenario hasreached its logical conclusion.

Self-Check12-5 Summarize the algorithm that lets one user make one selection.

You may send any message that you desire to any object you desire.Use any of the objects shown next as if the classes were alreadyimplemented. Add any message you like.

You are currently designing. Pretend you will be passing off yourCRH cards and the entire algorithm to another programmer whowill have to make it all work according to your design.

student currentStudent;track currentSelection;cardReader myCardReader;cdCollection myCdCollection;studentCollection myStudentCollection;trackSelector myTrackSelector;cdPlayer myCdPlayer;

There are many other possible scenarios. For instance, what if the student doesnot exist in studentCollection? What should happen? Or what if a student doesnot have enough credit or has already selected two tracks?

12.2.2.5 Scenario 2: “What happens when a student who has already played two trackson this date tries to select a third track?”

jukeBox: Let us skip up to the point where I send a canSelect message.

student: No, I can’t select a track.

jukeBox: I could simply send an appropriate message to the user.

So far, so good. However, Steve, who is holding the cdPlayer card, wonders whenand how a track ever actually gets played by the physical CD player so it can beenjoyed over the stereo system. It seems as if cdPlayer needs some stimulus. Theteam has questions. Which class is responsible for sending the message that plays a

459

track? And what happens when another track is already playing? If there are manytracks to be played, when and how will more than one track be played? Will the CDplayer be able to tell anyone when a track has finished? Misty asks, “Who is roleplaying the play list?” The team members check the lists of classes and to theirdismay, discover that there is no playList class.

Chelsea comforts the team. “This often happens. We are trying to discover classesthat represent an abstract view of the system. It is not unusual to discover usefulabstractions at any point of software development. So feel free to add a playListclass now.” playList should maintain the list of tracks selected by users.

12.2.2.6 playList, a new class to maintain track selections in order

Charlie wants to know if playList should be a data member of the cdPlayer class?Don’t CD players maintain their own play lists? Yes they do. Steve, who is role play-ing cdPlayer suggests that he contain playList as a data member.

The object expert suggests that this decision could be made at a later meeting.However, the team wants to force the issue now, as it is difficult to arrange a meetingtime that all members can attend.

Jessica and Jason then lead a conversation suggesting that the overall systemwould be easier to implement if the physical CD player maintained playList. Firstof all, there is reuse of existing software (play lists) and hardware (CD selectionmechanism, a clock, and hardware to read digital songs and convert them to realsound). Modern CD players not only maintain their own play lists, they also knowprecisely when to play the next track! If the system under development has to sendplayTrack messages at the appropriate time, jukeBox or somebody else would alsohave to maintain the time remaining on the currently played track—independent ofthe physical CD player. And how long does it take to load up CD #199 after CD #3has just been played—3 seconds, 10 seconds, 5 seconds, 1 minute? When shouldjukeBox ask cdPlayer to play the next track? Will a track be cut short? Will there beunnecessary delays?

Chelsea begins a discourse that addresses a recurring design decision with sys-tems that have concurrent (simultaneous) processes. Since the primary responsibil-ity of jukeBox is to coordinate activities, jukeBox could control when the next trackwill be played. This could happen by using what is known as a polling design. jukeBoxwould go out and frequently poll (ask) cdPlayer if it is playing a CD. If cdPlayerreplies “Yes,” jukeBox can go off and do other things. If cdPlayer replies “No, I amnot playing a track,” jukeBox could ask playList for the next track and then send amessage to cdPlayer to play it. In this case jukeBox continuously polls cdPlayer. In

12.2 ROLE PLAYING AND CRH CARD DEVELOPMENT

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

460

fact, this sounds a lot like waitForUser, a responsibility accomplished by polling—continuously asking cardReader if a card has been swiped.

It is also possible to have an interrupt-driven design. Each time cdPlayer fin-ishes playing a track, cdPlayer asks jukeBox for the next track to play. In this case,cdPlayer is said to interrupt jukeBox. The jukeBox accommodates by getting thenext track as soon as possible.

Matt reminds the team they have two computers. One is the PC that interactswith users as it maintains studentCollection and cdCollection. The second is aprocessor inside the physical CD player. Why can’t we reuse the existing softwareand hardware of the CD player? Matt goes on to tell the team that this is easily doneby setting the CD player to its internal program mode. His CD player at home canqueue up to 99 different tracks at any one time. Charlie says he could deal witheither a polled design, an interrupt-driven design, or this third option of havingconcurrent processes perform their responsibilities simultaneously on two separateprocessors.

Chelsea repeats, “Now that would be reuse!” She suggests that the team roleplay a scenario assuming playList resides in the physical CD player and follow aconcurrent process design. And even though playList is already implemented inthe physical CD player with a separate microprocessor, it might be useful to keepplayList as a class during role playing. “It really feels important,” suggests Blaine.

Chelsea asks the team to simplify the analysis. “All we need to do is send aplayTrack message to cdPlayer. The cdPlayer class will be responsible for commu-nicating with the physical CD player.” The CD player will continuously play songsin a first-to-last order all by itself while jukeBox is busy getting new track selectionsfrom users. In fact, if the computer fails, the physical CD player could play out theentire playList.

12.2.2.7 Scenario 3: “What happens when a student is willing and able to play a track,but several tracks are waiting to be played?”

Chelsea tells trackSelector to pick up a scenario that already has a valid student.

jukeBox: trackSelector, here is cdCollection. Please return the user’s musicalselection.

trackSelector: Okay, I now have the cdCollection, so user, please select a track.The user selects the “I’m the Cat” track from Jackson Browne’s CD titled Look-ing East. trackSelector returns this selected track, which jukeBox knows ascurrentSelection—an instance of the track class.

461

jukeBox: student, can you play the currentSelection?

student: Yes.

jukeBox: cdPlayer, please playTrack(currentSelection).

cdPlayer: Okay, I got it. However, a track is currently playing and there are othertracks to play before I can play your selection. What do I do now?

playList: Hey, that’s my job. I’ll add the currentSelection at the end of the queue(waiting line) of tracks to be played, if that’s what everyone thinks is fair.

Chelsea asks Blaine, the customer and domain expert, if this is the properpolicy—first come, first served. Blaine retorts, “Yes, absolutely.” Charlie, who has apart-time job as a network administrator at Lucent Technologies, pronounces thatsuch a fair policy is easily enforced as a first-in-first-out (FIFO) waiting line—whatcomputer scientists call a queue. Blaine asks Charlie how one can set up a waitingline inside a computer. Charlie says a queue is like a vector except that new thingscan be added only at the end. Things can only be removed from the front. Blainereminds Charlie that he knows a lot about student policies but very little aboutvectors and queues. Chelsea reminds Charlie to avoid discussing implementationdetails during analysis—even if he knows about an existing queue class that caneasily “queue up” tracks.

playList: Okay, I’ll write these responsibilities on my CRH card: queueUpTrack andgetNextTrackToPlay, even if I already exist in the CD player.

12.2.2.8 Scenario 4: “What happens when a student ID card is not found instudentCollection?”

jukeBox: Okay, I’m waiting for a user. Waiting, waiting, waiting . . .

cardReader: Okay, jukeBox, a user just swiped a card. Here is the student ID.

jukeBox: Thanks, cardReader. Now that I have the student ID, I need to verify if theuser is valid. Hey, you know what? I am going to give a name to what I am doing.It seems like I am performing an operation that gets the student ID, finds thestudent, asks trackSelector for the student’s selection, and so on. I’m going tosummarize this algorithm and write it on my card as processOneUser.

studentCollection: Well, since it is my responsibility to store the collection ofstudent objects, let me check to see if there is a student here with that ID. No,we have no student with that ID. What do we do now?

12.2 ROLE PLAYING AND CRH CARD DEVELOPMENT

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

462

jukeBox: I’ll just tell the alleged user that it’s a no-go.

“Whoooooaaa,” groans Jason. “A student with a valid student ID is a valid stu-dent. Let ’em in.” Jessica supports Jason’s suggestion by suggesting that “valid stu-dent” means something different each semester. Some students drop out in the middleof a term. New students come in at the beginning of a term. Jessica expresses con-cern about maintaining an accurate list of valid students—would we have to accessthe registrar’s database of students? Blaine suggests that the cashless jukebox isn’ta mission-critical system. Nor could anyone profit from its abuse. So even if a few“invalid” students get in, so what? The team members unanimously agree that anonexistent student with a valid ID card should have an account created automati-cally. “And how much time credit do we give that new student account?” questionsMatt. “1,500 minutes, of course,” replies Misty.

jukeBox: Let me change my previous action so the new student is added to the newcollection. Who should have that responsibility?

studentCollection: Why, me of course. Give me the student ID number from themagnetic ID card, and I will add a new student. I’ll write the action responsibil-ity addStudent on my CRH card. So jukeBox will not have to worry about thestudent returned. It may be someone who had been in the system, or it may besomeone who was just added.

Self-Check12-6 Play out the following scenarios by writing the class name and

narrative of each until it has reached its logical conclusion:

-a What happens when a student swipes her card for the firsttime on a given date and wants to play two different songs?

-b What happens when a student has no more time credit left, butwants to play a song?

-c What happens when the Student Affairs office wants to removea CD from the jukebox?

-d What happens when the Student Affairs office wants to add anew CD to the jukebox?

-e What happens when cdPlayer receives a playSong messageand the physical CD player is turned off or malfunctioning?

463

12-7 List several college-library scenarios that should be played out by ateam.

12-8 Script a college-library scenario that describes what happens whena user wants to check out a book.

12-9 Script a college-library scenario that describes what happens whena user wants to return a book that is not late.

12.2.3 Why CRH Cards?After role playing, discussion, arguments, laughter, and changed minds, the designis captured as a set of classes that model a solution. Class names and responsibili-ties have been recorded on CRH cards as the team role played the scenarios. CRHcards help the problem-solving and system-building processes in many ways. RebeccaWirfs-Brock writes [Wirfs-Brock 90]:

We have found that index cards work well because they are com-pact, easy to manipulate, and easy to modify or discard. Becauseyou didn’t make them, they don’t feel valuable to you. If the classturns out to be spurious, you can toss the card aside with few re-grets. . . . If you discover you have erroneously discarded a classcard, it is simple to retrieve it, or make a new one.

This is but one example of the many dynamics of CRH card use in software that gobeyond the scope of this textbook. The previous jukebox discourse was an attempt torepresent real-world object-oriented analysis and design.

In actuality, during October and November 1997, six students role played theseand other jukebox scenarios. Some of the issues that arose are left as analysis anddesign exercises. For example, the team members strongly felt that no track shouldbe played within the same hour. The author (acting as the customer and domainexpert Blaine) agreed this would be a good enhancement, but it would be a changedealt with as an enhancement later. It is an interesting design decision to make.There are several possibilities.

One of the benefits of having a team consisting of designers and customers isthe opportunity for everyone to develop an understanding of the system in commonterminology. Sometimes customers haven’t asked for what they really want. Experi-enced teams familiar with customer needs can actually help customers sharpentheir requirements. The team can also make suggestions like this: “Please don’t let

12.2 ROLE PLAYING AND CRH CARD DEVELOPMENT

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

464

the same track play over and over again. I couldn’t stand that. It happened too muchin high school. We had to turn the jukebox off.” Limits of two tracks a day couldprevent a lot of complaints.

12.2.4 Responsibilities and HelpersThe following summary of responsibilities and helpers is the result of the precedingCRH card development with the team role playing individual classes. These will beused in the next chapter to document the class names, action responsibilities, knowl-edge responsibilities, and collaboration for creating the class definitions. Knowledgeresponsibilities could become data members. Action responsibilities could becomemember functions. A helper might become a message send, a data member (contain-ment relationship), an argument in a message, or a return value from a message.You will see more about these relationships and class definition design in Chapter 13.

FIGURE 12.7. Major classes with responsibilities and helpers

Class: jukeBox

Responsibilities:

know current track

know current studentwaitForUser

processOneUser

Helpers:

trackSelector

student

cardReader

studentCollection

cdCollection

cdPlayer

Class: cardReader

Responsibilities:

getStudentID

Helpers:

physical card reader, which

in turn collaborates with

the magnetic student ID card

Class: student

Responsibilities:

know remaining credit

know how many songs played today

canSelect

Helpers:

date

Class: studentCollection

Responsibilities:

know all students

getStudent

addStudent

Helpers:

student

465

12.2 ROLE PLAYING AND CRH CARD DEVELOPMENT

Class: CD

Responsibilities:

know tracks

know play time

know CD title and artist name

allow references to individual tracks

Helpers:

Class: cdCollection

Responsibilities:

know all CDs CD

allow references to individual CDs

addCD

removeCD

Helpers:

Class: trackSelector

Responsibilities:

track getTrack(int) the user

track

CD

cdCollection

Helpers:

Class: track

Responsibilities:

know play time

know physical location in the CD player

(CD number, track number)

Helpers:

Class: cdPlayer

Responsibilities:

playTrack

playList

the physical CD player

CD

Helpers:

Class: playList

Responsibilities:

maintain list of selected tracks

queueUpTrack

getNextTrackToPlay queue

track

Helpers:

12.3 An Uninterrupted ScenarioChelsea congratulates the team. The responsibilities seem to be distributed over areasonable number of classes. If you consider that cdPlayer and playList are al-ready implemented, the team has to consider and implement only eight classes atonce.

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

466

Steve complains that he is still a bit confused. Each time a scenario began, itwas not completed without some interruption. Chelsea had a lot to say about object-oriented analysis and design. Blaine sometimes had to address policy issues such asthe play policy. Charlie just seemed to say too much about implementation. Addi-tionally, it seemed that while the team members were trying to understand theproblem, they also had to stop and make design decisions; should it be a polleddesign, an interrupt-driven design, or a concurrent design?

Jessica and Jason admit to some confusion. Jessica proposes that the team roleplay a scenario without interruption. This may be a repeat of what has been done,but it might help us understand the system better—a summary of sorts. Chelseabelieves this is a good idea. She suggests the team hold the same CRH cards androle play a scenario.

12.3.1 Summary Scenario: “What happens when a studentwithout an account wants to select a track?”

jukebox: I’ll start the scenario again. I’m waitingForUser, so cardReader, pleasegetStudentID.

cardReader: No one has swiped their card.

jukeBox: Okay, cardReader, I’ll ask again. Please getStudentID.

cardReader: No one has swiped their card.

jukeBox: Okay, I’m waiting for a user. Waiting, waiting, waiting . . .

cardReader: Okay, jukeBox, a user just swiped a card. Here is the student ID: 1234.

jukeBox: studentCollection, please getStudent with ID 1234.

studentCollection: Well, there is no such student, so I’ll create a new student ac-count and the student will have a time credit of 1,500 minutes and no songsplayed on this date. I suspect this would be a default student object.

jukeBox: Thanks, studentCollection, for the currentStudent. trackSelector, I’mgiving you cdCollection. Would you please give me the user’s currentSelection?

trackSelector: Okay, I’ll use cdCollection to show all the CDs and tracks to theuser. The user will have to select the track. Got it.

467

jukeBox: Okay, I have the currentSelection. student, can you select a song?

student: Yes, I can select a song.

jukeBox: Now, cdPlayer, please playTrack(currentSelection).

cdPlayer: playList, please add this track to the music we’ll eventually play.

playList: Okay, I can queue it up, but if you aren’t currently playing anything, whydon’t you play it now?

cdPlayer: Well, I am playing some good stuff now, so please queue it up.

playList: Okay, I’ll add it.

jukeBox: Actually, I don’t need to worry about what you guys did, I’m already wait-ing for another user.

Chelsea suggests that this scenario has reached its logical conclusion. jukeBoxis waiting for another user. The CD player is playing the selected tracks in an FIFOorder from playList.

Jessica, who has been role playing cdCollection, observes that she played norole in the scenarios. “You sent me to trackSelector, but I was never asked foranything. Why did trackSelector need me?” Chelsea agrees that something is amiss.It appears that cdCollection must make individual CDs available to trackSelectorin some reasonable order. “What about artist names alphabetically?” asks Jessica.Blaine replies, “Seems reasonable. It’s probably easier for students to pick an artistfirst, then a CD by that artist, then a track from that CD.”

Jessica recalls that vectors allow access to individual elements in the containerof objects. So it seems reasonable that cdCollection must also allow access to indi-vidual CDs from first to last. Charlie says he can handle it. Don’t worry about it.Chelsea thanks Charlie.

Now everything is wonderful, except . . . What happens if the same user wantsto play a second and then a third track? A new account will not be created this time,but somehow student must know if it canSelect. This new account should not beable to select a third track. No student should have unlimited time credit. In otherwords, student must be modified to reflect the fact that it selected a track and theCD player played the music. When should student updates occur?

12.3 AN UNINTERRUPTED SCENARIO

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

468

Chelsea, who was role playing student, suggests that she could have updatedherself when asked the canSelect question. She had the currentSelection, so shecould have deducted the time it takes to play that track during canSelect. She couldalso have recorded today’s date. When a second track was selected, she could havemodified herself again in the same way. When the third canSelect message wassent to student, student could simply reply, “No can do. And by the way, I won’tdeduct any time, nor will I record the fact that I selected a third song on today’sdate.”

The team can live with this, except Matt wonders how studentCollection willknow if one of its students has been modified. Charlie says studentCollection couldremove the old student and add the modified student. Blaine doesn’t like that sug-gestion. Charlie says, “Okay, simply return a reference to the student so any changeto student by jukeBox will also update the student in the studentCollection.”Blaine bemoans, “What’s a reference?” Charlie stops before he says a word. Instead,he quietly contemplates how to change students and maintain them so they are thesame later in the day and even later in the term or in a student’s career. Charlie hascompleted two computer science courses and he knows that references and files willprove useful helper classes.

The team meeting is over after Chelsea sets up a meeting with Charlie andMatt. Stay tuned for the class definition design and member function implementa-tions (see Chapter 13).

Chapter Summary* Object-oriented software development begins by identifying the key abstractions—

classes—that potentially model a solution. Software designers assign responsibili-ties to the appropriate classes.

* Analysis and design decisions can be documented as Component/Responsibility/Helper (CRH) cards. Each CRH card begins as a blank 3-by-5-inch index card (or itcould be 4 by 6 inches) with a class name and major responsibilities written on theback.

* Collaborative design and role playing enhance the object-oriented development pro-cess. Possible analysis classes arise not only from the problem specification itselfand domain expertise, but also from the words that are spoken as teams analyzeproblems.

* Team members assume the roles of these analysis classes, play out scenarios (whatwould happen when . . .), and establish relationships between classes. During role

469

playing, team members establish more detailed responsibilities—what an objectshould know and what it should be able to do—while recording them on the CRHcards.

Exercises1. The students are complaining. The same song plays again and again. One person

plays it twice and then has a friend play it twice. The Student Affairs office asksyou to modify the jukebox so it will not play any song that has been played in theprevious 60 minutes. The original team has graduated. You have to do it by your-self. List all classes that must be modified. What changes must be made to each?

2. What changes would need to be made to the jukebox design in order to maintainthe CD collection in this way: The jukebox has been running for a while. TheStudent Affairs office wants to replace the 10 least frequently played CDs with afresh 10. The original team has graduated. You have to do it by yourself. List allclasses that must be modified. What changes must be made to each?

3. After the jukebox has been running for a while, students begin to complain be-cause they can no longer select songs due to the fact that that they are out oftime. The Student Affairs office asks you to modify the jukebox so users can playup to 3,000 minutes of music. The original team has graduated. You have to do itby yourself. List all classes that must be modified. What changes must be madeto each?

4. After the jukebox has been running for a while more, students begin to complainbecause they can no longer select songs due to the fact that that they are runningout of time again. The Student Affairs office asks you to modify the jukebox sothere is no time restriction. The original team has graduated. You have to do it byyourself. List all classes that must be modified. What changes must be made toeach?

5. Students want to be able to play entire CDs on the weekends. The Student Af-fairs office asks you to modify the jukebox so each student can play one entire CDon any given date. The original team has graduated. You have to do it by yourself.List all classes that must be modified. What changes must be made to each?

EXERCISES

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

470

Analysis Tips

1. Model the real world when possible.Meaningful well-named abstractions can make the system design easier to under-stand.

2. Anthropomorphize.Don’t be afraid to give human characteristics to your objects. Ask these questionsoften:* What should an instance of this class be able to do?* What should an instance of this class know?

3. On your CRH cards, write action responsibilities as if theywere C++ identifiers (no spaces).This will help as you move on to designing class definitions. Conversely, write knowl-edge responsibilities like this:* know all CDs* know all tracks* know play time

4. Do not procrastinate.Write down the responsibilities as soon as you realize them during role playing.Early bouts of laziness can end up in frustration later.

5. Distinguish objects that are outside of the systemunder development.For example, the jukebox will communicate with the user. The jukebox will read thestudent ID card. However, both the user and the magnetic ID card are outside of thesystem.

6. The user is often confused as being a key abstraction tobe modeled.The user is important. However, there is usually some state object that models thereal-world user. Remember that there is a physical user that selects songs, but there

471

is also a software equivalent called student that knows how many songs the soft-ware equivalent has played today.

7. Definitely draw a picture of the major classes.Make the classes rectangular boxes with the class name and the major responsibil-ity (10 words or less). The picture should have arrows from the sender of a messageto the receiver of that message (see the jukeBox picture).

8. Helpers usually represent a one-way relationship.If class A asks class B for help, A is the sender, B is the helper. Write down thatresponsibility on B’s card. jukeBox asked a helper named studentCollection togetStudent. getStudent should be on the studentCollection card.

9. It is not a good idea to ask the physical user if he or she canselect.However, it is perfectly okay to ask the software object. The physical student mightsay, “Sure I can play 100 songs today.” Assume the programmer will not let the user’ssoftware equivalent lie. Besides, the user is not part of the system.

10. The first round of scenarios will often be interrupted bydiscussions.Interruptions are okay. This is called brainstorming. Five heads are better than one.Genius is more easily accomplished with more than one person. At some point, haveyour team play out a familiar scenario without interruption. You will see the objectsmore clearly and understand their responsibilities.

11. The jukebox and the projects at the end of this chapter arerelatively large systems.They certainly do more than convert from Fahrenheit to Celsius. If you don’t under-stand jukeBox, don’t worry. The best way to understand it is to do an analysis witha team. This could take hours. On more complex systems, this could take months.The projects of this chapter are less complex. However, they are complex enough tobenefit from an object-oriented approach to software development.

ANALYSIS TIPS

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

472

12. The jukebox has key abstractions that set a pattern for theanalysis projects coming up at the end of this chapter.As you perform your own analysis and CRH card development in a team project(12A, 12B, 12C, 12D) look for the following major classes (the analysis projects typi-cally have five, six, or seven classes). Like the jukebox, they include* a class that coordinates the major activities (jukeBox here)* a collection of objects (studentCollection and cdCollection here)* state objects (student, track, and CD here) stored in a container class* one or more classes that model something in the real world (student, cardReader,

and cdPlayer)

Object-Oriented Analysis / Design ProjectsEach of the following analysis projects assumes you are using a team approach involvingactivities like those described in this chapter. Team size should be two, three, four, or fivestudents.

1. Once you have a team, pick a project you want to do. Choose from this list:

Bank Teller (12A)

Voice Mail System (12B)

Video Rental Store (12C)

Checkbook (12D)

make one up

2. Next, analyze the problem to establish a reasonable set of classes that model asolution. Draw the classes on a piece of paper. Make sure each class has a nameand a major responsibility assigned to it.

3. For each useful class, write the name of the class and its major responsibility onthe back of a 3-by-5-inch index card (or an 8½-by-11-inch piece of paper if youdon’t have index cards). On the front, list the class, the more finely detailed re-sponsibilities, and any helpers the class uses to accomplish its task.

4. Run through scenarios that you invent. Using a pencil, write down responsibili-ties as they crop up. Remember, the class may have action responsibilities, knowl-edge responsibilities, or both. Also write down any helpers that exist. If you askanother object for help, that person (object) is a helper. You may erase, you may

473

cross off, or you may add responsibilities; in fact you may even tear up and recyclethat CRH card.

5. Role play as many scenarios as you can think of. Do them until you really under-stand the system. The CRH cards should provide an accurate portrayal of theresponsibilities of each class.

Save your CRH cards. They will be used to help you design class definitions (Chapter 13).Your project can be continued into the next chapter and on into complete implementation.

12A Bank Teller Application Adapted from Problem Solvingand Program Implementation [Mercer 91]

First read the notes above. The bank teller application allows any bank customers accessto their own bank accounts through their customer numbers. Once a customer swipes thebank card and enters the personal identification number (PIN), the user, with the help ofa teller, may complete any of the following transactions: withdraw money, deposit money,and query account balance. Customers may also see their own transaction logs. The sys-tem must maintain the correct balances for all accounts and also log each and every suc-cessful transaction.

12B Voice Mail System Adapted from Mastering Object-Oriented Design in C++ [Horstmann 96]

First read the notes above. Simulate a voice mail system. The system has a collection ofmailboxes, each of which may be accessed by an extension number (3445, for instance). Auser may put a message into any mailbox, so anyone on the computer may type in amailbox number and then type in a message. Any user with a valid mailbox and the validpassword may do any of the following:* play back messages* delete messages* change the greeting* change the password

An administrator is needed to activate new mailboxes and deactivate active mailboxes.The administrator is a user with a “super password.”

OBJECT-ORIENTED ANALYSIS/DESIGN PROJECTS

CHAPTER TWELVE OBJECT-ORIENTED SOFTWARE DEVELOPMENT: ANALYSIS AND DESIGN

474

12C Video Rental System from Data Structures via C++[Berman 97]

First read the notes above. Build a software system to support the operation of a videorental store. The system should automate the process of renting tapes and receiving re-turned tapes, including the calculation and printing of customer bills, which may or maynot be done at the same time a tape is returned. The system must also give the clerkaccess to information about the tapes, such as the number of copies on the shelf of anygiven video owned by the store. The system must be able to add and remove customers andtapes to and from the database. Each customer and each copy of each tape are associatedwith a unique bar-coded label.

12D Checkbook Application Adapted from Using CRC Cards[Wilkinson 95]

First read the notes above. Simulate an electronic checkbook. The checkbook manages alimited set of entries: checks written and bank deposits. The checkbook must maintain theproper balance and a record of all entries. The checkbook will be able to print a statementof all activities. The user should be able to look up any check number individually and seethe amount and who the check was written to.