Chapter 5 – Prototype and System Modeling

Chapter 5 System modeling

1

Topics covered

 Prototyping

 UML diagram types

Chapter 5 System modeling

2

Big questions

 What's the point of prototyping? Should I do it?

 Should I make my prototype on paper or digitally?

 How do I know whether my UI is good or bad?

 If so, when in the overall process or "lifecycle" should I?

 What are the ways in which a UI's "quality" can be quantified?

 What are some examples of software you use that have

especially good/bad UIs? What do you think makes them good/bad?

Usability and SW design

 Usability: The effectiveness with which users can

achieve tasks in a software environment.

 studying and improving usability is part of

Human-Computer Interaction (HCI)

 usability and good UI design are closely related

 a bad UI can have unfortunate results...

Achieving usability

 Some methods to achieve good usability:

• having users use the product and gathering data

 user testing / field studies

 evaluations and reviews by UI experts

• Show users various UI menus and ask them to group the ones that are similar, to see what UI tasks are seen as being related by users.

 card sorting

• paper prototyping

• code prototyping

 Good UI design focuses on the user, not developer or

system.

 prototyping

Prototyping

 prototyping: Creating a scaled-down or incomplete

version of a system to demonstrate or test aspects of it.

 What are some possible benefits of prototyping?

 aids UI design  help discover requirements  help discover test cases and provide a basis for testing  allows interaction with user and customer to ensure satisfaction  team-building

Some prototyping methods

 UI builders (Visual Studio, etc.)

 implementation by hand

 draw a GUI visually by dragging/dropping UI controls on screen

 paper prototyping: a paper version of a UI

 writing a "rough" version of your code

Question: Why not just code up a working code prototype?

 much faster to create than code

 can change faster than code  more visual bandwidth (can see more at once)  more conducive to working in teams

 can be done by non-technical people

Where does it fit in?

 At what point in the software lifecycle should we do

(paper) prototyping? When would it be most useful to do it? Why?

 We talk about requirements being about "what" and

design being about "how." Which is paper prototyping?

 PP helps uncover requirements and also upcoming design

issues

 do PP during or after requirements; before design  "what" vs. "how": PP shows us "what" is in the UI, but it also

shows us details of "how" the user can achieve goals in the UI

P.P. usability session

 user is given tasks to perform using paper prototype

 session can be observed by people or camera

 one developer can "play computer"

“Computer”

Facilitator

Observer(s)

User

Schneiderman's 8 Golden Rules

• Offer simple error handling. • Permit easy undo of actions. • Let the user be in control. • Reduce short-term memory

• Strive for consistency. • Give shortcuts to the user. • Offer informative feedback. • Make each interaction with

load on the user.

the user yield a result.

(from Designing the User Interface, by Ben Schneiderman of UMD, HCI/UI expert)

UI design and components

 When should we use:

 A button?

 A check box?

 A radio button?  A text field?

 A list?

 A combo box?

 A menu?

 A dialog box?  Other..?

UI design examples

Apple Mac user interfaces

UI Hall of Shame

 http://homepage.mac.com/bradster/iarchitect/shame.htm

Layout and color

Bad error messages

UI design - buttons, menus

 Use buttons for single independent actions that are

relevant to the current screen.

 Try to use button text with verb phrases such as "Save" or

"Cancel", not generic: "OK", "Yes", "No"

 use Mnemonics or Accelerators (Ctrl-S)

 tool tips are helpful, but don't rely on them

 Use toolbars for common actions.

 Use menus for infrequent actions applicable to many

screens.

