You are on page 1of 90

UML 九大圖形工具功能表

UML 的 4+1 觀點
UML 的模型觀點,主要取決不同使用者是
用那種觀點來檢視系統的結果,以及每個觀點的
設計考量為何。

使用個案觀點 (use case view)


設計觀點 (design view)
程序觀點 (process view)
實作觀點 (implementation view)
部署觀點 (deployment view)
類別圖
物件圖 元件圖
設計觀點 實作觀點
循序圖
合作圖
使用個案觀點
使用案例圖

循序圖 合作圖 程序觀點 部署觀點


狀態圖 活動圖 部署圖
物件導向分析與設計及塑模工具
(續 8 )
• 使用個案觀點
– 由描述系統行為的使用個案組成,這些系統行
為是由使用者、系統分析師、測試者的觀點來
描述,並不實際描述軟體系統的組織。
• 設計觀點
– 由類別、介面與合作組成,這些是來自於描述
問題及其解決方法中之詞彙描述。這個觀點主
要支援系統的功能需求,表達系統應提供給使
用者之服務。
物件導向分析與設計及塑模工具
(續 9 )
• 流程觀點
– 由執行緒與流程所組成,這些是來自於系統的平行與
同步機制,這個觀點主要表達系統之績效、產出與可
擴充性。
• 實施觀點
– 由可以不同方式組裝實際可運作系統之獨立的元件與
檔案所組成,這個觀點主要表達系統版本的結構配置
管理。
• 部署觀點
– 由構成系統之硬體類型的節點所組成,這個觀點主要
表達組成實際系統之零件的分配、傳遞訊息與安裝。
UML 各個觀點 (view) 所定義的圖形、功能
觀點(view) 圖型(diagram) 功能及目的
使用個案觀點 使用案例圖 (Use case 描述系統功能性的需求,找出使用案例(use
(use case view) diagram) case)與行動者(actor) 並界定系統的範圍。
設計觀點 類別圖 (class diagram) 表示物件類型之間結構上的關聯。
(design view) 物件圖 (object diagram) 表示系統某一時間點的狀態(亦即 snapshot)
程序觀點 循序圖 (sequence diagram) 表示物件之間動態的溝通模式。
(process view) 合作圖 (collaboration
diagram)
狀態圖 (statechar diagram) 表示物件狀態的變化。
活動圖 (activity diagram) 表示業務流程或一類型中單一操作
(operation)的邏輯流程。
實作觀點 元件圖 (component 表示模組或元件之間的關聯。
(implementation diagram)
view)
部署觀點 佈署圖 (deployment 表示處理程序(process)或執行緒(thread)
(deployment view) diagram) 對應到主機(processor)或裝置(device)的
實際狀況。
UML 各個圖示的適用者

圖示類別 適用者
使用個案圖、活動圖 使用者、設計人員、發展人員、測
試人員
類別圖、狀態圖、循序圖、合作圖、活動圖 設計人員、發展人員
元件圖 發展人員
狀態圖、循序圖、合作圖、活動圖,元件圖、配 發展人員、整合人員
置圖
配置圖 發展人員、整合人員、測試人員
RUP 模式生命週期
階段、目標與里程碑
 初始階段
目標:
瞭解專案範圍 建立企業個案 取得有關人員對推展該專案的認同
里程碑:完成專案生命週期目標
 詳述階段
目標:
降低主要技術之風險 創造系統基本結構 瞭解用何資源以建構系統
里程碑:完成生命週期結構
 建構階段
目標:
建構與演化可運作的系統版本
里程碑:初步可運作的系統版本 (常稱為 β 版)
 轉移階段
目標:
建立最終版本的軟體系統,並移交給客戶
里程碑:完成軟體產品出版
使用案例圖 (Use Case Diagram)
何謂使用案例圖:
使用案例圖 (Use Case Diagram ) 主要是描述一個
系統或類別提供給外界之交互作用者的功能。簡單來說就是
說明一個系統的功能及其使用者。
Use-case modeling typically starts early in a project and
continues throughout a system development process.

