Tải bản đầy đủ (.pdf) (247 trang)

Prentice hall UML for java programmers jun 2003 ISBN 0131428489 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.14 MB, 247 trang )

UML
for

Java
Programmers

Robert Cecil Martin
Object Mentor Inc.

Prentice Hall, Englewood Cliffs, New Jersey 07632
Don’t Panic Do n’t Panic Do n’t Panic Do n’t Panic Don ’t Panic Don ’t Panic Don ’t Panic Don ’t Panic Don’t Panic Don’t Panic Don’t Panic Don’t Panic Don’t Panic Don’t Panic Don’t Panic Don’t Panic Don’t Pan ic Don’t Pan ic Don’t Pan ic Don’t Panic Don’t Panic Don’t Panic Do n’t Panic Do n’t Panic Do n’t Panic Do n’t Panic Don ’t Panic Don ’t Panic Don ’t Panic


Martin, Robert Cecil.
The Principles, Practices, & Patterns of Agile Software Development
/Robert Cecil Martin.
p. cm.
“An Alan R. Apt Book.”
Includes index.
ISBNxxxxxxxxx
Publisher: Alan Apt
Production Editor:
Cover Designer:
Copy Editor:
© 2002 by Prentice-Hall, Inc.
A Simon & Schuster Company

The author and publisher of this book have used their best efforts in preparing this
book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The author and publisher shall not be liable in any
event for incidental or consequential damages in connection with, or arising out of, the
furnishing, performance, or use of these programs.



All rights reserved. No part of this book may be reproduced, in any form or by any
means, without permission in writing from the publisher.

Printed in the United States of America

10

9

8

7

6

5

ISBN 0-13-203837-4

4

3

2

1


PRENTICE-HALL INTERNATIONAL


(UK) Limited, London

PRENTICE-HALL OF A USTRALIA PTY. LIMITED,

Sydney

PRENTICE-HALL CANADA, I NC., Toronto
PRENTICE-HALL HISPANOAMERICANA,

S.A., Mexico

PRENTICE-HALL OF I NDIA PRIVATE LIMITED,
PRENTICE-HALL OF J APAN, INC.,

New Delhi

Tokyo

SIMON & SCHUSTER ASIA PTE. LTD.,

Singapore

EDITORA PRENTICE-H ALL DO BRASIL , LTDA.,

Rio de Janeiro


This book is dedicated to my grandchildren:
XXX: the son of Micah and Angelique.

Alexis: the daughter of Angela and Matt.
It has been said that grandchildren are the desert of life.
If that’s so, what am I supposed to do with all the many
main courses I’m not done with yet?


Source Code and Contact Information:
Much of the source code presented in this book can be obtained from the
Object Mentor Inc. web site. www.objectmentor.com/UMLFJP
Robert C. Martin:
Object Mentor Inc.:
www.objectmentor.com


i

Chapter :

Chapter 1:
Overview of UML for Java Programmers ..................................1
Diagram Types ......................................................................................2
Class Diagrams...................................................................................4
Object Diagrams.................................................................................5
Sequence Diagrams ............................................................................6
Collaboration Diagrams .....................................................................6
State Diagrams ...................................................................................7
Conclusion..............................................................................................8
Bibliography ..........................................................................................8

Chapter 2:

Working with Diagrams ....................................................................9
Why Model?...........................................................................................9
Why build models of software? .......................................................10
Why should we build comprehensive designs before coding? ........10
Making Effective use of UML ............................................................10
Communicating with Others. ...........................................................11
Back end Documentation .................................................................13
What to keep, and What to throw away. ..........................................14
Iterative Refinement ...........................................................................15
Behavior first....................................................................................15
Check the structure...........................................................................17
Envisioning the code. .......................................................................19
Iterative Refinement .........................................................................20
Minimalism ..........................................................................................21
When and how to draw diagrams......................................................21
When to draw diagrams, and when to stop. .....................................21
CASE Tools......................................................................................22
But what about documentation?.......................................................23
And Javadocs?..................................................................................23
Conclusion............................................................................................24

Chapter 3:
Class Diagrams ...................................................................................25


ii

The Basics ............................................................................................25
Classes ..............................................................................................25
Association .......................................................................................26