(many users don't know to hover to find them)

 Users don't like menus! Try not to rely

too much on menus.Provide another way to access the same functionality (toolbar, hotkey, etc)

Checkboxes, radio buttons

 Use check boxes for independent on/off switches

(boolean)

 Use radio buttons for a small number of related

choices, when only one can be activated at a time (enum / constants)

Lists, combo boxes, etc.

 use text fields (usually with a label) when the

user may type in anything they want  you will usually have to validate the input

 use lists when there are many fixed choices (too many for radio buttons to be practical) and you want all choices visible at once

 use combo boxes when there are many

fixed choices, but you don't want to take up screen space by showing them all at once

 use a slider or spinner for a

numeric value with fixed range

An example UI

 Did the designer of this UI choose the right components?

 assume there are 30 collections and 3 ways to search

(by title, author, relevancy)

LIBSYS: Search

Choose collection:

All

Phrase:

Search by:

T itle

Adjacent words

Y es

No

Default

Cancel

OK

UI design - multiple screens

 you can use a tabbed pane when there are many

screens that the user may want to switch between at any moment

 use dialog boxes or option panes to present temporary

screens or options

 or multiple pages, if it's a web site

 users hate popup dialogs; use them

very rarely

 don't prompt for lots of user input by

• instead, put the choices on the existing

window as buttons, etc.

popping up dialogs

"Wizards"

 wizard: series of dialog boxes to progress through a task

 In the mid-1990s, Microsoft changed most of its

Windows apps to use "wizards" for installation and settings.

 Why did they do this?

 What are the pros and cons

of a "wizard" UI?

Creating a paper prototype

 gather materials

 paper, pencils/pens

 tape, scissors

 identify the screens in your UI

 highlighters, transparencies

 think about how to get from one screen to next

 consider use cases, inputs and outputs to user

 this will help choose between tabs, dialogs, etc.

Application backgrounds

 draw the app background (the parts that matter for the

prototyping) on its own, then lay the various subscreens on top

Representing a changing UI

 layers of UI can be placed on top of background as user

clicks various options

Interactive widgets

widget how to simulate it

buttons or check boxes tape

tabs and dialog boxes index cards or small papers

text fields removable tape

combo boxes

put the expanded choices on a separate paper / Post-It

selections highlighted piece of tape

a disabled widget

cut out a separate gray version that can be placed on top of the normal one

Example paper prot. screen

Example paper prototype

Prototyping exercise

 Let's draw a prototype for a music player (e.g. iTunes).

 Assume that the program lets you store, organize, and play

songs and music videos.

 Draw the main player UI and whatever widgets are required to

do a search for a song or video.

 Things to think about:

 After the prototypes are done, we'll try walking through each UI.

 How many clicks are needed? What controls to use?  Could your parents figure it out without guidance?

UML diagram types

 Activity diagrams

 Use case diagrams

 Sequence diagrams.

 Class diagrams

 State diagrams

Chapter 5 System modeling

30

Use cases

 use case: a written description of the user's interaction

with the software product to accomplish a goal

• 3-9 clearly written steps lead to a "main success scenario" • written from actor's point of view, not the system's

 benefits of doing use cases?

 interactions between an actor and the system

 helps us discover and document functional requirements

 agreement as to the system's responsibilities  provides executives a skeleton for planning project priorities

 helps provide a list of error cases to test

Use cases vs. internal features

consider the software to run a mobile phone:

Use Cases Internal Functions

• call someone • receive a call • send a message • memorize a number Point of view: user • transmit / receive data • energy (battery) • user I/O (display, keys, ...) • phone-book mgmt. Point of view: developer / designer

Use cases and requirements

 Which of these requirements would probably be represented or mentioned directly in a use case?

 Special deals may not run longer than 6 months.  Customers only become preferred after 1 year.

 A customer has one and only one sales contact.

 Database response time is less than 2 seconds.

 Answer: None!

 Web site uptime requirement is 99.8%.  Number of simultaneous users will be 200 max.

 Most of these are non-functional requirements, so the use cases

wouldn't mention them. The user doesn't see them directly.

Actors, stakeholders, goals

 What are actors and stakeholders in a use case?

 actor: anything with behavior (that "acts" on the system)

 primary actor: initiates interaction to achieve goal

 stakeholder: anyone interested in the system

 supporting actor: performs sub-goals in use case

 supplier, stock agency, vendor

 goal: action that actor wants to accomplish

 stakeholder might not "act" in any scenario

 summary (multi-sitting), user (one sitting), subfunction (partial)

Styles of use cases

1. Actor / goal list (or UML use case summary diagram)

shows all use cases in system

2.

Informal use case

3. Formal use case

Let's examine each of these in detail...

1. Actor / goal list

 Often shown as a list or table of actors and their goals,

or a diagram of actors connected to use cases:

ACTOR

USE CASES INITIATED

Club Member

Submit Promotion Order Submit Regular Order

Potential Member Submit New Subscription

Past Member

Submit Subscription Renewal

Membership Dept. Request Membership

Marketing Dept.

Create Monthly Promotion Create Seasonal Promotion Create Subscription Program Request Promotion Reports Request Sales Reports

Services System

Send Subscription Offer Send Club Promotion Send Subscription Renewal

Use case exercise

 Consider a Netflix-like video rental web system.

 A customer with an account can use their membership and credit

card in the web app to order a video for rental.

 The software can look up movies and actors by keywords.

 Exercise:

 A customer can check out up to 3 movies, for 5 days each.  Late fees can be paid at the time of return or at next checkout.

 Come up with 3-4 use case names for this software.  Identify some of the actors and stakeholders in this system.

Informal use case

 informal use case: a paragraph describing the scenario

 Example (for a Netflix-style video rental system):

 Customer Loses a Disc

The customer reports to the system that he has lost a disc. The clerk displays the customer's rental record and alerts the customer that this will incur a fee. The customer is asked to confirm the decision. After confirming the decision, the database will be updated to reflect the lost disc, and the customer's record is updated as well to remove the disc and add the fee. The inventory manager is notified of the event and may authorize purchase of a replacement disc.

Extensions

 What is an "extension"? Why are they useful?

 extension: A possible branch in a use case scenario, often triggered by an error or failure in the process.

 Useful for finding edge cases that need to be handled and

tested.

 Do: Think about how every step of the use case could fail.

 Do: Give a plausible response to each extension from the

• Response should either jump to another step of the case, or end it.

system.

 Don't: List things outside the use case ("User's power goes out").

 Don't: Make unreasonable assumptions ("DB will never fail").

 Don't: List a remedy that your system can't actually implement.

Example formal use case

Use Case 12. Buy stocks over the web

Level: user goal

Primary Actor: Purchaser (user) Precondition: User already has PAF open and is logged in. Minimal Guarantee: sufficient log information exists that PAF can detect what went

wrong.

Success Guarantees: remote web site acknowledged purchase, user's portfolio updated.

Main success scenario: 1. User selects to buy stocks over the web. 2. PAF gets name of web site to use (E*Trade, Schwabb, etc.) 3. PAF opens web connection to the site, retaining control. 4. User browses and buys stock from the web site. 5. PAF intercepts responses from the web site, and updates the user's portfolio. 6. PAF shows the user the new portfolio standing.

Extensions: 2a. User wants a web site PAF does not support:

2a1. System gets new suggestion from user, with option to cancel use case.

Cockburn's 4 use case steps

1. Identify actors and goals

 What computers, subsystems, people will drive our system?  What does each actor need our system to do?

2. Write the main success scenario

 easiest to read; everything else is a complication on this  capture each actor's intent and responsibility

3. List the failure extensions

 usually almost every step can fail (bad credit, out of stock...)  note failure condition separately, after main success scenario

4. Describe failure-handling

 recoverable: back to main course (low stock + reduce quantity)  non-recoverable: fails (out of stock, or not a valued customer)

Use case exercise

 Recall our Netflix-like video rental web system example.

 A customer with an account can use their membership and credit

card in the web app to order a video for rental.

 The software can look up movies and actors by keywords.

 Exercise:

 A customer can check out up to 3 movies, for 5 days each.  Late fees can be paid at the time of return or at next checkout.

 Write a formal use case for Customer Orders a Movie.

How do we design classes?

 class identification from project spec / requirements

 CRC card exercises

 nouns are potential classes, objects, fields  verbs are potential methods or responsibilities of a class

• responsibilities: problems to be solved; short verb phrases • collaborators: other classes that are sent messages by this class

(asymmetric)

 UML

 write down classes' names on index cards  next to each class, list the following:

 class diagrams (today)  sequence diagrams  ...

Diagram of one class

 class name in top of box

 write <> on top of interfaces' names

 use italics for an abstract class name

 attributes

 should include all fields of the object

 also includes derived "properties"

 operations / methods

• but don't omit any methods from an interface!

 may omit trivial (get/set) methods

 should not include inherited methods

Class attributes

 attributes (fields, instance variables)

 visibility name : type [count ] = defaultValue

 visibility:

+ public # protected - private ~ package (default) / derived

 underline static attributes

 derived attribute: not stored, but can

be computed from other attribute values

 attribute example:

- balance : double = 0.00

Class operations / methods

 operations / methods

 visibility name (parameters ) : returnType

 underline static methods

 parameter types listed as (name: type)

 omit returnType on constructors and

when return is void

+ distance(p1: Point, p2: Point): double

 method example:

Inheritance relationships

 hierarchies drawn top-down with arrows

pointing upward to parent

• class : • abstract class : • interface :

solid, black arrow solid, white arrow dashed, white arrow

 line/arrow styles differ based on parent:

 we often don't draw trivial / obvious

relationships, such as drawing the class Object as a parent

Associational relationships

 0, 1, or more  1 exactly

• * • 1 • 2..4  between 2 and 4, inclusive • 3..*  3 or more

1. multiplicity (how many are used)

2. name (what relationship the objects have)

3. navigability (direction)

Multiplicity

 one-to-one

 one-to-many

 each student must have exactly one ID card

 a RectangleList can contain 0, 1, 2, ... rectangles

Car

Association types

aggregation

1

Engine

 aggregation: "is part of"  clear white diamond

 composition: "is entirely made of"

Book

composition

1

 dependency: "uses temporarily"

 stronger version of aggregation  the parts live and die with the whole  black diamond 1

Page

*

 dotted line or arrow  often is an implementation

dependency

detail, not an intrinsic part of that object's state

Random

Lottery Ticket

Class design exercise

 Consider this Texas Hold 'em poker game system:

• 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 from the

deck.

• As shared cards are dealt, more betting rounds occur, where each

player 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 all chips bet.  What classes are in this system? What are their responsibilities?

 2 to 8 human or computer players  Each player has a name and stack of chips  Computer players have a difficulty setting: easy, medium, hard  Summary of each hand:

Which classes collaborate?

 Draw a class diagram for this system. Include relationships

between classes (generalization and associational).

Class diag. pros/cons

 Class diagrams are great for:

 discovering related data and attributes

 getting a quick picture of the important entities in a system

 seeing whether you have too few/many classes  seeing whether the relationships between objects are too

complex, too many in number, simple enough, etc.

 Not so great for:

 spotting dependencies between one class/object and another

 discovering algorithmic (not data-driven) behavior

 finding the flow of steps for objects to solve a given problem

 understanding the app's overall control flow (event-driven? web-

based? sequential? etc.)