Use cases are a technique for capturing the functional


requirements of a system. Use cases work by describing the
typical interactions between the users of a system and the system
itself, providing a narrative of how a system is used.
• A use-case diagram may be considered a "table
of contents" for the functional requirements of a
system.
• don't put too much effort into the diagram.
Instead, concentrate on the textual content of
the use cases.
• There is no standard way to write the content of
a use case, and different formats work well in
different cases.
• The use case diagram shows the actors,
the use cases, and the relationships
between them:
• Which actors carry out which use cases
• Which use cases include other use cases
• Starting by describing scenarios
• The customer browses the catalog and adds
desired items to the shopping basket.
• When the customer wishes to pay, the customer
describes the shipping and credit card
information and confirms the sale.
• The system checks the authorization on the
credit card and confirms the sale both
immediately and with a follow-up e-mail.
• This scenario is one thing that can happen
.
• the credit card authorization might fail, and
this would be a separate scenario.
• In another case, you may have a regular
customer for whom you don't need to
capture the shipping and credit card
information, and this is a third scenario.
Actor
• This user goal is the key to use cases
• Each use case has a primary actor, which calls
on the system to deliver a service.
• A use case is a set of scenarios tied together by
a common user goal.
• There may be other actors as well with which the
system communicates while carrying out the use
case. These are known as secondary actors.
• the users are referred to as actors
• An actor is a role that a user plays with
respect to the system
使用目的
Use Case 模型使用的主要目的是以外部及內部的
觀點來描述系統的功能性需求, Use Case 的在系統發
展中所扮演的角色如下:
定義系統的功能性需求
找尋物件
決定物件應有責任 (responsibility)
定義物件之間之互動 (interaction) 情形與其間的介面
設計使用者介面
執行整合測驗 (integration testing)
定義測試案例 (test cases)
決定軟體系統欲新增的功能
撰寫使用文件與使用手冊
使用個案圖的元素
圖示 意義
(1) 系統(system)

(2) 行為者(actor)

<<actor>>
name

(3) 使用個案(use case)

(4) 溝通/關連名稱c( ommunicates)


<<溝通/關連名稱>>
• Each step in a use case is an element of
the interaction between an actor and the
system .
• You begin by picking one of the scenarios
as the main success scenario.
• You then take the other scenarios and
write them as extensions, describing them
in terms of variations on the main success
scenario.
(1) 系統 (system) :以矩形表示所要開發的系統

(2) 行為者 (actor) :


用來表示系統使用者、系統、組織及任何與系統發生
關聯的實體,也有可能是資料的輸出入者。我們可以
根據以下的幾個原則來判斷出系統的行為者。
•此系統的使用者或是操作者是誰 ( 主要的 actor)?
•這個系統所使用的外在資源 ?
•由誰會管理及維護這個系統 ( 次要的 actor)?
•資源或是資訊是否來自其它組織或是其它系統 ?
•系統的發展目的為?主要用在什麼地方?
•誰需要系統所產生的資訊?
(3) 使用個案 (use case)
• Use Case 是一個從開始一直到結束來描述完整的系統過程,它
可以描述 actor 與系統的互動關係。 UML 是基於各種使用個案
結需求模型一種概念性的集合。
• 如何找出系統的 Use Case ,我們根據以下的幾個原則來判斷
出系統相關的 Use Case :
行為者的工作是什麼 ?
系統所須具備的功能是什麼 ?
那些 Use Case 會支援及維護這個系統 ?
系統發生任何狀況會通知行為者嗎 ?
行為者會通知系統任何可能狀況嗎 ?
• in the scenarios, you can add some other
common information to a use case.
• A pre-condition describes what the system
should ensure is true before the system allows
the use case to begin.
• A guarantee describes what the system will
ensure at the end of the use case. Success
guarantees hold after a successful scenario;
minimal guarantees hold after any scenario.
• A trigger specifies the event that gets the use
case started
Levels of Use Cases
• a system use case is an interaction with the
software, whereas a business use case
discusses how a business responds to a
customer or an event.
• Sea-level use cases typically represent a
discrete interaction between a primary actor and
the system.
• Fish level -> sea level -> kite level
• Kite-level use cases are usually business use
cases, whereas sea and fish levels are system
use cases. You should have most of your use
cases at the sea level
(4) 溝通 / 關連名稱 (communicates) :

