Anda di halaman 1dari 106

The Object-Oriented

Design Process
Ch2

Chapter Topics
Part I
From Problem to Code
The Object and Class Concepts
Identifying Classes
Identifying Responsibilities
Relationships Between Classes
Part II
Use Cases
CRC Cards
UML Class Diagrams
Sequence Diagrams
State Diagrams
Using javadoc for Design Documentation
Part III
Case Study: A Voice Mail System

From Problem to Code


End
product

Problem
Programming tasks originate
from the desire to solve a
particular problem

Three Phases:

The end product


is a working
program.

(1) Analysis
(2) Design
(3) Implementation

Case Study: Voice Mail System

(1) Analysis Phase


A vague understanding of the problem is transformed
into a precise description of the tasks that the software
system needs to carry out.
Goal of this phase:
A complete description of what the software product should
be.

Results of this phase


A detailed textual description, called functional specification

Functional specification characteristics:

Completely defines tasks to be solved


Free from internal contradictions
Readable both by domain experts and software developers
Reviewable by diverse interested parties
Testable against reality

Example
A word-processing program
Define terms
E.g., fonts, footnotes, multiple columns,

Define interaction of those features


E.g., how footnotes in multiple-column text ought to
look on the screen.

Document the user interface


E.g., how the user is to enter and move a footnote

Describe the behavior of a system


I.e., a sequence of actions that yields a benefit for
user
Use Use Cases

Note
The analysis phase concerns itself with the
description of WHAT needs to be done, not HOW
it should be done.
The selection of specific algorithms, such as those that
insert page breaks or sort the index, will be handled in
the implementation phase

It is possible to use OO techniques in the analysis


phase as well as the design phase
Adv: the object model of the analysis phase can be
carried forward to the design phase.
Pitfall: customers of a software product are generally
not familiar with the terminology of object orientation

(2) Design Phase


The program designer must structure the
programming tasks into a set of interrelated
classes
Goals
Identify the classes
Identify the responsibilities of these classes
Identify the relationships among these classes

In practice
The above are goals, not steps.
Usually not possible to find ALL classes first, then
give a COMPLETE description of their responsibility,
then elaborate CORRECTLY on their relationship
The discovery process is iterative
The identification of one aspect of a class may force
changes in or lead to the discovery of others

(2) Design Phase


Artifacts
Textual description of classes and key
methods
Diagrams of class relationships
Diagrams of important usage scenarios
State diagrams for objects with rich state

Typically, this phase is more timeconsuming than the actual programming


A good design greatly reduces the time
required for implementation and testing

Note
The designer must strive for a result in
which
the classes are crisply defined and class
relationships are of manageable complexity.

The exact choice of data structure is not


concern
E.g., hash tables or binary search trees for a
collection
It is deferred until implementation

(3) Implementation
Phase
Goal
Classes and methods are coded, tested, and deployed

Avoid "big bang" integration


Few program are born according to plan out of a
successful big bang integration
OO development encourages the gradual growth of a
program
by successively attaching more working classes and class
clusters and repeated testing.

Prototypes can be very useful


A prototype is very helpful in influencing the design or
even the problem analysis
OO design is particularly suited for prototyping.
The objects supporting the prototype are likely to be the
same that need to be present in the final product

Object and Class


Concepts
Object: Three characteristic concepts
(1) State
(2) Behavior
(3) Identity

Class:
A class describes a collection of similar
objects
They support a common set of operations
They have a common set of possible states.

(1) State
State
An object can store information that is the result of its
prior operations
The collection of all information held by an object=the
objects state
The state may determine how the object behaves in the
future.

Example: a mailbox in a voice mail system


A mailbox object may be in an empty state or full.
This state affects the behavior of the mailbox object. E.g.,
a full mailbox may reject new mail message, or
a empty mailbox may give a special response (no message
waiting)

(2) Behavior
Behavior of an object
Defined by the operations that an object
supports
I.e., objects only permit certain
operations (not others)
E.g., a mailbox object can add a
message to its collection but not encrypt
it.

(3) Identity
Possible for two or more objects to
support the same operations and
have the same state,
Yet to be different from each other.

So, each object has its own identity


Example
Two different mailboxes may, by chance,
have the same contents, yet the program
can tell them apart.

