Tegarden SystemsAnalysis.S.205 226

download Tegarden SystemsAnalysis.S.205 226

of 22

Transcript of Tegarden SystemsAnalysis.S.205 226

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    1/22

    CRC Cards 2 5

    CRC Class-Responsibility-Collaboration) cards are used to document the responsibilitiesand collaborations of a dass. In some object-oriented systems-development methodo1ogies, CRC cards are seentobe an alternative competitor to the Unified Process employmentof use cases and dass diagrams. However, we see them as a useful, low-tech approach thatcan comp1iment a typical high-tech Unified Process approach that uses CASE too1s. We usean extended form of the CRC card to capture all relevant information associated with adass. 9 We describe the e1ements of our CRC cards 1ater, after we exp1ain responsibi1itiesand collaborations.Responsibilities and CollaborationsResponsibilities of a dass can be broken into two separate types: knowing and doing. Know-ing responsibilities are those things that an instance of a dass mus t be capable of knowing.n instance ofa dass typica11y knows the va1ues of its attributes and its relationships. Doingresponsibilities are those things that an instance of a dass must be capable of doing. In this

    case, an instance of a dass can execute its operations or it can request a second instance,which it knows about, to execute one of its operations on behalf of the first instance.The structural model describes the objects necessary to support the business processes

    mode1ed by the use cases. Most use cases invo1ve a set of severa1 dasses, not just one dass.These dasses form collaborations. Collaborations allow the analyst to think in terms ofdients, servers, and contracts. 10 A client object is an instance of a dass that sends a requestto an instance of another dass for an operation to be executed. A server object is theinstance that receives the request from the dient object. A contract formalizes the interactions between the dient and server objects. For examp1e, a patient makes an appointmentwith a doctor. This sets up an obligation for both the patient and doctor to appear at theappointed time. Otherwise, consequences, such as billing the patient for the appointmentregardless of whether he or she appears, can be dealt out. Also, the contract should spell outwhat the benefits of the contract will be, such as a treatment being prescribed for whateverails the patient and a payment to the doctor for the services provided. Chapter 8 providesa more detailed explanation of contracts and examples of their use.

    An analyst can use the idea of dass responsibilities and client-server-contract collaborations to h lp identify the classes, along with the attributes, operations, and relationships,involved with a use case. One of the easiest ways to use CRC cards in developing a structuralmodel is through anthropomorphism pretending that the classes have human characteristics. Members of the development team can either ask questions of themselves or be askedquestions by other members of the team. Typically the questions asked are of the form:

    Who or what are you?What do you know?What can you do?

    9 Our CRC cards are based on the work ofD. Bellin and S. S. Simone, The CRC Card Book (Reading, MA: AddisonWesley, 1997); I Graham, Migrating to Object Technology (Wokingham, England: Addison-Wesley, 1995); andB Henderson-Sellers and B. Unhelkar, OPEN modeling with UML (Harlow, England: Addison-Wesley, 2000).w For more information, see K. Beck and W. Cunningham, A Labaratory for Teaching Object-Oriented Thinking; Proceedings o OOPSLA, SIGPLAN Notices 24, no. lO (1989): 1 6; B. Henderson-Sellers and B. Unhelkar,OPEN Modelingwith UML (Harlow, England: Addison-Wesley, 2000); C Larman, Applying UMLand Patterns: AnIntroduction to Object-OrientedAnalysis and Design (Englewood Cliffs, NJ: Prentice Hall, 1998); B Meyer, ObjectOriented Software Construction (Englewood Cliffs, N): Prentice Hall, l994); and R. Wirfs-Brock,B. Wilkerson, andL Wiener, Designing Object-Oriented Software (Englewood Cliffs, N), Prentice Hall, 1990).

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    2/22

    206 Chapter Structural Modeling

    FIGURE 5 6Sampie CRC Card

    The answers to the questions are then used to add detail to the evolving CRC cards. example, in the appointment prob ern, a member of the team can pretend that he or shan appointment. In this case the appointment would answer that he or she knows abthe doctor and patient who participate in the appointment and they would know the dand time of the appointment. Furthermore, an appointment would have to know howcreate itself, delete itself, and to possibly change different aspects of itself. In some casthis approach will uncover additional obje

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    3/22

    R ards 207the dass s name, ID, type, description, associated use cases, responsibilities, and collaborators. The name of a dass should be a noun (but not a proper noun, such as the name of aspecific personor thing). Just like the use cases, in later stages of development, it is important to be able to trace back design decisions to specific requirements. In conjunction withthe Iist of associated use cases, the ID nurober for each dass can be used to accomplish this.The description is simply a brief statement that can be used as a textual definition for thedass. The responsibilities of the dass tend to be the operations that the dass must contain(i.e., the doing responsibilities).

    The back of a CRC card contains the attributes and relationships of the dass. Theattributes of the dass represent the knowing responsibilities that each instance of the dasshas to meet. Typically, the data type of each attribute is listed with the name of the attribute(e.g., the amount attributeisdouble and the insurance carrier is text). Three types of relationships typically are captured at this point: generalization, aggregation, and other associations. In Figure S-6, we see that a Patient is a-kind-of Person and that a Patient isassociated with Appointments.

    CRC cards are used to document the essential properties of a dass. However, oncethe cards are filled out, the analyst can use the cards and anthropomorphisms in roleplaying (described in the next section) to uncover missing properties by executing thedifferent seenarios associated with the use cases (see Chapter 4). Role-playing also canbe used as a basis to test the clarity and completeness of the evolving representation ofthe system.

    Role Playing R Cards with se Cases 2In addition to the object identification approaches described earlier ( extual analysis, brainstorming, common object lists, and patterns), CRC cards can be used in a role playing exercise that has been shown to be useful in discovering additional objects, attributes,relationships, and operations. In general, members of the team perform roles associatedwith the actors and objects previously identified with the different use cases. Technicallyspeaking, the members of the team perform the different steps associated with a specific sce-nario of a use case. Remember, a scenario is a single, unique execution path through a usecase. A useful place to Iook for the different seenarios of a use case is the activity diagrams(e.g., see Figures 4-7, 4-8,4-9, and 4-10 . A different scenario exists foreachtime a decisionnode causes a split in the execution path of the use case. Also, seenarios can be identifiedfrom the alternative/exceptional flows in a use-case description. Even though the activitydiagrams and use-case descriptions should contain the same information and given theincremental and iterative nature of object-oriented systems development, at this point in theevolution of the system, we suggest that you review both representations to ensure that youdo not miss any relevant scenarios.The first step is to review the use-case descriptions (see Figure S-2). This allows the teamto pick a specific use case to role-play. Even though it is tempting to try to complete asmany use cases as possible in a short time, the team should not choose the easiest use casesfirst. Instead, at this point in the development of the system, the team should choose theuse case that is the most important, the most complex, or the least understood.11 This step is related to the verification and validation of the analysis models (functional, structural, and behavioral). Because this deals with verification and validation that takes place between the models, in this case, functional and structural, we will return to this topic in Chapter 7.12 ur role-playing approach is based on the work of D. Bellin and S. S. Simone, The CRC Card ook (Reading,MA: Addison-Wesley, 1997).

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    4/22

    208 Chapter 5 Structural Modeling

    2 ldentify RelevantActors and Objects

    3. Role-Piay Scenarios

    4. Repeat Steps 1throughCLASS DIAGRAMS

    The second step is to identify the relevant roles that are tobe played. Each role is associawith either an actor or an object. To choose the relevant objects, the team reviews eachthe CRC cards and picks the ones that are associated with the chosen use case. For exaple, in Figure 5-6, we see that the CRC card that represents the Old Patient dass is assoated with Use Case number 2. So if we were going to role-play the Make Old Patient Ause case see Figure 5-2), we would need to indude the Old Patient CRC card. By revieing the use-case description, we can easily identify the Old Patient and Doctor actors Primary Actor and Stakeholders section ofthe use-case description in Figure 5-2). By reing the event section of the use-case description, we identify the internal actor roleReceptionist. After identifying ll of the relevant roles, we assign each one to a differmember of the team.The third step is to role-play seenarios of the use case by having the team members pform each one. To do this, each team member must pretend that they are an instance ofrole assigned to them. For example, if a team member was assigned the role of the Rectionist, then he or she would have to be able to perform the different steps in the scenaassociated with the Receptionist. In the case of the change appointment scenario, twould indude steps 2 5 6 S-3, S-1, and S-2. However, when this scenario is performrole-played), it would be discovered that steps 1 3 and 4 were incomplete. For exampin Step 1 what actually occurs? Does the Patient make a phone call? If so, who answers phone? In other words, a lot of information contained in the use-case description is oidentified in an implicit, not explicit, manner. When the information is not identifexplicitly, there is a lot of room for interpretation, which requires the team membersmake assumptions. t is much better to remove the need to make an assumption by maing each step explicit. In this case, step l of the Normal Flow of Events should be modifiOnce the step has been fixed, the scenario is tried again. This process is repeated until scenario can be executed to a successful condusion. Once the scenario has successfully coduded, the next scenario is performed. This is repeated until all of the seenarios of the case can be performed successfully. 13The fourth step is to simply repeat steps l through 3 for the remaining use cases.

    A cl ss di gr m is a st tic modelth t shows the dasses and the relationships among dasthat remain constant in the system over time. The dass diagram depicts dasses, whindude both behaviors and states, with the relationships between the dasses. The folloing sections present the elements of the dass diagram, different approaches that can used to simplify a dass diagram, and an alternative structure diagram: the object diagraElements o a Class DiagramFigure 5-7 shows a dass diagram that was created to reflect the classes and relationshassociated with the appointment system. This diagram is based on the dasses uneave

    13 In some eases, some seenarios are only exeeuted in very rare circumstanees. So, from a practical perspective, escenario eould be prioritized individually and only important seenarios would have to be implemented forfirst release of the system. Only those seenarios would have to be tested at this point in the evolution of the sys

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    5/22

    ....

    \ Q

    1.. 1..1 ppointment has Transaction Line llemccount Entry j Debit -tim ehas 1 .1 1.Cred it -date1 . 1 0 -reason1 . 1 . 1 +ca ncel without notice )

    0 . 1 . 1AssignedTo 0

    locatedAt I o IParticipant Place Prescription-Iastname-f irstname ...-address '-phone ::J-o

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    6/22

    21 Chapter 5 Structural Modefing

    FIGURE 5 8Class Diagram Syntax

    through the object-identification techniques and the role-playing of the CRC cardescribed earlier.Class The main building block of a dass diagram is the dass, which stores and maages information in the system (see Figure S-8). During analysis, dasses refer to the peple, places, and things about which the system will capture information. Later, durindesign and implementat ion, dasses can refer to implementation-specific artifacts suchwindows, forms, and other objects used to build the system. Each dass is drawn using

    A dass: Represents a kind of person, place, or thing aboutwhich the system will need to capture and s toreinformation. Has a name typed in hold and centered in its topcompartment. Has a Iist of attributes in its middle compartment. Has a Iist of operations in its bottarn compartment. Does not explicitly show operations that areavailable to all classes.An attribute: Represents properlies that describe the state of anobject.

    Can be derived from other attributes, shown byplacing a slash before the attr ibute s name.

    An operation: Represents the actions or functions that a dasscan perform.

    Can be dassified as a constructor, query, orupdate operation. Includes parentheses that may contain parametersor information needed to perform the operation.An association: Represents a relationship between multipleclasses or a dass and itself.

    Is labeled using a verb phrase or a role name,whichever better represents the relationship. Can exist between one or more classes. Contains multiplicity symbols, which representthe minimum and maximum times a dassinstance can be associated with the related dassinstance.

    A generalization: Represents a-k ind-of relationship betweenmultiple classes.An aggregation: Represents a logical a-part-of relationshipbetween multiple classes or a dass and itself.

    Is a special form of an association.A composition: Represents a physical a-par t-of relationshipbetween multiple classes or a dass and itself

    Is a special form of an association.

    attribute name/derived attribute name

    operation name ()

    AssociatedWith0

    __, >

    _o_. _ s _ a _ r t _ o _ f _ ~ 0

    1.. IsPartOf 1

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    7/22

    Class Diagrams 2three-part rectangle, with the class's name at top, attributes in the middle, and operationsat the bottom. We can see that the classes identified earlier, such as Participant, Doctor,Patient, Receptionist, Medical History, Appointment, and Symptom, are included in Figure 5-7. The attributesofadass and their values define the state of each object createdfrom the dass, and the behavior is represented by the operations.

    Attributes are properties of the dass about which we want to capture information(see Figure S-8). Notice that the Participant dass in Figure 5-7 contains the attributeslastname, firstname, address, phone, and birthdate. At times, you might want to storederived attributes which are attributes that can be calculated or derived; these specialattributes are denoted by placing a slash (/) before the attribute's name. Notice howthe person dass contains a derived attribute called/age, which can be derived by subtracting the patient's birth date from the current date. t is also possible to show thevisibility of the attribute on the diagram. Visibility relates to the Ievel of informationhiding to be enforced for the attribute. The visibility of an attribute can be public ( ,protected ( ), or private ). A public attribute is one that is not hidden from any otherobject. As such, other objects can modify its value. A protected attribute is one that ishidden from all other dasses except its immediate subdasses. A private attribute is onethat is hidden from all other dasses. The default visibility for an attribute is normallyprivate.Operationsare actions or functions that a dass can perform (see Figure S-8). The functions that are available to all dasses (e.g., create a new instance, return a value for a particular attribute, set a value for a particular attribute, delete an instance) are not explicitlyshown within the dass rectangle. Instead, only operations unique to the dass are included,such as the cancel without notice operation in the Appointment dass and the calculate lastvisit operation in the Patient dass in Figure 5-7. Notice that both the operations are followed by parentheses, which contain the parameter(s) needed by the operation. If an operation has no parameters, the parentheses are still shown but are empty. As with attributes,the visibility of an operation can be designated public, protected, or private. The defaultvisibility for an operation is normally public.

    There are four kinds of operations that a dass can contain: constructor, query,update, and destructor. A constructor operation creates a new instance of a dass. For example, the Patient dass may have a method called insert (), which creates a new patientinstance as patients are entered into the system. As we just mentioned, if an operationimplements one of the basic functions (e.g., create a new instance), it is normally notexplicitly shown on the dass diagram, so typically, we do not see constructor methodsexplicitly on the dass diagram.A query oper tion makes information about the state of an object available to otherobjects, but it does not alter the object in any way. For instance, the calculate last visit )operation that determines when a patient last visited the doctor's office will result in theobject's being accessed by the system, but it will not make any change to its information. fa query method merely asks for information from attributes in the dass (e.g., a patient'sname, address, phone), then it is not shown on the diagram because we assume that allobjects have operations that produce the values of their attributes.

    An update oper tion changes the value of some or all the object's attributes, which mayresult in a change in the object's state. Consider changing the status of a patient from newto current with a method called change status() or associating a patient with a particularappointment with make appointment (appointment).

    A destructor operation simply deletes or removes the object from the system. For example, if an employee object no Ionger represents an actual employee associated with the firm,the employee could need to be removed from the employee database, and a destructor

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    8/22

    212 Chapter 5 Structural Modeling

    FIGURE 5 9Sampie Association

    operation would be used to implement this behavior. However, deleting an object is onthe basic functions and therefore would not be induded on the dass diagram.Relationships A primary purpose of a dass diagram is to show the relationships, or aciations, that dasses have with one another. These are depicted on the diagram by drawlines between dasses (see Figure 5-8). When multiple classes share a relationship (or a dshares a relationship with itself), a line is drawn and labeled with either the name ofrelationship or the roles that the dasses play in the relationship. For example, in Figure 5the two dasses, Patient and Appointment, are associated with one another whenevepatient schedules an appointment. Thus, a line labeled schedules connects Patient Appointment, representing exactly how the two dasses are related to each other. Anotice that there is a small solid triangle beside the name of the relationship. The trianallows a direction to be associated with the name of the relationship. In Figure 5-7, schedules relationship includes a triangle, indicating that the relationship is to be reapatient schedules appointment. Indusion of the triangle simply increases the readabi

    of the diagram. In Figure S-9, three additional examples of associations are portrayed:Invoice is AssociatedWith a Purehase Order (and vice versa), a Pilot Flies an Aircraft, a Spare Tire IsLocatedin a Trunk.Sometimes a dass is related to itself, as in the case of a patient being the priminsurance carrier for other patients (e.g., spouse, children). In Figure 5-7, notice thline was drawn between the Patient dass and itself and called primary insurance carto depict the role that the dass plays in the relationship. Notice that a plus (+ sigplaced before the Iabel to communicate that it is a role, as opposed to the name ofrelationship. When labeling an association, we use either a relationship name or a rname (not both), whichever communicates a more thorough understanding ofmodel.

    Relationships also have multiplicity which documents how an instance of an obcan be associated with other instances. Numbers are placed on the association pathdenote the minimum and maximum instances that can be related through the associatin the format minimum number . maximum number (see Figure 5-10). The numbspecify the relationship from the dass at the far end of the relationship line to the end wthe number. For example, in Figure 5-7, there is a 0 . on the appointment end ofpatient schedules appointment relationship. This means that a patient can be associa

    lnvo ice AssociatedWith urehase rder0 . 1

    t----o__-11 ' Flies

    Spate Tire Trunklslocatedln0 ..1 0 .1

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    9/22

    FIGURE 5 10Multiplicity

    Class Diagrams 2 3

    A department hasI epartment I I Ixactlyone 1 oss one and only oneboss.An employee has

    Zero or more 0. I Employee I 0 .. 1 Child I zero to manychildren.A boss is responsibleI I Ine or more 1.. oss Employee for one or more1.. employees.An employee can

    Zero or one 0.. 1 I Employee I 0 .1I pouse I be married to zeroor on e spouse.An employee can

    Specified range 2 4 I Employee I 2 4 1 Vacation I take from two tofour vacations eachyear.An employee is a

    Multiple, disjoint 1..3,5 I Employee I 1 ..3,5 1 Committee I member of one toranges three or fivecommittees.

    with zero through many different appointments.At the patientend of this same relationship there is a 1..1, meaning that an appointment must be associated with one and onlyone (1 patient. In Figure S-9, we see that an instance of the Invoice dass must be AssociatedWith one instance of the Purehase Order dass and that an instance of the PurehaseOrder dass may be AssoeiatedWith zero or more instanees of the Invoice dass, that aninstance of the Pilot dass Flies zero or more instances of the Aircraft dass, and that aninstance of the Aircraft dass may be flown by zero or more instances of the Pilot dass.Finally, we see that an instance the SpareTire dass IsLocatedln zero or one instance of theTrunk dass, whereas an instance of the Trunk dass ean contain zero or one instance of theSpare Tire dass.There are times when a relationship itself has associated properties, especially whenits dasses share a many-to-many relationship. In these eases, a dass ealled an ssoci tioncl ss is formed, whieh has its own attributes and operations. 14 lt is shown as a reetangleattached by a dashed line to the association path, and the rectangle s name matches theIabel of the association. Think about the case of capturing information about illnesses andsymptoms. n illness (e.g., the flu) can be associated with many symptoms (e.g., sorethroat, fever), and a symptom (e.g., sore throat) can be associated with many illnesses

    14 Forthose familiar with data modeling, associative classes serve a purpose similar to the one the associative entityserves in ER diagramming.

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    10/22

    214 Chapter 5 Structural Modeling

    t S tuden t t1 o i o _cou_rse_-1 = = = P e r s o = - = - n - = - ~ _ f - 1 - . _. , C o m p a

    I U R 5 11 Sampie Association Classes

    e .g., the flu, strep throat, the common cold). Figure 5-7 shows how an association dacan capture information about remedies that change depending on the various combnations. For example, a sore throat caused by strep throat requires antibiotics, wheretreatment for a sore throat from the flu or a cold could be throat lozenges or hot teAnother way to decide when to use an association dass is when attributes that belang the intersection of the two dasses involved in the association must be captured. We cvisually think about an association dass as a Venn diagram. For example, in Figure 5-1the Grade idea is really an intersection of the Student and Course dasses, becausegrade exists only at the intersection of these two ideas. Another example shown in Fiure 5-11 is that a job may be viewed as the intersection between a Person and a Company. Most often, dasses are related through a normal association; however, there atwo special cases of an association that you will see appear quite often: generalizatioand aggregation.Generalization and ggregation ssociations A gener liz tion ssoci tion shows thone dass (subdass) inherits from another dass (superdass), meaning that the propertiand operations of the superdass are also valid for objects of the subdass. The generaization path is shown with a solid line from the subdass to the superdass and a holloarrow pointing at the superdass (see Figure 5-8). For example, Figure 5-7 communicatthat doctors, nurses, and receptionists are all kinds of employees and those employeand patients are kinds of participants. Remernher that the generalization relationshoccurs when you need to use words like "is a kind of to describe the relationship. Somadditional examples of generalization are given in Figure 5-12 . For example, Cardinala-kind-of Bird, which is a-kind-ofAnimal; a General Practitioner is a-kind-of Physiciawhich is a-kind-of Person; and a Truck is a-kind-of Land Vehide, which is a-kind-Vehide.

    An ggreg tion ssoci tion is used when dasses actually comprise other dasses. Fexample, think about a doctor's office that has decided to create health-care teams thindude doctors, nurses, and administrative personnel. As patients enter the office, they aassigned to a health-care team, which cares for their needs during their visits. We couindude this new knowledge in Figure 5-7 by adding two new dasses (Administrative Pesonne and Health Team) and aggregation relationships from the Doctor, the Nurse, an

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    11/22

    Class Diagrams 2 5

    nimal Person

    fI I r IBird Fish Physician Patientr I r I

    Cardinal Trout General Practitioner Specialist

    Vehicle

    L:l

    I lland ir Sea

    f TI I I I r lTruck ar Plane Helicopter Ship Submarine

    FIGURE 5 12 Sampie Generalizations

    the new Administrative Personnel classes to the new Health Team dass. A diamond isplaced nearest the dass representing the aggregation (health-care team), and lines aredrawn from the diamond to connect the classes that serve as its parts (doctors, nurses, andadministrative personnel). Typically, you can identify these kinds of associations when youneed to use words like is a part of or is made up of to describe the relationship. However from a UML perspective, there are two types of aggregation associations: aggregationand composition (see Figure S-8).Aggregation is used to portray logical a part of relationships and is depicted on aUML dass diagram by a hollow or white diamond. For example, in Figure 5-13, threelogical aggregations are shown. Logical implies that it is possible for a part to be associated with multiple wholes or that it is relatively simple for the part to be removed from

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    12/22

    216 hapter 5 Structural Modeling

    FIGURE 5 13Sampie AggregationAssociations

    FIGURE 5 14Sampie ompositionAssociations

    mployee 1.. lsPartOf 1 .*. ( , DepartmentV

    Wheel Vehide1.. lsPartOf 1( ; ,V

    Desk I Office ~ a ~ r t ~ ~ ~ 1 the whole. For example an instance of the Employee dass IsPartOf an instance of at leone instance of the Department dass, an instance of the Wheel dass IsPartOf an instanof the Vehide dass, and an instance of the Desk dass IsPartOf an instance of the Offdass. Obviously, in many cases an employee can be associated with more than odepartment, and it is relatively easy to remove a wheel from a vehide or move a defrom an office.Composition is used to portray a physical part of relationships and is shown by a bladiamond. hysical implies that the part can be associated with only a single whole. Fexample in Figure 5-14, three physical compositions are illustrated: an instance of a door cbe apart of only a single instance of a car an instance of a room can be apart of an instanonly of a single building; and an instance of a button can be a part of only a single mouHowever, in many cases, the distinction that you can achieve by induding aggregati(white diamonds) and composition (black diamonds) in a dass diagram mighnrot beworthe price of adding additional graphical notation for the dient to learn. Therefore, maUML experts view the indusion of aggregation and composition notation to the UML dadiagram as simply syntactic sugar and not necessary because the same information calways be portrayed by simply using the association syntax.

    Door 1 . lsPartOf 1 11 Car 1

    Room uilding1.. lsPartOf 1

    autton 1 . lsPartOf 1 ~ I M o u s e 1

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    13/22

    Class Diagrams 2 7

    Simplifying lass DiagramsWhen a dass diagram is fully populated with all the classes and relationships for a realworld system, the dass diagram can become very difficult to interpret i.e., can be verycomplex). When this occurs, it is sometimes necessary to simplify the diagram. One way tosimplify the dass diagram is to show only concrete dasses. 15 However, depending on thenumber of associations that are connected to abstract dasses and thus inherited down tothe concrete dasses this particular suggestion could make the diagram more difficult tocomprehend.

    A second way to simplify the dass diagram is through the use of a view mechanism.Views were developed originally with relational database management systems and aresimply a subset of the information contained in the database. In this case, the view wouldbe a useful subset of the dass diagram, such as a use-case view that shows only the classesand relationships relevant to a particular use case. A second view could be to show only aparticular type of relationship: aggregation, association, or generalization. A third type ofview is to restriet the information shown with each dass, for example, show only the nameof the dass, the name and attributes, or the name and operations. These view mechanismscan be combined to further simplify the diagram.

    A third approach to simplifying a dass diagram is through the use of packages i.e.,logical groups of dasses). To make the diagrams easier to read and keep the models at areasonable level of complexity, the dasses can be grouped together into packages. Packages are general constructs that can be applied to any of the elements in UML models. InChapter 4, we introduced the package idea to simplify use-case diagrams. In the case ofdass diagrams, it is simple to sort the dasses into groups based on the relationships thatthey share. 16Object DiagramsAlthough dass diagrams are necessary to document the structure of the dasses, there aretimes when a second type of static structure diagram called an object diagram, can be useful. An object diagram is essentially an instantiation of all or part of a dass diagram.Instantiation means to create an instance of the dass with a set of appropriate attributevalues.Object diagrams can be very useful when trying to uncover details of a dass. Generallyspeaking, it is easier tothink in terms of concrete objects instances) rather than abstractions of objects dasses). For example in Figure 5-15, a portion of the dass diagram in Figure 5-7 has been copied and instantiated. The top part of the figure simply is a copy of asmall view of the overalldass diagram. The lower portion is the object diagram that instantiates that subset of dasses. By reviewing the actual instances involved, John Doe, Apptl,Symptoml, and Dr Smith, we may discover additional relevant attributes, relationships,and/or operations or possibly misplaced attributes, relationships, and/or operations. Forexample, an appointment has a reason attribute. Upon doser examination, the reasonattribute might have been better modeled as an association with the Symptom dass. Currently, the Symptom dass is associated with the Patient dass. After reviewing the object diagram, this seems to be in error. Therefore, we should modify the dass diagram to reflectthis new understanding of the problem.

    5 See footnote 1.16 For those familiar with structured analysis and design, packages serve a purpose similar to the leveling and balancing processes used in data flow diagramming. Packages and package diagrams are described in more detail inChapter 7

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    14/22

    218 hapter 5 Structural Modeling

    Participant-Iastname-firstname-address-phone-birthdate-Iage II

    Patient-amount schedules-insurance carrier+make appointment() 1 . 1 0 .*+calculate last visit)+change status )+provide medical history) 1..1 Appointment

    0 .* 0 .* -time assignedTo *.* 1..-date+primary -reasoninsurance +cancel without notice )ca rrier

    suffers Symptom1..* -name

    John Doe: Patient Apptl: AppointmentIastname = Doe _ t ime 3:00firstname = )ohn date = 71712 12address = 1 000 Main St reason = Pain in Neckphone = 555-55 5-5555birthdate = 01/01/72age = 40 11 Symptoml: Symptomamount = 0.00insurance carrier = JD Health Ins name = Museie Pain

    FICURE 5 15 Sampie Object Diagram

    CRE TING STRUCTUR L MODELS USING CRC C RDSND CL SS DI GR MS

    _

    Doctor

    Dr Smith: DoctorIastname = Smithfirstname = )aneaddress = Doctors Clinphone = 999-999-9999birthdate : 12112/64

    age = 48

    Creating a structural model is an incremental and iterative process whereby the anamakes a rough cut of the model and then refines it over time. Structural models become quite complex in fact there are systems that have dass diagrams containhundreds of dasses. lt is important to remernher that R cards and dass diagrams be used to describe both the as-is and to-be structural models of the evolving system they are most often used for the to-be model. There are many different ways to identiset of candidate objects and to create CRC cards and dass diagrams. Today most ob

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    15/22

    1 Create CRCCards

    2 Review CRCCards

    3. Role Piay the CRCCards

    4 Create ClassDiagram

    Creating Structural Models Using CRC Cards and Class Diagrams 219

    identification begins with the use cases identified for the problern See Chapter 4 . In thissection, we describe a use-case-driven process that can be used to create the structuralmodel of a problern domain.We could begin creating the structural model with a dass diagram instead of CRC cards.However, owing to the low-tech nature and the ease of role-playing use-case seenarios withCRC cards, we prefer to create the CRC cards first and then transfer the information fromthe CRC cards into a dass diagram later. As a result, the first step of our recommendedprocess is to create CRC cards. Performing textual analysis on the use-case descriptionsdoes this. f you recall, the normal flow of events, subflows, and alternative/exceptional flows of the use-case description were written in a special form called Subject- Verb-Direct-Object-Preposition-Indirect object SVDP[). By writing the use-caseevents in this form, it is easier to use the guidelines for textual analysis in Figure 5 l to identify the objects. Reviewing the primary actors, stakeholders and interests, and brief descriptions of each use case allows additional candidate objects to be identified. It is useful to goback and review the original requirements to look for information that was not includedin the text of the use cases. Record all the uncovered information for each candidate objecton a CRC card.The second step is to review the CRC cards to determine if additional candidate objects,attributes, operations, and relationships are missing. In co njunction with this review, usingthe brainstorming and common object list approaches described earlier can aid the teamin identifying missing classes, attributes, operations, and relationships. For example, theteam could start a brainstorming session with a set of questions such as:

    What are the tangible things associated with the problem? What are the roles played by the people in the problern domain? What incidents and interactionstake place in the problern domain?

    As you can readily see, by beginning with the use-case descriptions, many of these questionsalready have partial answers. For example, the primary actors and Stakeholders are the rolesthat are played by the people in the problern domain. However, it is possible to uncover additional roles not thought of previously. This obviously would cause the use-case descriptions,and possibly the use-case diagram, to be modified and possibly expanded. As in the previousstep, be sure to record ll the uncovered information onto the CRC cards. This indudes anymodifications uncovered for any previously identified candidate objects and any informationregarding any new candidate objects identified.The third step is to role-play each use-case scenario using the CRC cards. Each CRC cardshould be assigned to an individual, who will perform the operations for the dass on theCRC card. As the performers play out their roles, the system tends to break down. Whenthis occurs, additional objects, attributes, operations, or relationships will be identified.Again, as in the previous steps, any time any new information is discovered, new CRC cardsare created or modifications to existing CRC cards are made.The fourth step is to create the dass diagram based on the CRC cards. Information contained on the CRC cards is simply transferred to the dass diagrams. The responsibilities aretransferred as operations, the attributes are drawn as attributes, and the relationships aredrawn as generalization, aggregation, or association relationships. However, the dassdiagram also requires that the visibility of the attributes and operations be known. As ageneral rule, attributes are private and operations are public. Therefore, unless the analyst

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    16/22

    220 Chapter 5 Structural Modeling

    5 Review ClassDiagram

    6. lncorporatePatterns

    7. Review theModel

    has a good reason to change the default visibility of these properties, then the defashould be accepted. Finally, the analyst should examine the model for additional oppornities to use aggregation or generalization relationships. These types of relationshipssimplify the individual dass descriptions. As in the previous steps, all changes mustrecorded on the CRC cards.The fifth step is to review the structural model for missing and/or unnecessary dassattributes, operations, and relationships. Up until this step, the focus of the process been on adding information to the evolving model. At this point, the focus begins to swifrom simply adding information to also challenging the reasons for induding the infmation contained in the model. One very useful approach here is to play devil s advocwhere a team member, just for the sake of being a pain in the neck, challenges the reasing for induding all aspects of the model.The sixth step is to incorporate useful patterns into the evolving structural model. A uful pattern is one that would allow the analyst to more fully describe the underlydomain of the problern being investigated. Looking at the collection of patterns availa(Figure 5-5) and comparing the dasses contained in the patterns with thosethe evolving dass diagram does this. After identifying the useful patterns, the analyst incporates the identified patterns into the dass diagram and modifies the affected CRC carThis indudes adding and removing dasses, attributes, operations, and/or relationships.The seventh and final step is to validate the structural model, induding both the CRC caand the dass diagram. We discuss this content in the next section of the chapter andChapter 7.ExampleThe first step is to create the CRC cards that represent the dasses in the structural modIn the previous chapter, we used the Library Book Collection Management System exaple to describe the process of creating the functional models (use-case and activity dgrams and use-case descriptions). In this chapter, we follow the same familiar exampBecause we are following a use-case-driven approach to object-oriented systems develoment, we first review the events described in the use-case descriptions (see Figure 5-16

    Normal Flow of Events:1. The Borrower brings books to the Librarian at the checkout desk.2. The Borrower provides Librarian their ID card.3. The Librarian checks the validity of the ID Card.

    If the Borrower is a Student Borrower, Validate ID Card against Registrar s Database.If lhe Borrower is a Faculty/Staff Borrower,Validale ID Card against Personnel Dalabase.If the Borrower is a Guest Borrower,Validale ID Card againsl Librarys Guest Database.

    4. The Librarian checks whether the Borrower has any overdue books and or fines.5. The Borrower checks out the books.

    SubFiows:Alternate/Exceptional Flows:

    4a. The ID Card is invalid, the book request is rejected.Sa. The Borrower either has overdue books fines, or both, the book request is rejected.

    FIGURE 5 16 Flow Descriptions for the Borrow Books Use Case Figure 4-14)

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    17/22

    Creating Structural Models Using CRC Cards and Class Diagrams 22

    Use Case Name: Borrow Books ID: 2 lmportance Level: HighPrimary Actor: Borrower l Use Case Type: Detail, EssentialStakeholdersand lnterests:Borrowe wants to check out booksLibrarian wants to ensure borrower only gets books deservedBrief Description: This use case describes how books are checked out ofthe library.Trigger: Borrower brings books to checkout desk.Type: External

    Relationships:Association: Borrower, Personnel Office, Registrar's Officelnclude:Extend:I Generalization: ----.1

    FIGURE 5 17 Overview Description for the orrow Books Use Case Figure 4-13

    Next, we perform textual analysis on the events by applying the textual analysisrules described in Figure 5-1. In this case, we can quickly identify the need to includeclasses for Borrower, Books, Librarian, Checkout Desk, ID Card, Student Borrower,Faculty/Staff Borrower, Guest Borrower, Registrar's Database, Personnel Database,Library's Guest Database, Overdue Books, Fines, Book Request. We also can easily identify provide operations to check the validity of a book request, to check out thebooks, and to reject a book request. Furthermore, the events suggest a brings relationship between Borrower and Books and a provides relationship between Borrowerand Librarian. This step also suggests that we should review the overview section of theuse-case description (see Figure 5-17). In this case, the only additional informationgleaned from the use-case description is the possible inclusion of classes for PersonnelOffice and Registrar's Office. This same process would also be completed for theremaining use cases contained in the functional model: Process Overdue Books, Maintain Book Collection, Search Collection, andReturn Books (see Figure 4-5). Because wedid discuss these use cases in the previous chapter, we will review the problern description as a basis for beginning the next step (see Figure 5-18) .The second step is to review the CRC cards to determine if there is any informationmissing. In the case of the library system, because we only used the Borrow Books usecase description, some information is obviously missing. By reviewing Figure 5-18, wesee that we need to include the ability to search the book collection by title, author, keywords, and ISBN. This obviously implies a Book Collection dass with four differentsearch operations: Search By Title, Search By Author, Search By Keywords, and SearchBy ISBN. Interestingly, the description also implies either a set of subclasses or states forthe Book dass: Checked Out, Overdue, Requested, Available, and Damaged. We willreturn to the issue of states versus subclasses in the next chapter. The descriptionimplies many additional operations including Returning Books, Requesting Books,

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    18/22

    Chapter 5 Structural Modeling

    FIGURE 5 18Overview Descriptionof the Library BookCollection ManagementSystem

    The functional requirements for an automated university library circulation system include the needto support searching, borrowing, and book-maintenance activities. he system should supportsearching by title, author, keywords, and ISBN. Searching the library s collection database should bavailable on terminals in the library and available to potential borrowers via the World Wide Web.lf the book of interest is currently checked out, a valid borrower should be allowed torequest thebook tobe returned. Once the book has been checked back in, the borrower requesting the bookshould be notified of the book s availability.

    The borrowing activities are built around checking books out and returning books byborrowers. There are three types of borrowers: students, faculty and staff, and guests. Regardlessof the type of borrower, the borrower must have a valid ID card. lf the borrower is a student,having the system check with the registrar s student database validates the ID card. lf theborrower is a faculty or staff member, having the system check with the personnel office semployee database validates the ID card. lf the borrower is a guest, the ID card is checkedagainst the library s own borrower database. lf the ID card is valid, the system must also checkto determine whether the borrower has any overdue books or unpaid fines. lf the ID card isinvalid, or if the borrower has overdue books or unpaid fines, the system must reject theborrower s request to check out a book; otherwise, the borrower s request should be honored.lf a book is checked out, the system must update the library s collection database to reflect thebook s new status.

    The book-maintenance activities deal with adding and removing books from the library sbook collection. This requires a library manager to both logically and physically add and removthe book. Books being purchased by the library or books being returned in a damaged statetypically cause these activities. lf a book is determined to be damaged when it is returned and ineeds to be removed from the collection the last borrower will be assessed a fine. However, ifthe book can be repaired, depending on the cost of the repair, the borrower might not beassessed a fine. Finally, every Monday, the library sends reminderemails to borrowers who haveoverdue books. lf a book is overdue more than two weeks, the borrower is assessed a fine.Depending on how long the book remains overdue, the borrower can be assessed additionalfines every Monday.

    Adding Books, Removing Books, Repairing Books, Fining Borrowers, and EmailiReminders.Next, we should use our own library experience to brainstorm potential additionclasses, attributes, operations, and relationships that could be useful to include in t

    Library Book Collection Management System. n our library, there is also the need Retrieve Books From Storage, Move Books To Storage, Request Books from the Interbrary Loan System, Return Books to the Interlibrary Loan System, and deal wiE-Books. You also could include classes for Journals, DVDs, and other media. s you csee, with very little information, many classes, attributes, operations, and relationshican be identified.

    The third step, role-playing the CRC cards, requires us to apply the three role-playisteps described earlier:

    Review Use Cases Identify Relevant Actors and Objects Role Play Scenarios

    For our purposes, we will use the Borrow Books use case to demonstrate. The relevaactors include Student Borrowers, Faculty/Staff Borrowers, Guest Borrowers, Libraans, Personnel Office, and Registrar s Office. These can be easily gleaned from toverview section of the use-case description (see Figure 5-17) and the use-case diagra(see Figure 4-5). The relevant objects seem to include Books, Borrower, and ID Car

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    19/22

    Creating Structural Models Using R Cards and Class Diagrams 3

    Finally, to role-play the scenarios, we need to assign the roles to the different membersof the team and try to perform each of the paths through the events of the use case (seeFigure 5-16). Basedon the Events of the use case nd the use case's activity diagram (seeFigure 5-19.), we can quickly identify nine scenarios, three fore chtype of Borrower(Student, Faculty/Staff, and Guest): Valid ID and No Overdue Books No Fines, Valid IDonly, and no Valid ID. When role-playing these scenarios, one question should come up.What happens to the books that are requested when the request is rejected? Based on thecurrent functional and structural models, the books are left sitting on the checkout desk.That doesn't quite seem right. In reality, the books are reshelved. In fact, the notion ofreshelving books is also relevant to when books are checked back in or after books havebeen repaired. Furthermore, the idea of adding books to the collection should also indudethe operation of shelving the books. s you should readily see, building structural modelswill also help uncover behavior that was omitted when building the functional models.Remember, object-oriented systems development is not only use-case-driven but also isincremental and iterative.The fourth step is to put everything together and to draw the dass diagram. Figure 5-20represents the first cut at drawing the dass diagram for the Library Book Collection Management System. The classes identified in the previous steps have been hooked up withother dasses via association, aggregation, and generalization relationships. For simplicity

    [Valid Crad]

    [No Ov erdue Books No Fines]

    FIGUR 5 19 Activity Diagram for the Borrow BooksUse Case (Figure 4-10)

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    20/22

    ook Collection Media

    ? r fID Borrower Il ook DVDl : :

    Locationr__Student Faculty/Staff Guest Fine Request 1II _:[ ook Location

    LibrarianLfI I1 J l lnterlibrary Loan Systemibrary Storage

    Student ID Fac/Staff ID Guest ID

    LfI I lIRegistrar s D Personnet D I Library D Shelf Reshelving II Checkout Desk II J I II II I

    FIGURE 5 20 First Cut Class Diagram for the Library Book Collection System

    IJournal Other Media

    Pers Off Registrar Off

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    21/22

    Creating Structural Mode ls Using CRC Cards and Class Diagrams 5

    Book ollection

    1Borrower Iook ook I Ocatlon

    0 . 0 . 0 .. 1 . 1L;:I l I l

    Student Faculty/Staff Guest lnter ary Loan System Library Storage

    ILibrarianIGURE 52 1 Second-Cut Class Diagram for the Library Book ollection System

    purposes, we only show the classes and their relationships; not their attributes operationsor even the multiplicities on the association relationships.

    The fifth step is to take a step back and carefully review what has been created. Notonly should you see if there are any missing classes, attributes, operations, and/or relationships, but you should also challenge every aspect of the current model. Specifically, arethere classes, attributes, operations, and/or relationships that should be removed from themodel? In this case there seem to be many classes on the diagram that should have beenmodeled as attributes . For example, the whole idea of IDs should have been attributes.Furthermore, because this is supposed to be a book collection management system, theinclusion of other media seems to be inappropriate. Finally, the Personnel Office and Reg-istrar s Office were actually only actors in the system, not objects. Basedon all of these deletions, a new version of the dass diagram was drawn (see Figure 5-21). This diagram ismuch simpler and easier to understand.

    The sixth step, incorporating useful patterns, enables us to take advantage of knowledge that was developed elsewhere. In this case, the pattern used in the library problernincludes too many ideas that are not relevant to the current problem. However, by lookingback to Figure 5-3, we see that one of the original patterns ( he one in the top left of thefigure) is relevant. We incorporate that pattern into the dass diagram by replacing Place byCheckout Desk, Participant by Borrower, Transaction by Check Out Trans, and Item byBook (Figure 5-22). Technically speaking, each of these replacements is simply a versionthat is customized to the problern at hand. We also then add the Transaction Line Item dassthat we had missed in the original structural model.The seventh step is to review the current state of the structural model. Needless to saytbe CRC card version and tbe dass diagram version are no Ionger in agreement with eacbother. We return to this step in tbe next section of the chapter.

  • 8/13/2019 Tegarden SystemsAnalysis.S.205 226

    22/22

    226 Chapter 5 Structural Modeling

    Checkout Desk Book Collection

    1 . 10 * 1*

    Check Out Trans Transaction Line ltem Book Book Loca1 . 1 1 .* 0..* 1 . 1 0. 1 . 1

    0 .1..1 I IBorrower lnterlibrary Loan System Library Storag

    I IStudent Faculty/Staff uestI

    Librarian

    FIGUR 5 22 Class Diagram with lncorporated Pattern for the Library Book Collection Syste

    5 1 ppointment System

    Using Figure 5 6 as a template, complete the CRC cards for the remaining identified classes in Figure 5 7 .

    5-2 Campus Housing

    /n Your Turn 4-4 , you created a set of use cases from thecampus housing service that helps students find apartments. Using the same use cases create a structural model

    least one potential derived attribute, aggregation relationship, generalization relationship, and association relationship for the model.