• 溝通 / 關連名稱 (communicates) 代表了行


為者與系統使用個案之間的關聯。
• 表示行為者使用或參與 Use Case 所提供的
功能。
使用個案範例 - 訂書系統
訂書系統

客戶基本資料管理

訂單處理

送貨處理
書店
業務員

顧客 存貨管理
When to Use Use Cases
• A first pass at use cases should be made
early on. More detailed versions of use
cases should be worked just prior to
developing that use case.
Class Diagram

– 何謂類別圖:
類別圖是模型建構技術的重要核心,用來描述一個系統
的靜態結構以及存在類別之間各樣的靜態關係 (static
relationships) 。
– 使用目的
主要是用來將一群有相同特質的概念或實體模組化。
類別圖的主要元素

圖示 意義
(1) 類別(class)

(2) 結合關係
(associations)

(3) 角色(Role)
角色

(4) 限制條件(constraint)
{限制條件}
(5) 修飾詞 修飾詞(qualifier)

(6) 反射(Reflexive)

(7) 繼承關係(Inheritance)

(8) 組合關係c
( omposition)
可改變的組合
不可改變的組合
類別
– 類別的涵意就是將物件經過分類或是抽像化的結果
,剔除物件間的差異只考慮相同的特性。
– 每個類別都有其屬性和其所產生的操作或稱方法。
– 我們把具有共同性質的物件集合稱作類別 (class) ,
並且為每一類別取一個適當的名字。
– 物件被稱作它們所屬別的實例 (instance) 。從某種
觀點來看,其實類別也是一個具有標識的實體,也
是物件的一種。
– 例如,人就是一種類別,屬性有姓名、年齡、身高
、體重…所產生的動作有 、看書、吃飯…。
類別的表示方法
名稱 (name)

屬性 (attribute)

操作方法
(operation)

其它…
Attributes

• The attribute notation describes a property


as a line of text within the class box itself
• visibility name: type multiplicity = default
{property-string}
• - name: String [1] = "Untitled" {readOnly}
• Only the name is necessary.
• This visibility marker indicates whether the
attribute is public (+) or private (-);
Attributes
• The type of the attribute indicates a restriction on
what kind of object may be placed in the
attribute. (String, Money, Boolean)
• The default value is the value for a newly
created object if the attribute isn't specified
during creation.
• multiplicity
• The {property-string} allows you to indicate
additional properties for the attribute. {read-only}
• Figure 3.2. Showing properties of an
order as attributes

材料清單類別
類別名稱 材料清單
材料編號
材料名稱
材料規格
類別屬 數量
性 價格

新增()
刪除()
修改()
類別操作 列印()
Associations

• 結合表示類別與類別之間的關聯及彼此
有結構上的關係。
• An association is a solid line between two
classes, directed from the source class to the
target class
• The name of the property goes at the target
end of the association, together with its
multiplicity
• The target end of the association links to the
Bidirectional Associations
• A bidirectional association is a pair of properties
that are linked together as inverses
• Car class has property owner:Person[1], and the
Person class has a property cars:Car[*].
• The inverse link between them implies that if you
follow both properties, you should get back to a
set that contains your starting point.
• like to label an association by using a verb
phrase (Figure 3.5)
Association

• Association is an arbitrary relationship between two


classes

• Example: A radiologist may consult a lawyer regarding the


interpretation of a contract

– The solid triangle points from the radiologist to


