Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Software Design Principles and Guidelines
Douglas C. Schmidt
[email protected] University, St. Louiswww.cs.wustl.edu/�schmidt/
May 25, 2003
Design Principles
Design Principles and Guidelines Overview
NETWORK
STUBS
OS KERNEL
NETWORKINTERFACE
MESSAGE-PASSINGMIDDLEWARE
HOME
MIDDLEWARE SERVICES(SECURITY, EVENT NOTIFICATION, TRANSACTIONS, PERSISTENCE, LOAD BALANCING,
FAULT TOLERANCE, A/V STREAMING, DYNAMIC RESOURCE MANAGEMENT, SCHEDULING,NAMING, TRADING, LOGGING, ETC...)
CALLBACKS
CONTAINER
operation()
MIDDLEWAREINTERFACE
OBJECT ADAPTER
CLIENT
OS KERNEL
NETWORKINTERFACE
COMPONENT
EXECUTOR
SKELETONS
NETWORKPROTOCOLS
NETWORKPROTOCOLS
� Design Principles
– Important design concepts– Useful design principles
� Development Methodologies
– Traditional approaches– Agile programming
� Design Guidelines
– Motivation– Common Design Mistakes– Design Rules
1
Design Principles
Motivation: Goals of the Design Phase (1/2)
EVENTSERVER
SUPERVISOR
CCMStream
ACERUN-TIME
TELECOMSWITCHES
Session RouterModule
Event FilterModule
Switch AdapterModule
Event AnalyzerModule
SUPERVISOR SUPER
VISOR
MIB
� Decompose system intocomponents
– i.e., identify the softwarearchitecture
� Determine relationshipsbetween components
– e.g., identify componentdependencies
� Determine intercomponentcommunication mechanisms
– e.g., globals, function calls,shared memory, IPC/RPC
2
Design Principles
Motivation: Goals of the Design Phase (2/2)
UP
ST
RE
AM
DO
WN
ST
RE
AM
open()=0close()=0put()=0svc()=0
STREAMHead
STREAMTail
� Specify component interfaces
– Interfaces should be well-defined
� Facilitates component testingand team communication
� Describe component functionality
– e.g., informally or formally
� Identify opportunities for systematicreuse
– Both top-down and bottom-up
3
Design Principles
Macro Steps in the Design Process
� In the design process the orientation moves from
– Customer to developer– What to how
� Macro steps include:
1. Preliminary Design– External design describes the real-world model– Architectural design decomposes the requirement specification
into software subsystems2. Detailed Design
– Specify each subsystem– Further decomposed subsystems, if necessary
4 Des
ign
Prin
cipl
es
Mic
roS
teps
inth
eD
esig
nP
roce
ss
�
Giv
ena
requ
irem
ents
spec
,des
ign
isan
itera
tive
deci
sion
proc
ess
with
the
follo
win
gge
nera
lste
ps:
1.Li
stth
eha
rdde
cisi
ons
and
deci
sion
slik
ely
toch
ange
2.D
esig
na
com
pone
ntsp
ecifi
catio
nto
hide
each
such
deci
sion
–M
ake
deci
sion
sth
atap
ply
tow
hole
prog
ram
fam
ilyfir
st–
Mod
ular
ize
mos
tlik
ely
chan
ges
first
–T
hen
mod
ular
ize
rem
aini
ngdi
fficu
ltde
cisi
ons
and
deci
sion
slik
ely
toch
ange
–D
esig
nth
eus
eshi
erar
chy
asyo
udo
this
(incl
ude
reus
ede
cisi
ons)
3.Tr
eate
ach
high
er-le
velc
ompo
nent
asa
spec
ifica
tion
and
appl
yab
ove
proc
ess
toea
ch4.
Con
tinue
refin
ing
until
alld
esig
nde
cisi
ons
are:
–hi
dden
ina
com
pone
nt–
cont
ain
easi
lyco
mpr
ehen
sibl
eco
mpo
nent
s–
prov
ide
indi
vidu
al,i
ndep
ende
nt,l
ow-le
vel
impl
emen
tatio
nas
sign
men
ts
5
Design Principles
Example: Designing a Web ServerWWWWWW
SERVERSERVER2: index.html2: index.html
1: GET ~schmidt1: GET ~schmidt
HTTP/1.0HTTP/1.0
COMMUNICATION PROTOCOLCOMMUNICATION PROTOCOL
((EE..GG.,., HTTP HTTP))
GUIGUI
HTMLHTMLPARSERPARSER
REQUESTERREQUESTER
GRAPHICSGRAPHICSADAPTERADAPTER
NETWORK
OS KERNEL
OS I/O SUBSYSTEM
NETWORK ADAPTERS
OS KERNEL
OS I/O SUBSYSTEM
NETWORK ADAPTERS
DISPATCHER
PROTOCOL
HANDLERS
WWW
CLIENTCLIENT
www.cs.wustl.edu/˜jxh/research/
� Web server designdecisions
– Portability issues– I/O demuxing and
concurrency– HTTP protocol
processing– File access
� Web servercomponents
– Event dispatcher– Protocol handler– Cached virtual
filesystem
6
Design Principles
Key Design Concepts and Principles
Key design concepts and designprinciples include:
1. Decomposition
2. Abstraction and information hiding
3. Component modularity
4. Extensibility
5. Virtual machine architectures
6. Hierarchical relationships
7. Program families and subsets
Main goal of theseconcepts and principles isto:
� Manage softwaresystem complexity
� Improve software qualityfactors
� Facilitate systematicreuse
� Resolve common designchallenges
7
Design Principles
Challenge 1: Determining the Web Server Architecture
� Context: A large and complex production web server
� Problems:
– Designing the web server as a large monolithic entity is tediousand error-prone
– Web server developers must work concurrently to improveproductivity
– Portability and resuability are important quality factors
8
Design Principles
Solution: Decomposition
� Decomposition handles complexity by splitting large problems intosmaller problems
� This “divide and conquer” concept is common to all life-cycleprocesses and design techniques
� Basic methodology:
1. Select a piece of the problem (initially, the whole problem)2. Determine the components in this piece using a design paradigm,
e.g., functional, structured, object-oriented, generic, etc.3. Describe the components interactions4. Repeat steps 1 through 3 until some termination criteria is met
– e.g., customer is satisfied, run out of time/money, etc. ;-)
9
Design Principles
Decomposition Example: Web Server Framework
Pipes and filters
Component confi gu rator
Com
po
nent
co
nfig
ura
tor
~
/home/...Protocolhandler
Protocolfilter
Protocol pipelineframework
Concurrencystrategyframework
Tildeexpander
Cached virtualfilesystem
I/O strategyframework
Adapter
Active object Strate gy
Sta
te
Acc
eptor
Asynchronous com pleti on token
Mem
ento
Reactor/Proactor Strate gy Singleton
Sta
te
Event dispatcher
� Features
– High-performance– Flexible concurrency,
demuxing, and cachingmechanisms
– Uses frameworks basedon ACE
www.cs.wustl.edu/�schmidt/PDF/JAWS.pdf
10
Design Principles
Object-Oriented Decomposition Principles
1. Don’t design components to correspond to execution steps
� Since design decisions usually transcend execution time
2. Decompose so as to limit the effect of any one design decision onthe rest of the system
� Anything that permeates the system will be expensive to change
3. Components should be specified by all information needed to usethe component
� and nothing more!
11
Design Principles
Challenge 2: Implementing a Flexible Web Server
� Context: The requirements that a production web server must meetwill change over time, e.g.:
– New platforms– New compilers– New functionality– New performance goals
� Problems:
– If the web server is “hard coded” using low-level system calls it willbe hard to port
– If web server developers write software that’s tightly coupled withinternal implementation details the software will be hard to evolve
12
Design Principles
Solution: Abstraction
IMPLEMENTATIONIMPLEMENTATION
ESSENTIAL
CHARACTERISTICS
UNESSENTIAL
DETAILS
INTERFACEINTERFACE
� Abstraction manages complexityby emphasizing essentialcharacteristics and suppressingimplementation details
� Allows postponement of certaindesign decisions that occur atvarious levels of analysis, e.g.,
– Representational andalgorithmic considerations
– Architectural and structuralconsiderations
– External environment andplatform considerations
13
Des
ign
Prin
cipl
es
Com
mon
Type
sof
Abs
trac
tion
1.P
roce
dura
labs
trac
tion
�
e.g.
,clo
sed
subr
outin
es
2.D
ata
abst
ract
ion
�
e.g.
,AD
Tcl
asse
san
dco
mpo
nent
mod
els
3.C
ontr
olab
stra
ctio
n
�
e.g.
,loo
ps,i
tera
tors
,fra
mew
orks
,and
mul
titas
king
ACEStreams
AC
E R
eact
or
EV
EN
T
LO
OP
EV
EN
T
LO
OP
APPLIC
ATIO
N-
SPE
CIF
IC E
VE
NT H
AN
DLE
R
FU
NC
TIO
NA
LIT
Y
CA
LL
BA
CK
SLO
CA
L
INV
OC
AT
ION
S
IPC
CLA
SS
ES
AD
TC
LA
SS
ES
AC
E T
ask
EV
EN
T
LO
OP
CA
LLB
AC
KS
CA
LLB
AC
KS
14Design Principles
Information Hiding� Information hiding is an important means of achieving abstraction
– i.e., design decisions that are subject to change should be hiddenbehind abstract interfaces
� Application software should communicate only through well-definedinterfaces
� Each interface should be specified by as little information as possible
� If internal details change, clients should be minimally affected
– May not even require recompilation and relinking...
15
Design Principles
Typical Information to be Hidden
� Data representations
– i.e., using abstractdata types
� Algorithms
– e.g., sorting orsearching techniques
� Input and OutputFormats
– Machinedependencies, e.g.,byte-ordering,character codes
� Lower-level interfaces
– e.g., ordering of low-level operations,i.e., process sequence
� Separating policy and mechanism
– Multiple policies can be implementedby same mechanisms
� e.g., OS scheduling and virtualmemory paging
– Same policy can be implemented bymultiple mechanisms
� e.g., reliable communicationservice can be provided by multipleprotocols
16
Design Principles
Information Hiding Example: Message Queueing
MessageBlock
MessageQueue
head_tail_
SYNCHSTRATEGY
MessageBlock
next()prev()cont()Message
Blocknext()prev()cont() Message
Blocknext()prev()cont()
Data_Block
Data_Block
Data_Block
Data_Block
next()prev()cont()
� A Message_Queue is a list ofACE_Message_Blocks
– Efficiently handlesarbitrarily-large messagepayloads
� Design encapsulates andparameterizes various aspects
– e.g., synchronization, memoryallocators, and referencecounting can be addedtransparently
17
Des
ign
Prin
cipl
es
The
AC
E_M
ess
age_B
lock
Cla
ss
# base_ : char *
# refcnt_ : int
ACE_Data_Block
ACE_Message_Block
+ init (size : size_t) : int
+ msg_type (type : ACE_Message_Type)
+ msg_type () : ACE_Message_Type
+ msg_priority (prio : u_long)
+ msg_priority () : u_long
+ clone () : ACE_Message_Block *
+ duplicate () : ACE_Message_Block *
+ release () : ACE_Message_Block *
+ set_flags (flags : u_long) : u_long
+ clr_flags (flags : u_long) : u_long
+ copy (buf : const char *,n : size_t) : int
+ rd_ptr (n : size_t)
+ rd_ptr () : char *
+ wr_ptr (n : size_t)
+ wr_ptr () : char *
+ length () : size_t
+ total_length () : size_t
+ size () : size_t
# rd_ptr_ : size_t
# wr_ptr_ : size_t
# cont_ : ACE_Message_Block *
# next_ : ACE_Message_Block *
# prev_ : ACE_Message_Block *
# data_block_ : ACE_Data_Block *
* 1
Cla
ssch
arac
teris
tics
�
Hid
em
essa
ging
impl
emen
tatio
nsfr
omcl
ient
s
ACE_Message
_Block
cont()
data_block()
wr_ptr()
rd_ptr()
PAYLOAD
ACE_Data
_Block
ACE_Message
_Block
cont()
data_block()
wr_ptr()
rd_ptr() ACE_Data_Block
ACE_Message
_Block
cont()
data_block()
rd_ptr()
wr_ptr()
reference_count() = 2
((11)) SSIIMMPPLLEE MMEESSSSAAGGEE SSTTRRUUCCTTUURREE
((22)) CCOOMMPPOOSSIITTEE MMEESSSSAAGGEE SSTTRRUUCCTTUURREE
18 Des
ign
Prin
cipl
es
The
AC
E_M
ess
age_Q
ueue
Cla
ss
+ A
CE
_M
ess
ag
e_
Qu
eu
e (
hig
h_
wa
ter_
ma
rk : s
ize
_t =
DE
FA
UL
T_
HW
M,
lo
w_
wa
ter_
ma
rk : s
ize
_t =
DE
FA
UL
T_
LW
M,
n
otif
y : A
CE
_N
otif
ica
tion
_S
tra
teg
y *
= 0
)+
o
pe
n (
hig
h_
wa
ter_
ma
rk : s
ize
_t =
DE
FA
UL
T_
HW
M,
lo
w_
wa
ter_
ma
rk : s
ize
_t =
DE
FA
UL
T_
LW
M,
n
otif
y : A
CE
_N
otif
ica
tion
_S
tra
teg
y *
= 0
) : in
t+
flu
sh (
) : in
t+
n
otif
ica
tion
_st
rate
gy
(s : A
CE
_N
otif
ica
tion
_S
tra
teg
y *)
: v
oid
+
is_
em
pty
()
: in
t+
is
_fu
ll ()
: in
t+
e
nq
ue
ue
_ta
il (ite
m : A
CE
_M
ess
ag
e_
Blo
ck *
, tim
eo
ut : A
CE
_T
ime
_V
alu
e *
= 0
) : in
t+
e
nq
ue
ue
_h
ea
d (
item
: A
CE
_M
ess
ag
e_
Blo
ck *
, tim
eo
ut : A
CE
_T
ime
_V
alu
e *
= 0
) : in
t+
e
nq
ue
ue
_p
rio
(ite
m : A
CE
_M
ess
ag
e_
Blo
ck *
, tim
eo
ut : A
CE
_T
ime
_V
alu
e *
= 0
) : in
t+
d
eq
ue
ue
_h
ea
d (
item
: A
CE
_M
ess
ag
e_
Blo
ck *
&,
tim
eo
ut : A
CE
_T
ime
_V
alu
e *
= 0
) : in
t+
d
eq
ue
ue
_ta
il (ite
m : A
CE
_M
ess
ag
e_
Blo
ck *
&,
tim
eo
ut : A
CE
_T
ime
_V
alu
e *
= 0
) : in
t+
h
igh
_w
ate
r_m
ark
(n
ew
_h
wm
: s
ize
_t)
: v
oid
+
hig
h_
wa
ter_
ma
rk (
void
) : si
ze_
t+
lo
w_
wa
ter_
ma
rk (
ne
w_
lwm
: s
ize
_t)
: v
oid
+
low
_w
ate
r_m
ark
(vo
id)
: si
ze_
t+
cl
ose
()
: in
t+
d
ea
ctiv
ate
()
: in
t+
a
ctiv
ate
()
: in
t+
p
uls
e (
) : in
t+
st
ate
()
: in
t
# h
ea
d_
: A
CE
_M
ess
ag
e_
Blo
ck *
# ta
il_ : A
CE
_M
ess
ag
e_
Blo
ck *
# h
igh
_w
ate
r_m
ark
_ : s
ize
_t
# lo
w_
wa
ter_
ma
rk_
: s
ize
_t
AC
E_
Me
ssa
ge
_Q
ue
ue
SY
NC
H_
ST
RA
TE
GY
Cla
ssch
arac
teris
tics
�
Not
eho
wth
esy
nchr
oniz
atio
nas
pect
can
best
rate
gize
d!
19
Design Principles
Challenge 3: Determining the Units of Web ServerDecomposition
� Context: A production web server that uses abstraction andinformation hiding
� Problems:
– Need to determine the appropriate units of decomposition, whichshould
� Possess well-specified abstract interfaces and
� Have high cohesion and low coupling
20
Design Principles
Solution: Component Modularity
NAMING
TRADING
LOCKING
EVENT
LOOP
APPLICATION-SPECIFIC
GLUE CODE
LOGGING
TIME
� A modular system is one that’s structuredinto identifiable abstractions calledcomponents
– A software entity that represents anabstraction
– A “work” assignment for developers– A unit of code that
� has one or more names
� has identifiable boundaries
� can be (re-)used by other components
� encapsulates data
� hides unnecessary details� can be separately compiled
21
Design Principles
Designing Component Interfaces
� A component interface consists ofseveral types of ports:
– Exports
� Services provided to othercomponents, e.g., facets andevent sources
– Imports
� Services requested fromother components, e.g.,receptacles and event sinks
– Access Control
� Not all clients are equal, e.g.,protected/private/public
CALLBACKS
CONTAINER
COMPONENT
EXECUTOR
HOME
FACETS
RECEPTACLES
EVENT SINK EVENT SOURCE
� Define components thatprovide multiple interfacesand implementations
� Anticipate change
22
Design Principles
Component Modularity Example: Stream Processing
NETWORK INTERFACE
OR PSEUDO-DEVICES
STREAMTail
Multiplexor
APPLICATION
Stream
STREAMHead
APPLICATION
Stream
UP
ST
RE
AMD
OW
NS
TR
EA
M
MESSAGE WRITETASK
READTASK
MODULE
open()=0close()=0put()=0svc()=0
� A Stream allows flexibleconfiguration of layeredprocessing modules
� A Stream component containsa stack of Module components
� Each Module contains twoTask components
– i.e., read and write Task s
� Each Task contains aMessage Queue componentand a Thread Managercomponent
23
Design Principles
Benefits of Component Modularity
Modularity facilitates softwarequality factors, e.g.,:
� Extensibility ! well-defined,abstract interfaces
� Reusability ! low-coupling,high-cohesion
� Compatibility ! design“bridging” interfaces
� Portability ! hide machinedependencies
Modularity is important forgood designs since it:
� Enhances for separation ofconcerns
� Enables developers toreduce overall systemcomplexity via decentralizedsoftware architectures
� Increases scalability bysupporting independent andconcurrent development bymultiple personnel
24
Design Principles
Criteria for Evaluating Modular Designs
Component decomposability
� Are larger componentsdecomposed into smallercomponents?
Component composability
� Are larger componentscomposed from existingsmaller components?
Component understandability
� Are components separatelyunderstandable?
Component continuity
� Do small changes to thespecification affect alocalized and limited numberof components?
Component protection
� Are the effects of run-timeabnormalities confined to asmall number of relatedcomponents?
25
Design Principles
Principles for Ensuring Modular Designs
Language support for components
� Components should correspond tosyntactic units in the language
Few interfaces
� Every component shouldcommunicate with as few others aspossible
Small interfaces (weak coupling)
� If any two components communicateat all, they should exchange as littleinformation as possible
Explicit Interfaces
� Whenever twocomponents A and Bcommunicate, this mustbe obvious from the textof A or B or both
Information Hiding
� All information about acomponent should beprivate unless it’sspecifically declaredpublic
26
Design Principles
Challenge 4: “Future Proofing” the Web Server� Context: A production web server whose requirements will change
over time
� Problems:
– Certain design aspects seem constant until they are examined inthe overall structure of an application
– Developers must be able to easily refactor the web server toaccount for new sources of variation
27
Design Principles
Solution: Extensibility
� Extensible software is important to support successions of quickupdates and additions to address new requirements and takeadvantage of emerging opportunities/markets
� Extensible components must be both open and closed, i.e., the“open/closed” principle:
– Open component ! still available for extension
� This is necessary since the requirements and specifications arerarely completely understood from the system’s inception
– Closed component ! available for use by other components
� This is necessary since code sharing becomes unmanageablewhen reopening a component triggers many changes
28
Design Principles
Extensibility Example: Active Object Tasks
EventHandler
handle_input()handle_output()handle_exception()handle_signal()handle_timeout ()handle_close()get_handle()=0
SharedObject
init()=0fini ()=0info()=0
SvcHandler
ServiceObject
A
APPLICATION-SPECIFIC
APPLICATION-INDEPENDENT
MessageQueue
SYNCH_STRATEGYPEER_STREAM
suspend()=0resume()=0
SYNCHSTRATEGY
AA
Taskopen()=0close()=0put()=0svc()=0
SYNCHSTRATEGY
A
� Features
– Tasks can register with aReactor
– They can be dynamicallylinked
– They can queue data– They can run as “active
objects”
� JAWS uses inheritance anddynamic binding to producetask components that areboth open and closed
29
Design Principles
Challenge 5: Separating Concerns for LayeredSystems
� Context: A production web server whose requirements will changeover time
� Problems:
– To enhance reuse and flexibility, it is often necessary todecompose a web server into smaller, more manageable unitsthat are layered in order to
� Enhance reuse, e.g., multiple higher-layer services can sharelower-layer services
� Transparently and incrementally enhancement functionality
� Improve performance by allowing the selective omission ofunnecessary service functionality
� Improve implementations, testing, and maintenance
30 Des
ign
Prin
cipl
es
Sol
utio
n:V
irtua
lMac
hine
Arc
hite
ctur
es
�
Avi
rtua
lmac
hine
prov
ides
anex
tend
ed“s
oftw
are
inst
ruct
ion
set”
–E
xten
sion
spr
ovid
ead
ditio
nald
ata
type
san
das
soci
ated
“sof
twar
ein
stru
ctio
ns”
–M
odel
edaf
ter
hard
war
ein
stru
ctio
nse
tpr
imiti
ves
that
wor
kon
alim
ited
seto
fdat
aty
pes
�
Avi
rtua
lmac
hine
laye
rpr
ovid
esa
seto
fop
erat
ions
that
are
usef
ulin
deve
lopi
nga
fam
ilyof
sim
ilar
syst
ems
AP
PL
ICA
TIO
N
PR
ES
EN
TA
TIO
N
SE
SS
ION
TR
AN
SP
OR
T
NE
TW
OR
K
DA
TA
L
INK
PH
YS
ICA
L
AP
PL
ICA
TIO
N
PR
ES
EN
TA
TIO
N
SE
SS
ION
TR
AN
SP
OR
T
NE
TW
OR
K
DA
TA
L
INK
PH
YS
ICA
L
AP
PL
ICA
TIO
N
PR
ES
EN
TA
TIO
N
SE
SS
ION
TR
AN
SP
OR
T
NE
TW
OR
K
DA
TA
L
INK
PH
YS
ICA
L
AP
PL
ICA
TIO
N
PR
ES
EN
TA
TIO
N
SE
SS
ION
TR
AN
SP
OR
T
NE
TW
OR
K
DA
TA
L
INK
PH
YS
ICA
L
NE
TW
OR
K
DA
TA
L
INK
PH
YS
ICA
L
NE
TW
OR
K
DA
TA
L
INK
PH
YS
ICA
L
NE
TW
OR
K
DA
TA
L
INK
PH
YS
ICA
L
NE
TW
OR
K
DA
TA
L
INK
PH
YS
ICA
L
HHO
ST
O
ST
AA
HHO
ST
O
ST
BB
GGA
TE
WA
Y
AT
EW
AY
AA
GGA
TE
WA
Y
AT
EW
AY
BB
VIR
TU
AL
LIN
K
PH
YS
ICA
L
LIN
K
31
Design Principles
Virtual Machine Layers for the ACE Toolkit
PROCESSES/THREADS
DYNAMIC
LINKING
SHARED
MEMORYSELECT/IO COMP
FILE SYS
APIS
WIN32 NAMEDPIPES & UNIX
STREAM PIPES
UNIX
FIFOS
CAPIS
SOCKETS/TLI
COMMUNICATION
SUBSYSTEM
VIRTUAL MEMORY & FILE
SUBSYSTEM
GENERAL OPERATING SYSTEM SERVICES
PROCESS/THREAD
SUBSYSTEM
FRAMEWORK
LAYER
ACCEPTOR CONNECTOR
NETWORKED
SERVICE
COMPONENTS
LAYER
NAME
SERVER
TOKEN
SERVER
LOGGING
SERVER
GATEWAY
SERVER
SOCK SAP/TLI SAP
FIFO
SAP
LOG
MSG
SERVICE
HANDLER
TIME
SERVER
C++WRAPPER
FACADE
LAYER SPIPE
SAP
CORBA
HANDLER
FILE
SAP
SHARED
MALLOC
THE ACE ORB
(TAO)
JAWS ADAPTIVE
WEB SERVERSTANDARDS-BASED MIDDLEWARE
REACTOR/PROACTOR
PROCESS/THREAD
MANAGERS
STREAMS
SERVICE
CONFIG-URATOR
SYNCH
WRAPPERS
MEM
MAP
OS ADAPTATION LAYER
www.cs.wustl.edu/�schmidt/ACE.html
32 Des
ign
Prin
cipl
es
Oth
erE
xam
ples
ofV
irtua
lMac
hine
s
Com
pute
rar
chite
ctur
es
�
e.g.
,com
pile
r
!
asse
mbl
er
!
objc
ode
!
mic
roco
de
!
gate
s,tr
ansi
stor
s,si
gnal
s,et
c.
Ope
ratin
gsy
stem
s
�
e.g.
,Lin
ux
Har
dwar
eM
achi
neS
oftw
are
Virt
ualM
achi
nein
stru
ctio
nse
tse
tofs
yste
mca
llsre
star
tabl
ein
stru
ctio
nsre
star
tabl
esy
stem
calls
inte
rrup
ts/tr
aps
sign
als
inte
rrup
t/tra
pha
ndle
rssi
gnal
hand
lers
bloc
king
inte
rrup
tsm
aski
ngsi
gnal
sin
terr
upts
tack
sign
alst
ack
Java
Vir
tual
Mac
hine
(JV
M)
�
Abs
trac
tsaw
ayfr
omde
tails
ofth
eun
derly
ing
OS
33
Design Principles
Challenge 6: Separating Concerns for HierarchicalSystems
� Context: A production web server whose requirements will changeover time
� Problems:
– Developers need to program components at different levels ofabstraction independently
– Changes to one set of components should be isolated as muchas possible from other components
– Need to be able to “visualize” the structure of the web serverdesign
34
Design Principles
Solution: Hierarchical Relationships� Hierarchies reduce component interactions by restricting the
topology of relationships
� A relation defines a hierarchy if it partitions units into levels (noteconnection to virtual machine architectures)
– Level 0 is the set of all units that use no other units– Level i is the set of all units that use at least one unit at level < i
and no unit at level � i.
� Hierarchies form the basis of architectures and designs
– Facilitates independent development– Isolates ramifications of change– Allows rapid prototyping
35
Design Principles
Hierarchy Example: JAWS Architecture
svc_run
REQUEST PROCESSING LAYER
Optionss
HTTPHandler
HTTPHandler
HTTPHandler
HTTPAcceptor Reactor
HTTPProcessor
MsgQueue
s
svc_runsvc_runsvc_run
QUEUEING LAYER
I/O DEMUXING LAYER
36
Design Principles
Defining Hierarchies
� Relations that define hierarchies include:
– Uses– Is-Composed-Of– Is-A– Has-A
� The first two are general to all design methods,the latter two are more particular to OO designand programming
ACE_IPC_SAP ACE_Addr
ACE_SOCK_IO ACE_SOCK
ACE_SOCK_Acceptor ACE_INET_Addr
ACE_SOCK_Stream ACE_SOCK_Connector
37
Design
Principles
The
Uses
Relation
(1/3)
Cla
ss
X
Cla
ss
Y
�
XU
sesY
ifthecorrectfunctioning
ofXdepends
onthe
availabilityofa
correctimplem
entationof Y
�
Note,uses
isnotnecessarily
thesam
eas
invokes:
–S
ome
invocationsare
notuses
�
e.g.,errorlogging
–S
ome
usesdon’tinvolve
invocations
�
e.g.,message
passing,interrupts,sharedm
emory
access
�
Auses
relationdoes
notnecessarilyyield
ahierarchy
(avoidcycles...)
38
Design Principles
The Uses Relation (2/3)
� Allow X to use Y when:
– X is simpler because it uses Y
� e.g., Standard C++ library classes– Y is not substantially more complex because
it is not allowed to use X– There is a useful subset containing Y and not
X
� i.e., allows sharing and reuse of Y– There is no conceivably useful subset
containing X but not Y
� i.e., Y is necessary for X to functioncorrectly
� Uses relationships can exist between classes,frameworks, subsystems, etc.
Acceptor-Connector
Reactor Proactor
ServiceConfigurator
Streams Task
39
Design
Principles
The
Uses
Relation
(3/3)
�
Ahierarchy
inthe
usesrelation
isessentialfor
designingreusable
software
systems
�
How
ever,certainsoftw
aresystem
srequire
controlledviolation
ofauses
hierarchy
–e.g.,asynchronous
comm
unicationprotocols,O
Ocallbacks
infram
eworks,signalhandling,etc.
–U
pcallsare
onew
ayto
controlthesenon-hierarchical
dependencies
�
Rule
ofthumb:
–S
tartwith
aninvocation
hierarchyand
eliminate
thoseinvocations
( i.e.,“calls”)thatare
notusesrelationships
40
Design Principles
The Is-Composed-Of Relation
� The is-composed-of relationship shows how thesystem is broken down in components
� X is-composed-of fxig if X is a group ofcomponents xi that share some commonpurpose
� The following diagram illustrates some of theis-composed-of relationships in JAWS
HTTPHandler
SockStream
HTTPHandler
SockStream
HTTPHandler
SockStream
HTTPAcceptor
SockAcceptor
Reactor
41
Design
Principles
The
Is-Com
posed-OfR
elation
�
Many
programm
inglanguages
supporttheis-com
posed-ofrelationvia
some
higher-levelcomponentor
recordstructuring
technique
�
How
ever,thefollow
ingare
notequivalent:
–level(virtualm
achine)–
component(an
entitythathides
oneor
more
“secrets”)–
asubprogram
(acode
unit)
�
Com
ponentsand
levelsneed
notbeidentical,as
acom
ponentmay
appearin
severallevelsofa
useshierarchy
42
Design Principles
The Is-A Relation
� This “ancestor/descendant” relationship isassociated with object-oriented design andprogramming languages that possessinheritance and dynamic binding
� class X possesses Is-A relationship with class Yif instances of class X are specialization of classY.
– e.g., an HTTP_1_0_Handler Is-AACE_Event_Handler that is specialized forprocessing HTTP 1.0 requests
ACE_Event_Handlerhandle_input()get_handle()
HTTP_1_0Handler
HTTP_1_1Handler
43
Des
ign
Prin
cipl
es
The
Has
-AR
elat
ion
�
Thi
s“c
lient
”re
latio
nshi
pis
asso
ciat
edw
ithob
ject
-orie
nted
desi
gnan
dpr
ogra
mm
ing
lang
uage
sth
atpo
sses
scl
asse
san
dob
ject
s
�
clas
sX
poss
esse
sa
Has
-Are
latio
nshi
pw
ithcl
ass
Yif
inst
ance
sof
clas
sX
cont
ain
anin
stan
ce(s
)of
clas
sY.
–e.
g.,t
heJA
WS
web
serv
erH
as-A
React
or
,H
TT
P_A
ccepto
r,
and
CV
_F
ilesy
tem
JAW
SW
ebS
erve
r
HT
TP
Acc
epto
r
Rea
cto
r
CV
_File
syst
em
44
Design Principles
Challenge 7: Enabling Expansion and Contraction ofSoftware
� Context: A production web server whose requirements will changeover time
� Problems:
– It may be necessary to reduce the overall functionality of theserver to run in resource-constrained environments
– To meet externally imposed schedules, it may be necessary torelease the server without all the features enabled
45
Design Principles
Solution: Program Families and Subsets
� This principle should be applied to facilitate extension andcontraction of large-scale software systems, particularly reusablemiddleware infrastructure
– e.g., JAWS, ACE, etc.
� Program families are natural way to detect and implement subsets
– Minimize footprints for embedded systems– Promotes system reusability– Anticipates potential changes
� Heuristics for identifying subsets:
– Analyze requirements to identify minimally useful subsets– Also identify minimal increments to subsets
46 Des
ign
Prin
cipl
es
Exa
mpl
eof
Pro
gram
Fam
ilies
:JA
WS
and
TAO
(1) T
HE
AC
E O
RB
(TA
O)
NE
TW
OR
K
RE
AL
-TIM
E O
RB
CO
RE
AC
E c
om
ponents
IOP
IOP
PL
UG
GA
BL
EO
RB
& X
PO
RT
PR
OT
OC
OL
S
PL
UG
GA
BL
EO
RB
& X
PO
RT
PR
OT
OC
OL
S
RE
AL-T
IME
I/O
SU
BS
YS
TE
M
HIG
H-S
PE
ED
NE
TW
OR
K IN
TE
RFA
CE
OS
KE
RN
EL
RE
AL-T
IME
I/O
SU
BS
YS
TE
M
HIG
H-S
PE
ED
NE
TW
OR
K IN
TE
RFA
CE
OS
KE
RN
EL
OR
B R
UN
-TIM
ES
CH
ED
UL
ER
IDL
SK
EL
ET
ON
IDL
ST
UB
S
opera
tion (
)
ou
t a
rgs
+ r
etu
rn v
alu
e
OB
JEC
T(S
ER
VA
NT
)
in a
rgs
RE
AL-T
IME
OB
JEC
TA
DA
PT
ER
CLIE
NT
OB
JR
EF
(2) T
he J
AW
S W
eb S
erve
r Fr
amew
ork
Service Configurator
Stra
tegy
Stra
tegy
Sing
leto
n
State State
Acceptor
Pipe
s an
d Fi
lters
Activ
e O
bjec
t
Adapter
Serv
ice
Conf
igur
ator
Even
t Dis
patc
her
Conc
urre
ncy
Stra
tegy
Fram
ewor
k
Prot
ocol
Hand
ler
Prot
ocol
Filte
r
Tild
eEx
pand
er/h
ome/
...
~
Reac
tor/P
roac
tor
Memento
I/O S
trate
gyFr
amew
ork
Cach
ed V
irtua
lFi
lesy
stem
Prot
ocol
Pip
elin
eFr
amew
orkAs
ynch
rono
us C
ompl
eton
Toke
n
�
TAO
isa
high
-per
form
ance
,rea
l-tim
eim
plem
enta
tion
ofth
eC
OR
BA
spec
ifica
tion
�
JAW
Sis
ahi
gh-p
erfo
rman
ce,a
dapt
ive
Web
serv
erth
atim
plem
ents
the
HT
TP
spec
ifica
tion
�
JAW
San
dTA
Ow
ere
deve
lope
dus
ing
the
wra
pper
faca
des
and
fram
ewor
kspr
ovid
edby
the
AC
Eto
olki
t
47
Des
ign
Prin
cipl
es
Oth
erE
xam
ples
ofP
rogr
amFa
mili
esan
dS
ubse
ts
�
Diff
eren
tser
vice
sfo
rdi
ffere
ntm
arke
ts
–e.
g.,d
iffer
enta
lpha
bets
,diff
eren
tver
tical
appl
icat
ions
,diff
eren
tI/O
form
ats
�
Diff
eren
thar
dwar
eor
softw
are
plat
form
s
–e.
g.,c
ompi
lers
orO
Ss
�
Diff
eren
tres
ourc
etr
ade-
offs
–e.
g.,s
peed
vssp
ace
�
Diff
eren
tint
erna
lres
ourc
es
–e.
g.,s
hare
dda
tast
ruct
ures
and
libra
ryro
utin
es
�
Diff
eren
text
erna
leve
nts
–e.
g.,U
NIX
I/Ode
vice
inte
rfac
e
�
Bac
kwar
dco
mpa
tibili
ty
–e.
g.,s
omet
imes
itis
impo
rtan
tto
reta
inbu
gs!
48
Design Principles
Conventional Development Processes
� Waterfall Model
– Specify, analyze, implement, test (in sequence)– Assumes that requirements can be specified up front
� Spiral Model
– Supports iterative development– Attempts to assess risks of changes
� Rapid Application Development
– Build a prototype– Ship it :-)
49
Design Principles
Agile Processes
� Stresses customer satisfaction, and therefore, involvement
– Provide what the customer wants, as quickly as possible– Provide only what the customer wants
� Encourages changes in requirements
� Relies on testing
� For example, eXtreme Programming practices
– Planning, designing, coding, testing
50
Design Principles
eXtreme Programming: Planning
TechnologySpike
SystemPrototype
UserStory
PlanningGame
IterationCommitmentSchedule
Change in Requirements, Risk,or Developement Environment
Risk Estimates
Time
Requirements
based on http://www.extremeprogramming.org/rules/planninggame.html
� Start with user stories– Written by customers, to
specify systemrequirements
– Minimal detail, typicallyjust a few sentences on acard
– Expected developmenttime: 1 to 3 weeks each,roughly
� Planning game createscommitment schedule forentire project
� Each iteration should take2-3 weeks
51
Design Principles
eXtreme Programming: Designing
� Defer design decisions as long as possible
� Advantages:
– Simplifies current task (just build what is needed)– You don’t need to maintain what you haven’t built– Time is on your side: you’re likely to learn something useful by the
time you need to decide– Tomorrow may never come: if a feature isn’t needed now, it might
never be needed
� Disadvantages:
– Future design decisions may require rework of existingimplementation
– Ramp-up time will probably be longer later
� Therefore, always try to keep designs as simple as possible
52
Design Principles
eXtreme Programming: Coding
� Pair programming
– Always code with a partner– Always test as you code
� Pair programming pays off by supporting good implementation,reducing mistakes, and exposing more than one programmer to thedesign/implementation
� If any deficiencies in existing implementation are noticed, either fixthem or note that they need to be fixed
53
Design Principles
eXtreme Programming: Testing
� Unit tests are written before code
� Code must pass both its unit test and all regression tests beforecommitting
� In effect, the test suite defines the system requirements
– Significant difference from other development approaches– If a bug is found, a test for it must be added– If a feature isn’t tested, it can be removed
54
Design Principles
Agile Processes: Information Sources� Kent Beck, Extreme Programming Explained: Embrace Change,
Addison-Wesley, ISBN 0201616416, 1999
� Kent Beck, “Extreme Programming”, C++ Report 11:5, May 1999,pp. 26–29+
� John Vlissides, “XP”, interview with Kent Beck in the PatternHatching Column, C++ Report 11:6, June 1999, pp. 44-52+
� Kent Beck, “Embracing Change with Extreme Programming”, IEEEComputer 32:10, October 1999, pp. 70-77
� http://www.extremeprogramming.org/
� http://www.xprogramming.com/
� http://c2.com/cgi/wiki?ExtremeProgrammingRoadmap
55
Design Principles
Design Guidelines: Motivation
� Design is the process of organizing structured solutions to tasksfrom a problem domain
� This process is carried out in many disciplines, in many ways
– There are many similarities and commonalities among designprocesses
– There are also many common design mistakes . . .
� The following pages provide a number of “design rules.”
– Remember, these rules are simply suggestions on how to betterorganize your design process, not a recipe for success!
56
Design Principles
Common Design Mistakes (1/2)
� Depth-first design
– only partially satisfy the requirements– experience is best cure for this problem . . .
� Directly refining requirements specification
– leads to overly constrained, inefficient designs
� Failure to consider potential changes
– always design for extension and contraction
� Making the design too detailed
– this overconstrains the implementation
57
Design Principles
Common Design Mistakes (2/2)
� Ambiguously stated design
– misinterpreted at implementation
� Undocumented design decisions
– designers become essential to implementation
� Inconsistent design
– results in a non-integratable system, because separatelydeveloped modules don’t fit together
58
Design Principles
Rules of Design (1/8)� Make sure that the problem is well-defined
– All design criteria, requirements, and constraints, should beenumerated before a design is started
– This may require a “spiral model” approach
� What comes before how
– i.e., define the service to be performed at every level ofabstraction before deciding which structures should be used torealize the services
� Separate orthogonal concerns
– Do not connect what is independent– Important at many levels and phases . . .
59
Design Principles
Rules of Design (2/8)
� Design external functionality before internal functionality.
– First consider the solution as a black-box and decide how itshould interact with its environment
– Then decide how the black-box can be internally organized. Likelyit consists of smaller black-boxes that can be refined in a similarfashion
� Keep it simple.
– Fancy designs are buggier than simple ones; they are harder toimplement, harder to verify, and often less efficient
– Problems that appear complex are often just simple problemshuddled together
– Our job as designers is to identify the simpler problems, separatethem, and then solve them individually
60
Design Principles
Rules of Design (3/8)
� Work at multiple levels of abstraction
– Good designers must be able to move between various levels ofabstraction quickly and easily
� Design for extensibility
– A good design is “open-ended,” i.e., easily extendible– A good design solves a class of problems rather than a single
instance– Do not introduce what is immaterial– Do not restrict what is irrelevant
� Use rapid prototyping when applicable
– Before implementing a design, build a high-level prototype andverify that the design criteria are met
61
Design Principles
Rules of Design (4/8)
� Details should depend upon abstractions
– Abstractions should not depend upon details– Principle of Dependency Inversion
� The granule of reuse is the same as the granule of release
– Only components that are released through a tracking system canbe effectively reused
� Classes within a released component should share common closure
– That is, if one needs to be changed, they all are likely to need tobe changed
– i.e., what affects one, affects all
62
Design Principles
Rules of Design (5/8)� Classes within a released component should be reused together
– That is, it is impossible to separate the components from eachother in order to reuse less than the total
� The dependency structure for released components must be a DAG
– There can be no cycles
� Dependencies between released components must run in thedirection of stability
– The dependee must be more stable than the depender
� The more stable a released component is, the more it must consistof abstract classes
– A completely stable component should consist of nothing butabstract classes
63
Design Principles
Rules of Design (6/8)
� Where possible, use proven patterns to solve design problems
� When crossing between two different paradigms, build an interfacelayer that separates the two
– Don’t pollute one side with the paradigm of the other
64
Design Principles
Rules of Design (7/8)
� Software entities (classes, modules, etc) should be open forextension, but closed for modification
– The Open/Closed principle – Bertrand Meyer
� Derived classes must usable through the base class interfacewithout the need for the user to know the difference
– The Liskov Substitution Principle
65
Design Principles
Rules of Design (8/8)
� Make it work correctly, then make it work fast
– Implement the design, measure its performance, and ifnecessary, optimize it
� Maintain consistency between representations
– e.g., check that the final optimized implementation is equivalent tothe high-level design that was verified
– Also important for documentation . . .
� Don’t skip the preceding rules!
– Clearly, this is the most frequently violated rule!!! ;-)
66
Design Principles
Concluding Remarks� Good designs can generally be distilled into a few key principles:
– Separate interface from implementation– Determine what is common and what is variable with an interface
and an implementation– Allow substitution of variable implementations via a common
interface
� i.e., the “open/closed” principle– Dividing commonality from variability should be goal-oriented
rather than exhaustive
� Design is not simply the act of drawing a picture using a CASE toolor using graphical UML notation!!!
– Design is a fundamentally creative activity
67