Multiplicity.......................................................................................26
Inheritance ........................................................................................27
An Example Class Diagram ...............................................................28
The Details ...........................................................................................30
Class Stereotypes..............................................................................30
Abstract classes ................................................................................31
Properties..........................................................................................31
Aggregation......................................................................................32
Composition .....................................................................................33
Multiplicity.......................................................................................34
Association Stereotypes ...................................................................35
Inner Classes ....................................................................................36
Anonymous Inner Classes................................................................36
Association classes...........................................................................37
Association Qualifiers ......................................................................38
Conclusion............................................................................................38
Bibliography ........................................................................................39

Chapter 4:
Sequence Diagrams ...........................................................................41
The Basics ............................................................................................41
Objects, Lifelines, Messages, and other odds and ends. ..................41
Creation and Destruction..................................................................43
Simple Loops....................................................................................44
Cases and Scenarios .........................................................................44
Advanced Concepts.............................................................................48
Loops and Conditions.......................................................................48
Messages that take time....................................................................49
Asynchronous Messages. .................................................................51
Multiple Threads ..............................................................................53

Active Objects ..................................................................................54
Sending Messages to Interfaces. ......................................................54
Conclusion............................................................................................56


iii

Chapter :

Chapter 5:
Use Cases ...............................................................................................57
Writing Use Cases ...............................................................................57
What is a use case.............................................................................58
The Primary Course .........................................................................58
Alternate Courses .............................................................................59
What else? ........................................................................................59
Use Cases Diagrams ............................................................................60
System Boundary Diagram ..............................................................60
Use Case Relationships ....................................................................61
Conclusion............................................................................................61

Chapter 6:
Principles of OOD ..............................................................................63
Design Quality .....................................................................................63
Design Smells...................................................................................63
Dependency Management ................................................................64
The Single Reponsibility Principle (SRP) .........................................64
The Open Closed Principle (OCP) ....................................................66
The Liskov Substitution Principle (LSP) ..........................................78
The Dependency Inversion Principle (DIP)......................................80

The Interface Segregation Principle..................................................81
Conclusion............................................................................................82
Bibliography ........................................................................................83

Chapter 7:
The Practices: dX ...............................................................................85
Iterative Development.........................................................................85
The Initial Exploration .....................................................................85
Estimating the features .....................................................................86
Spikes ...............................................................................................87
Planning ...............................................................................................87
Planning Releases.............................................................................87
Planning Iterations............................................................................87
The midpoint. ...................................................................................88


iv

Velocity Feedback............................................................................89
Organizing the Iterations into Management Phases........................89
What’s in an Iteration?.......................................................................89
Developing in Pairs ..........................................................................90
Acceptance Tests..............................................................................90
Unit Tests .........................................................................................91
Refactoring .......................................................................................91
Open Office ......................................................................................92
Continuous Integration .....................................................................92
Conclusion............................................................................................92
Bibliography ........................................................................................93


Chapter 8:
Packages ................................................................................................95
Java Packages ......................................................................................95
Packages ...........................................................................................95
Dependencies ...................................................................................96
Binary Components -- .jar files..........................................................97
Principles of Package Design .............................................................97
The Release/Reuse Equivalency Principle (REP) ............................98
The Common Closure Principle (CCP)............................................98
The Common Reuse Principle (CRP) ..............................................99
The Acyclic Dependencies Principle (ADP)....................................99
The Stable Dependencies Principle (SDP).......................................99
The Stable Abstractions Principle (SAP) .......................................100
Conclusion..........................................................................................100

Chapter 9:
Object Diagrams ..............................................................................103
A Snapshot in Time...........................................................................103
Active Objects....................................................................................105
Conclusion..........................................................................................108

Chapter 10:
State Diagrams ..................................................................................109


v

Chapter :

The Basics ..........................................................................................109

Special Events ................................................................................110
Super States ....................................................................................111
Initial and Final Pseudo States .......................................................113
Using FSM Diagrams........................................................................113
SMC ...............................................................................................114
ICE: A Case Study .........................................................................116
Conclusion..........................................................................................121