Qualities of modular software  decomposable

 composable

 can be broken down into pieces

 understandable

 pieces are useful and can be combined

 has continuity

 one piece can be examined in isolation

 protected / safe

 reqs. change affects few modules

 an error affects few other modules

Heuristics 2 quick reference

 Heuristic 2.1: All data should be hidden within its class.

 Heuristic 2.2: Users of a class must be dependent on its public interface, but a class

should not be dependent on its users.

 Heuristic 2.3: Minimize the number of messages in the protocol of a class.

 Heuristic 2.4: Implement a minimal public interface that all classes understand.

 Heuristic 2.5: Do not put implementation details such as common-code private

functions into the public interface of a class.

 Heuristic 2.6: Do not clutter the public interface of a class with items that users of

that class are not able to use or are not interested in using.

 Heuristic 2.7: Classes should only exhibit nil or export coupling with other classes, that is, a class should only use operations in the public interface of another class or have nothing to do with that class.

 Heuristic 2.8: A class should capture one and only one key abstraction.

 Heuristic 2.9: Keep related data and behavior in one place.

 Heuristic 2.10: Spin off non-related behavior into another class (i.e., non-

communicating behavior).

 Heuristic 2.11: Be sure the abstractions that you model are classes and not simply

the roles objects play.

Interface/implementation

 public interface: visible data/behavior of an object

 private implementation: internal data/methods in an

