Use case diagrams Entities: Search entries actors use cases <<include>> Relations: association between an List entries actor and a use case Reader generalization between actors Log in generalization between <<extend>> use cases Refuse Log in dependencies between use cases Submitter Comments: OpenID Log in system boundaries 33
How to write a use case (summary) Name of use case Actors Description of Actors involved in use case Entry condition “This use case starts when…” Flow of events Free form, informal natural language Exit condition “This use case terminates when…” Exceptions Describe what happens if things go wrong Special requirements Nonfunctional requirements, constraints 34
Aspects covered in lecture Functional model Use case diagram (requirements, client’s point of view) Object model Class diagram (classes and relationship between them) Dynamic model Sequence diagram (message passing, ordered in time) State diagram (object lifecycle) + Object constraint language (OCL) 35
Noun-Verb Analysis (Abbott’s Textual Analysis) Use cases represent an external view of the system No correlation between use cases and classes inside system Do a textual analysis of problem statement Take the flow of events and find participating objects in use cases and scenarios Nouns are good candidates for classes Verbs are good candidates for operations First create Analysis Object Model During detailed design refine to implementation classes 36
Classes Name Type TarifSchedule Attributes zone2price : Table Signature getZones( ) : Enumeration Operations getPrice( Zone ) : Price A class encapsulates state (attributes) and behavior (operations) Each attribute has a type Each operation has a signature The class name is the only mandatory information 37
More on classes Valid UML class diagrams TarifSchedule TarifSchedule zone2price getZones( ) getPrice( ) Corresponding BON diagram No distinction between attributes TarifSchedule and operations getZones (uniform access principle) getPrice NONE zone2price 38
Associations Most widely used relation on class diagrams In general means that classes know about each other - their objects can send each other messages (call operations, read attributes) Special cases: Class A has an attribute of type B Class A creates instances of B Class A receives a message with argument of type B Mostly are binary, but can be N-ary Can have different adornments that express additional information Optional label works for Person Company employee employer Optional roles Optional roles 39
Association adornments (1) Name (possibly with direction) works for Person Company Multiplicity of an end – how many objects of the class take part in the relation 1-to-1 1 is capital of 1 City Country 1-to-many 3..* Polygon Point many-to-many * works for * Person Company 40
Association adornments (2) Aggregation – part-of relation between objects an object can be part of multiple objects part can be created and destroyed independently of the aggregate * Curriculum Course Composition – strong aggregation an object can only be part of a single object exists only together with the aggregate 3 TicketMachine ZoneButton 41
Association adornments (3) Role of an end: name + interface subordination chief: IChief 0..1 * Position subordinate: ISubordinate Navigability of an end – whether the objects at this end can be accessed through this association 1 1 Password Hashcode * Person Company 42
Relations in UML Dependency – changing the independent entity may dependent independent influence the dependent one Association – entities are entity1 entity2 directly connected (e.g. aggregation) Generalization – an entity is a special case of another descendant ancestor entity, they satisfy the substitution principle Implementation – an entity is an implementation implementation interface of another entity (e.g. a class and an interface) 43
Association adornments (4) Ordering of an end – whether the objects at this end are ordered Changeability of an end – whether the set of objects at this end can be changed after creation Qualifier of an end – is an attribute that allows retrieving one object from the set at this end 3..* Polygon Point {frozen, ordered} {ordered} * lists 1 StockExchange tickerSymbol Company tickerSymbol 44
Generalization and specialization Generalization expresses a kind- of (“is-a”) relationship Superclass Generalization is implemented by Polygon inheritance The child classes inherit Subclass the attributes and operations of the parent class Rectangle Generalization simplifies the model by eliminating redundancy 45
Stereotypes and conventions UML provides stereotypes to attach extra classifications <<Entity>> <<Boundary>> <<Control>> Account Terminal Withdrawal Naming conventions help to distinguish kinds of objects (stereotypes lost during code generation) <<Entity>> <<Boundary>> <<Control>> Account Terminal_Boundary Withdrawal_Control 46
UML packages A package is a UML mechanism for organizing elements into P groups Usually not an application domain concept <<import>> Increase readability of UML models Q <<import>> Decompose complex systems into subsystems R Each subsystem is modeled as a package 47
Avoid ravioli models * * Bank Account Customer Amount Name Name AccountId Deposit( ) Withdraw( ) GetBalance( ) Savings Account Checking Account Mortgage Account Withdraw( ) Withdraw( ) Withdraw( ) Don’t put too many classes into the same package: 7 ± 2 (or even 5 ± 2) 48
Put taxonomies on a separate diagram Account Amount AccountId Deposit( ) Withdraw( ) GetBalance( ) Savings Account Checking Account Mortgage Account Withdraw( ) Withdraw( ) Withdraw( ) 49
Class diagrams IChief ISubordinate Entities: send_petition report classes (and <<instantiate>> interfaces) Report Relations: Position association between occupy classes free Department request_report generalization send_petition between classes <<call>> implementation between a class and IPosition occupy an interface free dependencies between classes Manager 50
UML 2.0: “Chupa-chups” notation IChief ISubordinate Entities: classes (and <<instantiate>> <<realize>> interfaces) <<realize>> Report Relations: Position association between occupy classes free Department request_report generalization send_petition between classes implementation <<realize>> between a class and an interface IPosition dependencies between classes Manager 51
Aspects covered in lecture Functional model Use case diagram (requirements, client’s point of view) Object model Class diagram (classes and relationship between them) Dynamic model Sequence diagram (message passing, ordered in time) State diagram (object lifecycle) + Object constraint language (OCL) 52
Overview Object model describes structure of system Dynamic model describes behavior Purpose: Detect and supply operations (methods) for the object model We look for objects that are interacting and extract their Sequence diagrams “protocol” We look for objects that have interesting behavior on their State diagrams own 53
Sequence diagrams Actors and Entities: objects: objects (including columns instances of actors) Relations: :Terminal :Client message passing insertCard( ) Sugar: Activation s: narrow lifelines rectangles activations Lifeline: creations insertPIN( ) dashed destructions line frames Time Messages: arrows 54
Nested messages :Terminal :ClientData :Display :Client insertCard( ) check( data ) Data flow ok / nok displayMessage( text ) The source of an arrow indicates the activation which sent the message An activation is as long as all nested activations 55
Creation and destruction Creation :Terminal start( ) :Session log( ) Destruction close( ) Creation is denoted by a message arrow pointing to the object In garbage collection environments, destruction can be used to denote the end of the useful life of an object 56
From use cases to sequence diagrams Sequence diagrams are derived from flows of events of use cases An event always has a sender and a receiver Find the objects for each event Relation to object identification Objects/classes have already been identified during object modeling Additional objects are identified as a result of dynamic modeling 57
Bancomat example: Withdraw event flow Actor steps System Steps 1. Authenticate (use case Authenticate) 2. Bancomat displays options 3. Client selects “Withdraw CHF” 4. Bancomat queries amount 5. Client enters amount 6. Bancomat returns bank card 7. Bancomat outputs specified amount in CHF (ext. point: Refuse Withdrawal) 58
<<Boundary>> <<Boundary>> <<Entity>> :Terminal :Display :Account :Client select initWthdr ( wthdrCHF ) ( cur ) <<Control>> :Withdrawal queryAmount( ) select wthdr ( option ) check( amount, cur ) ( amount ) okay withdraw( amount, cur ) displayConfimation( ) ejectCard( ) taken dispense( amount, cur ) 59
<<Boundary>> <<Boundary>> <<Entity>> :Terminal :Display :Account :Client select initWthdr ( wthdrCHF ) ( cur ) <<Control>> :Withdrawal queryAmount( ) wthdr select check( amount, cur ) ( amount ) ( option ) okay withdraw( amount, cur ) displayConfimation( ) ejectCard( ) dispense( amount, cur ) taken This diagram shows only the successful case Exceptional case (Refuse Withdrawal) could go either on another diagram or could be incorporated to this one Sequence diagrams show main scenario and “interesting” cases interesting: exceptional or important variant behavior Need not draw diagram for every possible case would lead to too many diagrams 60
Interaction frames :Container :Processor :Item loop process() [for each item] alt increase() [value < 100] [else] decrease() 61
Recommended layout of sequence diagrams 1st column: Actor who 2nd column: initiated the Boundary object use case <<Boundary>> <<Entity>> <<Boundary>> :Terminal :Account :Display :Client <<Control>> :Withdrawal 3rd column: Control object that manages the rest of the use case 62
Fork structure <<Control>> The dynamic behavior is placed in a single object , usually a control object It knows all the other objects and often uses them for direct queries and commands 63
Stair structure The dynamic behavior is distributed Each object delegates some responsibility to other objects Each object knows only a few of the other objects and knows which objects can help with a specific behavior 64
Fork or stair? Object-oriented supporters claim that the stair structure is better The more the responsibility is spread out, the better Choose the stair (decentralized control) if The operations have a strong connection The operations will always be performed in the same order Choose the fork (centralized control) if The operations can change order New operations are expected to be added as a result of new requirements 65
Interaction of the models: Modeling process Functional view Modeling usage Structural view Behavioral view Modeling Modeling structure behavior 66
Example: modeling the ATM Modeling usage: use case diagram Refuse <<extend>> Withdrawal Withdraw <<include>> Load <<include>> Authenticate Cash Card Client <<include>> Transfer 67
Use case example: Withdraw Initiating actor: Client Entry condition Client has opened a bank account with the bank and Client has received a bank card and PIN Exit condition Client has the requested cash or Client receives an explanation from the ATM about why the cash could not be dispensed 68
Withdraw event flow revisited Actor steps System Steps 1. Authenticate (use case Authenticate) 2. ATM displays options 3. Client selects “Withdraw CHF” 4. ATM queries amount 5. Client enters amount 6. ATM returns bank card 7. ATM outputs specified amount in CHF (ext. point: Refuse Withdrawal) 69
From use cases to sequence diagrams :Terminal :Display :Account :Client select initWithdraw (withdraw (cur) CHF) :Withdrawal queryAmount( ) select withdraw (option) check(amount, cur) (amount) okay withdraw (amount, cur) displayConfimation( ) ejectCard( ) taken dispense(amount, cur) 70
... and further to class diagrams Add a class for each object on the diagram For each object that receives an event add a public operation in the associated class :Account Account check (amount, cur) okay check ( int , Currency): boolean withdraw ( int , Currency) withdraw (amount, cur) Identify additional classes (e.g. for message arguments, messages with no receivers) Problem text analysis may help (nouns may correspond to classes, verbs – to operations) 71
Aspects covered in lecture Functional model Use case diagram (requirements, client’s point of view) Object model Class diagram (classes and relationship between them) Dynamic model Sequence diagram (message passing, ordered in time) State diagram (object lifecycle) + Object constraint language (OCL) 72
State-dependent behavior Objects with extended lifespan often have state- dependent behavior Typical for control objects Less often for entity objects Almost never for boundary objects Examples Withdrawal: has state-dependent behavior Account : has state-dependent behavior (e.g., locked) Display : does not have state-dependent behavior State-dependent behavior is modeled only if necessary 73
Events, actions, and activities Event : Something that happens at a point in time Typical event: Receipt of a message Other events: Change event for a condition, time event Action : Operation in response to an event Example: Object performs a computation upon receipt of a message Activity : Operation performed as long as object is in some state Example: Object performs a computation without external trigger 74
State diagrams Entities: states: name, activity, entry/exit action Relations: transitions between states: event, condition, action State 1 State 2 event (arg) [ condition ] / action do / activity do / activity entry / action entry / action exit / action exit / action Transitions: End States: arrows Start marker rounded marker rectangles 75
State diagrams: example 1 Copy Book 1..* borrow borrow return return Copy return( ) On loan On shelf borrow( ) entry / book.borrow( ) entry / book.return( ) return( ) Book return( ) Not Borrowable borrow( ) [ last copy ] borrowable borrow( ) [ not last copy ] 76
Example 2: ticket vending machine CollectMoney insCoin( amount ) / add to balance [ change < 0 ] TicketSelected selectTicket( tkt ) Idle entry / compute change entry/clearbalance [ change = 0 ] [ change > 0 ] ExactlyPaid [ change OverPaid [ ticket dispensed ] do / dispense ticket dispensed ] do / dispense change 77
State An abstraction of the attribute values of an object A state is an equivalence class of all those attribute values and links that do not need to be distinguished as far as the control structure of the class or the system is concerned Example: State of a book A book is either borrowable or not Omissions: bibliographic data All borrowable books are in the same equivalence class, independent of their author, title, etc. 78
Composite/nested state diagrams Activities in states can be composite items that denote other state diagrams Sets of substates in a nested state diagram can be denoted with a superstate Avoid spaghetti models Reduce the number of lines in a state diagram 79
State diagrams: example composite state TrafficLight On TurnOn Blinking Off SwitchOff Working SwitchOn after 30 sec after 3 sec Red TurnOff Yellow Red Green Yellow Green after 5 sec after 45 sec 80
Example: superstate CollectMoney insCoin( amount ) / add to balance [ change < 0 ] TicketSelected selectTicket( tkt ) Idle entry / compute change entry / clear balance [ change = 0 ] [ change > 0 ] ExactlyPaid [ change OverPaid [ ticket dispensed ] do / dispense ticket dispensed ] do / dispense change Superstate 81
Expanding the superstate Dispense as atomic activity [ change = 0 ] Dispense as ExactlyPaid [ change [ ticket composite do / dispense ticket dispensed ] dispensed ] activity do / issue ticket do / print ticket do / store coins Transitions from other states to the superstate enter the first substate of the superstate Transitions to other states from a superstate are inherited by all the substates (state inheritance) 82
State diagram vs. sequence diagram State diagrams help to identify Changes to an individual object over time Sequence diagrams help to identify The temporal relationship between objects Sequence of operations as a response to one or more events 83
Practical tips Create component and deployment diagrams only for large, distributed systems Create state diagrams only for classes with complex, interesting behavior (usually classes representing entities from the problem domain or performing control) Create activity diagrams for complex algorithms and business processes (not for every operation) Create sequence and communication diagrams for nontrivial collaborations and protocols (not for every scenario) Don’t put too much information on a diagram Choose the level of abstraction and maintain it 84
Entities in UML Structural Class – a description of a set of object with common attributes and operations Interface – a set of operations (a service), provided by a class or component Actor – an external entity that interacts with the system Use case – a description of a set of scenarios (sequences of events and actions) that produce a result, significant for some actor Component – physically replaceable artifact that provides a certain set of interfaces Node – a hardware resource 85
Entities in UML Behavioral State – a period in an object lifecycle, during which the object is satisfying some property, performing an activity or waiting for an event Activity – a state, in which the object is doing some work (instead of just passively waiting for an event) Grouping Package – a group of model elements (maybe including other packages) Annotating Note – arbitrary text comment attached to a model 86
Relations in UML Dependency – changing the independent entity may dependent independent influence the dependent one Association – entities are entity1 entity2 directly connected (e.g. aggregation) Generalization – an entity is a special case of another descendant ancestor entity, they satisfy the substitution principle Implementation – an entity is an implementation implementation interface of another entity (e.g. a class and an interface) 87
Aspects covered in lecture Functional model Use case diagram (requirements, client’s point of view) Object model Class diagram (classes and relationship between them) Dynamic model Sequence diagram (message passing, ordered in time) State diagram (object lifecycle) + Object constraint language (OCL) 88
UML is not Enough spouse spouse Person Urs: Person 0..1 Marry( ) “is married to” spouse Beat: Person Sile: Person Urs is married to Sile, Sile is married to Beat, and Beat is not married at all A valid instantiation of the class diagram! Associations describe relations between classes 89
UML is not Enough (cont’d) spouse spouse Person Urs: Person 0..1 age age = 18 Married persons are spouse Sile: Person at least 16 years old age = 11 Urs is married to Sile, who is only eleven A valid instantiation of the class diagram! Class diagrams do not restrict values of attributes 90
Expressing Contracts Natural language spouse expresses Advantage: Easy to “is married to” understand and use spouse: Person → Person Disadvantage: spouse = spouse –1 Ambiguous spouse ∩ id = ∅ Mathematical notation ∀ p: Person: p ∈ dom ( spouse ) ⇒ Advantage: Precise spouse( p ) ∈ dom ( spouse ) ∧ Disadvantage: Difficult p ≠ spouse( p ) ∧ for normal customers p = spouse( spouse( p ) ) Contract language spouse /= Void implies Formal, but easy to use spouse /= Current and spouse.spouse = Current Examples: Eiffel, JML 91
Object Constraint Language – OCL The contract language for UML Used to specify Invariants of objects Pre- and postconditions of operations Guards (for instance, in state diagrams) Special support for Navigation through UML class diagram Associations with multiplicities 92
Form of OCL Invariants Constraints can mention The context is self : the contextual an instance of Declares an a class in the instance invariant UML diagram Attribute and role names context Person inv : Side-effect free self .age >= 0 methods (stereotype <<query>>) Logical connectives A boolean constraint Operations on integers, reals, strings, sets, bags, sequences Etc. 93
OCL Invariants: Example owner * Account Customer amount age Role name SavingsAccount CheckingAccount A savings account has a non- context SavingsAccount inv : negative balance self .amount >= 0 Checking accounts are context CheckingAccount inv : owned by adults self .owner.age >= 18 94
OCL Invariants: Contexts owner * Account Customer amount age SavingsAccount CheckingAccount context CheckingAccount inv : Checking accounts are owned by adults self .owner.age >= 18 context Account inv : Accounts are owned by self .owner.age >= 18 adults context Customer inv : Customers are adults self .age >= 18 95
Collections OCL provides three predefined collection types Set, Sequence, Bag Common operations on collections size( ) Number of elements in the collection includes( object ) True iff the object is an element isEmpty( ) True iff collection contains no elements True iff expression is true for at least one exists( expression ) element forAll( expression ) True iff expression is true for all elements 96
Generating Collections Explicitly enumerating the elements Set { 1, 7, 16 } By navigating along 1:n associations Navigation along a single 1:n self .accounts association yields a Set Navigation along a single 1:n association labeled with the constraint { ordered } yields a Sequence { ordered } * Account Customer accounts amount age 97
Example: Multiplicity Zero or One spouse Person 0..1 age self can be spouse used omitted as set context Person inv : spouse->size( ) = 1 implies age >= 16 and spouse.spouse = self and spouse <> self spouse used as object 98
Example: Quantification and Type Information owner * Account Customer accounts amount age SavingsAccount CheckingAccount Subtype relation context Customer inv : age <= 18 implies accounts->forAll( a | a.oclIsKindOf( SavingsAccount ) ) ∀ a ∈ accounts: a.oclIsKindOf( Savingsaccount ) 99
Example: Composite Pattern * Component children 0..1 Leaf Composite parent A composite is the context Composite inv : parent of its children->forAll( c | c.parent = self ) components A component is context Component inv : contained in its parent parent->size( ) = 1 implies composite parent.children->includes( self ) 100
Recommend
More recommend