Design And UML Class Diagrams Suggested Reading

Transcription

Design and UML Class DiagramsSuggested reading:Practical UML: A hands on introduction for developershttp://dn.codegear.com/article/31863UML Distilled Ch. 3, by M. Fowler1

Big questions What is UML? Wh shouldWhyh ld I bother?b th ? DoD peoplel reallyll use UML?What is a UML class diagram? What kind of information goes into it?How do I create it?When should I create it?2

Design phase design: specifying the structure of how asoftware system will be written and function,functionwithout actually writing the completeimplementationa transition from "what" the system must do,t "how"to"h " ththe systemtwillill dod it What classes will we need to implement a systemthat meets our requirements?qWhat fields and methods will each class have?How will the classes interact with each other?3

How do we design classes? class identification from project spec / requirements nouns are ppotential classes,, objects,j, fieldsverbs are potential methods or responsibilities of a classCRC card exercises write down classes' names on index cardsnext to each class, list the following: responsibilities: problems to be solved; short verb phrasescollaborators: other classes that are sent messages by this class(asymmetric)UML diagrams class diagrams (today)sequence diagrams.4

UMLIn an effort to promote Object Oriented designs, three leadingobject oriented programming researchers joined ranks tocombine their languages: Grady Booch (BOOCH)Jim Rumbaugh (OML: object modeling technique)Ivara JacobseJacobsen (OOS(OOSE: object oorientede ted sosoftwaret aeeeng)g)and come up with an industry standard [mid 1990’s].

UML – UUUnifieded Modelingode g Languagea guage The result is large (as one might expect) Union of all Modeling Languages Use case diagramsClass diagramsObject diagramsSequence diagramsCollaboration diagramsStatechart diagramsgActivity diagramsComponent diagramsDeployment diagrams .But it’s a nice standard that has been embracedby the industry.industry

Introduction to UML UML: pictures of an OO system programming languages are not abstract enough for OO designUML is an open standard; lots of companies use itWhat is legal UML? a descriptive language: rigid formal syntax (like programming)a prescriptive language: shaped by usage and conventionit's okay to omit things from UML diagrams if they aren'tneeded by team/supervisor/instructor7

Uses for UML as a sketch: to communicate aspects of system as a blueprint: a complete design to be implemented forward design: doing UML before codingbackward design: doing UML after coding as documentationoften done on whiteboard or paperusedd to get roughh selectiveliideasidsometimes done with CASE (Computer-Aided SoftwareEngineering) toolsas a programming language: with the right tools, codecan be autoauto-generatedgenerated and executed from UML only good if this is faster than coding in a "real" language8

UML class diagrams What is a UML class diagram? UML classldiagram:dia pictureioff the classes in an OO system their fields and methods connections between the classes that interact or inherit from each otherWhat are some things that are not represented in aUML class diagram? details of how the classes interact with each otheralgorithmic details; how a particular behavior ispimplemented9

Diagram of one class class name in top of box attributes (optional) write interface on topp of interfaces' namesuse italics for an abstract class nameshould include all fields of the objectoperations / methods (optional) may omit trivial (get/set) methods but don't omit any methods from an interface!should not include inherited methods10

Class attributes attributes (fields, instance variables) visibilityy name : typeyp [[count]] default value visibility: public# protectedprivate package (default)/derivedunderline static attributesderived attribute: not stored, but canbe computed from other attribute valuesattribute example:- balance : double 0.0011

Class operations / methods operations / methods visibilityy name (p(parameters)) : return typeyp visibility: public# protectedprivate package (default)underline static methodsparametert typestlistedli t d as (name:(type)t)omit return type on constructors andwhen return type is voidmethod example: distance(p1: Point, p2: Point): double12

Comments represented as a folded note, attached to theappropriate class/method/etc by a dashed line13

Relationships btwn. classes generalization: an inheritance relationship inheritance between classesinterface implementationassociation: a usage relationship dependencyaggregationcomposition14

Generalization relationships generalization (inheritance) relationships hierarchies drawn top-downpwith arrowspointing upward to parentline/arrow styles differ, based on whetherparent is a(n): class:solid line, black arrow abstract class:solid line,line white arrow interface:dashed line, white arrowwe often don't draw trivial / obviousgeneralization relationships, such asdrawing the Object class as a parent15

Associational relationships associational (usage) relationships1 multiplicity1. *12.43.* (how many are used)0, 1, or more1 exactlybetween 2 and 4,, inclusive3 or more2. name3. navigability(what relationship the objects have)(direction)16

Multiplicity of associations one-to-one each student must carry exactly one ID cardone-to-manyy one rectangle list can contain many rectangles17

CarAssociation types1 aggregation: "is part of" symbolizedybyy a clear white diamond strongertversionioff aggregationtithe parts live and die with the wholesymbolized by a black diamondBookcomposition1*Pagedependency: "uses temporarily" symbolized by dotted lineoften is an implementationdetail, not an intrinsic part ofthat object's stateaggregationEnginecomposition: "is entirely made of" 1dependencyLotteryTicketRandom18

Composition/aggregationCopos t o /agg egat o eexamplea peIf the movie theatre goes awayso does the box office compositionbut movies may still exist aggregation

Class diagram exampleNo arrows; info canflow in both directionsAggregation –Order classcontainsOrderDetailclasses.lCouldC ldbe composition?

UML example: peopleL t’ addLet’sdd ththe visibilityi ibilit attributestt ib tCSE 403,Spring 2008,Alverson

Class diagram: voters22

Class diagram example:video ntal InvoiceAbstractClassRental ionCheckout ScreenDVD MovieVHS MovieVideo Game23