object

 can be seen and executed externally

 helps implement the public interface; cannot be directly

 client: code that uses your class/subsystem

accessed

• public interface is the speaker, volume buttons, station dial • private implementation is the guts of the radio; the transistors,

capacitors, frequencies, etc. that user should not see

 Example: radio

Poker design question 1

 Poker Deck class stores a list of cards; the game needs to

be able to shuffle and draw the top card.

 We give the Deck class the following methods:

add(Card), add(index, Card), getCard(int), indexOf(Card), remove(index), shuffle(), drawTopCard(), etc.

 What's wrong with this design?  Heuristic 2.3: Minimize the # of messages in the protocol of a

class.

 Heuristic 2.5: Do not put implementation details such as common-

code private functions into the public interface of a class.

 Heuristic 2.6: Do not clutter the public interface of a class with items that users of that class are not able to use or are not interested in using.

Minimizing public interface

 Make a method private unless it needs to be public.

• example: Card object with rank and suit (get-only)

 Supply getters (not setters) for fields if you can get away with it.

• example: If PokerGame has an inner set of Players, supply just an

iterator or a getPlayerByName(String) method

 In a class that stores a data structure, don't replicate that structure's entire API; only expose the parts clients need.

 Use a Java interface with only the needed methods, and then

refer to your class by the interface type in client code.

