emb edded - dre.vanderbilt.eduschmidt/pdf/design-principles.pdf · ho w macro steps include: 1....
TRANSCRIPT
DesignPrinciples
AnOverviewofObject-OrientedSoftware
Design
forDistributedReal-timeandEmbedded
Applications
DouglasC.Schmidt
VanderbiltUniversity,St.Louis
www.cs.wustl.edu/�schmidt/
0
Sponsors
NSF,DARPA,BBN,Bellcore,Boeing,CDI/GDIS,Kodak,
Lockheed,Lucent,Microsoft,Motorola,Nokia,Nortel,OTI,SAIC,
SiemensSCR,SiemensMED,SiemensZT,Sprint,USENIX
1
Design Principles
Goals of the Design Phase
EVENTSERVER
SUPERVISOR
CCMStream
ACERUN-TIME
TELECOMSWITCHES
Session RouterModule
Event FilterModule
Switch AdapterModule
Event AnalyzerModule
SUPERVISOR SUPER
VISOR
MIB
� Decompose system into
components
{ i.e., identify the software
architecture
� Determine relationships between
components
{ e.g., identify component
dependencies and determine
intercomponent communication
mechanisms
2
Design Principles
Goals of the Design Phase (cont'd)
UP
ST
RE
AM
DO
WN
ST
RE
AM
open()=0close()=0put()=0svc()=0
STREAMHead
STREAMTail
� Specify component interfaces
{ Interfaces should be well-de�ned
� Facilitates component testing and
team communication
� Describe component functionality
{ e.g., informally or formally
� Identify opportunities for systematic
reuse
{ Both top-down and bottom-up
3
DesignPrinciples
MacroStepsintheDesignProcess
�Inthedesignprocesstheorientationmovesfrom
{Customertodeveloper
{Whattohow
�Macrostepsinclude:
1.PreliminaryDesign
{Externaldesigndescribesthereal-worldmodel
{Architecturaldesigndecomposestherequirementspeci�cationinto
softwaresubsystems
2.DetailedDesign
{Specifyeachsubsystem
{Furtherdecomposedsubsystems,ifnecessary
4
DesignPrinciples
MicroStepsintheDesignProcess
�Designisaniterativedecisionprocesswiththe
followinggeneralsteps:
1.Listthedi�cultdecisionsanddecisionslikelyto
change
2.Designacomponentspeci�cationtohideeach
suchdecision
{Makedecisionsthatapplytowholeprogram
family�rst
{Modularizemostlikelychanges�rst
{Thenmodularizeremainingdi�cultdecisions
anddecisionslikelytochange
{Designtheuseshierarchyasyoudothis
(includereusedecisions)
3.Treateachhigher-levelcomponentasa
speci�cationandapplyaboveprocesstoeach
4.Continuere�ninguntilalldesigndecisionsare:
{hiddeninacomponent
{containeasilycomprehensiblecomponents
{provideindividual,independent,low-level
implementationassignments
5
DesignPrinciples
KeyDesignConceptsandPrinciples
Keydesignconceptsanddesign
principlesinclude:
�Decomposition
�Abstraction
�InformationHiding
�Modularity
�Extensibility
�VirtualMachineStructuring
�Hierarchy
�ProgramFamiliesandSubsets
Maingoaloftheseconcepts
andprinciplesisto:
�Managesoftwaresystem
complexity
�Improvesoftwarequality
factors
�Facilitatesystematicreuse
6
DesignPrinciples
Decomposition
�Motivation:handlecomplexitybysplittinglargeproblemsintosmaller
problems,i.e.,\divideandconquer"
�Basicmethodology:
1.Selectapieceoftheproblem(initially,thewholeproblem)
2.Determinethecomponentsinthispieceusingadesignparadigm,
e.g.,functional,structured,object-oriented,generic,etc.
3.Describethecomponentsinteractions
4.Repeatsteps1through3untilsometerminationcriteriaismet
{e.g.,customerissatis�ed,runoutofmoney,etc.;-)
7
Design Principles
Decomposition Example: External OS for PBX
NETWORKSWITCHES
SERVER
CLIENT
APPLICATION
FRAMEWORK
CALL CENTERMANAGER
DIRECTORYMANAGER
EXTENSIONMANAGER
CLIENT CLIENT
CLIENT
� Features
{ Allow clients to manage
various aspects of PBX
switches without modifying
the switch software
{ Support reuse of existing
components based on a
common architectural
framework
www.cs.wustl.edu/�schmidt/DSEJ-
94.ps.gz
8
DesignPrinciples
DecompositionPrinciples
1.Don'tdesigncomponentstocorrespondtoexecutionsteps
�Sincedesigndecisionsusuallytranscendexecutiontime
2.Decomposesoastolimitthee�ectofanyonedesigndecisiononthe
restofthesystem
�Anythingthatpermeatesthesystemwillbeexpensivetochange
3.Componentsshouldbespeci�edbyallinformationneededtousethe
component
�andnothingmore!
9
Design Principles
Abstraction
IMPLEMENTATIONIMPLEMENTATION
ESSENTIAL
CHARACTERISTICS
UNESSENTIAL
DETAILS
INTERFACEINTERFACE
� Motivation: manage complexity by
emphasizing essential
characteristics and suppressing
implementation details
� Common abstractions
1. Procedural abstraction
{ e.g., closed subroutines
2. Data abstraction
{ e.g., ADTs
3. Control abstraction
{ e.g., iterators, loops, and
multitasking
10
DesignPrinciples
InformationHiding
�Motivation:designdecisionsthataresubjecttochangeshouldbe
hiddenbehindabstractinterfaces
{i.e.,components
�Componentsshouldcommunicateonlythroughwell-de�nedinterfaces.
�Eachcomponentisspeci�edbyaslittleinformationaspossible.
�Ifinternaldetailschange,clientcomponentsshouldbeminimally
a�ected
{Maynotevenrequirerecompilationandrelinking...
�Informationhidingisonemeanstoenhanceabstraction
11
Design Principles
Information Hiding Example: ACE 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()
� Message Queue and
Message Block hide Stream
messaging implementations from
clients
� e.g., reference counting can be
added transparently
MessageBlock
cont()next()
ref_count()base()
DataBlock
MessageBlock
cont()next()
PAYLOAD
12
DesignPrinciples
TypicalInformationtobeHidden
�Datarepresentations
{i.e.,usingabstractdata
types
�Algorithms
{e.g.,sortingorsearching
techniques
�InputandOutputFormats
{Machinedependencies,e.g.,
byte-ordering,character
codes
�Policy/mechanismdistinctions
{e.g.,OSscheduling,
garbagecollection,process
migration
�Lower-levelcomponent
interfaces
{e.g.,orderingoflow-level
operations,i.e.,process
sequence
13
Design Principles
Modularity
Session RouterModule
PresentationModule
Event FilterModule
Event AnalysisModule
PresentationModule
Switch AdapterModule
� A Modular system is one that's
structured into identi�able
abstractions called components
{ Components should possess
well-speci�ed abstract interfaces
{ Components should have high
cohesion and low coupling
� Modularity is important for both
design and implementation phases
14
Design Principles
Modularity Example: ACE Stream
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 contains a stack of
Modules
� Each Module contains two
Tasks
{ i.e., a read Task and a
write Task
� Each Task contains a
Message Queue and a pointer
to a Thread Manager
15
DesignPrinciples
ComponentDe�nitions
�Acomponentis
{Asoftwareentityencapsulatingtherepresentationofanabstraction,
e.g.,anADT
{Avehicleforhidingatleastonedesigndecision
{A\work"assignmentforaprogrammerorgroupofprogrammers
{Aunitofcodethat
�hasoneormorenames
�hasidenti�ableboundaries
�canbe(re-)usedbyothercomponents
�encapsulatesdata
�hidesunnecessarydetails
�canbeseparatelycompiled(ifsupported)
16
DesignPrinciples
ComponentInterfaces
�Acomponentinterface
consistsofseveralsections:
{Imports
�Servicesrequestedfrom
othercomponents
{Exports
�Servicesprovidedto
othercomponents
{AccessControl
�e.g.,
protected/private/public
�Heuristicsfordetermining
componentinterfaces:
{De�neonespeci�cation
thatallowsmultiple
implementations
{Anticipatechange
�e.g.,useobjectsfor
parameters
17
DesignPrinciples
Bene�tsofModularity
Modularityfacilitatessoftware
qualityfactors,e.g.,:
�Extensibility!
well-de�ned,
abstractinterfaces
�Reusability!
low-coupling,
high-cohesion
�Compatibility!
design
\bridging"interfaces
�Portability!
hidemachine
dependencies
Modularityisimportantforgood
designssinceit:
�Enhancesforseparationof
concerns
�Enablesdeveloperstoreduce
overallsystemcomplexityvia
decentralizedsoftware
architectures
�Increasesscalabilityby
supportingindependentand
concurrentdevelopmentby
multiplepersonnel
18
DesignPrinciples CriteriaforEvaluatingModularDesigns
Componentdecomposability
�Arelargercomponents
decomposedintosmaller
components?
Componentcomposability
�Arelargercomponents
composedfromexisting
smallercomponents?
Componentunderstandability
�Arecomponentsseparately
understandable?
Componentcontinuity
�Dosmallchangestothe
speci�cationa�ectalocalized
andlimitednumberof
components?
Componentprotection
�Arethee�ectsofrun-time
abnormalitiescon�nedtoa
smallnumberofrelated
components?
19
DesignPrinciples PrinciplesforEnsuringModularDesigns
Languagesupportforcomponents
�Componentsshouldcorrespondto
syntacticunitsinthelanguage
Fewinterfaces
�Everycomponentshouldcommunicate
withasfewothersaspossible
Smallinterfaces(weakcoupling)
�Ifanytwocomponentscommunicate
atall,theyshouldexchangeaslittle
informationaspossible
ExplicitInterfaces
�Whenevertwo
componentsAandB
communicate,thismust
beobviousfromthetext
ofAorBorboth
InformationHiding
�Allinformationabouta
componentshouldbe
privateunlessit's
speci�callydeclaredpublic
20
DesignPrinciples
Extensibility
�Motivation:aspectsofadesign\seem"constantuntiltheyareexamined
inthelightofthedependencystructureofanapplication
{Atthispoint,itbecomesnecessarytorefactortheframeworkor
patterntoaccountforthevariation
�Therefore,componentsoftenmustbebothopenandclosed,i.e.,the
\open/closed"principle:
{Opencomponent!
stillavailableforextension
�Thisisnecessarysincetherequirementsandspeci�cationsarerarely
completelyunderstoodfromthesystem'sinception
{Closedcomponent!
availableforusebyothercomponents
�Thisisnecessarysincecodesharingbecomesunmanageablewhen
reopeningacomponenttriggersmanychanges
21
Design Principles
Extensibility Example: ACE Task
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 a
Reactor
{ They can be dynamically
linked
{ They can queue data
{ They can run as \active
objects"
� Note how OO techniques use
inheritance and dynamic
binding to produce
components that are both
open and closed
22
DesignPrinciples
VirtualMachineStructuring
�Motivation:decomposesystemintosmaller,moremanageableunits,
thatarelayeredhierarchically
�Avirtualmachineprovidesanextended\softwareinstructionset"
{Extensionsprovideadditionaldatatypesandassociated\software
instructions"
{Modeledafterhardwareinstructionsetprimitivesthatworkona
limitedsetofdatatypes
�Avirtualmachinecomponentprovidesasetofoperationsthatare
usefulindevelopingafamilyofsimilarsystems
23
Design Principles
Virtual Machine Example: OSI Protocol Stack
APPLICATION
PRESENTATION
SESSION
TRANSPORT
NETWORK
DATA LINK
PHYSICAL
APPLICATION
PRESENTATION
SESSION
TRANSPORT
NETWORK
DATA LINK
PHYSICAL
APPLICATION
PRESENTATION
SESSION
TRANSPORT
NETWORK
DATA LINK
PHYSICAL
APPLICATION
PRESENTATION
SESSION
TRANSPORT
NETWORK
DATA LINK
PHYSICAL
NETWORK
DATA LINK
PHYSICAL
NETWORK
DATA LINK
PHYSICAL
NETWORK
DATA LINK
PHYSICAL
NETWORK
DATA LINK
PHYSICAL
HHOST OST AA HHOST OST BB
GGATEWAY ATEWAY AA GGATEWAY ATEWAY BB
VIRTUAL
LINK
PHYSICAL
LINK
24
DesignPrinciples
OtherExamplesofVirtualMachines
Computerarchitectures
�e.g.,compiler!assembler!objcode!
microcode!gates,transistors,signals,etc.
Operatingsystems
�e.g.,Mach,BSDUNIX
HardwareMachineSoftwareVirtualMachine
instructionsetsetofsystemcalls
restartableinstructionsrestartablesystemcalls
interrupts/trapssignals
interrupt/traphandlerssignalhandlers
blockinginterruptsmaskingsignals
interruptstacksignalstack
JavaVirtualMachine(JVM)
�AbstractsawayfromdetailsoftheunderlyingOS
25
DesignPrinciples
Hierarchy
�Motivation:reducescomponentinteractionsbyrestrictingthetopology
ofrelationships
�A
relationde�nesahierarchyifitpartitionsunitsintolevels(note
connectiontovirtualmachines)
{Level0isthesetofallunitsthatusenootherunits
{Leveliisthesetofallunitsthatuseatleastoneunitatlevel<
iand
nounitatlevel�i.
�Hierarchiesformthebasisofarchitecturesanddesigns
{Facilitatesindependentdevelopment
{Isolatesrami�cationsofchange
{Allowsrapidprototyping
26
Design PrinciplesHierarchy Example: The ACE Framework
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
27
DesignPrinciples
De�ningHierarchies
�Relationsthatde�nehierarchies:
{Uses
{Is-Composed-Of
{Is-A
{Has-A
�The�rsttwoaregeneraltoalldesignmethods,thelattertwoaremore
particulartoOOdesignandprogramming
28
DesignPrinciples
TheUsesRelation
�XUsesYifthecorrectfunctioningofXdependsontheavailabilityofa
correctimplementationofY
�Note,usesisnotnecessarilythesameasinvokes:
{Someinvocationsarenotuses
�e.g.,errorlogging
{Someusesdon'tinvolveinvocations
�e.g.,messagepassing,interrupts,sharedmemoryaccess
�Ausesrelationdoesnotnecessarilyyieldahierarchy(avoidcycles...)
29
DesignPrinciples
TheUsesRelation(cont'd)
�AllowXtouseYwhen:
{XissimplerbecauseitusesY
�e.g.,StandardClibraryroutines
{YisnotsubstantiallymorecomplexbecauseitisnotallowedtouseX
�i.e.,hierarchiesshouldbesemanticallymeaningful
{thereisausefulsubsetcontainingYandnotX
�i.e.,allowssharingandreuseofY
{thereisnoconceivablyusefulsubsetcontainingXbutnotY
�i.e.,YisnecessaryforXtofunctioncorrectly
30
DesignPrinciples
TheUsesRelation
�Howshouldrecursionbehandled?
{GroupXandYasasingleentityintheusesrelation
�A
hierarchyintheusesrelationisessentialfordesigningnon-trivial
reusablesoftwaresystems
�Notethatcertainsoftwaresystemsrequiresomeform
ofcontrolled
violationofauseshierarchy
{e.g.,asynchronouscommunicationprotocols,call-backschemes,signal
handling,etc.
{Upcallsareonewaytocontrolthesenon-hierarchicaldependencies
�Ruleofthumb:
{Startwithaninvocationhierarchyandeliminatethoseinvocations
(i.e.,\calls")thatarenotusesrelationships
31
DesignPrinciples
TheIs-Composed-OfRelation
�Theis-composed-ofrelationshipshowshowthesystem
isbrokendown
incomponents
�X
is-composed-offxigifX
isagroupofunitsxi
thatsharesome
commonpurpose
�Thesystem
structuregraphdescriptioncanbespeci�edbytheis-
composed-ofrelationsuchthat:
{non-terminalare\virtual"code
{terminalsaretheonlyunitsrepresentedby\actual"code
32
DesignPrinciples
TheIs-Composed-OfRelation
�Manyprogramminglanguagessupporttheis-composed-ofrelationvia
somehigher-levelcomponentorrecordstructuringtechnique
�Note:thefollowingarenotequivalent:
{level(virtualmachine)
{component(anentitythathidesasecret)
{asubprogram(acodeunit)
�Componentsandlevelsneednotbeidentical,asacomponentmayhave
severalcomponentsonseverallevelsofauseshierarchy
33
DesignPrinciples
TheIs-AandHas-ARelations
�Thesetworelationshipsareassociatedwithobject-orienteddesignand
programminglanguagesthatpossessinheritanceandclasses.
�Is-AorDescendantrelationship
{classXpossessesIs-ArelationshipwithclassYifinstancesofclassX
arespecializationofclassY.
{e.g.,asquareisaspecializationofarectangle,whichisaspecialization
ofashape...
�Has-Aorclientrelationship
{classXpossessesaHas-BrelationshipwithclassYifinstancesofclass
Xcontainaninstance(s)ofclassY.
{e.g.,acarhasanengineandfourtires...
34
DesignPrinciples
Program
FamiliesandSubsets
�Motivation:facilitateextensionandcontractionoflarge-scalesoftware
systems
{e.g.,theACEframework
�Programfamiliesarenaturalwaytodetectandimplementsubsets
{Minimizefootprintsforembeddedsystems
{Promotesreusability
{Anticipatespotentialchanges
�Heuristicsforidentifyingsubsets:
{Analyzerequirementstoidentifyminimallyusefulsubsets
{Alsoidentifyminimalincrementstosubsets
35
Design Principles
Example of Program Families: External OS for PBX
DATABASE
SessionRouter
EventAnalyzer
Reactor
SwitchAdapter
SWITCHES
SERVER
CLIENT
CLIENT
CLIENT
CALL CENTERMANAGER
DIRECTORYMANAGER
EXTENSIONMANAGER
NETWORK
ACEFRAMEWORK
36
DesignPrinciples
OtherExamplesofProgramFamilies
andSubsets
�Di�erentservicesfordi�erentmarkets
{e.g.,di�erentalphabets,di�erentvertical
applications,di�erentI/Oformats
�Di�erenthardwareorsoftwareplatforms
{e.g.,compilersorOSs
�Di�erentresourcetrade-o�s
{e.g.,speedvsspace
�Di�erentinternalresources
{e.g.,shareddatastructuresandlibraryroutines
�Di�erentexternalevents
{e.g.,UNIXI/Odeviceinterface
�Backwardcompatibility
{e.g.,sometimesitisimportanttoretainbugs!
37
DesignPrinciples
ConcludingRemarks
�Gooddesignsgenerallycanbeboileddowntoafewkeyprinciples:
{Separateinterfacefromimplementation
{Determinewhatiscommonandwhatisvariablewithaninterfaceand
animplementation
{Allowsubstitutionofvariableimplementationsviaacommoninterface
�i.e.,the\open/closed"principle
{Dividingcommonalityfrom
variabilityshouldbegoal-orientedrather
thanexhaustive
�DesignisnotsimplytheactofdrawingapictureusingaCASEtoolor
usinggraphicalUMLnotation!!!
{Designisafundamentallycreativeactivity
38