Reminder
Goals of Design Phases
Identify the classes
Identify the responsibilities of these
classes
Identify the relationships among these
classes

Identifying Classes
Step 1
Rule of thumb: Look for nouns in problem
description (or the functional specification)
Which phase produces the functional specification?

Example: Voice mail system:

Mailbox
Message
User
Passcode
Extension
Menu
Many, but not necessarily all of them, are good choices
for classes

Identifying Classes
Class name
Singular noun:
e.g., Message, Mailbox

Adjective prefixed:
e.g., RectangularShape, BufferedReader

Stay away from too generic names:


e.g., Task, Item, User

On the wrong track if naming classes after


verbs:
e.g., PrintingReport, DoTask

Identifying Classes
Step 2
Turn your attention to other classes that are
required to carry out necessary work,
after harvesting the classes that are obvious from the
specification.

Example: Voice mail system:


Storing messages in a mailbox in a FIFO fashion
MessageQueue (with FIFO behavior) is suggested

Focus on concepts
The exact implementation of the queue is of no
interest in design phase.

Identifying Classes
Step 3
Look at different categories of classes for
more identification:

(i) Tangible Things


(ii) Agents
(iii) Events and Transactions
(iv) Users and Roles
(v) Systems
(vi) System interfaces and devices
(vii) Foundational Classes

Identifying Classes
(i) Tangible Things
They are the easiest classes to discover as
they are visible in the problem domain.

(ii) Agent classes


Sometimes it is helpful to change an operation
into an agent class
Agent classes of then end in er or or.
E.g., the compute page breaks operation
could be turned into a Paginator class.
E.g., Scanner and Iterator

Identifying Classes
(iii) Event and Transaction classes
They are useful to model records of activities
that describle what happened in the past or what needs to be
done later

E.g., the MouseEvent class remembers when and where


the mouse was moved or clicked

(vi) User and Role classes


They are stand-ins for actual users of the program
E.g., An Administrator class is a representation of the
human administrator of the system.
A Reviewer class models a user whose role is to add
critical annotations and recommendations for changes

Identifying Classes
(v) System classes
Their roles are typically
to perform initialization and shutdown
to start the flow of input into the system

(vi) System interface classes


They model interfaces to the host operating system, a
database, and so on.
E.g., the File class

(vii) Foundation classes


E.g., String, Date, or Rectangle
At the design stage, simply assume that these classes
are readily available.

Identifying
Responsibilities
Rule of thumb: Look for verbs in problem
description
Example: voice mail system
Messages are recorded, played, and deleted;
Users log in;
Passcodes are checked.

After discovering a responsibility, you


must find one (and only one) class that
owns that responsibility

Identifying
Responsibilities

When discovering responsibility, commonly make


wrong guesses
Example: Add message to mailbox
Is the responsibility of the Message or Mailbox class?
Message is not a good idea.
Think how a message perform the responsibility.
In order to add itself to a mailbox, the message needs to know
the internal structure of the Mailbox, e.g., array or link list. But
we always assume that those details should be private to
Mailbox class, and that Message class has no insight into them.

Helpful to have more than one person involved


If one assigns a responsibility to a class, another can
ask hard questions

Class Relationships
(1) Dependency ("uses")
(2) Aggregation ("has")
(3) Inheritance ("is")

(1) Dependency (uses)


C depends on D: If C (its method)
manipulates objects of D
Example: Mailbox depends on Message

If C doesn't use D, then C can be


developed without knowing about D
Example: Message does not use Mailbox

As shown, dependency is an
asymmetric relationship

Coupling
To minimize dependency: reduce
coupling
It is one important design goal

Why ???

Coupling
Example:
public class Message
{
void print() {System.out.println(text);}
. . .
}

The method prints the message to Systme.out.


So, Message is coupled with both Systme and PrintStream

If the class is deployed in an embedded device or others in


that there is no Systme.out, changes need to be made.

Better to have a method:


public String getText()

It is up to some other part of the system to send the


returned string to Systme.out, to a dialog box, to a log file,
or to other context.

(2) Aggregation (has)


C aggregates D: if its objects contain objects
of D
Example: MessageQueue
MessageQueue has Messages objects
So, we say that the MessageQueue class
aggreates the Message class