Chapter 11:
Heuristics and Coffee .....................................................................123
The Mark IV Special Coffee Maker................................................123
A Challenge....................................................................................126
A Common, but Hideous, Coffee Maker Solution.........................126
MissingMethods. ............................................................................126
Vapor Classes.................................................................................127
Imaginary Abstraction....................................................................128
God Classes ....................................................................................129
A Coffee Maker Solution ..................................................................129
Crossed Wires ................................................................................130
The Coffee Maker User Interface...................................................131
Use Case 1: User pushes brew button. ...........................................131
Use Case 2: Containment Vessel not Ready. .................................132
Use Case 3: Brewing Complete. ....................................................132
Use Case 4: Coffee all gone. ..........................................................134
Implementing the Abstract Model..................................................134
Use Case 1. User pushes Brew Button (Mark IV) .........................135
Implementing the isReady() functions. ..........................................136
Implementing the start() functions. ................................................137
How does M4UserInterface.checkButton get called? ....................138
Completing the Coffee Maker........................................................139

The Benefits of this design.............................................................141
How did I really come up with this design?...................................141

Chapter 12:
SMC Remote Service: Case Study .............................................153


vi

Caveat Emptor................................................................................153
Unit Tests. ......................................................................................154
The SMCRemote System..................................................................154
SMCRemoteClient ............................................................................154
SMCRemoteClient Command Line ...............................................155
SMCRemote Communication Protocols ........................................155
SMCRemoteClient .........................................................................157
The Loggers....................................................................................164
The Remote Sessions. ....................................................................165
RemoteSessionBase .......................................................................166
The Remote Registrar.....................................................................169
The Remote Compiler ....................................................................171
FileCarrier ......................................................................................176
SMCRemoteClient Conclusion ......................................................177
SMCRemoteServer ...........................................................................178
SocketService .................................................................................178
SMCRemoteService .......................................................................183
SMCRemoteServer.........................................................................187
ServerSession .................................................................................190
Three Level FSM ...........................................................................192
UserRepository...............................................................................192

OReillyEmailSender.......................................................................202
PasswordGenerator.........................................................................202
Conclusion..........................................................................................203
Tests for SMCRemoteClient .......................................................204
Tests for SocketService .....................................................................211
Tests for SMCRemoteServer
..................................................214
Other Tests.........................................................................................224
ServerController (SMC Generated) ...............................................227
Bibliography ......................................................................................235


________________________

1

________________________
Overview of UML for Java
Programmers
The Unified Modeling Language (UML) is a graphical notation for drawing diagrams of
software concepts. One can use it for drawing diagrams of a problem domain, a proposed
software design, or an already completed software implementation. Fowler1 describes
these three different levels as Conceptual, Specification, and Implementation. This deals
with the last two.
Specification and Implementation level diagrams have a strong connection to source
code. Indeed it is the intent for a Specification level diagram to be turned into source code.
Likewise it is the intent for an Implementation level diagram to describe existing source
code. As such there are rules and semantics that diagrams at these levels must follow.
Such diagrams have very little ambiguity, and a great deal of formality.
On the other hand, diagrams at the Conceptual level are not strongly related to source

code. Rather they are related to human language. They are a shorthand used describe concepts and abstractions that exist in the human problem domain. They don’t follow strong
semantic rules and therefore their meaning can be ambiguous and subject to interpretation.
Consider, for example, the following sentence: A dog is an animal. We can create a
Conceptual UML diagram that respresents this sentence. (See Figure 1-1.)
This diagram depicts two entities named Animal and Dog connected by generalization relationship. An Animal is a generalization of a Dog. A Dog is a special case of an
Animal. That’s all the diagram means. Nothing more can be inferred from it. We might be
asserting that our pet dog, Sparky, is an animal; or we might be asserting that dogs, as a

1. [Fowler00], p??

1


Diagram Types

2

Animal

Dog

Figure 1-1
A Dog is an Animal
biological species, belong to the animal kingdom. Thus, the diagram is subject to interpretation.
However, the same diagram at the Specification or Implementation level has a much
more precise meaning:
public class Animal {}
public class Dog extends Animal {}
This source code defines Animal and Dog as classes connected by an inheritance