Poker design question 2

 Proposed fields in various poker classes:

 A Hand stores 2 cards and the Player whose hand it is.  A Player stores his/her Hand, last bet, a reference to the other Players in the game, and a Deck reference to draw cards.  The PokerGame stores an array of all Players, the Deck, and

an array of all players' last bets.

 What's wrong with this design?

Cohesion and coupling

 cohesion: how complete and related things are in a

class

 coupling: when classes connect to / depend on each

other

(a good thing)

(too much can be a bad thing)

• (in other words, minimize unnecessary coupling)

 Heuristic 2.7: Classes should only exhibit nil or export coupling with other classes; that is, a class should only use operations in the public interface of another class or have nothing to do with that class.

Reducing coupling

• example: Bet and PlayRound

 combine 2 classes if they don't represent a whole abstraction

• example: list and list iterator; binary tree and tree node • example: GUI window frame and event listeners

 make a coupled class an inner class

• example: provide methods (newGame, reset, ...) in PokerGame so that clients do not need to manually refresh the players, bets, etc.

 provide simpler communication between subsystems

Heuristics 3 quick reference

 Heuristic 3.1: Distribute system intelligence horizontally as uniformly as possible,

that is, the top-level classes in a design should share the work uniformly.

 Heuristic 3.2: Do not create god classes/objects in your system. Be very suspicious

of a class whose name contains Driver, Manager, System, or Subsystem.

 Heuristic 3.3: Beware of classes that have many accessor methods defined in their

public interface.

 Heuristic 3.4: Beware of classes that have too much noncommunicating behavior.

 Heuristic 3.5: In applications that consist of an object-oriented model interacting with

a user interface, the model should never be dependent on the interface.

 Heuristic 3.6: Model the real world whenever possible.

 Heuristic 3.7: Eliminate irrelevant classes from your design.

 Heuristic 3.8: Eliminate classes that are outside the system.

 Heuristic 3.9: Do not turn an operation into a class. Be suspicious of any class