Aggregation is a special case of dependency


because if a class contains objects of another
class, then it is acutely aware of the existence of
that class

Multiplicities
Informally described as the has-a relationship.
There may be a 1:1 or 1:0...n relationship:
E.g.,: A mailbox has one greeting (1:1)
public class Mailbox
{. . .
private Greeting myGreeting;
}

E.g.,: A message queue may has many


messages (1:n)
public class MessageQueue
{. . .
private ArrayList<Message> elements;
}

(3) Inheritance (is)


More general class = superclass
More specialized class = subclass
Subclass inherits from superclass
Subclass supports all method interfaces of
superclass (but implementations may differ)
Subclass may have added methods, added
state

Example:
A forwarded message is a message.
ForwardedMessage inherits from Message
Greeting does not inherit from Message (Can't
store greetings in mailbox)

Summary
From problem to code
Three
Analysis
phases?

Design
Indentify
Three
goals?
classes
Their
responsibil
ities
Their
relationshi
ps

Implementat
ion
Nouns in the
specification, etc
Verbs in the
specification, etc
1. Dependency ("uses")
2. Aggregation ("has")
3. Inheritance ("is")

Part II

Use Cases
An Analysis technique
To describe how a system should work
(formally)

Each use case focuses on a specific scenario


= a sequence of actions necessary to bring it to
successful completion

Each action= an interaction between the


actors and the system
Actors = people or entities outside the system

Each action yields a result


Each result has a value to one of the actors
Most scenarios that potentially deliver a
valuable outcome can fail for some reasons
Use variations for exceptional situations

Use Cases
A System
Scenario 1

Use Case 1

Action1 Action2 . . . ActionN

Scenario 2

Use Case 2

Action1 Action2 . . . ActionN

.
.
.

.
.
.

Scenario N

Use Case N

A System

Action1 Action2 . . . ActionN

interaction
between the actors
and the system

Use Cases
Voicemail system
Many scenarios:
Leave a message, Retrieve message, etc

The use case Leave a message


Describe the steps that a caller must take to dial an extension
and leave a message
Actor = ???
the caller leaving a message
Value to the caller = the message is deposited in the
appropriate mailbox

The use case Retrieve message


Describe the steps needed to listen to the messages in the
mailbox.
actor =???
the mailbox owner

Sample Use Case


Leave a Message
1. Caller dials main number of voice mail system
2. System speaks prompt
Enter mailbox number followed by #
Variation Here
3. User types extension number
4. System speaks
You have reached mailbox xxxx. Please leave a
message now
Variation Here

5. Caller speaks message


6. Caller hangs up
7. System places message in mailbox

Sample Use Case -Variations


Variation #1
1.1. In step 3, user enters invalid extension
number
1.2. Voice mail system speaks You have typed
an invalid mailbox number.
1.3. Continue with step 2.

Variation #2
2.1. After step 4, caller hangs up instead of
speaking message
2.3. Voice mail system discards empty message

CRC Cards
CRC = Classes, Responsibilities,
Collaborators
An effective design technique for
discovering classes, responsibilities, and
relationships
Proposed by Kent Beck and Ward Cunningham,
A Laboratory for Teaching Object-Oriented
Thinking,
OOPSLA 89 Conference, Oct 1-6, 1989.

CRC Cards
A CRC card = an index card for a class:
Class name (top)
Responsibilities (left)
Collaborators (right):
Other classes that need to collaborate with so that it can fulfill its
responsibilities

CRC Cards

Why index cards?


Small

Discourage you from piling too much responsibility into a single class

Low-tech
So they can be used by groups of designers gathered around a table

Rugged than sheets of paper


Can be handed around and rearranged during brainstorming sessions.

CRC Cards
Responsibilities should be high level
DONT write individual methods

1 - 3 responsibilities per card


What you should do if a class has more
responsibilities than you can fit on the card?
- Make two new cards, distribute the responsibilities
among them, and tear up the old card.

Collaborators are for the class, not for each


responsibility.
Simply list collaborators as you discover them,
without regard for the ordering

Walkthroughs
CRC cards are intuitive for walking
through use cases:
Use case: "Leave a message"
Caller connects to voice mail system
Caller dials extension number

"Someone" must locate mailbox