relationship. Whereas the Conceptual model says nothing at all about computers, data processing, or programs, the Specification model describes part of a program.
It is unfortunate that the diagrams themselves don’t communicate what level they are
drawn at. Failure to recognize the level of a diagram is the source of significant miscommunication between programmers and analysts. A Conceptual level diagram does not
define source code, nor should it. A Specification level diagram that descibes the solution
to a problem does not have to look anything like the Conceptual level diagram that
describes that problem.
All the rest of the diagrams in this book will be at the Specification/Implementation
level, and will be accompanied by corresponding source code where feasible. We have
seen our last Conceptual level diagram.

Diagram Types
Below is a very quick tour of the primary diagrams used in UML. Once you read through
it, you will be able to read and write most of the UML diagrams you will usually need.
What remains, and what subsquent chapters address, are the details and formalisms that
you will need to become proficient in UML.
UML has three main kinds of diagrams. Static diagrams describe the unchanging logical structure of software elements by depicting classes, objects, and data structures; and
the relationships that exist between them. Dynamic diagrams show how software entities
change during execution by depicting the flow of execution, or the way entities change


3

Chapter : Overview of UML for Java Programmers

state. Physical diagrams show the unchanging physical structure of software entities by
depicting physical entities such as source files, libraries, binary files, data files, etc., and
the relationships that exist between them.
Consider the code in Listing 1-1. This program implements a map based upon a simple binary tree algorithm. Familiarize yourself with the code before you consider the diagrams that follow.
Listing 1-1
TreeMap.java

public class TreeMap {
TreeMapNode topNode = null;
public void add(Comparable key, Object value) {
if (topNode == null)
topNode = new TreeMapNode(key, value);
else
topNode.add(key, value);
}
public Object get(Comparable key) {
return topNode == null ? null : topNode.find(key);
}
}
class TreeMapNode {
private final static int LESS = 0;
private final static int GREATER = 1;
private Comparable itsKey;
private Object itsValue;
private TreeMapNode nodes[] = new TreeMapNode[2];
public TreeMapNode(Comparable key, Object value) {
itsKey = key;
itsValue = value;
}
public Object find(Comparable key) {
if (key.compareTo(itsKey) == 0) return itsValue;
return findSubNodeForKey(selectSubNode(key), key);
}
private int selectSubNode(Comparable key) {
return (key.compareTo(itsKey) < 0) ? LESS : GREATER;
}
private Object findSubNodeForKey(int node, Comparable key) {

return nodes[node] == null ? null : nodes[node].find(key);
}
public void add(Comparable key, Object value) {
if (key.compareTo(itsKey) == 0)
itsValue = value;
else
addSubNode(selectSubNode(key), key, value);
}


Diagram Types

4

Listing 1-1 (Continued)
TreeMap.java
private void addSubNode(int node, Comparable key,
Object value) {
if (nodes[node] == null)
nodes[node] = new TreeMapNode(key, value);
else
nodes[node].add(key, value);
}
}

Class Diagrams
The Class Diagram in Figure 1-2 shows the major classes and relationships in the
program. It shows that there is a TreeMap class that has public methods named add and
get. It shows that TreeMap holds a reference to a TreeMapNode in a variable named
topNode. It shows that each TreeMapNode holds a reference to two other TreeMapNode

instances in some kind of container named nodes. And it shows that each TreeMapNode
instance holds references to two other instances in variables named itsKey and
itsValue. The itsKey variable holds a reference to some instance that implements the
Comparable interface. The itsValue variable simply holds a reference to some object.

2
TreeMap
+ add(key, value)
+ get(key)

topNode

nodes

TreeMapNode
+ add(key, value)
+ find(key)
itsKey

«interface»
Comparable

itsValue
Object

Figure 1-2
Class Diagram of TreeMap
We’ll go over the nuances of class diagrams in a subsequent chapter. For now, there
are only a few things you need to know.



Rectangles represent classes, and arrows represent relationships.



In this diagram all the relationships are associations. Associations are simple
data relationships in which one object holds a reference to, and invokes methods


5

Chapter : Overview of UML for Java Programmers

upon, the other.


The name on an association maps to the name of the variable that holds the reference.



A number next to an arrowhead typically shows the number of instances held by
the relationship. If that number is greater than one then some kind of container,
usually an array, is implied.



Class icons can have more than one compartment. The top compartment always
holds the name of the class. The other compartments describe functions and variables.




The «interface» notation means that Comparable is an interface.



Most of the notations shown are optional.