Class diagram example: studentStudentBody main (args : String[])Address1100Student- firstNamefi tN: StringSt i- lastName : String- homeAddress : Address- schoolAddress : Address toString() : String- streetAddress : String- city : String- state : String- zipCode : long toString() : String24

Tools for creating UML diags. Violet (free) Rational Rose http://horstmann rational.com/Visual Paradigm UML Suite (trial) http://www.visual-paradigm.com/(nearly) direct download link:http://www visual paradigm com/vp/download jsp?product vpuml&edition roduct vpuml&edition ce(there are many others, but most are commercial)25

Class design exercise Consider this Texas Hold 'em poker game system: 2 to 8 human or computerppplayersyEach player has a name and stack of chipsComputer players have a difficulty setting: easy, medium, hardSummary of each hand: Dealer collects ante from appropriate players, shuffles the deck,and deals each player a hand of 2 cards from the deck.A betting round occurs, followed by dealing 3 shared cards fromth deck.thed kAs shared cards are dealt, more betting rounds occur, where eachplayer can fold, check, or raise.At the end of a round, if more than one player is remaining,players' hands are compared, and the best hand wins the pot of allchips bet so far.What classes are in this system?yWhat are theirresponsibilities? Which classes collaborate?Draw a class diagram for this system. Include relationshipsbetween classes (generalization and associational).26

27

CSE 403UML Sequence DiagramsSuggested reading:UML Distilled Ch.Ch 4,4 by MM. Fowler28

UML sequence diagrams sequence diagram: an "interaction diagram" thatmodels a single scenario executing in the system perhaps 2nd most used UML diagram (behind class diagram)relation of UML diagrams to other exercises: CRC cardsuse cases- class diagram- sequence diagrams29

Key parts of a sequence diag. participant: an object or entity that acts in thesequence diagram sequence diagram starts with an unattached "found message"arrow message: communication between participant objects the axes in a sequence diagram: horizontal: which object/participant is actingvertical: time (down - forward in time)30

Sequence dg. from use case31

Representing objects Squares with object type, optionally preceded by objectname and colon write object's name if it clarifies the diagramobject's "life line" represented by dashed vert. line32

Messages between objects message (method call) indicated by horizontalarrow to other object write message name and arguments above arrow33

Messages, continued message (method call) indicated by horizontalarrow to other object dashed arrow back indicates returndifferent arrowheads for normal / concurrent(asynchronous) methods34

Lifetime of objects creation: arrow with 'new'written above it notice that an object createdafter the start of the scenarioappears lower than theothersdeletion:dl tian X att bottomb ttoffobject's lifeline Java doesn't explicitly deleteobjects; they fall out ofscope and are garbagecollected35

Indicating method calls activation: thick box over object's life line; drawnwhen object'sobject s method is on the stack either that object is running its code, or it is on the stackwaiting for another object's method to finishnest to indicate recursionActivationNesting36

Indicating selection and loops frame: box around part of a sequence diagram to indicateselection or loop if- (opt) [condition]if/else - (alt) [condition], separated by horizontal dashed lineloop- (loop) [condition or items to loop over]37

linking sequence diagrams if one sequence diagram is too large or refers to another diagram,indicate it with either: an unfinished arrow and commenta "ref" frame that names the other diagramwhen would this occur in our system?Customer InforefVerify customer creditApproved?38

Example sequence diagram39

Forms of system control What can you say about the control flow of each of thefollowingg systems?y Is it centralized?Is it distributed?40

Why not just code it? Sequence diagrams can be somewhat close to the codelevel So why not just code up that algorithm ratherlevel.than drawing it as a sequence diagram? a good sequence diagram is still a bit above the levelof the real code (not all code is drawn on diagram)sequence diagrams are language-agnostic (can beimplemented in many different languagesnon-coders can do sequence diagramseasier to do sequence diagrams as a teamcan see many objects/classes at a time on samepage (visual bandwidth)41

Sequence diagram exercise 1 Let's do a sequence diagram for the following casualuse case,case Start New Poker Round :The scenario begins when the player chooses to start a newround in the UI. The UI asks whether any new players want tojoin the round; if soso, the new players are added using the UIUI.All players' hands are emptied into the deck, which is thenshuffled. The player left of the dealer supplies an ante bet ofth proper amount.thet NextN t eachh playerlisi dealtd lt a handh d off twotcards from the deck in a round-robin fashion; one card to eachplayer, then the second card.If the player left of the dealer doesn't have enough money toante, he/she is removed from the game, and the next playersupplies the ante. If that player also cannot afford the ante,this cycle continues until such a player is found or all playersare removed.42

Sequence diagram exercise 2 Let's do a sequence diagram for the following casualuse case,case Add Calendar Appointment :The scenario begins when the user chooses to add a newappointment in the UI. The UI notices which part of the calendar isactive and ppopsp upp an Add Appointmentppwindow for that date andtime.The user enters the necessary information about the appointment'sname, location, start and end times. The UI will prevent the user fromentering an appointment that has invalid information,information such as anempty name or negative duration. The calendar records the newappointment in the user's list of appointments. Any reminder selectedby the user is added to the list of reminders.If the user already has an appointment at that time, the user isshown a warning message and asked to choose an available time orreplace the previous appointment. If the user enters an appointmentwith the same name and duration as an existing group meeting,meeting thecalendar asks the user whether he/she intended to join that groupmeeting instead. If so, the user is added to that group meeting's listof participants.43

44

Consider this Texas Hold 'em poker game system: 2 to 8 human or compppyuter players Each player has a name and stack of chips Computer players have a difficulty setting: easy, medium, hard Summary of each hand: Dealer collects ante from appropriate players, shuffles the dec