Neither Mailbox nor Message can do this
New class: MailSystem
Responsibility: manage mailboxes

Walkthroughs
CRC cards are intuitive for walking through use cases:
Example:
Leave a Message
1. Caller dials main number of voice
mail system
2. System speaks prompt
Enter mailbox number followed
by #
3. User types extension number
4. System speaks
You have reached mailbox xxxx.
Please leave a message now
5. Caller speaks message
6. Caller hangs up
7. System places message in
mailbox

"Someone" must locate


mailbox
The responsibility of
Message?
The responsibility of
Mailbox?
Neither they can do this
New class: MailSystem
Responsibility: manage
mailboxes

Walkthroughs
CRC cards are intuitive for walking through use cases:
Example:

Leave a Message
1. Caller dials main number of voice
mail system

2. System speaks prompt


Enter mailbox number followed

by #

3. User types extension number


4. System speaks
You have reached mailbox xxxx.

Please leave a message now


5. Caller speaks message
6. Caller hangs up
7. System places message in
mailbox

It needs to deliver the message to


that mailbox.
Look again at the existing Mailbox
CRC card.
It has a responsibility of manage
new and saved messages
It is up to the job of storing the
message.
So, add Mailbox as a collaborator.

Tips
Avoid mission creep
If a class acquires too many responsibilities, then
consider splitting it in two.

Watch out for unrelated responsibilities


A class should represent a coherent concept. With
related responsibilities

Resist the temptation to add responsibilities just


because they can be done.
E.g., someone may have suggested a Mailbox
responsibility sort messages. But the task at hand
requires no sorting.

A class with no responsibilities surely is not useful.


Eliminate classes that dont seem to contribute to
solving the problem at hand.

UML Diagrams
Graphical notations are very
good for conveying design
information
Easier to extract relationship
information by looking at a diagram
than by reading documentation.
Which phrase produces documentation?

You know flowcharts?


For quite some time, there was
no similar standard for OO design
diagrams
A number of diagramming
conventions had been proposed
over time.

UML Diagrams
Three well-known researchers (Booch,
Rumbaugh, Jacobson) got together to
unify their disparate notations and
develop UML
UML = Unified Modeling Language
Many diagram types
We'll use three types:
Class Diagrams
Sequence Diagrams
State Diagrams

UML Diagrams
Best-known commercial programs:
Rational Rose
http://www.ibm.com/software/rational/

Together
http://wwww.borland.com/together

Freely available programs


Violet tool
http://horstmann.com/violet

UMLet
http://www.umlet.com/

ArgoUML
http://www.gentleware.com

Class Diagrams
Rectangle with class name
Optional compartments
Attributes
Methods

Often, an attribute = an instance field


Occasionally, an attribute is conceptual
Usually, not list all attributes and methods (only the key ones)

Class Diagrams

You can also specify the type of an attribute:


text : String

You can specify the parameter and return types of a method


getCurrentMessage(index : int) : Message

Often, they are omitted to conserve space.


So, if you see methodName(), you cannot automatically assume that
the method has no parameters and no return values.

Class Relationships
Use
Has
Is

Multiplicities

any number (0 or more): *


one or more: 1..*
zero or one: 0..1
exactly one: 1

MessageQueue aggregates Message


MessageQueue has Message
1 MessageQueue has one or more Message

Composition
Special form of aggregation
Contained objects don't exist outside container
Example: MessageQueue permanently contained
in Mailbox

In contrast, Message move throughout the system


and dont always reside in a MessageQueue

Association
Some designers don't like
aggregation
Because they feel it is too
implementation-specific

More general association relationship


Association can have roles

Association
Some associations are bidirectional
Can navigate from either class to the other
Example: Course has set of students, student has set of
courses

Some associations are directed


Navigation is unidirectional
Example: A MessageQueue needs to be able to locate the
messages inside, but a message doesn't know about
message queue containing it

Interface Types
Interface type describes a set of
methods
No implementation, no state
Class implements interface if it
implements its methods
In UML, use stereotype interface

Tips
Use UML to inform, not to impress
Don't draw a single monster diagram
Each diagram must have a specific
purpose
Omit inessential details