whose name is a verb or is derived from a verb, especially those that have only one piece of meaningful behavior (don't count set, get, print).

 Heuristic 3.10: Agent classes are often placed in the analysis model of an

application. During design time, many agents are found to be irrelevant and should be removed.

Poker design question 3

 Our PokerGame class:

 stores all the players

 stores an array of cards representing the card deck

 stores all bets and money  does the logic for each betting round

 performs the AI for each computer player's moves

PokerGame

 What's wrong with this design?

God classes

 god class: a class that hoards too much of the data or functionality of a system.

 Heuristic 2.8: A class should capture one and only one key

abstraction.

 Heuristic 3.2: Do not create god classes/objects in your system.

Be very suspicious of a class whose name contains Driver, Manager, System, or Subsystem.

 Heuristic 3.4: Beware of classes that have too much non-

communicating behavior, that is, methods that operate on a proper subset of the data members of a class. God classes often exhibit much non-communicating behavior.

Poker design question 4

 Each new game round, the PokerGame wants to deal cards to each player. During the game, players draw additional cards.

 We will create a Dealer class that the PokerGame asks to deal

the cards to every player.

 Player objects will store a reference to the Dealer.

During the game, they will talk to the dealer to draw their cards. The Dealer will notify the Game once all players have drawn.

 What's wrong with this design?

Poker design question 5

 Cards belong to one of four suits. So we have created classes Club, Diamond, Heart, Spade class to represent each suit.

 In each game round, one player is the dealer and one is the first better. Also each turn there is a next better waiting. So we have created classes Dealer, NextBetter, FirstBetter.

 Every game has several betting rounds, each round consisting of

several bets. So we have created classes Bet and CurrentBettingRound.

 What's wrong with this design?

Proliferation of classes

 proliferation of classes: too many classes that are too small in size/scope; makes the system hard to use, debug, maintain

 Heuristic 2.11: Be sure the abstractions that you model are

classes and not simply the roles objects play.

• often have only data and get/set methods; or only methods, no

real data

 Heuristic 3.7: Eliminate irrelevant classes from your design.

• don't model a Blender just because your company sells blenders;

don't necessarily model a User just because the system is used by somebody

 Heuristic 3.8: Eliminate classes that are outside the system.

Poker design question 6

 A player may bet only as much $ as they have; and if a prior player has made a "call", the current player cannot raise.

• Player checks whether a "call" has been made. • Player checks whether he/she has enough to make a given bet.

 Where should these policies be enforced?  Design 1: Player class remembers whether that player is in the game, what that player's current bet is, whether it is his turn, etc.

• PokerGame class remembers who is in the game. • Betting class remembers every player's current bets, checks $. • Dealer class remembers whose turn it is.

 Design 2:

Related data and behavior

• avoids having to change two places when one change is needed

 Heuristic 2.9: Keep related data and behavior in one place.

 Heuristic 3.3: Beware of classes that have many accessor

• "policy" behavior should be where that policy is enforced/enacted

methods ... [This] implies that related data and behavior are not being kept in one place.

UML sequence diagrams

 sequence diagram: an "interaction diagram" that models a single scenario executing in the system

 relation of UML diagrams to other exercises:

 perhaps 2nd most used UML diagram (behind class diagram)

 CRC cards  class diagram  use cases  sequence diagrams

Parts of a seq.diagram

Sequence diag. key parts

 participant: object or entity that acts in the diagram

 message: communication between participant objects

 the axes in a sequence diagram:

 diagram starts with an unattached "found message" arrow

 horizontal: which object/participant is acting

 vertical: time (down = forward in time)

Seq. diag. examples

Representing objects

 Squares with object type, optionally preceded by "name

:"  write object's name if it clarifies the diagram  object's "life line" represented by dashed vert. line

Messages between objects

 messages (method calls) indicated by arrow to other

object  write message name and arguments above arrow

Messages, continued

 messages (method calls) indicated by arrow to other

object  dashed arrow back indicates return  different arrowheads for normal / concurrent (asynchronous)

calls

Lifetime of objects

 creation: arrow with 'new'

written above it

 deletion: an X at bottom of

object's lifeline

 notice that an object created after the start of the scenario appears lower than the others

 Java doesn't explicitly delete objects; they fall out of scope and are garbage-collected

Indicating method calls

 activation: thick box over object's life line; drawn when

object's method is on the stack

 either that object is running its code,

or it is on the stack waiting for another object's method to finish

 nest activations to indicate recursion

Activation

Nesting

Selection and loops

 frame: box around part of diagram to indicate if or loop

-> (opt) [condition]

 if  if/else -> (alt) [condition], separated by horizontal dashed line

 loop -> (loop) [condition or items to loop over]

Linking sequence diagrams

 If one diagram is too large or refers to another, indicate

with:

 an unfinished arrow and comment,

• when would this occur in our system?

 or a "ref" frame that names the other diagram

Example sequence diagram

Forms of system control

 What can you say about the control flow of each

system?  Is it centralized?  Is it distributed?

Flawed sequence diagram 1

 What's wrong with this sequence diagram?

(Look at the UML syntax and the viability of the scenario.)

Flawed sequence diagram 2

 What's wrong with this sequence diagram?

Why not just code it?

 Sequence diagrams can be somewhat close to the code

level.

 So why not just code up that algorithm rather than

drawing it as a sequence diagram?

 a good sequence diagram is still a bit above the level of the real

code (not all code is drawn on diagram)

 sequence diagrams are language-agnostic (can be implemented

in many different languages

 non-coders can do sequence diagrams

 easier to do sequence diagrams as a team  can see many objects/classes at a time on same page (visual

bandwidth)

Sequence diagram exercise

 Let's do a sequence diagram for the following

poker casual use case, Start New Game Round :

The scenario begins when the player chooses to start a new round in the UI. The UI asks whether any new players want to join the round; if so, the new players are added using the UI. All players' hands are emptied into the deck, which is then shuffled. The player left of the dealer supplies an ante bet of the proper amount. Next each player is dealt a hand of two cards from the deck in a round-robin fashion; one card to each player, then the second card. If the player left of the dealer doesn't have enough money to ante, he/she is removed from the game, and the next player supplies the ante. If that player also cannot afford the ante, this cycle continues until such a player is found or all players are removed.

Poker sequence diagram

Sequence diagram question

 Consider the possible poker use case, Betting Round :

 Why is it hard to diagram this case as a sequence

diagram?

The scenario begins after the Start New Round case has completed. The UI asks the first player for a bet. That player chooses to either bet a given amount, or check (no bet). The next player is asked what to do. If the prior player placed a bet, the next player must either match ("see") it, or match it plus add an additional bet ("raise"), or choose not to match and exit the round ("fold"). This continues around the table until an entire pass is made in which all players have either matched all other players' bets or folded. If the next player doesn't have enough money to match the current bet, the player is allowed to bet all of their money. But they can then win only up to the amount they bet; the rest is a "side pot" among the more wealthy players remaining in the round.

Poker sequence diagram 2

Sequence diagram exercise

 Let's do a sequence diagram for the following casual use case for a scheduler app, Add Calendar Appointment :

The scenario begins when the user chooses to add a new appointment in the UI. The UI notices which part of the calendar is active and pops up an Add Appointment window for that date and time.

The user enters information about the appointment's name, location, start

and end times. The UI will prevent the user from entering an appointment that has invalid information, such as an empty name or negative duration. The calendar records the new appointment in the user's list of appointments. Any reminder selected by the user is added to the list of reminders.

If the user already has an appointment at that time, the user is shown a

message and asked to choose an available time or replace the appointment. If the user enters an appointment with the same name and duration as an existing meeting, the calendar asks the user whether he/she intended to join that meeting instead. If so, the user is added to that meeting's list of participants.

UML state diagrams

 state diagram: Depicts data and behavior of a single

object throughout its lifetime.

 set of states (including an initial start state)

 transitions between states

 similar to finite state machines (DFA, NFA, PDA, etc.)

 What objects are best used with state diagrams?

 entire diagram is drawn from that object's perspective

 large, complex objects with a long lifespan

 domain ("model") objects

 not useful to do state diagrams for every class in the system!

State diagram example

States

 state: conceptual description of the data in the object

 entire diagram is drawn from the

central object's perspective

 represented by object's field values

 only include states / concepts that this object can see and influence

 don't include every possible value for the fields; only ones that are conceptually different

Transitions

 transition: movement from one state to another

 signature [guard] / activity

 signature: event that triggers (potential) state change

boolean condition that must be true

 transitions must be mutually exclusive (deterministic)

 guard:  activity: any behavior executed during transition (optional)

 must be clear what transition to take for an event

 most transitions are instantaneous,

except "do" activities

Internal activities

 internal activity: actions that the

central object takes on itself

 entry/exit activities

 sometimes drawn as self-transitions (events that stay in same state)

 reasons to start/stop being in that state

State diagram example

t n e m e g a n a m

t n u o c c a r e s U

Super/substates

 When one state is complex, you can include substates in

it.

 Caution: Don't over-use this feature.

 drawn as nested rounded rectangles within the larger state

 easy to confuse separate states for sub-states within one state

State diagram example

k n a b a t a s e t a t s e r a w

t f o s M T A

State diagram example

s e t a t s d a e r h t a v a J

Implementing states

 What are some ways to write

code to match a state diagram?

 state tables (pseudo-code)

 nested if/else

 switch statements  state enums

 State design pattern

State pattern

 state pattern: An object whose sole purpose is to

represent the current "state" or configuration of another larger object.

 A behavioral pattern.  Often implemented with an enum type for the states.

 Each object represents one specific state for the larger object.

 The larger object sets its state in response to various mutations.

 Allows various observers and interested parties to quickly and

 Analogous to the notion of finite state machines.

accurately know what is going on with the larger object's status.

 Set of states (nodes)

 Set of edges (mutations that cause state changes)

State enum example

/** Represents states for a poker game. */ public enum GameState { NOT_STARTED, IN_PROGRESS, WAITING_FOR_BETS, DEALING, GAME_OVER; } /** Poker game model class. */ public class PokerGame { private GameState state; public GameState getState() { return state; } public void ante(int amount) { ... state = WAITING_FOR_BETS; // change state setChanged(); notifyObservers(state); } }