Association
• Example: A lawyer with a broken leg consults a
radiologist
– The solid triangle points in the other direction

• Using the solid triangle in this way is called navigation in


UML
(Multiplicity 或 Cardinality)
用來表示一個類別的實例可以對映另一類
別的實例個數。下表是各種維度的表示方式。
符號 意義
* 多個
1 唯一、只有一個
0..* 零個以上
1..* 一個以上
0..1 零或一個
N..M N~M 個

範例:一個教師可教導 1 到多個學生,一個學生可以被 1 到多個老師


教導。如下圖所示:

教師 1..* *..1 學生
單項關係
若要強調類別之間的關係是單項的 ,則可以箭頭來表示 。範例如下

範例:客戶填寫訂單 ,如下圖 所示:

顧客 訂單

姓名 * 1 訂單編號
性別 價格
信用狀況 發送 ( )
• Optional implies a lower bound of 0.
• Mandatory implies a lower bound of 1 or
possibly more.
• Single-valued implies an upper bound of
1.
• Multivalued implies an upper bound of
more than 1: usually *.
• If the ordering of the orders in association
has meaning, you need to add {ordered}
to the association end.
• If you want to allow duplicates, add
{nonunique}.
• (If you want to explicitly show the default,
you can use {unordered} and {unique}.)
Operations
• Operations are the actions that a class
knows to carry out .
• Operations most obviously correspond to
the methods on a class.
• Normally, you don't show those operations
that simply manipulate properties,
because they can usually be inferred.
• visibility name (parameter-list) : return-type {property-
string} .
• This visibility marker is public (+) or private (-); protected
(#), package(~).
• The name is a string.
• The parameter-list is the list of parameters for the
operation.
• The return-type is the type of the returned value, if there
is one.
• The property-string indicates property values that apply
to the given operation
• The parameters in the parameter list are notated
in a similar way to attributes. The form is:
• direction name: type = default value
• The name, type, and default value are the same
as for attributes.
• The direction indicates whether the parameter is
input (in), output (out) or both (inout). If no
direction is shown, it's assumed to be in.
• An example operation on account might be:
+ balanceOn (date: Date) : Money
• UML defines a query as an operation that gets a
value from a class without changing the system
state.
• You can mark such an operation with the
property string {query}.
• I refer to operations that do change state as
modifiers, also called commands.
• A getting method returns a value from a field.
• A setting method puts a value into a field.
• An operation is something that is invoked on an
object—the procedure declaration—
• whereas a method is the body of a procedure.
• The two are different when you have
polymorphism.
• If you have a supertype with three subtypes,
each of which overrides the supertype's getPrice
operation, you have one operation and four
methods that implement it.
Generalization
• With a software perspective, the obvious
interpretation is inheritance .
Inheritance (contd)
• Credit Card Class and Debit Card Class
are both subclasses of class Bank Card
Class
Notes and Comments
• Notes are comments in the diagrams.
Notes can stand on their own, or they can
be linked with a dashed line to the
elements they are commenting (Figure 3.6
).
Example: Bank Account Class
• public operations deposit and withdraw can be
invoked from anywhere in the information
system
Dependency
• A dependency exists between two elements if
changes to the definition of one element (the
supplier) may cause changes to the other (the
client).
• A dependency is shown as a dashed-line path
from the source element to the target element
• Many UML relationships imply a dependency.
The navigable association from Order to
Customer in Figure 3.1 means that Order is
dependent on Customer. A subclass is
dependent on its superclass but not vice versa.
• Your general rule should be to minimize
dependencies.
• eliminate cycles at a broader level, particularly
between packages.
• Be selective and show dependencies only when
they are directly relevant to the particular topic
that you want to communicate. To understand
and control dependencies, you are best off using
them with package diagrams
• KeywordMeaning
• «call»The source calls an operation in the target.
• «create»The source creates instances of the target.
• «derive»The source is derived from the target.
• «instantiate»The source is an instance of the target. (Note that if the source is a
class, the class itself is an instance of the class class; that is, the target class is a
metaclass).
• «permit»The target allows the source to access the target's private features.
• «realize»The source is an implementation of a specification or interface defined by
the target (page 69).
• «refine»Refinement indicates a relationship between different semantic levels; for
example, the source might be a design class and the target the corresponding
analysis class.
• «substitute»The source is substitutable for the target (page 45).
• «trace»Used to track such things as requirements to classes or how changes in one
model link to changes elsewhere.
• «use»The source requires the target for its implementation.
限制條件 (Constraint)
表示類別之間的關係中存在條件,在 UML 中以 { 條件 } 表示。

班級中可以有許多學生,學生是班級中的成員。
在班級中是以學號來排列學生的次序。一個班級中只有一個班長,
而這個班長也是班上的期中一個學生。如下圖所示:

班級成員

1..* 1
ordered
{ by student ID}
{subset}

學生 班級
1 班長 1
角色 (Role)
角色是用來表示類別與類別之間關係所扮演的角色。例如在家庭父妻關係
中男主人的角色是老公,家庭的女主人角色是老婆,孩子與女主人的母子關係
中 ,角色分別是為兒子與媽媽 。孩子與男主人的父子關係中,角色分別是為兒
子與爸爸。如下圖所示 :

老公 老婆
男主人 女主人

爸爸 媽媽

兒子 兒子
小孩
反射 (Reflexive)
相同類別物件之間的關係,例如教師必須實習教學課程後才成為正式
的教師。如下圖所示:

教師 實習教學
組合 / 彙總 (aggregation)
組合關係表示物件與物件之間擁有部分 (part-
of) 和被包含於 (contained) 的關係,表示某物件
是由其它若干個物件組合而成,所以合成又稱『組
合』或『集結化』,組合關係是屬於結合關係的一
種特殊。在 UML 中以空心的菱形表示可改變的組合
;以實心的菱形表示不可改變的組合。
Aggregation
• Example: A car is constructed from a
chassis, engine, wheels, and seats
可改變的組合
公車是由司機與乘客所組成,司機是公車的一部分。
公車若沒了司機或乘客,還是公車,所以公車與司機、
公車與乘客之間的關係是可改變的。如下圖所示:

1 1 司機
公車 1 0..*
乘客
Composition

汔車是由 4 個車輪所組成,車輪是汔車的一部分。
汔車若沒了車輪,就不是汔車,可能要改名為”三
輪車”了。所以汔車與車輪之間的關係是不可改變
的。如下圖所示:

汔車 車輪
1
4
When to Use Class Diagrams
• Don't try to use all the notations available to you.
Start with the simple stuff in this chapter:
classes, associations, attributes, generalization,
and constraints
• Don't draw models for everything; instead,
concentrate on the key areas. It is better to have
a few diagrams that you use and keep up to date
than to have many forgotten, obsolete models.
Overview
• Object design is situated between system
design and implementation.

• Object design is not very well understood


and if not well done, leads to a bad
system implementation.
Object Design Activities
• Developers perform transformations to the object model
to improve its modularity and performance.
• Developers transform the associations of the object
model into collections of object references, because
programming languages do not support the concept of
association.
• If the programming language does not support contracts,
the developer needs to write code for detecting and
handling contract violations.
• Developers often revise the interface specification to
accommodate new requirements from the client.
• All these activities are intellectually not challenging
– However, they have a repetitive and mechanical flavor that
makes them error prone.
Object Design Activities
• The Vision
– During object design we would like to implement a system that
realizes the use cases specified during requirements elicitation
and system design.
• The Reality
– Different developers usually handle contract violations
differently.
– Undocumented parameters are often added to the API to
address a requirement change.
– Additional attributes are usually added to the object model, but
are not handled by the persistent data management system,
possibly because of a miscommunication.
– Many improvised code changes and workarounds that
eventually yield to the degradation of the system
Model Transformation Example
Object design model before transformation
LeagueOwner Advertiser Player
+email:Address +email:Address +email:Address

Object design
model after
transformation: User
+email:Address

LeagueOwner Advertiser Player


Refactoring Example: Pull Up Field
public class User {
private String email;
}
public class Player {
private String email; public class Player
extends User {
//...
//...
}
public class LeagueOwner }
{ public class LeagueOwner
private String eMail; extends User {
//... //...
} }
public class Advertiser {
private String public class Advertiser
email_address; extends User {
//... //...
} }
Example: Pull Up Constructor Body
public class User { public class User {
private String email; public User(String
} email) {
this.email = email;
}
public class Player }
extends User { public class Player
public Player(String extends User {
email) { public Player(String
this.email = email; email) {
} super(email);
} }
}
public class
LeagueOwner extends public class
User{ LeagueOwner extends
public User {
LeagueOwner(String public
email) { LeagueOwner(String
this.email = email; email) {
} super(email);
} }
}
public class Advertiser public class Advertiser
Forward Engineering Example
Object design model before transformation

User LeagueOwner
+email:String +maxNumLeagues:int
+notify(msg:String)

Source code after transformation


public class LeagueOwner
public class User { extends User {
private String email; private int
public String getEmail() { maxNumLeagues;
return email;
public int
}
getMaxNumLeagues() {
public void setEmail(String
value){ return
email = value; maxNumLeagues;
} }
public void notify(String msg) { public void
// .... setMaxNumLeagues
}
(int value) {
/* Other methods omitted */
maxNumLeagues =
Agenda
• Overview

• Optimizing the Object Design Model

• Mapping Associations

• Mapping Contracts to Exceptions

• Mapping Object Models to Tables


Collapsing Class Diagrams
Collapsing an object without interesting behavior
Object design model before transformation

Person SocialSecurity
number:String

Object design model


after transformation

Person
SSN:String
Delaying expensive computations
Object design model before transformation

Image
filename:String
data:byte[]
paint()

Object design model


after transformation Image
filename:String
paint()

image
ImageProxy RealImage
1 0..1
filename:String data:byte[]
paint() paint()
Agenda
• Overview

• Optimizing the Object Design Model

• Mapping Associations

• Mapping Contracts to Exceptions

• Mapping Object Models to Tables


Mapping a one-to-one association
Object design model before transformation
1 1
Advertiser Account

Source code after


transformation
public class Advertiser {
private Account account;
public Advertiser() {
account = new Account();
}
public Account getAccount() {
return account;
}
}
Bidirectional one-to-one association
Object design model before transformation

Advertiser 1 1
Account

Source code after


transformation
public class Advertiser { public class Account {
/* The account field is /* The owner field is
initialized initialized
* in the constructor and * during the constructor
never and
* never modified. */
* modified. */
private Advertiser owner;
private Account account;
public
public Advertiser() { Account(owner:Advertiser)
account = new {
Account(this); this.owner = owner;
} }
public Advertiser
Bidirectional, one-to-many association
Object design model before transformation
1 *
Advertiser Account

Source code after


transformation
public class Account {
public class Advertiser { private Advertiser owner;
private Set accounts; public void setOwner(Advertise
public Advertiser() { newOwner) {
accounts = new if (owner != newOwner) {
HashSet(); Advertiser old = owner;
} owner = newOwner;
public void if (newOwner != null)
addAccount(Account a) {
accounts.add(a); newOwner.addAccount(this);
a.setOwner(this); if (oldOwner != null)
}
public void old.removeAccount(this);
removeAccount(Account a) { }
accounts.remove(a); }
a.setOwner(null);
Bidirectional, many-to-many association
Object design model before transformation
* {ordered} *
Tournament Player

Source code after


transformation
public class Tournament { public class Player {
private List players; private List tournaments;
public Tournament() { public Player() {
players = new tournaments = new
ArrayList(); ArrayList();
} }
public void public void
addPlayer(Player p) { addTournament(Tournament t)
if (!players.contains(p)){
{ if
players.add(p); (!tournaments.contains(t)) {
tournaments.add(t);
p.addTournament(this); t.addPlayer(this);
} }
} }
Bidirectional qualified association
Object design model before transformation

* *
League Player
nickName

Object design model before


forward engineering
0..1
League nickName * Player

Source code after forward engineering


Bidirectional qualified association
Source code after forward engineering

public class Player {


public class League {
private Map leagues;
private Map players;

public void addLeague


public void addPlayer
(String nickName, (String nickName, League l)
Player p) { {
if if (!leagues.containsKey(l))
(!players.containsKey(nick {
Name)) { leagues.put(l,
nickName);
players.put(nickName, p);
l.addPlayer(nickName, this);
p.addLeague(nickName, }
this); }
} }
}
Transformation of an association class
Object design model before transformation

Statistics

+getAverageStat(name)
+getTotalStat(name)
+updateStats(match)

Tournament Player
* *

Object design model after


transformation: 1 class and
two binary associations Statistics

+getAverageStat(name)
+getTotalStat(name)
+updateStats(match)
1 1
Tournament Player
* *
Agenda
• Overview

• Optimizing the Object Design Model

• Mapping Associations

• Mapping Contracts to Exceptions

• Mapping Object Models to Tables


Exceptions and contract
violations
• Many object-oriented languages, including Java do not include built-
in support for contracts.
• However, we can use their exception mechanisms as building blocks
for signaling and handling contract violations
• In Java we use the try-throw-catch mechanism
• Example:
– Let us assume the acceptPlayer() operation of
TournamentControl is invoked with a player who is already part
of the Tournament.
– In this case acceptPlayer() should throw an exception of type
KnownPlayer.
– See source code on next slide
The try-throw-catch Mechanism in Java
public class TournamentControl {
private Tournament tournament;
public void addPlayer(Player p) throws
KnownPlayerException {
if (tournament.isPlayerAccepted(p)) {
throw new KnownPlayerException(p);
}
//... Normal addPlayer behavior
}
}
public class TournamentForm {
private TournamentControl control;
private ArrayList players;
public void processPlayerApplications() { // Go through all
the players
for (Iteration i = players.iterator(); i.hasNext();) {
try { // Delegate to the control object.
control.acceptPlayer((Player)i.next());
} catch (KnownPlayerException e) {
// If an exception was caught, log it to the
console
ErrorConsole.log(e.getMessage());
}
}
Implementing a contract
For each operation in the contract, do the following
• Check precondition:
– Check the precondition before the beginning of the method with a test
that raises an exception if the precondition is false.
• Check postcondition:
– Check the postcondition at the end of the method and raise an exception
if the contract is violoated. If more than one postcondition is not satisfied,
raise an exception only for the first violation.
• Check invariant:
– Check invariants at the same time as postconditions.
• Deal with inheritance:
– Encapsulate the checking code for preconditions and postconditions into
separate methods that can be called from subclasses.
Heuristics: Contracts and Exceptions
Be pragmatic, if you don’t have enough time.

• Omit checking code for postconditions and


invariants.

• Omit the checking code for private and protected


methods.

• Focus on components with the longest life

• Reuse constraint checking code.


Object Diagrams
• An object diagram is a snapshot of the
objects in a system at a point in time.
• Because it shows instances rather than
classes, an object diagram is often
called an instance diagram
UML Convention for Objects
• The name of an object is written in
– boldface underlined but all in lowercase letters
• Each name takes the form instance name : class
name.
• Both parts of the name are optional.
• If you use only the class name, you must
include the colon. You can show values for
attributes and links, as in Figure 6.2.
When to Use Object Diagrams
• Object diagrams are useful for showing
examples of objects connected together.
• In many situations, you can define a
structure precisely with a class diagram,
but the structure is still difficult to
understand.
• In these situations, a couple of object
diagram examples can make all the
difference.

You might also like