Sequence Diagrams
Class diagram are static they display the
relationships.
A sequence diagram shows dynamics of a
particular scenario.
Sequence diagram describe interactions between
objects.

Sequence Diagrams
The text inside an object rectangle has one of the
formats:
objectName:ClassName (full description)
objectName (class not specified)
:ClassName (object not specified)

Activation bar
Executing a method

Call a
method

Start an bar
at the end
of the call
arrow
The bar
ends when
the method
returns

Self call

Object Construction

Tips
Principal purpose of a sequence diagram
To show the objects that are involved in
carrying out a particular scenario and the order
of the method calls that are executed

If you played through a use case when


using CRC cards,
Probably a good idea to use a sequence
diagram to document that scenario.

No requirement to use sequence diagrams


to document every method call.

State Diagram
Some objects have a discrete set of states
(that affect their behavior).
Example: a voice mail system:
Waiting state: the system is idle and waiting
new call
Connected state: when a caller first connects
to it.
Recording state: after the caller chooses an
targeted mailbox

Also called State Transition diagram

State Diagram
Waiting
A caller connected to the system
Voice recorded
Connecte
d
Destination chosen

Recording

Design Documentation
Recommendation: Use Javadoc comments
Leave methods blank
/**
Adds a message to the end of the new messages.
@param aMessage a message
*/
public void addMessage(Message aMessage)
{
}

Don't compile file, just run Javadoc


Makes a good starting point for code later

Part III

Case Study: Voice Mail


System
Consider the task of writing a program that
simulates a telephone voice mail system
A caller dials an extension number and leaves a
message.
The mailbox owner can later retrieve the messages,
keep them, or delete them.

Simplified version
Use text for voice, phone keys, hangup
1 2 ... 0 # on a single line means key
H on a single line means "hang up"
All other inputs mean voice

Its role is to crisply define the behavior of the system.


We will define the behavior through a set of use cases.
Note that the use cases by themselves are not a full specification of a system.
The functional specification also needs to define system limitations,
performance, and so on.

Analysis Phase

Use Case: Reach an


Extension
1. User dials main number of system
2. System speaks prompt
Enter mailbox number followed by #
3. ???
4. System speaks
You have reached mailbox xxxx. Please leave
a message now

Use Case: Leave a


Message
1. Caller carries out Reach an
Extension
2. Caller speaks message
3. ???
4. System places message in mailbox

Use Case: Log in


1. Mailbox owner carries out Reach an
Extension
2. Mailbox owner types password and #
(Default password = mailbox number. To
change, see Change the Passcode)
3. System plays mailbox menu:
Enter 1 to retrieve your messages.
Enter 2 to change your passcode.
Enter 3 to change your greeting.

Use Case: Retrieve


Messages
1. Mailbox owner carries out Log in
2. Mailbox owner selects "retrieve messages" menu option
3. System plays message menu:
Press
Press
Press
Press

1
2
3
4

to
to
to
to

listen to the current message


delete the current message
save the current message
return to the mailbox menu

4. Mailbox owner selects "listen to current message


5. System plays current new message, or, if no more new
messages, current old message.
Note: Message is played, not removed from queue
6. System plays message menu
7. User selects "delete current message". Message is removed.
8. Continue with step 3.

Use Case: Retrieve


Messages
Variation #1
1.1. Start at Step 6
1.2. User selects "save current
message.
1.3. ???
1.4. Continue with step 3.

Use Case: Change the


Greeting
1. Mailbox owner carries out Log in
2. Mailbox owner selects "change
greeting" menu option
3. ???
4. Mailbox owner presses #
5. System sets new greeting

Use Case: Change the


Greeting
Variation #1: Hang up before
confirmation
1.1. Start at step 3.
1.2. Mailbox owner hangs up.
1.3. System keeps old greeting.

Use Case: Change the


Passcode
1. Mailbox owner carries out Log in
2. Mailbox owner selects "change
passcode" menu option
3. Mailbox owner dials new passcode
4. Mailbox owner presses #
5. System sets new passcode

Use Case: Change the


Passcode
Variation #1: Hang up before
confirmation
1.1. Start at step 3.
1.2. Mailbox owner hangs up.
1.3. System keeps old passcode.

CRC Cards
Walkthrough
UML

Design Phase

Initial CRC Cards