Look carefully at this diagram and relate it to the code in Listing 1-1. Notice how the
association relationships correspond to instance variables. For example, the association
from TreeMap to TreeMapNode is named topNode and corresponds to the topNode
variable within TreeMap.

Object Diagrams
Figure 1-3 is an Object Diagram. It shows a set of objects and relationships at a particular moment in the execution of the system. You can view it as a snapshot of memory.

:TreeMap

topNode
:TreeMapNode
- itsKey = "Martin"

nodes[LESS]

nodes[GREATER]

:TreeMapNode
- itsKey = "Bob"

nodes[LESS]


:TreeMapNode
- itsKey = "Robin"

nodes[GREATER]

nodes[LESS]

nodes[GREATER]

:TreeMapNode

:TreeMapNode

:TreeMapNode

:TreeMapNode

- itsKey = "Alan"

- itsKey = "Don"

- itsKey = "Paul"

- itsKey = "Sam"

Figure 1-3
TreeMap Object Diagram


Diagram Types


6

In this diagram the rectangle icons represent objects. You can tell that they are objects
because their names are underlined. The the name after the colon is the name of the class
that the object belongs to. Note that the lower compartment of each object shows the value
of that object’s itsKey variable.
The relationships between the objects are called links, and are derived from the associations in Figure 1-3. Note that the links are named for the two array cells in the nodes
array.

Sequence Diagrams
Figure 1-4 is a Sequence Diagram. It describes how the TreeMap.add method is implemented.

:TreeMap
add(key, value)
value

key

[topNode == null]

topNode:
TreeMapNode

add(key, value)
[topNode != null]

Figure 1-4
TreeMap.add
The stick figure represents an unknown caller. This caller invokes the add method on

a TreeMap object. If the topNode variable is null, then TreeMap responds by creating a
new TreeMapNode and assigning it to topNode. Otherwise the TreeMap sends the add
message to topNode.
The boolean expressions inside square brackets are called guards. They show which
path is taken. The message arrow that terminates on the TreeMapNode icon represents
construction. The little arrows with circles are called data tokens. In this case they depict
the construction arguments. The skinny rectangle below TreeMap is called an activation.
It depicts how much time the add method executes.

Collaboration Diagrams
The diagram in Figure 1-5 is a Collaboration Diagram depicting the case of
TreeMap.add where treeNode is not null. Collaboration diagrams contain the same
information that sequence diagrams contain. However whereas sequence diagrams make
the order of the messages clear, collaboration diagrams make the relationships between the
objects clear.


7

Chapter : Overview of UML for Java Programmers

1: add(key, value)
:TreeMap

[topNode != null]
1.1:add(key, value)
topNode
:TreeMapNode

Figure 1-5

Collaboration Diagram of one case of TreeMap.add
The objects are connected by relationships called links. A link exists wherever one
object can send a message to another. Traveling over those links are the messages themselves. They are depicted as the smaller arrows. The messages are labeled with the name
of the message, its sequence number, and any guards that apply.
The dot structure of the sequence number shows the calling hierarchy. The
TreeMap.add function (message 1) invokes the TreeMapNode.add function (message

1.1). Thus message 1.1 is the first message sent by the function invoked by message 1.

State Diagrams
UML has a very comprehensive notation for finite state machines. Figure 1-6 shows just
the barest subset of that notation.

coin / Unlock
pass / Alarm

Locked

Unlocked

coin / Thankyou

pass / Lock

Figure 1-6
State Machine of a Subway Turnstile
Figure 1-6 shows the state machine for a subway turnstile. There are two states
named Locked and Unlocked. Two events may be sent to the machine. The coin event
means that the user has dropped a coin into the turnstyle. The pass event means that the
user has passed through the turnstile.

The arrows are called transitions. They are labeled with the the event that triggers the
transition, and the action that the transition performs. When a transition is triggered it
causes the state of the system to change.


Conclusion

8

We can translate Figure 1-6 to english as follows:


If we are in the Locked state, and we get a coin event, then we transition to the
Unlocked state and we invoke the Unlock function.



If we are in the Unlocked state and we get a pass event then we transition to the
Locked state and we invoke the Lock function.



If we are in the Unlocked state and we get a coin event, then we stay in the
Unlocked state and we call the Thankyou function.