Some obvious classes, whose nouns
appear in the functional specification
are:
???
???
???

Initial CRC Cards:


Mailbox
The mailbox should keep track of which messages
are new and which are saved.
The messages need to be kept somewhere.

Initial CRC Cards:


MessageQueue
The messages need to be kept somewhere so
that they can be retrieved, saved, and deleted
We retrieve messages in a first-in, first-out
fashion.

Initial CRC Cards:


MailSystem
Where are the mailboxes kept?
There needs to be a class that contains
them all

Telephone
Who interacts with user?
Telephone takes button presses,
voice input
Telephone speaks output to user

Telephone
Two responsibilities:
Input from user
Output to user

Connection
With whom does Telephone communicate
With MailSystem?
Superficially, that sounds like a good idea.

What if there are multiple telephones


connected to the system?
Each connection can be in different state
(dialing, recording, retrieving messages,...)
Should mail system keep track of all
connection states?
Better to give this responsibility to a new class

Connection

Walkthrough
Now we have some idea of the
components of the system.
It is time for a simple scenario
walkthrough.

Analyze Use Case: Leave a


message
1. User dials extension. Telephone sends number to Connection
(Add Connectionas a collaborator of Telephone)
2. Connection asks MailSystem to find matching Mailbox
3. Connection asks Mailbox for greeting
(Add responsibility "manage greeting" to Mailbox,
add Mailbox as a collaborator to Connection)
4. Connection asks Telephone to play greeting
5. User speaks greeting. Telephone asks Connection to record it.
(Add responsibility "record voice input" to Connection)
6. User hangs up. Telephone notifies Connection.
7. Connection constructs a Message object that contains the
recorded message
(Add Message as a collaborator of Connection.
Make a Message card with a responsibility manage message
contents.)
8. Connection adds the Message object to Mailbox

Result of Use Case


Analysis

Result of Use Case


Analysis

Result of Use Case


Analysis

Result of Use Case


Analysis

Analyse Use Case: Retrieve


messages

1. User types in passcode. Telephone notifies Connection


2. Connection asks Mailbox to check passcode.
(Add responsibility "manage passcode" to Mailbox)
3. Connection sets current mailbox and asks Telephone to speak menu
4. User selects "retrieve messages". Telephone passes key to
Connection
5. Connection asks Telephone to speak menu
6. User selects "listen to current message". Telephone passes key to
Connection
7. Connection gets first message from current mailbox.
(Add "retrieve messages" to responsibility of Mailbox).
Connection asks Telephone to speak message
8. Connection asks Telephone to speak menu
9. User selects "save current message". Telephone passes key to
Connection
10. Connection tells Mailbox to save message
(Modify responsibility of Mailbox to "retrieve,save,delete messages")
11. Connection asks Telephone to speak menu

Result of Use Case


Analysis

CRC Summary
One card per class
Responsibilities at high level
Use scenario walkthroughs to fill in
cards
Usually, the first design isn't perfect.
(You just saw the author's third
design of the mail system)

UML
Now we use UML to help design.

UML Class Diagram for Mail


System
CRC collaborators yield dependencies
Mailbox depends on MessageQueue
MailSystem depends on Mailbox
Message doesn't depends on Mailbox
Connection depends on Telephone,
MailSystem, Message, Mailbox
Telephone depends on Connection

Dependency
Relationships

Aggregation
Relationships
A mail system has mailboxes
A mailbox has two message queues
A message queue has some number
of messages
A connection has a current mailbox.

UML Class Diagram for


Voice Mail System

Sequence Diagram for Use Case: Leave


a message

Interpreting a Sequence
Diagram
Each key press results in separate call to dial, but
only one is shown
Connection wants to get greeting to play
Each mailbox knows its greeting
Connection must find mailbox object:
Call findMailbox on MailSystem object
Parameters are not displayed (e.g. mailbox
number)
Return values are not displayed (e.g. found
mailbox)
Note that connection holds on to that mailbox
over multiple calls

Sequence Diagram for Use Case:


Retrieve messages

Connection State
Diagram

Message.java
MessageQueue.java
Mailbox.java
Connection.java
MailSystem.java
Telephone.java
MailSystemTester.java

Implementation Phrase

Anda mungkin juga menyukai