If we are in the Locked state and we get a pass event then we stay in the
Locked state and we call the Alarm function.
Diagrams like this are extremely useful for figuring out the way a system behaves.
They give us the opportunity to explore what the system should do in unexpected cases,
like when a user drops a coin, and then drops another coin for no good reason.



Conclusion
The diagrams shown in this chapter are enough for most purposes. Most programmers
could live without any more knowledge of UML that what is shown here.

Bibliography
[Fowler00]: UML Distilled, 2d. ed. Martin Fowler, Addison Wesley, 199?


________________________

2

________________________
Working with Diagrams
“Before we explore the details of UML, it would be wise to talk about when and why we
use it. Much harm has been done to software projects through the misuse and overuse of
UML.

Why Model?
Why do engineers build models? Why do aerospace engineers build models of aircraft?
Why do structural engineers build models of bridges? What purposes do these models
serve?
These engineers build models to find out if their designs will work. Aerospace engineers build models of aircraft and then put them into wind tunnels to see if they will fly.
Structural engineers build models of bridges to see if they will stand. Architects build
models of buildings to see if their clients will like the way they look. Models are built to
find out if something will work.
This implies that models must be testable. It does no good to build a model if there are
no criteria you can apply to that model in order to test it. If you can’t evaluate the model,

the model has no value.
Why don’t aerospace engineers just build the plane and try to fly it? Why don’t structural engineers just build the bridge and then see if it stands? Because airplanes and
bridges are a lot more expensive than the models. We investigate designs with models
when the models are much cheaper than the real thing we are building.

9


Making Effective use of UML

10

Why build models of software?
Can a UML diagram be tested? Is it much cheaper to create and test than the software it
represents? In both cases the answer is nowhere near as clear as it is for aerospace engineers and structural engineers. There are no firm criteria for testing a UML diagram. We
can look at it, and evaluate it, and apply principles and patterns to it; but in the end the
evaluation is still very subjective. UML diagrams are less expensive to draw than software
is to write; but not by a huge factor. Indeed, there are times when it’s easier to change
source code than it is to change a diagram. So then, does it make sense to use UML?
I wouldn’t be writing this book if UML didn’t make sense to use. However, the above
illustrates just how easy UML is to misuse. We make use of UML when we have something
definitive we need to test, and when using UML to test it is cheaper than using code to test
it.
For example, lets say I have an idea for a certain design. I need to test whether the
other developers on my team think it is a good idea. So I write a UML diagram on the
whiteboard and ask my teammates for their feedback.

Why should we build comprehensive designs before coding?
Architects, aerospace engineers, and structural engineers all draw blueprints. Why?
Because one person can draw the blueprints for a home that will require five or more people to build. A few dozen aerospace engineers can draw blueprints for an airplane that will

require thousands of people to build. Blueprints can be drawn without digging foundations, pouring concrete, or hanging windows. In short, it is much cheaper to plan a building up front, than it is to try to build it without a plan. It doesn’t cost much to throw away
a faulty blueprint, but it costs a lot to tear down a faulty building.
Once again things are not so clear cut in software. It is not at all clear that drawing
UML diagrams is much cheaper than writing code. Indeed, many project teams have spent
more on their diagrams than they have on the code itself. It is also not clear that throwing
away a diagram is much cheaper than throwing away code. Therefore, it is not at all clear
that creating a comprehensive UML design before writing code is a cost effective option.

Making Effective use of UML
Apparently neither architecture, nor aerospace engineering, nor structural engineering provide a clear metaphor for software development. We cannot blithely use UML the way
those other disciplines use blueprints and models. So when and why should we use UML?


11

Chapter 2: Working with Diagrams

Communicating with Others.
UML is enormously convenient for communicating design concepts between software
developers. A lot can be done with a small group of developers at a whiteboard. If you
have some ideas that you need to communicate to others, UML can be a big benefit.
UML is very good for communicating focussed design ideas. For example, the diagram in Figure 2-1 is very clear. We see the LoginServlet implementing the Servlet
interface and using the UserDatabase. Apparently the classes HTTPRequest and
HTTPResponse are needed by the LoginServlet. One could easily imagine a group of
developers standing around a whiteboard debating a diagram like this. Indeed, the diagram
makes it very clear what the code structure would look like.

«interface»
Servlet


HTTPRequest

HTTPResponse
User
Database
+ getUser()

Login
Servlet
+ processRequest()

Figure 2-1
Login Servlet
On the other hand, UML is not particularly good for communicating algorithmic
detail. Consider the simple bubble sort code in Listing 2-1. Expressing this simple module
in UML is not very satisfying..
Listing 2-1
Bubble Sort
public class BubbleSorter
{
static int operations = 0;
public static int sort(int [] array)
{
operations = 0;
if (array.length <= 1)
return operations;
for (int nextToLast = array.length-2;
nextToLast >= 0; nextToLast--)
for (int index = 0; index <= nextToLast; index++)
compareAndSwap(array, index);

return operations;
}


Making Effective use of UML

12

Listing 2-1 (Continued)
Bubble Sort
private static void swap(int[] array, int index)
{
int temp = array[index];
array[index] = array[index+1];
array[index+1] = temp;
}
private static void compareAndSwap(int[] array, int index)
{
if (array[index] > array[index+1])
swap(array, index);
operations++;
}
}

The diagram in Figure 2-2 gives us a rough structure, but is combersome and reflects
none of the interesting details. The diagram in Figure 2-3 is no eaiser to read than the code
and is substantially more difficult to create. UML for these purposes leaves much to be
desired.

BubbleSorter

+ sort(array: int[]) : int
- swap(array : int[], index : int)
- compareAndSwap(array : int[], index : int)

Figure 2-2
Bubble Sorter

BubbleSorter

sort

compareAndSwap(array, index)
for (int index = 0; index <= nextToLast; index++)
for (int nextToLast = array.length-2; nextToLast >= 0; nextToLast--)

Figure 2-3
Bubble Sort Sequence Diagram


13

Chapter 2: Working with Diagrams

UML can be useful for creating roadmaps of large software structures. Such roadmaps give developers a quick way to find out which classes depend upon which others and
provide a reference to the structure of the whole system.
For example, in Figure 2-4 it is easy to see that Space objects have a Polyline constructed of many Lines which are derived from LinearObject which contains two
Points. Finding this structure in code would be tedious. Finding it in a roadmap diagram
is trivial.

Geometric

Object

itsOutline
PolyLine
Point

Authored
Space

Space

LinearObject
2

2

*
Portal
Ray

InfiniteLine

Line

Human
Portal

Door

Window


WallOpening

Figure 2-4
Roadmap
Such roadmaps can be useful teaching tools. However, any team member ought to be
able to throw such a diagram up on the whiteboard at a moments notice. Indeed, I drew the
one above from my memory of a system I was working on five years ago. Such diagrams
capture the knowledge that all the developers must keep in their heads in order to work
effectively in the system. So, for the most part, there is not much point is going to a lot of
trouble to create and archive such documents. Their best use is, once again, at the whiteboard.

Back end Documentation
When is the best time to create a design document? At the end of the project as the last act
of the team. Such a document will accurately reflect the state of the design as the team left
it, and could certainly be useful to an incomming team.


Making Effective use of UML

14

However, there are some pitfalls. UML diagrams need to be carefully considered. We
don’t want a thousand pages of sequence diagrams! Rather, we want a few very salient
diagrams that describe the major issues in the system. No UML diagram is worse than one
that is cluttered with so many lines and boxes that you get lost in the tangle (See Figure 25). Don’t do this.

fravitz

fradle


fivvle

gazatch

parnangle

gabaduchi

goassach

turnatls

tolanomatine
gilmaso
coriadon
Kobe
teliadora

dorasifus

bisotias

Sobe

castigamator

quidatle

Kaastor


zelsofus
sagatock
freedle

meek

denar

garmatos
Gorsage

Gossage

Figure 2-5

What to keep, and What to throw away.
Get into the habit of throwing UML diagrams away. Better yet, get into the habit of not
creating them on a persistent medium. Write them on a whiteboard, or on scraps of paper.
Erase the whiteboard frequently, and throw the scraps of paper away. Don’t use a case tool
or a drawing program as a rule. There is a time and place for such tools, but most of your
UML should be short-lived.
Some diagrams, however, are useful to save. There are diagrams that express a common design solution in your system. There are diagrams that record complex protocols
that are hard to see in the code. There are diagrams that provide roadmaps for areas of the


×