This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
'.It'lhen speCIfying ,he detaol< of a class, we start wllh the do maIn cia ses def,ned durong requirement< Wle ga,her the attrobu'es already defined a nd add addi ' io nal attribu ' es reqUired for deSIgn Wle also der.ne cia,s and method Invariants, and me' hod pre - a nd postcond " ions . Pseud ocode IS wrottcn de,cnbe how each me' hod is '0 be Impleme nted. W e ' hen add ad diti o n classes necessary ' 0 comple ,e the dc
'0
'0
describe nontnvlal algorithrn~ Some.: detailed designs are best commun icated via detaded scqllcncl.' dlagramc; o r de,ailed da,a Row d,agrams. Sequcn e diagrams sho w , he obJe ' s assoeoa,ed with a partIcular use ase and the messa ges (, c ., func"on ca lls) ,ha, flow be,ween ,hem . Da,a flow d,a gra ms show procesSIng demen', (, c ., methods) In a program and ,he da,a ,h., flow between ,hem The de ,a lied de
19.15 EXERCISES 1 Explain the followln !! la ) -rn, purpose nf detaolcd deSIgn (I", 'hrec hendl" ) Ib ) Howl' dolfers from s,,(,ware ..th"e<.lurc
Cc) Why
Il ,\ gencrJlly
i1
quc"Illonablc ,dcJ to J.(O dire
dy
from JrChlit:<..lurc to Imp! cf1l l.'nti1t1on
505
506
CHAPTER 19 DETAILED DESIGN
2 Your ompa ny produ es
3 E. lIm atr the num ber of lines of Jav3 ode fo r the fo ll owln 8 sc t of me tho ds. T he met hods arc o rdered fTom malles t to large t. Assum e t bat th ere IS no thin g un usual abou t t he Job ",apt as indica ted In th e informatt on below ,
Met hod L 110, Me th od 2, T ex t, Me tho d 3, Calcu latio n; Me th o d 4. Log ic, Met ho d 5: Data , Me th o d 6: Calcul atIO n; Me th o d 7: T ex t, Me th o d 8: Da ta; Me th o d 9: et· up. Me th o d 10: Calcul ati o n; Me th o d II : T ex t; Me th od 12· D ata
4.
o mpic te th e fo lioWIn!:, ex pl ai nin g und er what ci rcumstan ces you would use th e fo llowi ng in detai led desig n. (a) Usc activity d iag rams whc n the logic _____ . (b) Use p eud ecode fo r a meth o d whe n _ _ __
5. Define appro priate interface th at th e fo llowing cia , exhibits (o r "impl eme nts" in Java te rms). Assume that addll'l o nal meth o ds w ill be required as th e appl ica tio n g ro ws. Ex plain your reaso ning. Hi,,! Th e Interfaces ind icate w.hat kind of tran saction th is is.
6 Describe in your ow n wo rds th e advantagc:s of specifying preconditions. postcond itions. and
In varia nts. H ow, speCificall y, do th ey help to increase th e quality o f fun ctio ns? 7. Perform a desig n (bo th architectural and detail ed ) fo r a check· ba lanc ing appl icatio n with the fo llow,"g req uire me nts. Fix defects in th e requireme nts if yo u Rnd th em . Yo u can play th e role of customer If and w hen the cusromcr's input is required. Repa n the l ime you spent on Sig nificant actl viril-s to the neares t five minutes.
I. The system , hall d is play th e current balance ," th e system windo w.
2. The sy tern perm its the user to reco rd deposits of up to $ 10 ,000. 3. Th e system perm its th e user to wit hdra w any amount (rom th e current balance. A n error message 1""his wi thd rawa l amount exceeds your bal ance" is d ispl ayed w hen (he user att empts to withdraw an amount exceeding th e balance.
S. A cl05S1C Liskov substitut ion princi ple exa mple co nSiSts of two closses, Squa re and Rectan gle. Since a
is-c, recta ngle, the rela tionship be twee n the two ca n be modeled using inheritance, w ith Squarr derivi ng fTOm Rerum!!/,. Sup pose that Rectangle has met hods to setlget the width, and setlget th e length .
square
Explain how th IS relationship betwee n quare and Rectangle vio lates the Liskov substitutio n princi ple.
TEAM EXERCISES SOD Provide an SDD fo r )'our project. Usc, or improve upon the IEEE standa rd. Please enclose the btest vorsion of yo ur SRS.
BIBLIOGRAPHY
Report [he rime pent h) the indl vldu :l l!) :l nd th e- group on rh e parrs o f (hl ~ as::,.ignrnenc. Break rh b down IntO a ctl\' Ltlt"~. in ludlllg 3fl· hu ("<.'tu re, lnsPCl..' tl O!l , reV ICW, and dt l3i led design. o mmcnt o n how lhl" tim e spe nt uJd h.I' " heen hen "r olJ"""tcd.
BIBLIOGRAPHY 1 f\ brtm RolX"rt A9.1t Sojhi •• Ht Dn'tlopI'IICI'II P'lP1ul'ln Purim!. DIlJ P,.ldlCt'I P"mltlC Hall 100J 2 M~"ln Roben 'DnJ9" P'JP1ctpln .",(11)0111" P,,'knh 2000 ''''''''''' ohlcctmcntm l.()m ' n;..ourc<..~"'r1Ic1C'VPnnclplc.",_i) nd_I),mcrn' pdf l )(.cc"~ No\'cmtxr 2<) lOOQ ] 3 13rtlO Rolxrt . Th Dt~J(JIIY Itlw,.,u)r\ PnP1C1p/r . •• Rerort lI.1.:J.) 19Q6, hup ''''......., obJC'clmentOr com..r·c.. ourcc .... 3n .cll!"'i. dip pdf " 5 6 1
l.lcC'e-...ed 'ovcmbcr 29 2009 } Thc ObJct t ~li"lJ8("mcnl ,mup ...."""'" omg orlo: ( ! 999) lurJcn!!o Iln StUff Sy)rt7rl\ I)nxlop"'(11\ 11"111, Llt\ ll pnnRer, 2005 Humphr("V \X'ltl.. A D')(lp/"t( jilt ojIU',H( En911fuwlQ 'f=( Snln In _oJhi'.Jtr EII9"l(trI,,!/ ), Add, ..on Wc:..lcy 1(1') Jon~, .:apcr .. "ApplIed Sof/lI'tl rt ,\t(;l\u ft'l'llrrrl As\un0l9 P'O.rUtlll'l/), uOIn (.lw.,llly. 2nd c:d'Llo n Nc",' Yorl.. M Cra\\ HIli 199(, Q M r'1Jm.tlon Pornt Lan.,.'U:st;c.. T.:able, (A pn l 2005 VersI on ~ O) Imp '1 ",,,,.,,,. q ~m cOITlJre~ourcc"dun<.hfJn pOint Lm,,;u.lMe<. ·tahlc
,"deJe htlnl [accc:,.. ovcmbc:r 2Q 20091 9 !cyer Ikruand Ob)t'C I.OnmleJ 50jlll'I'II./"JOI ~ccond Edition Prcnt KC' 11311 20<,7 10 L,~l..ov B.a rbJr.l and John UU;:J.I<: Ab-t,... dIOIf anJ IltnfiWh"" '" Pr~rdm DnH/"pmtnl i\IIT rrc:-.~ IQS6
/
/
507
uality and Metrics
Design
Planning
•
How do you assess the degree of understandability in a software design?
•
How do you assess the degree of cohesion and coupling? - degree of sufficiency?
Maintenance Testing
The Software Development Ufecycle
- robustness? -
Requirements
analysis Implementation
flexibility. reusability? time efficiency. space efficiency? reliability? security?
•
How is quality in architecture selection measured?
•
How is the quality of a detailed design measured?
Figure 20.1 The context and learning goals for thiS chapter
Si n c a se t or requirements can be accommodated by several possible de igns . we can compare lhe q"<1/ily o f ca nd id"e designs . As explained in C hap, cr 15. 'he qua lilies a a design Include uHdcrsttJnda b.lily , modularity , ('obtsio 'l , cOL/pIing , suffi ItH CY, robiot sh1rH, flexibility , r(u sab""y~ rjfintHcy. and rcl,obil"y . PrO)CCI leadership specif,,:s the desired level s of quali,y in lhese respeCIS, ba lanced allain t the: avai lable rc s o urcc~ . Reca ll that suffiCIency meilns that the desig n accommodates th ~ requirements. Any measure of design quality includes this at a minmlUm . For example , suppose that the requirements arc tor an application that
,
DESIGN QUALITY AND ME I Hies
manage, I 0 renlol , A de"g n o n"'lln8 o nl y of Ihe cia
How
•
• understandabl e (H ow coheSive Jnd cleJr arc th e parh and hov.' low I the number o f o nnectl o n between pans)
0:
lcdr p,uts mId
IIH
10
many (Dlmecllom mtlot'g limn
very Llndcrst,wdablr pa rts
t()llh
feu 1 mlCrCOlltiCc/l ons
• sufficient (H ow eVid entl y It accommodalC:s th e requlrc." ml'nts)
0: "",rla'rd to the 10·
Ob l1l0U
rcq l4lrcrnnTh
I)' accot1llnoda lrs
(PO), rcqlUrctflol l
• robu st
0: (IHY ,"put alforuoly hilS scnous oll srqu(Jl(ts 10: tvtr)' ",put (momaly acconlltl oda ttd smoothly Figure 20.2 Qualities of a deSign-rough metrics, 1 of 3
How
•
• flexi ble O. a~hclpattd (lddr "o~al rrqrurmwrls rtqulrt rxt(H ~Wt ciJangc 10 tlu drsrgll 10 most tml' ,palta rtqurrtnltllfS rrqUlrt 110 I](wgr to flu drs /gIl
• reusable O. t10 part of tht dtSlg t1 eml br IIsrd III otlJtr aPP/IC(lII01l5 10 mort Ihml 75% of Ihr classts Cntl br used", ol/'rr appi,ca lrOPls Figure 20.3 Quahties of a deSign-rough metrics, 2 of 3
How
• dficient. Imp lcmwta lr oll basta OJ! tim Jr '9" . o WIll probably 1101 c.uel/lr (II rcqurrrd sptrJ or IfSt rrqUlrtd slomgr 10 . wd/ exe "Ie ","h as much sprlll mltl slorngc 10 PIlrC as rttl)ol/ably ,"ouerllla!,le • reliable: ' ,"plt,","I""o» blll
• 0 • 10
•
wdl probal,/y rxccrd 11K rrl'tl X/lfIlHn alloulnnlr 11IIII/crab,l,t)' tWill w/II,lrob"bly heW! IH jtW lJuhlrmbrl"Ir\ tH ( .111 IJr rXI)rc /rJ
Fjgure 20.4 Ouahoes of a design- rough metriCS, 3 of 3
509
510
CHAPTER 20 DESIGN QUALITY AND METRICS
20.1 DEGREE OF UNDERSTANDABILITY, COHESION, AND COUPLING The main rcason for a design is to (orm an lInd('r~tandIO B among the software engineer) of how the applicatIon
wIll a nlally beeoded I,' reall y a foml of communi a"on , and ,0 ,he qua lilYof a desIgn depends, In pari , on II< under
'0
Ilugh t as \\.Ie ll co nsi der tht" clpplica tlOn to co nSist of emirci y scpar.ltc ones.)
Fan-III andfnn.olll are measures of the degret" of coupling of modules Fan -In (or a co mpo nent counts (he
number of co mponents that referen ce , to' f
by spec,al,z ,ng ,he na'UTe of the refe rences (e .g , ' call ing a funct io n o f"). Low coupling is refleered by low fan- in and low fan-oul. For morc o n ,h is , sec [ I ) and [2]. TI,e fo llOWIng IS an example of a melTic for understandabiloty. It de pend o n definitions of "stro ngly cohe ivc" and "ve ry few ," but the c can be made precise fo r a givc"'n fa m ily of app lica tions.
Understa ndabil ity metric = III x Percen,age of strongly cohesive modules
+ !II
x Percentage of modules co nnec ted to very few oth ers
Section 20. 10. I descri bes melTics for connectedn ess alo ne.
20 .2 DEGREE OF SUFFICIENCY AS A QUALITY GOAL An c se ntial quality goa l is to produce a design that accommodates the requirements. Designs can co nsist of
man y parts, bu , we' ll co nsi der a si mple exa mple store appl ica ti o n ha
'0 illustrate degrees o f sufficie ncy. Suppose that o ur VIdeo
the fo llOWing requ iremen t
Clerks shall be ab le
'0
c heck in DVDs
Clerks hall be ab le to check out DVDs The Jrgrrt oj ,.JfiCl<,,0' measures the ease with which a design accommodates these requirements. DesIgn I In , F,gure 20.5 , for example, would probably score very low o n this q uali,y scale because it fai ls to capture 'he DVD , the CUSlomer, o r the rental on a rea dIl y Idenlifiable way. (This desig n could be ",ad, to work-it's Just not a high ·quahty deSign give n th e reqUirements .) Design 2, on th e oth er hand , is su fAcie nt to capture the requiremen ts (or a reall ti C vi deo store
The following is a useful me lric measuTlng sufficie ncy I, depends o n having a tho rough set of detailed • requirements.
Sufficiency metric = Percentage of de,ailcd requirements clearl y accommodated by the des ig n
IncreaSI ng the number of classes does not necessaril y raise the quali ty of a deSIg n, Redundan, classes act uall y derract from qua lity . AdditIonal classes may be needed fo r other quality measures such as Aexib,llty and robustness
DEGREE OF ROBUSTNESS AS A QUAUTY GOAL
Design 1 / /
VldeoSlore /
checkln()
.-
/'
/
Design 2
/
// /
checkOuI(j /
/ /
/
./
1
VSCuslomerBase
VSCuslomer
1
/ / /
/
/
/
/
,----, VldeoSlore
DVDRenlalSel
::::::
1
DVDR ental
checklnO checkOutO
1
1
•
DVDlnvenlory
DVD
Figure 20.5 Measuring the sufficiency of a design-video store example
20.3 DEGREE OF ROBUSTNESS AS A QUALITY GOAL A good SRS contains explicit robustness reqUirements. For exa mple , Ihc vi deo store ma y requ ire that the application react to the entry of an inva lid vIdeo name by refreshing the rdevant screen " 'Ih a blank In the oidro 1111, window an d popping ul' a window stali ng "No such video - Please re ·e nter." Explrcit ro blls mess requir<menls like this are measured with the "sufficie nc y" qua lity metnc. If a slalement like thi s IS nOI an t:
Design 1
Design 2
1 •
VSCuslomers
•
VSCuslomer
1
VSCuslomer
VideoSlore
customers DVDs renlals
DVD
DVDRenial
I I I I I I I I I I
VldeoSlore
DVDR eniais
•
DVDRenial
1
1 DVDs
I I
•
Raure 20.6 Measuring the robustness of a design- VIdeo slore example
•
DVD
511
5'2
CHAPTER 20
DESIGN QUALITY AND METRICS
Degree
(0
which (he
design rea cIs ideally 10 anomslous mput 10
..---.--.....- - - - - - .. - ..- .- -..- ..--------..... ---.........- • I•
I I •
5
I•
------_.._-----_ ... - ... __ ..
•
I I
•
I• •• ••
I•
i•
,
• ••• •
I AppliC<1(ion will crash hall _ _ _ _ _ _ _'----> •
o
•
the time when it
WIthout a trace if It
encounters any wrong or unanticipated input:
encounters any wrong or
Will recover ideally half
unantIcipated input
the time
Application w/IJ crash
:>
Application will recover Ideally from any wrong or unanticipated input
Figure 20.7 A rough robustness metric
In Design I . the VideoS ,"" class cOnlains a collecti on of VSC",'omrr objects, a collection of DVD objects. and a collection of rentals . Each rentJI can be maintained as a paIr consisting of a Customer object and a DVD object. DeSign 2 wa.s discussed above. To assess the robustness of Design I , we think about how to handle anomalous irualions such as attempt to en ler data for a none xis tent custo mer. This is more easily
accommodated with a class con taining all customers- si mdarl y for DVDs. The deSign should also accommodate: erroneous rental cntries-for example, a customer forgetting to take hi s vi deo rental with him from the store. Thi s attribute of
IS
more easily accommodated with a separa te
DVDRrulais class than with a vector
V,JroStort, because the latter is less visib le and because it occurs among several other, differing
attributes.
A metric for the robustness of a design is shown in Fib'ure 20.7. It uses the ph""es "reacts Ideally" and "recovers Ideally." These have to be defined in the co ntext of the application .
20.4 DEGREE OF FLEX IBILITY AS A DESIGN QUALITY GOAL It is com mon to assume that the more fl exi ble a design, the higher Its quality Reca ll. however, that flexibility may come: with a price in lcmlS of deSign, development, and maintcnance time required. For these reasons, it IS not always pursued. Agile programming. for example, aims (or deSigns that atlsfy clear requIrements and no
more . Nevertheless, a judicious choice of fleXibility in a design can save time by facilitatrng change Figure 20.8 show the trade·offs of creating flexibility in dcslgns. To measure the degree of flexibility of a dcsign. one can CO Unt the levels of class inhentance and th. number of dcsign pattems used . Although these give some indication, they can al 0 encourage poor qualities in other respects if pursued Simply to make a metnc become favorable . Exton ibility is one face t of flexibIlity And so another way to measure extensibility, in pan. is to make a I,st of reasonable additions to the application's requirements and to evaluate the deSign's ability to extend and cover them .
DEGREE OF REUSABIlITY AS A DESIGN QUAlITY GOAl
Costs of Flexible Designs ® EXira cost (time) needed ® May resuil in clunered and
Benefits 01 Flexible DesIgns
e e
Facilitates added requirements
less understandable design
May result in more elegant
® Time wasted if requirements
expand in unexpected direction
and understandable designs
~
Figure 20.8 Cost-benefit trade-off of design flexibility
20.5 DEGREE OF REUSABILITY AS A DESIGN QUALITY GOAL Reusability has many benefi ts but may detract from an application's quality because it I intended to benefll future projects rather than justth. current one For example , some energy is di verted from the current project. However, if the application under design '"'' a reusable component , then thIS usua lly benefits Its quality because the component is likely to be more reliable than those ye l unused. Ler's assume that we want a particular compone nt (e.g., a cia 5) to be reusable. Fo r example, how do we ensure that the DVD class ca n be used in multiple applicarionsl How do we measure the extenr to which a particu lar class is reu ablel First , the component must have high quahty in the usual se nse-be wellte ted, for example Interestingly, Items can be reusable because they arc generic (we use "wood" In many projects) but also beca"s. they arc speCific (we use I 'I. -inch machine screws 10 many projecrs). Th i difference places classes into roughly lWO reuse categories· those that are usefu l becau e they belong in a framework and arc reused because they are general : and those that are special to the business al hand, and form part of its too lkit. ParameterizlOg a method makes it reusable but too many parameters make it clumsy. Figure 20.9 hst some of the key qualities we want for reu ability, and their limitations. (The last point In thIS ~gure refers to multiple parameterizations of methods with the same name and si mdar purposed.) Figure 20. 10 indica tes how these may be measu red listing 20. 1 is an example of a cia s that would rale high o n rell abdity , as explained below U s 109 the measure of Figure 20. 10, we would rate the reusablhty of this code as follows ·
• Abstract enough to get wide coverage • But too abstract = usc Ie. • For example, class R
513
5'~
CHAPTER 20
DESIGN QUALITY AND METRICS
• Degree or coverage o = ncghgi ble cove ro se or dllle"' ''1 apphCJ II OnS 2 = as wide as co n be expecled • Degree or conlenl o = neglig ible o nlt'nl or subslance 2 = very n ch onlcnt or associa tion... • Parameterization of method.s-a llows method reuse
o=
very restrictive meth ods; very narrow scope
2 = widely applicable methods Figure 20.10 Measuring reusability Degree o f coverage: V.dlOP(odu Cf covers any video item thal a vi deo stOre could possess, so "coverage"
would rale 2. Degree of content: The complete version of this class docs not have extenSive content , but nor does it havt:-° negli gible content , so we can rate this as I .
Parameterization of methods: The names arc about as complete as one ca n expect so thi s would rate 2.
lis reusabililY index is Ihus 5 OUI or a possible 6.
Usting 20.1: A detailed design example to be rated for reusability
1*
* Example of a class design highly rated for reuse
*
* Intent: Capture all of the properties and functionality of video
products * that companies can deal with.
*
* Examples of potent ial subclasses: DVD, Video *1 public abstract class VideoProduct {
--- ---------------------=---------------II CONSTANTS ----------------------------------------pr ivate final stat ic int MAXIMUM_TITLE_ LENGTH = 100; private final static int KAXIMUM_NAME_LENGTH = 100; private final static int MAXIMUM_NUM_STARS = 20; -------------------------- ----------------------- --------II METHODS --------------------------j ••• * •••• ** ••••••••••••• * •••••••••••••••••••••••
* Returns: The copy number
* Example:
3; i f title is "Gone With the Wind," then this would be the
DEGREE OF REUSABIUTY AS A OESIGN QUAUTY GOAl
* third copy of this v ideo product. */ public abstract int getCopyNumber ( ); / ***********************************************
* Returns: durat ion of this video product in minutes -- if
* otherwise
> 0;
0
*/ public abstract int getDurationInMinutes(); j***********************************************
* Returns: Title of this video product in English */ public abstract Str ing getEnglishTitle ( ) ; / ***********************************************
* Intent: Enter the title of this product in English
* * Preconditions: * (1) aTitle !=null * (2) aTitle has between 1 and MAXIMUM_TITLE_LENGTH characters */ public abstract void setEnglishTi tIe (St ring aTH Ie) ; j***********************************************
* Returns:
Name of the director of this video product, if known; * "unknown" if not * Example: Returns "Stanley S. Kubr ik IV" */ public abstract Str ing getDirector ( ) ; /**********************************************-
* Intent: Enter the name of the director of this video product * Example: setDir ector ( "s tanley S. Kubr ik IV" ) ;
* Preconditions:
aDirectorName != null (2) aDirectorName has between 1 and MAXIMUM_NAME_LENGTH characters (3) aDir ectorName is the name in the form fir st / last, fir st / MI / last, or first/MI/last/suffix
• (1)
* •
* • •
*/ public abstract void setDirector(String aDirectorName);
/* ••• **************************************** ••• • I n tent : Enter the name of the director of this vid eo product • Example: setDi rector( " Stanley ", 'S', "Kubrik", " III " ) ; * Preconditions:
515
516
CHAPTER 20
OESIGN QUALITY AND MEmlCS
* (1) aDirectorFirstNarne ! = null
* (2) aDirectorFirstName has between * char acters * (3) aDirectorLastName ! = null
1 and MAXIMUM_ NAMEJ,ENGTH
*
( 4 ) aDirectorLastNarne has between 1 and MAXIMUM_NAME_LENGTH * character s * ( 5 ) aDirectorSuffix ! = null * (2) aDirector Suff ix has between 1 and MAXIMUM_NAME_LENGTH * char act er s
*/ public abstract void setDirector ( St ring aDirector F ir stNarne, char aDir ectorMiddleInit ial , Str ing aDirectorLastNarne, StringaDirectorSuffix) ; / **********************************************-
* Returns:
Title of this video product
*/ publ ic abstr act Str ing getTi t le ( ) ; / ***********************************************
* Intent: Enter the title of this product in characters as close as
* possible to the orginal * * Preconditions:
*
(1) aTitle != null * (2) aTitle has between 1 and MAXIMUM_TITLE_LENGTH characters
*/ public abstr act void setTit le (Str ing aTit le) ; /******************************* •• **************
* Returns: Stars of this video product if known; otherwise * a single object "unknown" */ public abstract Str ing [1 getStars ( ) ; /*******.***************************************
* Intent: Enter the stars of this video product if known; otherwise
* a single object "unknown" * * Preconditions: * (1) someStaxs !=null
* (2) someStaxs has between 1 and MAXIMUM_NUM_STARS obj ects
*/ public ahstJ:act void setStaJ:s(StJ:ing( 1 someStars); }
DEGREE OF TIME EFFICIENCY AS A DESIGN QUALITY MEASURE
20.6 DEGREE OF TIME EFFICIENCY AS A DESIGN QUAUTY MEASURE ~7~ In~ct desIgns, and Quantl(y how fa>! they arc likely to execute whcn bU Ilt . F,rst. one identifies each
who e peed o( execution IS o( interest For example , we codd (ocu o n the speed Wllh which the Encounter video game transit lo n< (rol11 arca to arca " ,he n a hyperlinkcd connection i pressed. ( I( thIs take tOO long, the game loses the player's intN.S!. ) This opera tion IS illustrated in Fig"'c 20. 1 I. To assess the timc d lency o( thIs actIon , we trace the sequence of method calls that require its <,xecution and exa llllne ('ach o( the method< (or timing F,gure 20. 12 ,how the seque nce of function calls begInning with the pre si ng o( a hyperlll1k and end Ing with the mo nitor d,sp lay, ng the de tlnatio n arca. T o assess probable time delays, a table lIke T able 20 I can be used , It identifie the methods that are potential sources o( delay . We then tackle prob lem method one by one For example , we usc double buffering or build a op''ra11 0 11
compo ite image before rendenn g
It
on th e monitor.
The example in Figure 20. 13 co ntains no paralle li
IS
measu red on the rime
aXI
Figure 20.11 Time effitlency example from Encounter VIdeo game-lime to transition among areas
51 7
518
CHAPTER 20 DESIGN QUALITY AND METRICS
user
:EncounterEnvironment
:RPGMouse EvenlLislener
1. press
area
:Wailing
:EncounlerCasl
:AreaConneclionHyperlink
connection
:EncounlerGame
hyperlink
2. mouseClickcdO
3. handJeEvonlO 4. handleEvenlO 5. sotVlSlble( lalse ) X~
on
6. dlsplayAreeO
:Area 7. display()
:PlayerCharacler
8. dJsplayPlayorCharacterO
-j
9. showCnarllctorO
I
Figure 20.12 .o.ssessing time efficiency example using a sequence diagram from Encounter video game Metrics for time efficiency include the fo llowing,
Averaged elapsed time for opor-llion X. Maximum elapsed time fo r opcr.J ti on X.
Table 20.1 Identifying methods that are highest pOlenlial source of delay
Function
Relative speed o = negligible 1 = neither 2 = sigmficant
Press area connection hyperlink
a
2
mouseclickedO
3
handleEventO
a a
4
handleEventO
a
5
setVislble(false)
,
6
displayAreaO
2
7
displayO
,
8
displayPlayerCharacterO
2
9
shOWCharaclerO
Step
,
,
TOTAL
7112
DEGREE OF SPACE EFFICIENCY AS A DESIGN QUAUTY MEASURE
Execute method 1
1.. 1_ _ _ _--'1
[I=====:JI Execute method 2
thread 1
LI_...JI
Execute method 3
---------------------------------------I
I Execute method 4 I
I Execute method 5 ,-w_a_it/ L.I_ _ _ _--.JI Execute method 2
thread 2
IL-_--'I Execute method 6
f-I- -1--1--t-I- -1-1--t-I--11 --It------II~>
time
Figure 20.13 Timing diagram for parallel execution
20.7 DEGREE OF SPACE EFFICIENCY AS A DESIGN QUALITY MEASURE The second major efficiency issue is pace usage, seco nd ary (ty picall y, disk) storage, RAM usage, and binary source size. We will discuss secondary storage first. Analyzing econdary storage usage can be pcrfomled by identifying the operations that create storage n<eds outside RAM . T his divides hlrthcr into tempora ry data (which IS no t needed after execution ) and permanent da ta. Table 20 2 is typical of how we migh t account fo r this in the ca e of the Video Store application Table 20.2 Analyzing secondary storage SOurce method and class of storage creation or reclamation
Temporary or permanent?
Rental: saveRenralO
T
Maximum rate of Increase, uncompressed
Minimum rate of decrease, uncompressed
514 bytes per minute for 2 days
worst case 6 chents; Title 100 bytes; director 30 bytes; stars 4 bytes • 30; length 2. One title every 3 minutes.
Rental: removeRentalO
DVDlnventory' saveDvD() DVDtnvenrory removeDVD()
o bytes per minute for 2 days
P
• • •
•
., •
• •
•
•
•
90% of rentals returned within 2 days •
•
•
• •
519
'" ~ 101
9
11 1
12
13
':1
Q ~
;;1
;0
'"0
-
0
m
-
VI
"z
0
c
--
-
I --
- .4~t - ·75 i
•
~
••
l>
·:J)I • .45 1 I,
c ~
--
» z 0
•
•
•
;:
~
'"n-
VI
' 500 «OJ J
+-
3000 1,;oQ
2000
1500 1000 500
o 1
2
3
Figure 20.14 secondary storage needs over time video store example
4
5
6
7
8
9
10
11
12
13
1
DEGREE OF REUAB ILITY AS A DESIGN QUALITY MEASURE
Data are often compressed pnor to storage (at the ex pense of speed) . In that case the uncompressed IOrage needs are converted inlO comprt'Ssed·form needs. Usuall y, the key Issue in slorage i the amount required over the long run-in other words, the accumulation of dala . Suppose for simplicity that the 514 maximum bytes are compres cd to 100 bytes and that the store is open 15 hours a day. The accumulating needs are shown in the spreadsheet and grarh 10 Figure 20. 14. and they sugge t thc problem that requires resolution . Storage needs that increase without bound require special consideration. For this reaso n. designs often IOvolve periodic archiving or purging. In the ca. e of the video store, this could consist of itelating through the database weekly, charging all customers with videos whose fi nes exceed the DVO's value and archiving those DVD records.
20.8 DEGREE OF RELIABI LITY AS A DESIGN QUA LITY MEASURE This section discusses means for e nsuri ng and a sessing reliability at deSign time To assess re"abili ty 10 an overall deSign , we look for points at which the applicat io n i most likely 10 fail. Recall that the UML deSign models are us< casr. class , dala flow . and laIr. We look for a h ig h level fo r failure likelihood withIO each of these models. Figure 20. 15 indicates places for use cases where failure is typicall y most likely. Now let's consider how failures arc likely to be evident at the cla ss level. Here . we seck parts of the las model that are most likely 10 harbor failures . Figure 20 16 illustrate< twO likel y ty pes of fadure , choke pOlnls and
deep mbrrilaHcc. • Data collection
• From users • From other applications • From data communication
• Steps causing complexity • Use case indicates involved ope ratio ns • Anomalous situations • For example, attempt 10 rent multiple copies of a mOVie
Figure 20.15 Identifiable places in use cases where failure is typically most likely to occur Rental
• Cho ke po i nts
A class that relates to many other classes
VStoreRental ~
DVD
VStoreCuslomer
Customer
• Deep Inheritance Three or more levels of substantive inheritance
,~
RentalCus\omer
VStoreCustomer
,~
DVDRent.ICuatom.,
flcure 20.16 Identlflable places In class model where failure Is typically most likely to occur- video store example
521
522
CHAPTER 20 DESIGN QUALITY AND METRICS
member Get deposit
banks I bank
name
error
accounl ll & deposit
Validate atert/none
deposit
Get inquiry
User
account
account /l
dlsptay
Check for
atert/none- - -
accounlll accounl/l & deposit
launderingy /
& deposit
Validate inquiry
account # "-~__/
Make • • Inquiry
account /I
error
Printer
Display account Do deposit transaction
balance
account
query
data deposit transaction - _ __..
. database account
account data
Create account summary
Figure 20.17 Identifiable places," data flow diagrams where fail ure is typically most likely to occur-ba nking example
Ch oke points arc potentially probicmatica l because developers tend to make mIStakes when the sirua ti on IS complicated Deep inheritance can harbor errors because inherited propcnlcs arc not readil y
apparent to the develo per. The number uf types employed should be reduced, or aggregation should be used Instead to Indi ca te what qua l itlC~s arc added between ty pes.
Dataflcw diagrams
can expose failure pOints most readil y where multiple StTC3nl of datil converge.Figure:'
20 17 how< a partial data now for an ATM application. The valldal' d,posi/ and oal,da l' Inquiry functions eaeh relate to the most streams . The ilccount da tabase
dara now dia gra ms, we would invesligate by checking whether u e eases behave clearly 31 these points. We would ask whether a different decomposi tion wou ld make thiS clearer-fo r example, whe th e r it IS advisable (0 ge t separale types of Inquiries via separa te operatio ns
Choke points can be reduced by introdUCing additional proces ing nodes and by dccomposlOg nodes into multiple nodes. For example, we could split
\Ia',dalt
{nqUl ry IOto several validation o perati ons.
,'a',
The final desig n model we can inspect for reliability is the mod". Figure 20. 18
of
waiting
DEGREE OF SECURITY AS A DESIGN QUAUTY MEASURE
Setting qualities
Player --i Reporting dismisses repon window
Setting up Player completes setup
Player dismisses
set qualities window
Player
Player
requests
requests to
status
___~ set qualities
Foreign character
enters Brea Waiting Player moves t~ Player
ad/soont Drea
quits
Encounter compleled
"
l,orelgn character
Engaging
presenl} ..........
Foreign ___~::::
{foreIgn character
character
enters area
absent}
Figure 20.18 Identifiable places in Slate models where failure is typically most likely to occur- Encounter video game example
20.9 DEGREE OF SECURITY AS A DESIGN QUALITY MEASURE ~QJrity is a special casc amo ng metries because it concern illcgillmate "functionality" of the application that
it i capable of but is not specified. It may requ ire a ski ll ed perpetrator to obta in rh is functionality An example IS ' shall be capable of sending custome r c red it card info rmation to any specified e -mail !" How can one measure the degree of secu rity of a design? Recognize first that every applic ation must commu nicate with hardware or oftwa re externa l to itself, otherwise it could not execute. In so dOi ng , however, it acquires some vulnerabi lity . Figure 20. 19 illustrates the kinds of .n ifacts with which an applica tio n's object code co uld make o ntacr. These, in turn , ca n make con ta ct with o ther an,facts. In a sessi ng the degree of securit y of a design. we arc thus obliged to take a systems approach-that is, one that aCCOunts for the vu lne rab ili ty of o ur application In th e co ntext of the large r system within which it
[ Drive c:
Objecl code
FIgure 20.19 Analysis for security quality
Operating system
I
I
Drive Ed:
I
523
524
CHAPTER 20 DESIGN QUAUTY AND METRICS
I
no",
oontMltl~
In •
u 'gll IOCIUon
Security encrypl() gelUsersFromURLO
•
User Id' passwordl
/ /
/ /
""""""' " .....to tot
and password
Figure 20.20 Beginning design for simple secure login
must operate. The added dimension here is that we must look not only at the potential of our application for exploitation and damage . but also at its potential to harm artifacts to which it is connected .
Figure 20.20 shows a start for a design of a cmica l security clement of an application . Inspecting it for each security factor in Figures 20.21 and 20.22 provides a framework for assessing its level of security. We need to satisfy ourselves that an Impi""",lalioH neisls of the class model that satisfies every security factor-the class model by itself does not guarantee any of Ihe m. There are many approaches to measuring the security of a detailed design . We will discuss a few examples. In the Arst example , we make rough assessments, on a scale of a to 10 , of the main aspects of securi ty, as introduced in Chapter 18, These arc shown in Figures 20.21 and 20.22. Although it is difficult to make these assessments based on • detailed design , this process is better than making a single, overall assessment about the d.egree of security. For a second appro.ch example, consider the following metric examples, adapted from (3). Metric I Baseline Defenses Coverage, This is • measuremenl of how well the detatled design enables o ne to protect the environment of the application against "the most basic infonnation security thrcats"ll,ese require careful deAnition. but they do include viruses, for example. This metric assumes that security tools will be used such as firewa ll s and antivirus softw.re. Some vendors claim thai the coverage of devices by these
• Confidentiality • Degree to which data passed may become visible
10
the unauthOrized
• Estimated percentage of data compromi ses' • Nonrcpudiation • Degree to which parti e can prove the existcnce or agreement • Estimated percentage or unprovable agreements
• Integrity • Extent or ability to validate that data are not altered • Estimated percentage or messages alterable: in transit
In
transit
·i.e., of a specified severity Figure 20.21 Property· based security metriCS, 1 of 2
ASSesSING QUAUTY IN ARCHITECTURE SELECTION
• Authentication • Extenl of ability 10 validale user's Identity • E timated percentage of improper authentications • Authorization • Degree 10 which pcm'ission to deal wllh pnvi leged dala may be compromised • Estimated percentage of unauthorized permisSions • Availabi lity • Degree 10 which availability could be compromi cd; c.g., by denlal ·of·service attacks • Estimated number of availability' compromises per year "i.e , of g iven severity Figure 20.22 Property·based security metrics, 2 of 2
security lools should be "in the range of 94 percen! to 98 percent." The meaning of these percentages would require definition 100 , and backup for claims would be needed . Metric 2 Patch Latency, This is the time between the iden tification of a succe'Ssful securi ty exploll and Ihe devdopment of a patch that renders it impossible . Patches are usually replacement files . Thus, if the detailed design decomposes the application into an appropriate number of ,vell·iden!lfied (, Ies, patch latency is likely to improve Metric 3 Password Strength: This metric measures how hard it is to break (guess at) a password , in some ",ell·defined sense, including finding pOlential weak spo t where systems use defaull passwords. BreakinS passwords is usually perfonmed with Ihe assistance of separate software. Melric 4 Legilimate T rafflc Analysis: This is a family of metncs that measures the extent to which iIIegilimate traffic cou ld be allowed. It includes incoming and outgoing traffic volume, incomi ng and outgoi ng traffic size, and traffic Aow wilh the app licalion . A third approach is 10 put the detailed desi gn under a microscope, as it were, and measure Ihe extent to which it is likely to avoid common known securily gaps. One example is buffer overAow, In which the bound of an array are exceeded in order 10 access data in regions of memory adjacent to it. The content type of Ihese regions is effectively guessed al . Another IS SQL injection , which exploits the manner III which database queries are processed . This exploit e(fectively insert commands such as "send all credIt cards .. • wilhin an appa rontly innocuous input data Reid . Detailed designs ca n be speCified that help guard against many such oxploils. Tools are availab le to c heck for these type of overSights in code, but desig ns are less slandardized and tools checking for secu rity naws are rarer. In reality, we combine elements of all three approaches. A good reference for some of Ihe Ideas In this section is Anderson [7].
20.10 ASSESSING QUALITY IN ARCHITECTURE SELECTION
So far, Ihis chapter has ba cd design asse sment on the individual qualities that good de igns mllst po«c« ow we explore a more holisllC VICW of quality, starti ng with the hi gh·level view.
20.10.1 Metrics for Architecture Quality Although most applications can be Implemented USIOS one of evera l possible architectures, some cholce< are much better than others Important decisions like .rchite ture e lectio n arc made by first developing and comparinij alternatives Proposed archllectures are thorough ly exammed for defe ts, be allse finding a dde t at an early development ,tage has a huge payoff compa red wllh allOWing one to pC""t through the proc(' , and thcn trying to rcpalr It. As described In F'gurc 20 23 , one si mpl e way to comrarc ar hll ccture<" to weight the attnbllte, reqUired lind then »slgn a fuzzy qualifier to each candidate The kmd of procedure d("'~nbed In l' lllure 202 Lan then be
525
526
CHAPTER 20
DESIGN QUAUTY AND METRICS
Architecture alternative State paltern I.
design
Quahty weight , Quality
High
I· 10
2. ad hoc CUI· driven
3. State·transillon table
= 9; Medium = 5 , Low = 2
Extension
9
Hig h
Low
Medium
Change
7
High
Low
Medium
Simplicity
5
Low
H ig h
Medium
Efficiency , speed
5
Medium
H ig h
Medium
Efficiency, storage
2
Low
Low
Medium
183
126
140
TOTAL. (higher = beller)
Figure 20.23 A tuny method for comparing architectures used to compare alternatives. For the sake of simplicity, we have omitted some of the design qualities discussed above," this example. One way to weight qualities is to pick the most important one and give it a weight of 10, or 9 (if you want to provide for a qu.hty that may be introduced later). The least significant are assi g ned 1. and the remain ing ones arc given weights in between.
Important decisio ns such as architecture are often made by groups. A group uses a Dtlphi process when the members make individual deciSIons first . then submit them to the coordinator or leader. Boehm and Farquhar (sec. for example, (4)) introduced the "wideband" Delphi process in which the leader plots the results on a chart without artributlon to the owners and leads a discussion on the faCtors involved. The (oIJowtng metrics from the IEEE (5) can be used to measure the complexity to software designs. IEEE metric 13 . Numb" of ",Inrs a"d ",ils per madill, (package ) This can be equated with the number of public methods accessible from outside the module. The number of exit poi nts can be counted by the number of public functions that return values to the caller or make changes in the environment external to themsel ves. The goal is to keep this mea sure as low as possible to favor narrow interfaces.
IEEE metric 15. Gr"ph.lb,ortlic complrxily for a"hil,elu". 11,e simpler ("static") version of this metric is (Number of modules in the architecture) (Number of modules having at least one connection between them ) + I The goal is to keep this number high, since a low number indicates many connections and thus an increased potential for errors.
IEEE metric 25. Dala or i"formalto" flow complrxily. Thi measures the information flow of large.scale structures, the procedure and module How compleXity, and the complexity of the interconnections between modul ... The read .. is rderred to metric 4.25 of [5 J for the delails
ASSESSING QUAUTY IN ARCHITECTURE SEUECTlON
~
...
,I
SimConfiguration :
, "':
:
r - - - - - - - - , ,, ,/ "
"
~ ......
/ / / / / / ' .... ~...... ......
: ,,
/
,
,,
/
/
/
Simulation exeoute() initlalizeO
setUPO ,, ,, , ,, ,,
,
ITellerl<> serviiouration - --- ---- --------- -. --.--.~
time()
... .
,-------- _
:, Random :
,,
,,, ,, ,,,
~- ' - -- ---
j,olNumberl
,
~-- - - --------- --
,
..
,, ,,, ,, ,, ,,, ,, ,
. ~.
·i· ...·.. ·· .. I I I I
...
SimConfiguration
,,
;.n ___ n u __ .! __ ___
: ISimltem L L . . ; : //:..~ _________ __ Cl ----i SimEvent l
, laueueForTefle¥
,, ,,,
,---- ---- --- -"j : SimEvents :
: Slmltems : !. _n" : :
;. __ u . _ u n _ n . __ u , I
... ----.---
•
I
·!
.------------, : SimDriver :,
---~ - --~ -- ------ - --- ...
I
:,
I I
I
ScheduledEvents addEvent()
,, removeEa~ iestO ,, __ • ___ ___ _ __ _ __ ___ _ _ _ ______ _ _ J
Figure 20,24 An architecture for a simulation
A conn,etion between modules A and B is dependence in either direction As an example , we can app ly metric 15 to the architecture of a bank simulation shown in Figure 20.24 . The architecture d ivides the simulation into the following pac kage . SimConfiguralion-which describes the way in which the stat io ns are laid o ut wilhin the bank Sim/irms-which describes the e ntiti es that move abo ut with", the bank (primaril y customers ) SimEvrnls-which handles the pre ent and fu ture simulated eve nts that take place in the bank (e .g ., a customer arriving at a teller window )
Simu/o,ion-t he mechanism that drives the simulatio n (primarily by selectin g the next even t to execu te , eX~c\lting it, then orchestrating the consequences, includin g the ge ne rati o n of resultin g events, and
queuing them in the Sch,du/cdEoOl ls o bjec t)
Random-the package that ha ndles th e ge ne rati o n of random numbers accordin g to variou di stributio n (for example, produci ng th e duratio n of service for the ne xt transacti o n) This architec ture is desig ned using th e Facade deSig n pallern , and we will suppose th a t th e o nl y inl
527
528
CHAPTER 20
DESIGN QUAUTY AND METRICS
-------------,
i RoiePlaylngGameJ r-- ---- - - -------- -- ---- - ------------ -~------ -- - -- I I I I
~l1a l.
RPGame
I I
handle Evenl()
I
-
I I
.l
I I I I
I
GameState
( stalo .handleEvont{).
I I
lIandloEVtJnI()
I I
I I
I
I I
- -------- ----- - ------------------- ----- -- ------ , --
EncounterGame
--------- ----- -
.,.
~-- -------- ~ : EncounterGome II
- --- --- - - - -- -
~
I I I
Waiting
~
handleEvenlO
handleEventO
I I I
I I I
I
I
I
SettingUp
Reporting
Engaging
I
handleEventO
handJeEvenlO
handleEvenlO
I
I
I
I I
.. _- ----- --- --------------------- - --- - - ---- ------- -
Figure 20.25 An archItecture for Encounter. State design pattern applied to the video game
20.10.2 Choosing an Architecture among Alternatives We res. [the urge to commit immediately to one arch itccrure by compa ring alternatives. A an example , let's co nsider th e architectu re the Encounter case srud y. Alternative I for the Encounter case srudy: State design pattern . As shown In Figure 20.25 , the State design pattern is a possible architeclllre for Encou nter. and we will
or
,,,,de " off agai nst ot her cand idates. Alternative 2 for the Encounter case , tud y. ad hoc C UI ·driven arc hileel'lIre. A second arc hItecture mig ht dispense with the idea of state altogether and build scparale eventhandli ng code into each CUI object th at is sen itive to mouse or keyboard actions. Such an arch itecture is
shown in F,gure 20 .26, where selected metho ds arc included to clarify it. r- _
___ _
_
-,
I ActionLlstener I
_____ _
c~
_ - - - - __ J I
Area
2
•
dlsplay(}
AreaConnector areal area2 IransilionO
ForeignCharacter I
PlayerCharaclerWindow PlayerCh.racte r
Figure 20.26 A second alternative architecture for Encounter
set( Quality. float) exltO
ASSESSING QUALlTY IN ARCHITECTURE SEI.ECTlON
Kry
if"'-
Event
tMll 0Ct1i" d..Ir~1rr
.", ... 1
_m.-
,..[onorht ('0110,...:»1,"9 dOflrllltbc
Rcqu<St Old on
q .. llty
exI.
CNnac
Co '0 Ind.otcd uca
DlsmiU qUJllity window
Forc!an character
Foreign dYractCT Ic.ava
.nten
Show quality
~~ qua,llty
window
window, and
Ch1r.lClcn,
Tr3osltion to
tnMltlOn 10
W4rlrnt1
&.Jilgi..,
0&
st3te
how both and
SI41tc'
Compute
results Engoging
or
engagement,
(do 00Ih'"8)
and transition
Current State
to Wallmg "Iat~
SrHlng
T r;lnSllion
quUttcs
\\'''1/'''9 Slate
to
Tr.lns,llon to
Tran"llIon to
E"g3!11J19 Siale
Wall/Kg :l.lale
Figure 20.27 A tIlird alternative architecture ror Encounter: table-<1riven state·transitions
In this architecture the hy perlinks at the exi ts to areas are (C UI represe ntati o ns of) Art. Co"",elor objects; and each has event . handhn g code . Fo r example, clicklOg o n an exi t to the dungeon sh ould cause the screen to display the dunge o n arca . The resulting design is CU I·drive n, somewha t ad hoc, an d language· specific . There is no clear connection , howeve r, between the code for this design an d the conception of the game as a series of srate transi ti o ns. As a benefit , however, the lass model co ntains fewer classes. Alternative 3 for the Encounter case stud)" stare · transitio n t.ble. A third architectural alternative is to re tain the idea of states, bur ex press the slate transitions by means 01 a table. Table·driven state transi tio ns arc emphasized by Shlaer and Mell o r (6), fo r example r.gur. 20.27 is an example of such a table. n,is architecture uses the State co ncept, but it does not use the State design pattern . Here is a list of pros and cons contrasling the Srate desig n patte rn with the table·driven approach . A flliler comparison of the three architectures follows . Pros of uSIn g the State desig n pattern, • Can easily add o r mo di fy states to accommodate c han lle in ga me desig n • OariAes what actions ca n be done ," various circumstances • OasSifles all mouse eve nts that ca n affect En o unter Cons of using the State desig n pattern ' • Oa<s model is more IOvolved ~nd In.tially more difficult to under
529
530
CHAPTER 20
Fuzz
DESIGN QUALITY AND METRICS
me tho d for compann!;
Arc hitecture alternative
ar h,rectllrcs
2. ad hoc CU I·
I. Stall design pattem
Quality weight, I . 10
Quality
driven
High
-
3. State · transitIon table
9; Medium ' 5; Low = 2
Extension
9
Hig h
Low
Med,um
Change
7
High
Low
Medium
Simplicity
5
Low
Hig h
Medium
Efficiency, speed
5
Medium
Hig h
MedIum
Efficiency, storage
2
Low
Low
Medium
183
126
140
TOTAL (hig her
= bener)
Figure 20.28 Fuzzy method for comparing architectures for Encounter Pros of lIsi ng a table (or describing state:
• The table
IS
easy to understand and the contents are
C,lSy
to cha nge .
• n"us architecture can be implemented in a non -abject-ori ented language.
• DocumentatIon o n thi approach is av.i lable using the Shl.er- Mellor metho d . Co ns of usi ng a table for describin g state, • It requires a data
Fi gure 20.28 shows a comparison of the three architectures usi ng the proslco ns tec hn ique described above. Given th e weightong shown, which favors extensibility and chan ge, the architecture based on the State design pattern comes out ahead. R~ga rdlC'ss or the sys tematic means one uses to evaluate alt crnativt"s , engineers also perfonn "sanity
checks," uSing holisti c pcrspcctiv~ and the in tuition and experience o r tearn members . Thi s may concern the
number of classes Invo lved or even subjective factors such as e legance. If the result disagrees ",ith th.t of the more objective process we have d~cri b(:d. engeneers ma y re -ex amine th e process and the result'S.
20.10.3 Verifying Architectures Usc ca es are developed to expre ss customer requirements . Th ey ca n't take IOto account the applicatIOn's architecture SInce it wi ll nOt yet have been dt:tcnnincd. Once th e architecture has been e1 ~cted , howcv~r, it
is <<sential to revisit the usc cases to check that the arc hI tecture supports t hem adequatel y. For example, the Engag
ASSESSING THE QUALITY OF DETAILED DESIGNS
..._--1 Reporting
Setting up
Player
Preparing
dismIsses
Player
WIndow
completes Player dismisses qua/Illes
menu
Player
requests status
Move 10
Foreign character
enters area
Player
ready 10
Waiting character
_
Engaging
_____~p~r~oc~e:e:d~-=~
enters area
Figure 20.29 Defects ,n the state· transition diagram for Encounter Since we r("tam the domain classes throughout the process, th e cla .. sc~ Orlg mally rel'e rred
(0 111
the u.. e
CJC
should be present among the lasses in the deSign. T YP icall y, Ihe <equcnce d,agr.lms for Ihe u<e ca,es now involve additional architectural clas es (e.g., Facade cI",es). Architectures are inspected against rcqwn.:mcntCi. The me-t n
c; nlcntl o lH.-d
above provide.: a
oncrc[C'
baSIS for the inspection. For example, in
20.11 ASSESSING THE QUALITY OF DETAILED DESIGNS Recall that detailed de Ign con
I
20.11 .1 Techniques for Assessing the Quality of Detailed Designs Figures 20.30, 20 3 1, and 2032, how "cpS for en
properly
1'\
compicte h
'rc
I') c:3
v l'nough to c he k lhJl every
111c...' thod
of evcry clao;;~ .,
,f,cd , bUI how do we know thai we have InLlu(kd a\l of Ihe la"e, and method, that arc nccC5~ry? To do fhlet , we r ' IUrn to the: req UIrement .. Jnd ell.)urc: that th e dt'tal1cd dC'lgn We have dl'vclol"cd accommoda tes all of lh r QlIlfl.'Il1Cntf.o If we lI~C: tl1(; rc:qulrc nH;' nt~ org;\lHzilllon ", In tht· CJ ;"C ,Iud tht'n \\.: kncsw Ih;lI every (uncllonnl r ' qulfCnlCnt Lorrc<.pond, to J ~pl·c..dl C fncthocl nlll''' , th e fun cIIOll:l1 COlllpICtCIlC,\' tilk II r duccd '" cn,"r/ni/lhat ca( h of thel Ill~thod, Lan be la ll ed at an appr pnate pOint In the c'c IItlon CUn!.,d r, (or ex.amplc.', the
r<.'qul(CnI
~ nt
531
S32
CHAPTER 20 DESIGN QUAUTY AND METRICS
I
2.
3 4. 5.
6.
Prepare to record metrics durong the design process . o Include ( I. 1) time taken , ( 1.2) Iype of defect; ( 1.3 ) severity Ensure that cach architecture module is expanded Ensure that each element of the detailed design is part of the architecture. o If an element docs not belong to any such module , the architecture may ha ve to be revised Ensure that th e de is n fulfills its required functions . Ensure that design is complete (classes and methods ). Ensure that the deSign IS testable .! !See C hapter 5 for inspection procedures.
Figure 20.30 Inspecting detailed designs, , of 3
7. Check detailed deSign for • Simplicity a design (hilt few can understand (after a legitimate dfort!) is expensive to maintain , and can result in
defects • generalit y o
enables design of si milar applications) cxpandability enable c:nhancements~
o
o
effiCiency speed , stora ge portability
Figure 20.31 Inspecting detailed designs, 2 of 3
8, Ensure that all detail is prOVided o
Classes • C lass Invaria nts clear] (required limits on attributes; required relationships among attribut~ )
o
Method • Preconditions
• Invariants • Postconditions o
Pseudocode
Figure 20.32 Inspecting detailed designs, 3 of 3 •
3.2.EC.3 .2 ConM u,.bifity of Encounter eboraetrr quafity vafu" Whenever an E"counttr character is alone in an area, the value of any of its qualities may
be
sct.
The value chosen must be less than or equal to the sum of the quality values. We have already ensured that a function to perfonn this requirement exists, but to verify that our desill" supports the execution of this function , we have to dfcctivdy walk through a fully rep~nt'li~ s..! of
-
. ASSESSING THE QUAUTY OF DETAILED DESIGNS
functio n alhng sequences. each of which exe rCises the funclion . This amounts 10 develo ping a scI of menIal tOSI aSt'>, and the re ult< should be aved for Ihe tcstlng pha e Here" such a set. Bcjln
game'l cflll liP wmdo w to stt qwaillJC), srI quality, sri qualify "galli , dJsmls wmdoUl
AIOl't 10 area
Ull'"
no forti9" hamrlcr, call liP u.),"dow to 5(1 4I1al,IIrs, sri qual,ty, d'srtusS wmdolD
Camplttt rngagtfflnrt, wall 1111111 jomgll charaeltr drpnrts . call liP Illllldow to 5(1 quaI, tits,
set qualIty, dISmISS
IPtndow
For each of these cenanos. we verify Ihat Ihe classes and method< do Indeed eXist 10 accommodale II Once we ha ve done Ihls fo r every functional rl'quirement, we will have ve ri fied our deSign from the fu ncll o nal POint of VICW \Vlc can perform a Similar process with our detailed deSign for every nonfunctional rC'qlllrcmcnt ~
\'(Ie can venfy mentally, and via calculalion (e g., In the ase of liming) Ihatthe deSign suppons each of Ihem Once again . the work we do to crea te each of these sequence can be used to develop lest Ihat we apply once the impleme ntatio n has been performed . Step 6 calls for testabdllY In o lherwords. is It a reasonable process to te I Ihe elements of Ihe design' A design thaI can'l be readily separated into parts rend to be untestable An effecllve way to ensure Ih,s properry is to wrlle tests for each deSign eleme nt as "oo n as it IS SPCCdlCd
Step 7 concern the properties that we deSIre from our detadod deSigns We de Ife all of these prop
ror implementation on each dl.'slrcd platform
Step 8 checks that every detad is given, short of code. The onhodox definition of "de tad" refers to a complele description of the design ho n of code itself. Agile methods te nd to foc us o nly on key detads up front , t)' pKally leavmg most detads until code time It is common for de Igners to po
I
usually a mistake. There are many ISSUl'5 to consi der at implementallo n tim e, and so thinking through the detad . of critica l seCtions beforehand, and IIlspectlng them separarely, can pay 011 handso mel '
20.11 .2 Metrics for Detailed Design Detaoled deSign metncs include cou nting the number of mo dule , functions , cntry pOlnl" and e "POint For oblect,orlented Implementallon<, th i' translate IntO ountlng th e number of package<. the number of cia se<. the number of metho ds, the numbe r of para me te rs, th e number of atrrlbutes, and <0 on When clas es are proVided wllh complete class ,"varlanl , th is ,"c reases the han es that the re>ultll'g method i of high quality When pre ond,t ,ons, Invariant<, and PO
Percentage of cla"c> supplied With pre
I
class In varlan t<
Pcrc.cnta~e of nontrivial m('lhods \upplled WIth pr
llie pre o nclitlon\ . IIl VanJll h
and p ,tLondltlcm,
5]]
534
CHAPTER 20 DESIGN QUALITY AND METRICS A o mprch cn"ve , .Ihelt more complicated metric IS IEEE met'rlc 19 "deSIgn structure" (sec (5]), whl~h dc te",,,ne, "the
20.11.3 Inspection of Detailed Designs The overa ll pnn iples and practice of inspectIons were expressed in C hapter 5 The Inspection of deeaded dCc\Ignc; consists
or inspec tin g clast;Ocs , thclr metho d pro to types ( name, return type , and parameter ty pe~), th e
nowchans and p eudocode. and the relatIonships amo ng classes and meth ods WIthin various models. Th ...e modds ca n Include ,he usc case models and their associ ated sequence diagram s, the clas model, the state models, and the data fl ow model. As wnh all inspecti ons . data about eac h defect arc no ted, including its seve rity, its ty pe. and the probable source of the defect in the project life cycle. The IEEE standard 10 44 . 1 classifies seventy as shown In Figure 20 33 . Designanng a defec t classification scheme helps to pnorltize repair work: H oweve r, we avoid usi ng more categon es than necessary because time is con sumed categorizing ddecls. The triage classifica tion,
shown in Figure 2034 , IS fast but provides less information than IEEE 1044 . 1. Defect Iyprs can include those listed below , which have been taken fro m IEEE standard 1044. 1·1995. TI,e types that apply 10 detailed designs for Jav.doc· level inspections are marked "XDOC: and for pseudocode · level inspectio ns arc marked "PS". • Logic problem (Forgonen cases o r steps; duplicate logic; eXlreme conditions neglected; unn~cessary (-unc ti on ; misinterpretation; mI ssi ng condition test; checking wrong variable; itcrating loop incorrectly.
etc) PS • ComputatIo nal problem (eq uation in ufflcient or incorrect; precision loss; sign convention fault)
Severity
Description
Urgent High Medium
Failure causes system crash, unrecoverable data loss; or jeopardizes pcrsonnel
PS
Low
Causes impairmcnt of critical system functIon s, and no workaround solution does exist auses Impairment of criti ca l sys tem functions. though a workaround solution does exist Causcs Inconvenience or annoyance
None
None of the above
Figure 20.33 IEEE 1044.1 Severity classification SOUra' IfEE lOU 1. 1995
Defect Severity ClaSSIfication using Triage Severity
Description
Major Medium Trivial
Requirement(s) not satisAed Neith('r major nor trivial A ddect that
will
not affect operation or maintenance
Figure 20.34 Classifying defects by severity using triage
ASSESSING THE QUAUTY OF DETAILED DESIGNS
• Inrerta "ffm"ns problem (lnlcrruplS handled Incorrectl y: 1/0 liming incorrecl : ubrouline/modulc Im,ma l h) PS • Dala· handlms problem (miliali zed dala incorrectl y; accessed or lored dala Incorrec tl y, ,caling or Ullits of d,ta mcorrect; dimension of dala Incorrecl) XDOC, PS
•
pc of dala Incorrect XDOC, PS
• Data problem (sensor data In orrect or m"si ng, o perator data Incorrect or miSSing, embedded data In table< InCOrTCct or missing; external data inco rrect or missing; output data Incorre ct or nllSslngj Input data Incorrect or missing ) XDOC, PS • Documentation problem (ambiguous descripti on, etc. ) XDOC, PS • Document quality problem (app licabl e st andard not mel , etc. ) XDOC, PS • Enhancemcnt (change In program requ irem en ls,
Th is reqUiremenl IS Implemenled by the fun cti on IId)II"OII.IIIy (Slnll9 .0ll.I,Iy, flolll "OIll,I'Iy\l"I",) Wllh the pseudocode to be In
"increa"c"),
Recailihal the In
535
536
CHAPTER 20
DESIGN QUALITY AND METRICS
1
IF aQuality is not recognized
2
Log error to log Ii Ie
3
Inform user qualities unchanged
4
S8tOU8111y()
IF aQualityValue out of bounds
5
mentIoned
Log error to log file
6 7 8 9
should be
Inform user qualities unchanged
ELSE Set the stated quality to aQualityValue
'-----,
Reduce the remaining qualities,
Make these
... retaining their mutual proportion ,
preconditions
... making the sum of qualities unchanged
as well
F
ENDIF
Lacks detail on how to allocate the remaining quality values
Figure 20.35 Inspecting pseudocOde for defects
20.12 SUMMARY A soft ,,'are design IS assessed in term s of desig n qualities sllc h as ",ffidrnty . robu' h"'.' , flexibilily, rtu,ability, cffi"tllty . and rtllllbolity. Metrics are defi ned , collected, and assessed fo r each quality . In addition, the IEEE has defined several metrics for assessing the com pl exi ty of designs. These include nllttlbtr oj (ulries mid exits pcr module , graph-lhcortllC (omplexlty for ard'ltccturc. and data or IIIfonnal/oll ]low complexity. When se lecting an appropriate softwa re archItecture for an application , we explore several alternat ives and co mpare their relative streng th s and weaknesses . Each is mea sured against severa l qualities to determine which alternative I the strongest.
The quality of detailed des,gns is pursued by fo llowi ng steps such as ensuring that each arch itectural module is expa nded, each part of th e detailed design maps back to part of the architecture, the desig n fulfills ItS reqUirements , the desig n is complete and testable. and all the necessary deta il s arc provi dcd .
Inspecllons arc used to fi nd des,g n defects TI,ey focus o n inspecting classes. their me th o d prototypes (name . return type, and parameter ty pes). th e flowcharts and pseudocode, and th e relatio nships among classes and meth o ds within vanous models, such as use case , class, data Oow, and state. D efect types can be classified U inS th e ca tegories specified In IEEE standard 1044 . t · 1995 . These include the fo llowi ng types of problems: logic. co mputational , interface/timing, data handling , incorrect scope, data , documentation , perfonnancc, Interopcrability. and standards conformance:: .
20.13 EXERCISES I a
list the qua"ti.s that desig ns sho uld possess. In your ow n words, descri be the meaning of each
b Choose three of these qua"ties. For each, give enough of two differe nt des,gns for the follow, ng appl ,catio n to clearly distinguISh one that cores hig her than th e other on terms of
BIBUOGRAPHY
the qualit>, The appl, at ,on takes" ,nput the academi record of a h,g h
o n"der an apph allon that helps manage a fabric store A sume that the storrs sell fabncs and as ociatcd Items >u h as buttons and ribbons. Give three 10 (our robus tness IS ucs spccd\c to (hl~ applicallon Explain your c ho,ces.
3 Below is code for a me th od d,o,d,() Make the method more robust ,n at least twO ways.
public double divide( Double aNumerator, Double aDenominat or ) {
return aNumerator . doubleValue( ) I aDenominator . doubleValue(); )
4. Con ider a design for a video SlOre appl' allon
a Suppose that we usc ju tone clas. \/,d,oSIOrt, wh,ch allows the entry and removal of a v,deo name ass igned to a customer, s tored via a telephone number as key What exactly 1<; In nc~(Iblc about this design ) b. G,ve an alternallve U ML clas, model that would accommodate the inclUSI o n of addlt ,o nal operations.
c Wh,ch of the classes that you introduced arc likel y to be reu,able
In
other app hca tl ons)
d. How can you make more reusable the classes that rderence \I,d,o ) c. Which classes are unlikely to be reusable
111
o ther applications
In
any case)
5 Your instruc tor will pair up student project team Conduct an ",spec t,on of the othe r team's softwa re desig n. Evaluate the classes spec ified", the des'gn and core them U
BIBLIOGRAPHY I H enry .
, and D KJrur.l ~Sohwan: <;tructurc "' Iem
Bil\.Cd on InfomliHlon Ao.... , IEEE
No s pp 5 10-518 SC'ptcmlxr 198 1 ShC'p~rd. Milnm , "O C'oIj7(n melne: .. an empIrical 3naly ..... ,
T"'I1(';ldI O'1\
Or! oflll'l," &t.J1"an~ , Volume
E-7
(EEE SO/IIl',m tnill"lf"ll1!/ 'ournJ I Vol 5 0 1 IJlluarv !lNO pp ~ - I ('I ScoIL A FNJ C.oo.:l 'n/Of?14Jlb./:m Savnly Mrln('\, July 2005 , hltp J/~' c-.oon llne: convolrtld 220 1621AJ't:w_ :~.xUnformallon_ Staul1Y 1<~1pal« I ) I"w:<<<
1 3 BcnnatO,
7 AndC'n(Hl,
R
Roo. .. , "5wUl I),
f.nqIHttnnl/
John Wiley ~ C:;on.. ]0(1 I
537
Advanced and Emerging Methods in Software Design Online Chapter
21.1 DESIGNING IN A DISTRIBUTED ENVIRONMENT 21.2 INTRODUCnON TO ASPECT-ORIENTED PROGRAMMING 21 .3 DESIGNING FOR SECURITY WITH UMLsEc 21.4 MODEL-DRIVEN ARCHITECTURES 21.5 THE FORMAL DESIGN PROCESS IN B 21.6 SUMMARY 21.7 EXERCISES
To access this online chapter please visit www.wiley.com/college/braude.
principles of Implementation
•
How do teams choose programming languages for Implement'atlons?
•
How does one define classes? methods?
•
•
What are standard Implementation practIces?
Requirements
•
How do you handle vanable namIng? Global vanables? Function parameters? Initialization ? Comments?
•
What
•
How do you handle errors?
•
Wh at does It mean to ~en f o r ce Inlenhons?H
•
Whal are good codI ng siandards?
•
What Implementallon lools and enVlronmenls are available for programming?
•
How do sollware engineers working on large
Planning: Maintenance
TeslJng
The Software Development Lile Cycte
analysIs
Impllmlnlatlon
-
Deslgn
IS ~defenslve
programming"?
projecls go aboul programming?
•
Figure 22.1 The context and learning goals for thi s chapter
How should Siuden t toams organlzo lor the Implemunlatlon phase?
540
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
ode IS realed fro m de
ode listi ngs arc provided chapte r
In
ect lon 22 . 15 lhat Illustrale <evera l of the precepts discussed In thiS
22.1 AGILE AND NON·AGILE APPROACHES TO IMPLEMENTATION ThIS book ha< reviewed the idea that agi le and no n·agile approaches differ but also support each o ther. If the approach used on a proje t I agile, the n impleme ntati on-the subjec t of thi s c hapter- is begun just as soon as the Rrst user Story has been understood . That is very earl y compared with no n. ag " e approaches. Fo r agile projects, Implementation IS viewed not o nly as building the applicat io n bUI also as a process of understanding the requi reme nts The very act o f determining classes and methods is a process
or fleshing out a realization
or th e C'J rrcnt user story. There i no oth er requirements analYSIS o r deSign or documentation process unless
th e team fetls the need fo r these III the course of implementing each user story As the implementation progresses, the proce of refac to ring (see C hapter 24 ) is viewed as enabling devel opers to alter the deSign and implementat ion to suit evolVing requirement .
O n the o ther hand , if the approac h is non·agile, then req uiremen ts and a design (though no t necessarily of the enllre application) arc in place when implcmcnt(Jtion beg inS.
22.2 CHOOSING A PROGRAMMING LANGUAGE The programm ing language selected fo r implementing a de ign is usuall y dICtated by the company, the customer, or th e environment
10
which th e applica tio n must run . For example,
if
the application is Web -
based, some JavaScnpt ma y be reqUired. If the compa ny is a Microsoft ·o nl y shop, then CN may be the o nl y choice. Given a programming lilnguilgc, it
IS
th en necessary to selec t an interactive develo pment environment
such as Eclipse fo r Java o r Visual Studio fo r Cff. When the freedom eXISts to select a program ming language, an Ident ifica tion and weigh ti ng of selec ti o n criteria can be used to aSS ist th e deciSIo n. Features of languages needed for th e appl iCCl tl on constitute o ne set of cri {cria. Another criten o n is th e avai labili ty of uscfullibrancs.
Th e degree of softwarc engineers' expertise in a language is yet an o th er ractor, and its weight is usually hi gh
As of 2009, most languages used are o bject·oriented . Many of the principles dis ussed in this c hapter apply, whether the language is object·orie nted or not, o ther< make sense on ly fo r 00 app lica tio ns.
22 .3 IDENTIFYING CLASSES Let us f,r
DEFINING METHODS
• Domain class •
rrc ponds to a fCQlllf('ments paragraph
• Example, DIID • Design class • peClhcd in DD •
lot a domain cia,,,
• E."mplc· ROllal/le,. • Implementation class • Too millor to ~ pecdy In design
Figure 22.2 Where the classes In an 00 Implementation come from
Ihe la more reloable . The ROII"I class In LISting 22 .2 ( eClion 22 . 15 I), for example, specifies the fol lo"10£ Invana nt and a method, heck/"ullnaH I() used for unit test ing
/ * Class invar iant : EITHER the rental is inactive , id == IO_WHEN_RENTAL_NOT_IN_EFFECT, rentalCustomer == null , and rentalItem == null OR 10- l'iHEN - RENTAL - NOT-IN- EFFECT < id < = HIGHEST_ALLOWABLE_RENTAL_IO , rentalCustomer 1= null, and rentalItem 1= null
*/ The mo
I
Importa nt goa l of a block of code
IS
for it lO sa tisfy Its purpose. We refer
to
,uch code a,
"correct " Th is means, first , that the programmer knows w hat that purpose IS se a nd , th(· programmer wntl'S
do",n that purpose precisely wit hin th e com ment s, thord, the ode Im plements the purpose, and fourth , the programmer explain , formally or IOformall y, why the code fulfi ll s the purpo,e The IIIIOIl/pr(co"JoIIOII' postconJ",om/rrtundm/ltlc (0 ,","01' (ormat cover<.:d III lhe next ~c lion I S de Igncd to ht·l p realize the goal of correctness .
22.4 DEFINING METHODS When alliS said and done , the work of an application IS performed b It S method< (also know n procedure or funclIons ) ror that rcason we ,ake spe ,al care to ,tatc the purpo,e of eac h w,lh,n the c de comment< The," can be effec ti vely organized under t3 tC'J.:0rJC, c;uc.h JS mrwI , prrcoml,',oll , pO~llo"Jlllo'l . rdunl , UHleIr"",t, rxcrp'loPi and blow" ISSUes The HtUut .:lnd Jmoum I NlC~ arc Informal , but th e rcS t
Intent : Gf'
h
n xt av ilable number for ass igning a
1
ental
541
542
CHAPIER 22 PRINCIPLES OF IMPLEMENTATION
l1"s help, 3 lot In expla"",,!: the meaning of the melhod. NOle thai II " not a precisc or thorough deAnttlon If the method corresponds ro a documented detailed reqUirement or if it i, ,pcc,f,ed in the de,ign, the
'"'nl'
· tatcm~nl may simply rdcrcn e th,'i.
11,e preconditions deAne the assumption lhat the method makes about the value of variables external 10 the method , including the parameters. nIl excludes loca l variables. The method srlldO In Listing 22.2./or example, has the followln8 preconditions,
anld > RENTAL_IO_WHEN_NOT_IN_EFFECT anld < = HIGHEST_ALLO·WABLE_RENTAL_IO
&&
In ot her words, rhe method's code assumes that mIld is within the legal bounds. Notice that the specification of preconditions IS precise-usually Slated in term s of concrete, named va riables. For all but the "lnlent" SeCtl OM , vague statements lead to ambiguity and should be avoided . The po tconditions specdy the method's effects. Every method has a return or a postcondition . This is because methods exist to have dfects. There is no reason for rheir existence otherwise . The effect does not have to be permanent. For example , a method that displays the acknowledgement "DVD Rental Completed" has the following postcondition,
"OVO Rental Completed " is present on the monitor, More commonly, postconditions refer to variClblcs whose values could change . The co nstructor
public Rental ( intan ld ,RentalCust omeraRentalCust omer, RentalltemaRent alltem) throw> Except ion has the following postconditions,
as for post conditions of setld( anld) (2) RentalCustomer == aRentalCustomer ( 3) RentalItem== aRentalItem
(1)
When a method depends on another method from which preconditions or posteonditlons are to be repeated, it I preferable not to literally repeat the precondition , but merel y to reference the methods on which ir depends This practice is applied in precondirion ( I ) The beneRt of such a rderence is that if the preconditions in the ca lled method change, it IS not necessary lO then update the preconditions in (very method using them . The postconditions in thi s example arc pretty much what o ne would expect for a constructor.
As another example, if we define a method
int weirdSum( int addendl, int addend2 ) so rhat .dd,"d2 is asSIgned the sum of .ddtlfJ, and nddmd2 , then .dJrnd2 is mentioned in the postconditions as follows ,
Postcondition: addend2' = addendl + addend2
DEFINING METHODS
• /t:I",1 An in(o rm,1 st,t emont o( wha t the me th od is inte nded to d o • Don'l spe ify the det."s here the other categones provide them • prcton.l,"OJlS Condi ti ons On nonloca l variabh:s that the meth od assum es • Include parameters • Verifi allon of the e condilions not pron" ed 10 method II e1( • Po f o"d,ltotls Value of no n· 10ca1 variab les ah~ r execu tion • Includes parametci
• No tatIon:
x' denotes the value
01 variable x after execution
Figure 22.3 Programming conventionS-documenung methods. 1 of 2 The notallon
x' refers to the v.lue o( a vanable " at the conclu ,on of a method
The Invariant SPCCdlCS a r('latl onship among the variab le... thal the method doC's not alter ThiS program · mer may want to draw altcntlO.n to an invanant . For example, he may want to Sln: S that the class Invariant IS
honored
by
the method.
pOSlCond,tions. The return
pCCliles
pecifYlng an Invariant IS equivalent to qallng the exact nature of what the mcthod
IS
It
among the preconditions and the
Int('ndcd to rt-turn Once Jgaln , thiS
IS
sp~Clfied in prcCI
e terms Figures 22.3 and 22 4 summanze these poinls Figure 22 5 shows an example Instead of po tcondllion I, we could have speclfted that the anginal dements o( garnrBoard are Inv.n.nt because move already rnade should nOl be hanged A me thod is purdy j,mcl{ou.a1 if it has a rl'tum , no postcondiuons, and us prccondilion refer only to parameters. In thi asc , Rrl,,", de cribes the cnllre "'ason (or the meth od's eXIStence We make methods purely functional unless we want (hem to partlctpalt' In an objcct -o rlented design ( \\,hlch
I
often , however).
When there arc objects of a class at runlm,e-whlch we WJnt in mOSl cases-we need methods that
manipulate the attributes o( the objects and arc thus 1101 purely functional Take, (o r example the method "rta() EO the class Rtcta"glr. \VIc could denne arta() purely (unctionally b p3Sslng the length and wldlh, as ,n
class Rectangle { . . . public double area ( double aLength , double awidth )
. . .
'
}
• l"uana"1 , Relatio nsh ip a mo ng no nlocal va ria bles th. 1 th e me lhod's executio n leaves un cha nged (The val ue, 01 th o Individual va nable< may c hange, however ) • Equivalent to Inclusion In both pr{' · and po~t o ndlllOn
• There may also be In vanants among loca l v,nable< • Rrlurn : • What the method returns • Kno lDn ISSIltS . • Honest ,Iatement of what h. 10 be d one, delecI, that have not been repaired, etc • ExcqHIOHS • n,ese arc of l en thrown \vhen the prcc.ondillon..; arc: not Illet becJlI\c dw;; In{he'He," an abn rTllalu) In exeCUtion •
Figure 22.4 ProgrammIOg conventlons-documentlng mel hods, 2 of 2
543
544
CHAPTER 22
PRINCIPLES OF IMPLEMENTAnON
/ n Intent : Record anOorX at aRo w/aCol if aRaw/aCal blank ; Retu r n ' N' if • not permitted ; return anOorX i f full row/column/diagonal
• 1>
Preconditlo n s : a nOorX = ' Q ' ORa nOorX= ' X '; 1< = aRowO(:;;3 ; 1<;aCol<=3
• * Postco nditio ns (note use of x and x ' ) " Post.O . All preconditio ns are met OR Ey. ceptio n thrown • Post 1 . gameBoard ' co n tains all n o n - b la nk eleme n ts of gameBoard • Post2. gameBaardlaRow- l] laCo l - l ] = " OR retu r n = ' N' • Past3 . gameBoardlaRaw- l llaCo l - l] ! = " OR • gameBaard ' laRow- l] laCal - l] = anOo rX * Post4 . There is n o full li n e o f anOo rX i n gameBoard ' OR r etu r n:;; a nOor X
·
/
public static char ma ke Mave( c har a nOa rX , ; n t aRo w, i n t aCal) t h r o ws Exce p t i o n { Figure 22.5 Example of method documentation-tic·tac·toe
This has th e pro perty o f being independent of th e class It belo ngs to . and we would ty picall y make" , Iallc. We wo uld invo ke this vers Io n of nr
. . . Rectang l e . area ( 1 , w ) Al terna ti vely, we could de fi ne R,elnH91" a in
•
•
•
•
nrenO with preconditions on the instance va riables 1"'91h and widlh of
c lass Rectangle { . . . public double area () . . . . } This leverages the object· oriented nature of R, InH91,. We would invoke th is version of
. . . rectangle.area ()
•
•
.renO as on
•
22.5 IMPLEMENTATION PRACTICES Figures 22 .6, 22 7, and 22 .8 summanze good habits for imple me ntin g cod e. The y arc described in more dotail in the following scctians, and many of them arc put Into practi ce in, listong 22.2, found in Section 22 . 15. 1i and also applocd to the R'Hlnl class of our video store example.
22.5,1 Use Expressive Naming When assigning names to vilriables , parameters. functions. classes, ilnd so on, the most important criteria a~
that the names are expressive and that they convey meaning. They should not include vague, ambiguous terms. This helps the reader to understand their purpose (recall that Our job includes produci ng ma intainable work). Consider the following piece of code,
IMPLEMENTATION PRACTICES
• U se expressive naming: th e names of the (unction , th e parameters, and the va nables shou ld indicate
the" PUll>0 e
•
m(llllpuinlr(jloal aFlMt, .,... r mrl"r) -
•
g"&",ROIsrdToExpo,,mt(floll' ,113,,,,, ,", ""Expo"ml) ~ belter
poor
• Avoid g lobal va riab les : consider pa 'ln8 paramelers Inslcad labl, = } _ replace] • rx'rac,(,., a"E" lry ) { • ""'r
±
7
Figure 22.6 Good implementation practices, 1 of 3-naming variables; global variables
• Do n't use parameters as method variables myMelhod(lnl ,) ( . . . . 10r(i =0, .. - no l • limit number of parame ters to 6 or 7 • Give names [0 numbe rs for(i = 0, I < 8927; I I i) - poor: why 89277 Inslead: inl UM_CELLS = 8927 /1 . , for(celiCo unler = 0, celiCollnlcr < NUM _CELLS: I t celiC ounter) • Introduce variables near th eir first usage
Figure 22.7 Good implementation practices, 2 of 3-parameters; no unnamed numbers
• Initialize all variables • fe -initialize where necessary to "re set"
• Check loop co unt e rs, especially for ran ge correctness • Avoid nes tin g loops mo re than 3 levels • Introduce aUXiliary methods to aVOid • Ensure loo p termin a ti on • a proof I ideal- In any case , document reasoning
Figure 22.S Good implementation practices, 3 of 3-initlalizing vanables; handling loops
/ / Example of poor use of naming int Dolt ( int a , int b) { int c ;
c=a*b ; return
c;
}
Whal does llll< fun c llon do] Il mulliplies Ihe IWO pJr.lmtICI'. Jnd re lums the ""u ll , bUI whJI eXJ t1y" Il, purpo\ 'l it " hard lO le ll hy Ihe name' of th e funcllon or Ihe vanob le ' - lhcy do nOl o n ey "ny mean",!;
Now
cono,lder lhl\ li lmpl e fun lion
rewritten u~ lng
C'
~5
~6
CHAPTER 22 PRIN CIPLES OF IMPLEMENTATION
i nt Co mput e Re ctan gl e Ar e a ( i nt l e n gth , i nt Wi dth ) {
i nt ar ea ; area = l e n gth
* width ;
r e turn a r e a ; } Even with ou t co mment s, th e purpose of tht" (unctio n IS now cl ea r: it co mputes th e area of a recta ngle,
lI
22.5.2 Global Variables G loba l van.bles are dat a accesSIble fTom an ywhere in a prog ram . Using g lo bal va ria bles compromises the
Chapler 15. InstcJd. w e want to minim ize thei r usc to
pri nCip le o f mJOfrn a liOll h.dll19, w hich we discussed in
reduce the dependence o n o th er part s o f the im pl("m Cn lari o n and to hide implementati o n detail s.
22.5.3 Function Parameters D on't usc parame ters as wo rking variables th is is not th eir purpose. Parameters sho uld o nly be used to pass info rmatio n into and out o f a functio n. If a wo rking variable IS nceded . It should be decla red within the funct ion O th erw ise, unintended errors can be introduced . For example,
If an
input param eter is used as a
working varia ble. Its original value ma y be mod ified. T hcn if the parameter IS used late r in the fu nc tion with th e assumption that it contains it s o ri ginal value . an error will occur. limit the numbe r o f para mete rs to 6 or 7-lt is hard to keep trac k o f parame te r and use them properl y if the re arc morc than 60r 7 Also. the more parameters are used , ,he more li ghtl y coupled the call ing func tio n is with the called fu nc tion If so much data need to be passed, reexamine the design and sec wheth er the coupled fu nctions should be combi ned. or if they belo ng in the same class, With the parameters becoming pri va te class members.
22.5.4 EXplicit Numbers It
IS
no t good practice to use explici t numbers in code. ConSider the follow ing:
f or( i = 0 ; i < 8927 ; ++ i ) It I nOt clea r what 8927 means. Why loo p 8927 limes? Usi ng a number like this hides the truc meaning o f the loo p. Now consider ,he fo llowi ng,
cons t int NU M_CE LLS = 892 7 ; / /
•
•
•
•
•
•
•
for( c e ll Co un te r = 0; ce llCount e r < NUM_CELLS; ++ cellCo un ter ) Th is is much clearer all of them.
the program containS cells. thcr. are 8927 of them. and we are looping through
IMPLEMENTATION PRACTICES
n,e other problem wIth U
.r
e
22.5.5 Initialization and Declaration 22.5.5.1 Variable Declaration Ir IS good practice to dcclJr(' va nable .. a.. clo C (0 thl'lr hr<.lll'c a') po",blt: If you arc rcadlng you ~rlll then be m o re likel y to hnd J l'ld undc.::'-"'la lld th\.' v.:lnablc, I t rd('r('nct:~
a
pu:c(' 01 c.ode
22.5.5.2 Variable Initialization The reaso n we In lli aliz\.' vJnabh:~ I ~ to take cOlltro l of th t.:m . avold lll g ddallit or garbage va lue . . that tht.: "y.,lcm as Igns. n ll c; aVOids POLt.:llt lai error.; where J v;:t nablc '''' used and con tainS an uncxpt.: lcd valu\.' It I') good practice to in itiali Ze (J variab le when Il I') declared, a . . In thL' (ollowlng example
float balan ce = 0 ; / / Ini t ia lize ba lance to 0
22.5.6
LOOps
Loops. ca n be c01l1phcatcd and arc common "'OUfce... of . . e n ou... (adurc..·... TI1C arc.:: thu., 'peclal targch 01 vc n ficJ tl o n McConnell [ I J ... uggCq S the fo ll OW ing question, to I t: an ... wt;..' red a, gllldc(,nc ... to tn.,unng loop CO lTectne~.;
• I, a whol, loop oelng u<ed Inslead of a for loo p' • 1< Ihc loop enlered from Ih e lOp? • Does Ihe loo p oody havl' , o mcl h,ng ,n II ' I,
• I. . the loop ... ho rt cnough
10 ( eV I(..: \'/
all
al
on
II
n" "e mpl Y)
('7
• H ave lo ng loop (.onlt.'nt" hee n moved into thl',r ow n fun lion '"
• I, Ih~ loop Iomlted to al 010<1 Ihree I cvc1<~ • If Ih loop IS a Jor loop , doe, Ihe hod y 01 Ihe loop aVO Id mod,fy,ng Iht loop Inde vanablc' • Doc\ Ihe If)()p alway, lermlnale'
• (( b,tak or
(oH lmur
arc u,cd arc th..:-v u\l,d (..orrcu ly
They arc dc.,trrhed In more (il-ta dll1 dl(' fO ll ()WII1~ "l' l l tnn., Jnd Ill anv or them J l l' r llt InW rr~(;tI (' an I",t",~ 22 2. fuund "' '><(l IO" n 15 I and ar plo ed hI Ihe Rnll,,1 la" (,lour vlden 'tOfl' e,.mplc
547
548
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
22.6 DEFENSIVE PROGRAMMING n dIe IIw p,"c ti cc lo r nliniml z lIlg bugs is to a ntICIpate po te ntIa l e rror> and Impleme nt code to handle th em ll'l ~ t(. hn iquc IS Glilcd dcjt11Sil)c progrmtf'"ltIg nc orthe most common erro r sour cs 1\ Illegal data, either (rom a bad vallie in a (-un tl o n's II1put param eters, or from an external source su h JS f! file, database, or data
communIcatio n lone . In each case the bad data must be detected and a stra legy e mpl oyed to handle il. There are a numbe r 01 crlec live defen Si ve <[ra
ExC/P lloli halldl"'9 IS J mechanism lhat paSSl'S contro l to erro r handling code that kn o ws ho w to respond to lhe erro r. Many I.nguages such as Java and C++ have bu dt · in e xceptio n· handling laclloll es. Exception handling IS covered In Se lio n 22 .6.2. O th er meth ods 0 1 dden Ive programrr.in g include bufler o verflo w preve nt io n and "e nlo rclng inten· lio ns · Eac h is dIscussed al the end 0 1 this sectio n.
22.6.1 Error Handling Deve lo pers are constantl y faced with the issue 01 what to do with po tentIally illegal data . An example 0 1 illegal data is an account number that docs not correspond to an ac tual bank account. Altho ugh we try to make ImplementatIons as simple as pOSSIble, the real world is not simple. A large fractIon of programming goes toward the handlmg of errors A dISCIplined approac h is essential , pick an approach , state it, and be sure everyo ne o n the team understand and abides by il. Gi ven that the possibiliry of errors must be dealt with , how does one program a method to handle illegal input-tor example, a merhod that gives the balance on an account number when the method's preconditions
clearly require that the account parameter be legal l lf all of the aspects of the development process have been properly practiced, the method's parameters wi ll always be legal whenever the method is ca lled. But should we program a check of the parameter value in case our design or Implementation is flawed, The answer depends on the requ irements . For example, suppose there is a system requirement thOlt the continued eXc.."Cution or the
application is paramount. even if the execution is degraded or flawed . In this case, the programmer must deal with all inputs , even those that ",ake no sense. Techniques for hand long illegal data are described below [ I]. Wait for a legal data value. If the illega l data are from an external source such as allser interface, database, or commUnication device, onc possibili[)' is to interact with the data Source until the input is changed to a legal onc before the processing continues. This is possible for much of uscr interface programming, where we can
often ensure that only legal inputs are permitted. If the only allowable strings that can be entered in a text Reid arc "car:"'rruck ," or "bus," it is easy to prevent the user from continuing until a legal entry is made . A list box is a common way to do thiS. Even here, however, subtle errors may creep in. For example, the user may cntt.'T date or
birth as I/ I/ SO and age (on 20(0) of 30. It is possible to check consistencies, but the onus i on the designer to handle all possible consistency and boundary checks (sometimes called 'business rules"). Another example might be when data are transmitted over a faulty communica tion line. The receiving method may be deSIgned to expect certai n data, but the application is ofte n explicitly required to continue execution, even when the data arc not legal. Here, the data mllst be checked and errors processed in accordance with the requirements (e.g., "If the signal is not between 3.6 and 10.9, discard the signal and listen for the next signal . . . ") . Sct a default value. Sometimes a default value can replace a bad data value . As an example, consider an application that monitors heart functions and controls an oxygen supply to a patient. Let's uppose thaI we are coding a method process (int measurementType, • . . ) where mra,umromlTy/>t must be poSllive. LeI us assume that Ihis application cannot afford to crash even when an internal mel hod has been given an illegal integer due to a development defecl. To deal with this, the code would check Ihe inpul
DEFENSIVE PROGRAMMING
and set ",fe default value If po .. bk If th" " not po Sible, It may place the entire applic.tlon '" a default mode of operotlon In e ither cosc, some kind of .lert would be raised indicating .n Internal error oCC1lrred Use the previous result . ome soft,vare contmuou Iy monitors the va lue of something-for example, real-time tock qUOtes. If one tll11e the . oftw.re read all Illegal value, a pos>ible reac tio n I to u<e the lastlcg.1 "Jllie th.t , . read 11l1S a !lood approac h when Ih e dala va lue, arc read frequently enough Ihal you don'l ~xpcct much deViation bctwet'n read" However, If Illegal values are rcad consecutively, the program may ,,'ant to raise an alen or log an error to IndiCate th e prob lem . Log error . j\1any software applicanons Implcmt:nt a loggIng ~ubsy~ l e m to store erro r ,nformallon for later use. Log IIlfOmlatl o n I>:. tYPically wntten to non vola tile 'Storage ..;uch as a file, With dara save d Including an ('rTordcscriptlon . SOi l,yare funen o n whl."re erro r 0 cu rrcd . ca ll ,tack at tlml' of error, regI ster values. and 0 o n Throw an exccption . Exce pti ons arc a mt.."chanlsm to handl e unexpectcd program errors, mcludmg
Illegal data va lues. Languages slic h a C+-r and Java have bu.lt -In exception suppOrt Exceptlo n< are covere d to more dctad In the next sec ti o n
Abo rt. In some appl.catl o ns any bad ddta are con>ldercd fa lal.nd the system most often the
COl C 10
applicatIOn s w here sarC:1Y
IS
IS
aborted and resc l This IS
a o nccrn and a bad va lue can cau cham, TI,ls ca n al
occur In embedded SYSl crn" that manage th"lr Own memory and detect memory corruption
If 10gg1Og
0 !
available, error Infonna tl o n IS saved before thc o hwarc reSet
In some of our prevl ou examples, the ac tio n take n quirements : abort
III
if afct y.crill cal. use th e plcvi o u rc"u lt.f It
conSIder methods whose exceptIo nal behaVior
IS
respon>e 10 dlegal data
!!!o
IS
dictated by the re-
not expected to cha nge. and ~o on
ow let us
no t dctcnnlned by th e rcqU!ff;:menb F'f\l , the ir precondl '
tion mu t be th oroughl y speci fied so Ihal the co nd ition> under " ,h ,ch they are ca ll ed arc clear-bul should their parameter va lues be checked to ensure tha t the preconditio ns arc mc{ ~ '\ c dlc;;ttngUish here: betw(Ocn
execution dunng development and execution during de pl oyme nl Executing dunng deve lo pment al: ows l CS t and VC nnC3 11 0 n code In man y pans of an applltallon and \\'C
nllght well want to insert code rhal checks preco nditi o n" as In the fo ll owlIlg
1 ** preconditi o n : parameters are positive *1 int sum ( int int IP , i nt int2P ) { I I ver if icat ion code for use in development : check par amet ers posit ive
·
,
.
I I n ow do the work
·
.
.
}
Execu llng the de li ve red producl reqUires 0 dlfferenl perspecti ve II ,he mel ho d I ca lled w llh negallve parameters, tim Indi cate a defec I In Ihe app l, ca ll o n Itself \VIe wou ld like to protect o""e lv« aga ln>1 our own mIStakes, but the Cure mu,t be rrde rable 10 Ihe dines,
1*· precondition : parameters are positive * 1 int sum( int intlP , int int2P } { II verif~cation code for deployed applica ion : check parameters • pos~t~ve
II only 1f we have a clear philosophy of what to do i f parameters no
· II
·
,
,
nO'N
,
POS] tive
.
do the work }
~9
SSO
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
Developers lose o ntro l o( their appl,catIOn when they apply an arb it rary default whose consc quen c are not kn ow n Th is must be balanced against the contInued execution of an appht.al lon WIth wrong va lues. h owe ve r. It may be une th ica l to di tribute, WIthout warn In!! , an applicatIOn that handl« dc('ctive d('vcl opment With an inco rr.ccl continuati on (i e., a co ntinuatio n not slaled in the reqUire -
ments). A defec t i a n1l take , but an arbitrary defo ult no t cxp hci tl y specified in the reqUIreme nts is • cover-up. It IS often preferable to rc launc h an abortl·d app hca tl o n rather than ha ve It execute Incorrectly (think of an applicatio n p lo tt ing airp lane course ). Undisci plined error procesSIng hides defec ts, and It becomes expensive to fi nd the defect compared WIth allowi ng the application to c ras h (hopefu ll y at test t Ime ).
22.6_2 Exception Handling Exce ptions arc a mechanis m to handle une xpected program errors. languages suc h as C ++ and Java have built-in support (or exceptions. For those languages wi thout explici t support. developers sometimes design and impleme nt the ir own exception-handl ing code. In general, w hen an error is detected an Cxc(.'pt io n is t"rolo", mea ning co ntrol IS pa ssed to that part of the program that kn ows how to deal with the error. Th is is also kn own as calcbill9 the excepti,," . As a ge neral rule you should catch those exceptions that you know how to handle. A method handling an exceprion looks like
ReturnTyp e myMethod ( ___ ) { __ _ try{ ___ / / call method throwing Exc eptio nX } catch(E x ceptio nX e) ( ___ // h andle it)
...
}
A method
110 1
handhng an excep tion (I.e .. passin!: it to callers) looks like the foliGwi ng .
ReturnType my Meth od( ___ ) thr ows ExceptionX{ ___ } Th e followi ng are some guidelines fo r implement ing exceptions.
• I( the present method cannot handle the exceptio n, there ha to be a handler in an outer scope that ca n do so.
• If you can handle part of the exception, then handle that part and then rethrow the exception (or handl ing within an outer scope.
• Make reasonable expectations about the ability of ca ll ers to handle the exception otherw ISe, fin d an alternative design si nce unhand led excepti o ns crash applicatio ns
YOll
are throwing;
• "I ( you mU St choose between throwi ng an exception and continui ng the compu tation, continue if you can-
[2)- The point here is thaI the continuation of an applicatio n can be preferable to shu tt ll1s when the con eQuences have been thou ght through.
It
down in cases
As an example, the Encounter case study continues to perform wit h a default name when given a faulty parameter strin g (e.g., null ), si nce th is is preferable to shuttin!! down the ga me jllSt beeau e a name is Illegal. On the other hand, a banking trans.ction WIth an illegal amount would not be allowed to continue.
DEFENSIVE PROGRAMMING
There arc differcn es of opi nIon conce rnIng lhe use of excepllons when a method IS c.lled .nd does not sail fy It'S precondltton; ome believe lh al lhl IS a leglllmate usc fo r exceptIon , others dlS.gree, and belteve that thl is a matt er for testIng alone, The aUlhors' o pInion IS that stnce code IS naturally error-prone, a con
tent policy (or thro,,'ing exceptio ns
1
In
uch ca cs
11)
a benehClal practice
22_6_3 Buffer Overflow Prevention Some langu.ges, notabl y and ++, . 1I0w writIng to memory lh.l exceeds lhe space declared in the code For "ample, the followIng C code declares an array wIthIn a method char rnyCh arArray[ 10] ;
Clearly, we intend to WrHe no more lhan 10 charac ter< to ",yCha rArr.y. Howeve r, Ihe follOWing code "-III place new bits be)'ond Ih e memory allocated to ",yChnrArray If lom,(I""Array happens 10 be longer than I0 characters. strcpy( rnyCharArray , sorneCharArray ) ;
The effects of thIS ove".ntlng can be benign , bllt the y ca n al 0 be catastrophIc lor the appltcatlon, If exploited by a m.llci oll hacker, they ca n prod uce a securilY breach Thl ca n be prevented by checking v.na ble size at ke y pOInts (e.g., when a lIse r proVIde Inpu t) .
22_6.4 "Enforce Intentions" If YOll Intend somethlllg about how the code yo u arc con tmcling IS 10 be used by other parts of Ihe appltcatton , Ihen Iry to enforce this Intentton . The aUlhors ca llihi Ihe "Enforce Inlent lons pnnClple It IS often evI dent In uscr tnterlace , where appltca tt ons try to preve nt Ih e lIser from entenng dleg.1 dala \VIe are stressIng the "Enforce Intentions" pnnciple for mltnltll proc{"t:;s lng heft" . The prinCiple ISJnalogolls to conslru tln g curbs and
ISlands on roadways 10 direct traffic along JU I those palh intended by tra flic engineers , and no olhers enforct.'mcnt of intentions makes road s safer,
It IS
comm only apphl'd
In
lIch
many l'nglnec:nng dlsopllnes The
followlog Includes cxa mple of Ihe "Enforce Inten ltons" pnnclple In software englneenng • Us<: qualtflers such asji"al, co,,<1 In C+ +, and abstra
don't glVt' them Wider scope If th iS I) nOt you r Intention
• Usc Ihe Single Ion deSIgn pattem
.r Ih
re IS to be only one In'tan e of a clas. (see
hapter 17).
• Generally spcakl ng, make member. In accc" lble If lhey are nOI !,eclAca ll y Intended directly
.r
to
be acces' ed
• Make a1l nbules protecled Ac.cess Ihent Ih roug h more pub lt c acc«sor fu n lI on reqUired (In IJ a makIng attnbules prolcuecl Hlvn On)e IS of ,"bda<,es JcceSS 10 member< r Ihelr ba e IJ"'" whIch I' oflen undeSIrable ) • M.ke nWlh"ds
p,,,,.,, .r Ihey arc for u", on ly by melhods of Ihe >ante
IJ"
551
552
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
o n'\Idcr IIlt ro du 111 & c1J \ 40c \ to encapsulate legJ I parame ter va lu es that prevent bad da la For exa mpl e. If th e intent io n ror a meth od Clw iUtl lc() is to accept only I' ear," "tru ck," or "bu s" 3 C, parameters, then
be won lWl hilc
be Ju se It Intro du ce th e po s'lbdltY of ill ega l parame ler< It would be belle r to de fi ne a cla« suc h a Spr ", /mJVd"c/, with a priva te conStruCto r and
It nu ghl
n Ot to u C
" 1119 JS 3 pJram <.' tc r
/.. tory fun c ti o ns.
Sp ecia l izedVeh i cle c r ea t eACa r ( ) { . . . } Sp ec ializedVe hi c l e c rea t eAT ru c k ( ) { . . . } Sp ecializedVe hicle crea t e ABus ( ) { . . . } The method
In
question can the n ,ake o nly a parameter of th is type. In o the r words, instead of
evaluate ( Str i ng ve h ic l e) . . . / / pr o bl e m wit h illega l st r i ngs use
ev a l u a t e ( Spe c ial iz e d Vehicle vehicle ) . . . / / par am e ter value cannot b e illega l When the posSIble parameter values arc restricted but infinite, a separate class can stili be valuable. For exa mple, a person's age is an integer between 0 and 105 , let's say, and so a method
ge t Ye ar Of Bi rth ( int age ) may have to deal with errors. In fact , the same error proceSSing would have to be repeated for all methods taking "g' as a parameter. O n the other hand, a class Agr with a private constructor and a publ ic fac tory method
Age g e tAge ( int ag e P ) would handle erroneous input In a consistent manner, located In the same place as all the other aspec" of age. Some options for dealing wit h this error are described below. The disadvantage of this method is the proliferation of additional classes, and the slig ht awkwardness of ca lls suc h as
. . . getYearOfBirth ( getAge ( n ) )
•
•
•
in place of such simpler calls as
. . . getYearOfBirth ( n )
•
•
•
22.7 CODING STANDARDS Applying coding standards across a team improves diSCipline, code ",adability, and code portability. We will prescnt o ne set 0/ standards as an example. Some of these arc adapted from Scan Ambl.r ( 3). Oth.; s~ncUrds
CODING STANOAPDS
orporallon's Java He The exact nature of a ~{a ndard is not nearly as Important as the tact that the tcarn u'\cs one
can be found at
un
22.7.1 Naming Conventions U
C J. naming
convention for variables. Engineers lcnd to become emotional about their favonte conventl0 nc;.
and true consen us
I
often Impossible. Nevertheless, convl."niions arc nc cs ary A limited time should be c;;ct
aside for decidi ng on conventions and a method for finaliZing them . For example, a team member can be d Ignated to draft conventions, c·mail them 10 the other members for comments, then have the choices finalized by the deSignated person with the approval of the team leader There shou ld be gtlldehnes a. to when C'xceptlons to convent ion arc to be allowed
The following are example
•
or
naming conventi ons In the Java trad inon
lame: entities wilh concatenated \yords as In
IrnglhCylmdcr
Thc<;c arc ea y to understand and they con crvc:
<pace ExceptIOns may be pemlltted at the discreti on of the programmer • 8egln class nc)me wirh capitals. ThiS distlngUl ~ hc s them fro m va nablc:s. enriries with standard letters or combinations of letters. such as
.
orne tools precede the name of
. (or classes as
In
CuslOntlr This IS
u clul when the importance of knowing the types of name, exceeds the resuiling awkwardnes, • Name variables beg inning With lowercase letters . •
on tant, may be excepted.
ame consta nt with capital, as In I_AM_A_ ONSTANT (usc static final ) lAMA ONSTANT IS hard to read; JamA Coll5tant cou ld be confused with a class , ,AmANamr gives no indICati on thal Il is a constant
• Some orga nizao on distingUiSh between vanables local to a method and those of the class ("Instance vanallles). For example, begin (or end ) the name of instance vanables of classes With an under-co re a< In _"rn,OjDay to dislinglllsh them from other variables, since they are global to the" oOject, th" I u.ed by Gamma et a!. [4] but derided by Ambler [5]. A convent io n used In the ca . e study IS to append the suff" I to Indicate Instance vanable , as In lim,OjD"yl. Each Instance van able is global to each clas. Instance . and when one IS encountered in a block of code, It is useful to know thiS • ConSider uSing a notation to dist ingui sh the stallc v.nob les of a class. The ca,e stud y u'es the surRx S, as In n"rnC.'sEutrBu iIt5 Reca ll that a static vanable IS global to a cia... and It is heipful to know that. vanable encountered In a block of code IS one of these
• Usegrt
, sri , and IS for acce sor methods as In 9,INllm,O, srINII"" O, IsBox() (where the laner returns a boolean value). Alternatively use "",,,,0 and ,,"m,(51'ltIg), for attribute name (c g., In ORBA-.ee [6]) .
• Augment these wllh standardized addil10nal "getters" and "setters" of co!lecllons, for eXJmple 1I11tr1l"loNamr{),
'''''O!J,F,,,,,,Narn,O, n,wNam,O. • Consl dc:r a convcnllon for parameter" One
o n Vl'n tl o n I
to
lI~e the' prc~x a, a... III 11"*(1111 nnhllcrg,n . mt
anlnlrrgm j. The case stud y u.cs the:
22.7.2 other Conventions u ~ a conSI~ t om standa rd ((Jr~(!paratlon InCe s lll ~ l e bbnk Ilnc~ arc u~dul (or C;t:para tlll J.C Odl" ... e(.tlolh Within mtthods. a conSISt "nt "andard IS to use dOllble blank line, bet,.een method, \'(/lIh,,) method, CGn Ider "~/1dard, such a~ the
loll owII1i!
553
SS4
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
• Perform o nl y o ne o pcrJtl o n pt' r lint'.
• T 1)' to kee p mel ho ds 10 ,
22 .S COMMENTS Comments arc no n<:x t'cut<:d lines in a program whose purpose is to describe the intcnt of the program Effecti ve usc of comments is impo rtant to understanding code. Good co mments sho uld nOI simpl y repeat what is o bvio us fro m readin g the code. They sho uld provide mean ing . explaining how and why a piece of code is doing something. Fo r example,
i -'-+ ;
I I i n c r e me nt i
The comment here pro vide no additi o nal inrOmlJtion regardin g what the variable j means and why it is being incre mented. Now consider thi s example . using the hlnction dollO we saw earlier in the chapter.
i n t dolt (i nt a , int b ) {
in t C i c=a *b; r et urn c i }
With no commenls and poor naming of the function and parameters, the purpose of Dolt is nOt obvious. By addin g commentS we can make its purpose clear.
I I dolt - compute and return the area of re c tangle given its length and width I I a - length li b - width intdolt(inta, intb) {
tnt c;
c=a*bi return c;
}
Evrn though thr names of thr function and parameters are still unclrar, thr commrnts c1arify.ts pul"J'OS" and the mraning of Ihe parameters.
TOOLS AND ENVIRONMENTS FOR PROGRAMMING
22.S.1 Documenting Attributes
.,S
For rach I." aurobUlt " a'e purpo<e dnd prov.de all appilcabl~ mvaroan< . Fo r example • •n the class T/1i111gl,. ,,'e wou ld code omewhat ilke th~ follOWin G class Tr iangle { private static final double DEFAULT - TRIANGLE - SIDE = Double . MAX - VALUE ;
II
Invariant : 0 < len1 <=Do uble . MAX_VALUE protected double len1 = DE FAULT - TRIANGLE - SIDE '' II Invariant : 0 < len2 <= Double . MAX_VALUE protected double len2 = DEFAULT - TRIANGLE - SIDE ; II Invariant: 0 < le n3 < =Double . MAX_VALUE protected double len3 = DEFAULT- TRIANGLE - SIDE ; II Invariant: lenx + leny > le n z for ( x , y , z) = (1 , 2 , 3) , (1 , 3 , 2 ) Il and (2 , 3 , 1)
•
•
•
•
}
lor example,
" 1 < _age < 130 " or " 36 < _ l e ngth *_widt h < 193 " . As a reviewer of thiS book has no ted , onc can wnte a eparalC pnvatc..· or protected mcth od that IS ca lled
by other method when the invarianl n~eds c h~ckin g
22.9 TOOLS AND ENVIRONMENTS FOR PROGRAMMING It has been ~ald ohen that, a. . a species, we
art loolmakcrlO, and thi S 1(,; no less tnlc of oftwa n.'" developers An
increaSing number of tool arc .v.dable lhat help developer<. Interact.ve developme nt enviro nments riDEs) are Widel y u
• Time
mr",: fully III hap I"r 24 ~cra l obJo~ I -()n e l1l e d lool, (sut h " Rotlo nal Ro
555
556
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
w i" h Ihe pro~ ralllmtr Illu't wo rk to pro duce th e cventu,l,mple me ntalio n H o weve r, ' 5 o ur diSC USSio n o ( MDA In I"pter 2 1 sho wed, pl,ns arc under way fo r ,mb,ll ou o dc gc nc rnll o n , p, b"",,,, The <. me tools also pcrio m"l reverse englOcenng by mc:chani ally pr du !OJ.( ci a, models fro m SOllr c code (hence: th e term "round# tnp eng meering") . The history o( tools in other branc hes o( engineering (e . ~ ., CA DI AM )
22.10 CASE STUDY: ENCOUNTER IMPLEMENTATION • Im pltmcu tation Holt'S A document is mainta ined by Note to the Student,
This section contains Implementation notes (or the Encounter case study. The source code for Encounter is available online so that the student can inspcct the final product.
Several purely implcm~ntation issues need to
be documented, as listed next. We include a discu sion of whrr' these issues should be documented. The sections that (ollow con tai n examples of the documentation content.
• Prog rammm9 (o nvttltioru. These can be provided 10 the SPMP since they arc part o( projec t ma nage · ment to a degTee. Thcy could be prOVided in the SOD although they arc not part o ( the ac tual desig n. They could be stated m a separate docu ment, but there are already many documents They co uld be provided in a document dedic.ted to implementati o n, which would be useful. F,n,lIy, they co uld be mcluded in the SQAP Ince they arc direct contributor to quality The Encounter case stud y selected thiS option .
i1
• The impiC17lnllnlio" model This speCifics how the phYSical file are o rganized (source code, binary, help files , etc. ). The SOD is a possible repository (or thiS, although the implementation model is not actually part of the de ign. A scparnte document IS a po sibilaty A document on implementation is uc alone would be appropriate. Another passi .
biiLty is the SCMP since it is concerned Wllh (onAgUlJtions and version. The Encounter case
study selected this option.
individual engineers to describe (he current state of
thcir wo rk.
22.10_1 programming Conventions
Programm ing conven tions are added to Section 5, Standards, Practices, Conventions, and MelTics, o( the Encounter SQAP.
5.2. 1 Programming Conventions (t h IS scc tion has becn added to the standard) The (ollowing conventions will be used . I. Parts of nonconstant names arc dclineated by
capi t. liza tio n, (or example, Ibi, fsANam, . 2. Class and interface names begin with a capital : ror example, Account. 3. Instance variables in classe
beg in with a low-
crcase char.cter and end wllh "I", (or example,
bainllcc/ 4. Static (class) vari.bles begin With a lowcrcase character, and end with "S", (or example, j'llrrrslRtI rtS .
5. Variabl es defined in, and global to, a method begin with a lowcrcase chClracter and end With
"MO. fo r example, In,,,,,I/ll 6 . Parameters begin with a lowerca~e character and
end with "I"', (o r ex,mple, pn'" ipaiP. 7. Final variables hall be wntten in c,pltal, and sh,1I use underscor . for example
BANK_NAM.E.
CASE STUDY; ENCOUNTER IMPLEMENTAnON
5.2.2 Notation for Showing the Location of Files
22.10.2 Implementation Model
We will uS< UML 10 de cnbe the imp lemenlalion [7]. A description of the impleme ntatio n model , wh ich describes how the phYSICal Rles are organized, is added as an append ix to , he Encounter SCMP.
5.2.3 personal Software Documentation Each enginee r wi ll maintain documentation of his
curre nl wo rk, wh ich is referred 10 as h is Persona l Software Documl'nlal io n (P D J. This enab les Ihe cnginc~r to report s tatus at all rimes , and it becomes pari of the project's arch ive The team or
Appendix for Encounter SCMP: Implementation Model
projec t lead er wil l determ ine how to organize rhe
r SD of the lea m. T ypical ly, a perso nal software docu menl set correspo nds to a task th at has been allocated to th e e ngi necr and co nSISts of a sct of classes.
An example of PSD 22. 10.3 be lo w.
IS
A part of the Encounter implemenr-atl on model IS
how n
10
Figure 22 .9
22.10.3 Implementation Notes for Encounter: Part 1 of 2 This documcllI is mainlalOed by IOdividual
provided in Sectio n
engi neers to describe the current state of their
work . II should be complete enough to allow
Design model
Im!2lementation model
Framewo rkRPG. RolePlayin gGame
'--------------- -----1
iI RolePlayingGame :
--L __ u __ u _ "'j
IRPGame~~, ,,
IRPGEvent H,--
'1..
J utile)) ~ utile »
,,
,,
RPGEvent.java
r - -- --, , GameState
I
H-,, - , ''
H.-
-11 RPGMouseEventListener •, I --------------------------------
- --
~ RPGame .java
,,
,,,
c(file))
ufils )) RPGame.java
:r
" file »
R PGame .class
~ " file » -~ RPGEvent.class
-'
__[_ -'l " file " -t RPGame .c lass ___ ~_ --'i " file »
-c. RP .... .java
F1&ure 22.9 Design model and Implementation model for Ihe Encounter video game
RP ..... class
557
558
CHAPTER 22
PRINCIPLES OF IMPLEMENTAnON
3. Time Recording Log
the ~n!! 'neer to reporl his or her taNS at m ~et ln 8s , or to allow another engineer to take ovcr the work in a rea onable amount of tIme If necessary
EngIneers ma In ta In records of how long it takes them to perfom"l the various ilctlvltieS requi red by software engineering. The e data are es~n·
ti.1 for th e project, and they prOVIde the engi· neer wIt h a professional "toolkit.' T,ming dam can be collected via written fo m.s or software tools reSIding o n d esktop computers, hand· held computers, and so o n Engineers have to dc· velop a common understanding of the degree of precision required by the orga nizatio n. No~
1. Introduction ThIs document descrobcs th e work of Jo hn Jo nes o n the class EncounterCharacter. It is under configura ti o n cont rol with the file name PSD_EncounterCharacter. The fi le referenced here are stored in the directory Encou nter'IPSD\JJones o n the Galaxy system.
that approximate time measurements can easily become too inconsis tent (or practical usc.
2. Defect Recording Log Th ese data are to red in fi le Tl mt_Rtcordin9_l..o9 The log in Figure 22 . 10 is maintained in fi le d,frcILo9 .
clnd an example is shown In Figure 22 . 1 I .
Date
Number
Type
Phase Inj"cted
Phase Removed
6/ 14/99
142
In terface
Personal
Personal code
detailed desig n
reView
Repair Tim" (minutes) 10
•
Description - omlued checks on name length in EncolmlrrCbnracttr.
6/ 16/99
14 3
Documen tation
Perso nal code
Code
4
•
review
Description: incorrect Javadoc description of EucolwlrrClJar"cttr . • ••
• ••
••
••
. .. _ .
.
,.
.
_ . .
,.
'"
•
••
• •
Th is table concludes with defects fou nd duron g unit test Figure 22.10 Example of a defect recording log Sourc~
HumQhrey, WDtts S. "Introduction LO the Team SOftware Proct>SS: ' Addison-Wesley, 2000.
Oat"
Start
SlOP
Interruptn • .
6/99
10,04 am
10,25 am
4
1,20 pm
4,34 pm
15
6/99 7/99
•
•
•
Figure 22.11 A time recording log
+
6
Time taken
Phase
Comments
\I
Detai led Design
Consulted with
V.N. +
20
159
Personal Code review
Defect 14
CASE STUDY: OPENOFFICE
22.10.4 Source Code (without Test Code):
Ef/COUntefCharacter The r
'0
Add.ll o n.1 rulcs. The named of me' hods should follo w commo n prac'ice for namin g gellers (g,'X()), sellers (wX()) . and predica,c. (" XC), baIXO). ..
ection 22. 15 2 fo r a itSii ng
22.12 CASE STUDY: OPENOFFICE
[ThIS sec' io n pre e nlS examples of Op",OfJi ' docu· 22.11 CASE STUDY: ECLIPSE
mentation thal relates to Implem entatio n.]
No'" ' 0 thc Student, Thc implcmen' ation of Eclipse is a large body of code and rdated artifacts. This see,io n sclcct. just onc vcry small example of stan · dards as an Illustration.
Eclipse devel o pmen' stand ards and resources ar< I."ed at (8 ). They arc q uo ,ed fro m (8 ) as fo ll ow .
22.12.1 OpenOffice Standards
'0
No te th e S tudent· There arc many standards assoCiated with O penOffice dcvclo pmen, W e w tll gwe o ne mall exa mple.
Eac h OpenOf[,ce class must begin w.th ,he fo ll owi ng header from [9 ]
/ * * * * ** * ******** * *** ** ****.***** *OpenOffice . o rg - amulti - platform * office pr oductivity suite
conventions and Guidelines These cover coding standards, naming co nve nti ons, and o,h .. guidelines. Fo r exampl e , naming co nven · 'ioAS arc decomposed as fo llo ws,
* * SRCS f ile : code , v S *
• Eclipse workspace projects
* * last change : SlIuthor : st S SDate :
• Java package
* 2005 / 09 / 02 16 : 31 : 54 S
• Classes and interf.ces
*
* The Co n tents of this file are made
• Methods
* available subject to the terms of * GNU Lesser Ge n eral Public Lic e nse * version2 . 1 .
• Vanables • Plug-ins and ex te nsion p Oint s .
* SRev is ion : 1. 2 S
•
*
* GNU Lesser General Public License * version2 . 1
Ne"." we give an example of one of the abo ve.
Mcthods, Me ,h o ds shou ld be ve rbs, In mixed ca"" wi,h ,hc Ars, lelle r lowercase, wi,h ,he firs t Jellcr of each Inlt rn al wo rd capi,. lt zcd . Exa mples·
*------------------------ -----------------------------------* Copyr ight 2005 by Sun Micro * systems , Inc . * 901 San Antonio Road , Palo Alto , CII * 94303 , USA
*
* This runl) : runF'~ ~
(J,.
getBd ckqco und() ;
library is f r ee software ; you • can redistribute it and/ or modify * it under the terms of the GNU Lesser * Gen e r al Public Lic e nse v e rs io n
559
560
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
• 2 . 1 , as published by the Fr ee • Software Foundation .
•
• This library is distr ibuted in th e • hope that it will be useful , but • IHTHOUT ANY WARRANTY; wi thout even " the implied warrant y of MERCHANT " ABILITY or FITNESS FORA PARTICULAR • PURPOSE . See the GNU Lesser Ge n e ral "Publ ic License for more details .
•
" You should have received a co py of " the GNU Lesser General Public "Licenseal o ngwiththislibrary; i f " not , wr ite to the Free Software " Founda t ion , Inc . , 59 Te mp Ie Place , "Suit e 330 , Boston , MA 02 111-1307 " USA
all Impo rtant aspec" of ,,,ftware dc:vci(>pmcn, wit h OpenOff,cc o r~ , ,"c1udlll ~ ,h e ba
wtll be dC'scribed in de,atl combIOed wi,h a set of UM L diagrams and exa mple, how '0 u,e ,he,e API, Th h Ar\l version I;;' an Init ial Slep for an ongolOg do umen'a" o n la k and Su n Mlcro
.,
nl ty
"
The develo per's gUide title page a nd URL arc shown partially In r-' gure 22 . 12
• ***************** ** *********** / •
•
•
22.12.2 Developer's Guide
Section I (Readers Guide) begins to explain the scope of this documenl. The idea is thaI to add O pcnOffice, 'he developer crea ' es compo ne nts using a set of sta ndards. We con,inue to quote direc tl y from the Develop·
'0
The following is quoted from ( 10). Notice that the teon "guide" is used here instead of "stan· dards." Since many developers contribu te to OpenOfnce, th is is a useful document for unraveling th e i mpl~mentat ion structure.
er's Guide with occasional , minor editing.
1.1 What This Manual Covers
'0
"The OpcnOfAce.org SDK contai ns now the new Developer's Guide (PDF version ). The goal of the guide is to give developers and solution provi ders the necessary means to use OpenOfllee.org as com· ponentwarc:. usi ng it
In
their own projects £Ind
extending it according to their needs. The primary
target languages are Java and C++, although the usc of OpenOffice.org Ba.sic, CLI (. NET), Python, and MS Automation Is treated as well. The initial version of th is guide was a coli abo· ration work of the 000 core developers and IWO external authors. The developers have collected their detailed knowledge about UNO ' and the OpenOffiee.org API.. .. .. The manual will cover I
Thi s manual describes how wn'e progra ms usi ng ,he componen, ,ec hno logy UNO (Unive rsal Net work Objects) wi,h OpenOffice .org , Most examples provided arc wntten in Java , As well as Java, ,he language binding for C++, ,he UNO accc< for OpenOffice.org Basic and 'he OLE Au,omallon bridge ,ha, uses OpcnOfficc.o rg through Microsolt's compo nen, technology COrvVDCOM is descnbed.
1.2 How This Book Is Organized First Steps The First S,eps c hap'er desc ribes the selling up of a Java UNO development ~ n viron m cn t
The componen, l
IS)
(0
ac h i~\lc th e
olutions
CASE STUDY: OPENOFFICE
)
" .. r' ,· ~ , 1.,1·... • ·.. " uIII. ·
··1H~u~"fllnll"'Tnf"t I IoIplorr, pruvul,.d by [onuo,,' tI~h ",.,.t:'d Intt"mC't
1- ~ ~__~________ ._,__ ._~~
.-
SCU'ce code? • • OoNm""U • hI •• - VentOI' CO"'"'
I
Contents 1
. Oeve lo p.,'s G.... ,d. ' 10l
,.1'.'."0:.
• JOL 0 ... 19" Guid. o JDl DON G.... ld.
- SDIt • SOl<. S... ,....~
RQQde(s Culde 1 1
Wha t Thl$ Manual COkers
1.2
Ho .... This SOok IS OrgaO/;ed
1.3
OPBoQ(fjCg,o(Q v ersIon Hist ory
1.4 Belited docym entatlon
• [ " 4mp t••
• J . .... U"O
l.S
Convention s
• C++ UNO
1.6
Ac l'oow ledament s
R,f. re n,e R.f.""O'ICt
• Do... n lo.d 'Tip. 'fI'
tnd<.
2
· lnt"," .. 1 00 s p ou •E
First steps 2. 1
Programming Wi th VJiQ
2 .2
Fr!Jtld s o f AppllcatlQn for UNO
2 .3
Gftt lng S tartelj
Ima l A..fOU ' CI,
• MI,~ U . n .ov,
• D. .... rop •• P'ojecu • Hllh n9 Un Rul ... · Hev,: l.tt., Ard\' ....
2 .3 . 1
Regu1ff d FIles
2 ,3,2
In stallation Sets
2 ,3 , 3
Configurat loQ
I Figure 22.12 Contents of OpenOffice developer's guide
you need. At the end of thi s chapter, you will be equipped wit h the essentia ls re· qu ired for the following c hapters about the OpenOffice.o rg applica tions. •
•
•
F,gure 22. 13 is an example of the selected use of UML in this document. It how the inheri · tance of a pair of classes and the interfaces idt:noted with circles) that each of the two d'5~ ,mplement.
.
.,
Th ere is much more to the Developer's Guide, but our sample ends he re.
22.12.3 Sample open Office Code All haptt'rs prOVide o ne r more exa mples that . how the use of the API in the current de criptlons of this gllldc. . .
The fo llowi ng sample, Listing 22 I, i. from [ II J. The aut ho r, comme nts arc III di ffere nt type and in bold.
561
562
CHAPTER 22
PRI NCIPLES OF IMPLEMENTATION
com.sun.star.view.XPrintable get?,;nter ~etPrinter •
print
com.sun.star.frame.XStorable haslocation getLoc.ltion i,R•• dOnly store
com.sun.star.document. Office Document
"oreA,UrI "oreToUrt
com.sun.starJrame.XModel anachResource getURL
getArgs connectControlier disconnectCont roller
lockControliers unlockControliers hasControlierslocked Sl!tC urre nf Cont ro tIe r getCu rrentControlier
com.sun.star.utH.XModifiable isModified
..tModified
com.sun.star.text.xTextDocument getText reformat
com.sun.star.uti\.x5earchab\e com.sun.star.text. TextDocument «servicl!»
createSearch Descriptor
===
findAIl findFirst
findNext
com.sun.star.utiI.XRefreshable refresh addRefreshListener re move Refresh li st ene r Figure 22.13 UML excerpts from OpenOffice developer's glJlde
CASE STUDY. OPENOFFiCE
lJsdnI 22.1: Code excerpt from OpenOffice I ·*··****·*··~***··*··**·*··
* $RCSfile: ViewSample. java , v $
•
*SRevision: 1.3$
•
* last II
*
•
change; $Author : hr $ $Date: 2003/06/3015 : 46 : 21 $
tt .....ill be • li . t of th••• •
•
*** * •• * * *******************. / u.ort com . sun . star . uno . UnoRuntime;
11___________ implementation___________________ ,'0' Create and modify a spreadsheet view .
*1 public cl . . .
ViewSample extends Spr eadsheetDocHelper
{
11 -------------------------------
public otatic void
main ( Str ing args [J )
{ try {
ViewSample aSample = n•• View Sample ( ar gs ) ; aSample . doSampleFunction () ; )
catch (Except ion ex) {
System . out . println ( "Sample caught e xception! " + ex); System . exit ( 1 ) ; }
System.out.println(" \ nSamples done . " System . exit( 0) ;
);
}
//--------------------------public ViewSample ( Str i ng [1 args ) {
..... r ( args ) ; )
// ----------------------------1** This sample fun c tion performs all change s o n the view. /I
into. . .l daocription
*1
S63
564
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
publi c void doSampleFunct ion () throw s Except ion {
com . sun . star . s h eet . XSp r eads h eetDocume nt xOoc = ge tOocum e n t ( ) ; com . sun . star . frame . XModel xMod el = (com . sun . star . frame . XModel) UnoRuntime . queryInterface(com . su n. star . fram e . XModel.class , xOoc ) ; com . sun . star . frame . XControlle r xController = xM odel . getCurrentController() ;
I 1 --- Spr eadshee t view --II freez e the first column and first two rows com . sun . star. sheet . XViewFr eezab Ie xFr eeze = (co m. sun . sta r. sheet . XviewFreezable) UnoRuntime . queryInterface( com.sun.star.she et . XViewFreezahle . class , xController); i f ( null != xFr ee ze ) Syst em . out .pr int In ( "got xFreeze" ) ; xFre eze .f reezeA tPosition( 1, 2 ) ;
I I --- View pane --I I get the cell range shown in the se co nd pane and assign a cell / I background to them
com . sun . star . contain er . XIndexAccess xIndex = UnoRuntime .queryI n terface( com.sun.star.container.XIndexAccess. class , xController ) ; Obj ect aPane = xIndex. getByIndex ( 1 ) ; •
•
•
I I --- View settings --•
•
•
/ I --- Range selection --•
•
•
synchronized {
(aList ener) / / exteneive us. of synchronize to prevent interruption
aList e ner.wait () ; /1 wait until the selection is done }
xRngSel . removeRangeSelectionListener ( aListener ) ; •
•
•
}
11 _______________________ II listener to react on finished sel ection ExampleRangeListener xRangeSelectionListener
private
cl. . .
implements com. sun. star. sheet.
{
Str ing aResult; F''''uc 'lDicS done ( com. sun. star. sheet. RangeSelect ionEvent aEvent ) pubUc
STUDENT TEAM GUIDANCE FOR IMPlfMENTATlON
{
aResul t : aEve nt. RangeDescr iptor; synchron ized ( thia ) {
notify( ) ; } }
public void abor ted (com . sun . star. sheet . RangeSe lect ionEvent aEvent) {
synchr on ized
( this )
{
notify () ; } }
public void disposing( com.sun.star . 1ang.EventObject aObj ) { } }
11 ______________________ }
The following paragraph inviles readers 10 contribule 10 Ihe develo pe r's guide. This kind of invilalion helps 10 crcale a cooperative almosphere. Developers arc less likel y 10 feel conSlncred by standards and guidelines when Ihey partici pate in establishing them .
Make a contribution We would like to invite yo u to participa te in this effort. so as to cover the necds of the commu niry and to hnng in the community' expe rience Please let us know wh.1 you would expect fro m Ihe Developer's CUlde, what might be rni sc;ing in the current version, which usc cases the gU id e hou ld cover and wh ich CXlCnStOns you ca n think of . .
12.13 STUDENT TEAM GUIDANCE FOR IMPLEMENTATION
following documentatio n, using the Encounter case
study as .n example, I . Programming co nve ntio ns
2. Implementatio n model 3. Integratio n plan The prog rmltmiHg cOll vrn tions need no t ~ extensive, but should provi de enough del.il so thaI code produced by differe nt students exhibit. consiste nt style. It is important to document your Implcmmtation moci,' so the e ntire team kn ows where files are to be stored and fro m where they are to be retrieved . An i" fcgmtiol1 pia" is written so you undernand the o rder of imple menl.tio n and how modules will be tested. O nce YO ll have completed the document.tio n listed above, usc your detailed design as a gui de and Implement your project. At a minimum you can
S.fore ommencin!! with the Implementation of Yoor student team prole t, you hould produce the
Implement key portions of your applicalion to fonn a prototype .
5dS
566
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
22.14 SUMMARY Pr gra m o de" rc. lcd lrom designs. In Ihe o bJect · o n ented paradigm , cla«"' fo rm the basi, of the de
programmin g.
There are a number of hr51 practice'S to fo llow when im plel11 cnt ing cod e, i ncludl ng lISlng expressive naming , aVOid uSing global va riable" nOl usi ng parameters and mel hod va nables, lim iting Ihe numbe r o f function paramcters, U Ing named co nstants , inIt ializi ng va riables. c heck ing loop counters, and e nsuring loo p tcrm ina· tlon. Each IS Inlended 10 reduce Ihe likelihoo d or inlroducing errors and make code mo re ma int ainable . Progrm"mi"g sla"dards are used 10 improve Icam discipl ine, code readab il ity , and code portability. Sta ndard cover all aspect of cod ing including namln!: co nventio ns, code la youI , usc of brackets, and use of parentheses Commolls , especia ll y those that observe progra mmin g standards, are an importa nt aid to understanding code. They sho uld convey meaning , purpose, and intent, and not repeat what is o bVIOUS from rc.ding the code In particular, • good w.y to defi ne a met hod within a class IS to expliCIt ly specify In comment It s IHlm l, prccotidiIlOt1 S, poslcotldill Ons , ;,warlants, (Xcrp rio1ls , and b,owtl issues. Poslco ndltio ns deline a metho d's purpose precisely. The result IS an increased unde rsla ndin g of the method , whi ch leads to a reduced likelihood of errors.
22.15 CODE LISTINGS REFERRED TO IN THIS CHAPTER 22.1 S.1 Code Listing for Video Rental EXample The code In listing 22 .2 below illustrates some of the prinCiples discussed in thi' cha pter, applied to th e Rmlal class of our VIdeo sto re example.
Listing 22.2: Video store application code Rental, Rental/tern classes
----------------------------------/ **-----------* Oescr ibes a OVD */
cIa.. OVD ."t.nds RentalItem { }
/ **
* Intent : SOD for * * Known issues :
Rental Framework : http: // . . . . .
* (1) This class is not complete for a first build
* * *
( 2 ) Relies on log() method to log dev elopme nt problems -- not yet created (3} Un it test to be moved frommain() and upgraded to use JUnit .
*/
CODE lISTlNGS REFERRED TO IN THIS CHAPTER
••
• Java. ~o . ; *auact. c1 ••• Rental
UpOrt
{
I I CONSTANTS = = = = = = = = = = = = = = 99999999 ; 10_WHENJENTAL_ NOT_ IN_EFFECT = 0 ; TOLERANCE_ON_RENTAL_ID = 1000; F1LE_WITH_NEXT_USABLE_RENTAL_NUMBER = "RentalNumb er . txt " ;
private lInu atatic int privatellnal atatic int privatellnu atatic int private atatic Str ing
-
-
H1GHEST-ALLOWABLE RENTAL 10
I I VARIABLE S = = = = = = = = = = = = = = == = = == protected int id = ID_WHEN_RENTAL_NOT_I N_EFFECT ;
I I renta l
identificat ion protected Ren talCustomer r entalCust omer = null; I I cust o me r rent e d t o protected RentalItem rentalItem = null; I I it e m rent e d
1* Class invar iant : EITHER the r ental is i na ct ive, id == ID_ WHEN_ RENTAL_NOT_ IN_EFFE CT , rentalCust omer == null, and rentalItem == null OR ID WHEN - RENTALNOT -IN -EFFECT < id < = HIGHEST- ALLOWABLE RENTAL_ID, rentalCus to mer != nu ll , and rentalItem!= null
-
*1 - - -- - --- -- - -- - ---- - - II CONSTRUCTORS -- -- -/ ********************** ***** *** ****** * Intent: Satisf y class invariant with rental n o t in e ff e ct • Postc ondi t ions : id == ID_WHEN_RENTAL_NOT_ IN_EFFE CT, * ren talCustomer == null, and rentalltem == nul l
*1 public Rental () / ************** ********************** / {
-
id = 10- WHEN- RENTAL NOT- IN- EFFECT ; rentalCustomer = null; rentalItem = null; }
j* ••• ******************************** • Intent: Creat e a s p ecific rental
•
* Preconditions:
• (1) * (2 ) • (3 ) • (4)
anID > 1D WHEN_RENTAL_ NOT_I N_E FFE CT anID <= HIGHE ST_ ALLOWABLE_ RENTAL_ ID aRental Cu sto me r ! = nu l l aR e nta llte m ! = null
-
567
568
CHAPTER 22
PRINCIPLES OF IMPLEMENTAnON
•
* Postcondi t ions:
*
(1) as for setId( anld) * (2) rentalCustomer == aRentalCustomer * (3) rentalltem== aRentalltem
*
* Known issues: * (1) Exception
*
not specific enough (2) No handling of violated precondit io n s
*/ public Rental ( int anld, RentalCustomer
aRentalCust omer, Rentalltem aRentalltern)
throws Exception / *********************************** / {
setld ( anId ) ; rentalCustomer = aRentalCustomer ; rentalltem = aRentalItem; checkInvariant(); }
---------------------// METHODS ---------------------/************************************ * Intent: A check that the class invar iant is valid; present for
* demonstation only. It is possible that this method is n ot actually
* used. * Exception: Thrown if the class invar iant is violated * Known issues: Exception not specific enough */ public void
checkInvar iant () throw. Except ion
j ****************************** / {
id = = ID_WHEN_RENTAL_NOT_IN_EFFECT) && ( ( rentalCustomer ! = null) II ( rentalItem ! = null ) ) )
if ( (
{
thrown_Exception( "Invariant in 'Rental' violated" ) ; }
if ( ( id > ID_WHEN_RENTAL_NOT_INJFFECT ) && ( ( id > HIGHEST...J!LLOWABLE_RENTAL_IO) I I ( rentalCustomer == null} II ( rentalItem == null) ) ) { tbrown • •
Exception( "Invariant in 'Rental' "violated" ) ;
} }
/************************************ * Intent: Get the next available number for assigning a rental
* * Returns:
The integer on the only line of the local file
CODE LISTINGS REFERRED TO IN THIS CHAPTER
* FILE_WITH_NEXT_USABLE_RENTAL_NUMBER
•
* postcondition:
The integer on the local file FILE_WITH_NEXT_ • USABLE_RENTAL_NUMBER has been incremented
•
• Exception that exits the application: * If the file ca.nn ot be accessed or the data is not an integer
*/ pri_t. autic int getNextRentalNumber ()
/***.**** •• ************************** / {
Str ing nextRentalNumberStr ing = new Str ing ( ) ; / / Str ing form int nextUsableRentalNumberReturn = - 1000 ; BufferedReader reader = null; FileReader f ileReader = null; DataOutputStream wr iter = null; try {
/ / Prepare to read from the file FileReader = new FileReader ( FILE_WITH_ NEXT_USABLCRENTl.L_NUHBE:R) reader = new BufferedReader ( fileReader ) ; nextRentalNumberStr ing = reader. readLine () ; System. out .println ( nextRentalNumberString ) ; / / Convert to integer nextUsableR entalNumberReturn = ( new Integer ( nextRentalNumberStr ing ) ) . intValue () ; / / Increment the next available number for assigning a rental int incrementedNumber = 1 + nextUsableR e nta lNumberR eturn ; Integer integer Form = new Integer ( incrementedNumber ) ; / / and replac e the existing record WI iter = new DataOutputStream ( new F ileOutputStream( FILE:_WITH_NEXCUSABLE_RENTAL_NUMBER ) ) ; writer.writeByt es( integerForm.toString() ) ; } catch ( Except io n e) (
System. out .p rintln( e) ; System. out .println( e.toString() ) ; } return
nextU sable Renta lNumbe rR etur n;
}
/** ••••••••••• ******,.**.****** ••
;
569
570
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
" Intent : Self - test of this class " Known issue : Not migrat ed to JUnit
*1 public static void main ( Str ing [l args ) throw. Except ion / *********************************** / {
II Create concrete classes because all are abstract class RentalTest extends Re nt al {
public RentalTest () throws Excepti on { super( ) ; }
public RentalTest ( int anld, RentalCustomer aRentalCustomer, Rentalltem aRentalltem ) throws Except ion { super ( anld, aRentalCustomer , aRentalI tem ) ; }
};
class ConcreteRentalCustomer extends RentalCustomer {} ; class ConcreteRentalltem extends Rentalltern{};
I I Create obj ects ConcreteRentalCustomer concreteRentalCustorner = new ConcreteRentalCustorner() ; ConcreteRentalltern concreteRentalltem = new ConcreteRentalltem() ;
II Test invariant checker first because it is used in testing
// -------------RentalTest rentalTestO = ne .. RentalTest () ;
II TestO.l rentalTestO. id = 0; rentalTestO . rentalCustomer = null; rental TestO . r entalI tern = null; try
{
rentalTestO .checklnvariant() ; System. out . pr int In ( "Test O. 1 succeeded "
);
}
catch ( Ex ceptio n e) {Systern . out .p rintln( "Test 0.1: Should be no exception "
I I Test 0 .2 rentalTestO. id = 1 + HIGHEST_ALLOWABLE_RENTAL_ TD ;
); }
CODE LISTINGS REFERRED TO IN THIS CHAPTER
rentalTestO.checklnvariant(); System. out- println( "Test 0 . 2 succeeded"
);
}
cat.cb( Exception e ) (System. out .prin tln( "Test 0 . 2 : Exception as expected "
); }
//Test 0.3 rentalTestO. id = 1; rentalTestO. r entalCustomer = null; rentalTestO. rentalltem = concreteRentalltem; try{ rental TestO. checklnvar iant ( ) ; System . out . pr int In ( "Test 0 . 3 succeeded" ) ; } catch ( Except ion e ) (System. out .println ( "Test 0 . 3: Exception as expected " ) ; } //Te st 0.4 rentalTestO. id = 1; renta1TestO. renta1Customer = concreteRenta1Customer; rentalTestO. rentalltem = null; try (
rentalTestO.checklnvariant( ) ; System. out .println ( "Test 0.4 succeeded"
);
)
catch ( Exception e) (System. out .println ( "Test 0.4 : Exception as expected"
); }
/ / Test constructor s ~ -----------------
/ / Test 1.1: Empty constructor RentalTest rentalTest1 =
ne..
RentalTest () ;
try (
rentalTestl.checklnvariant( ) ; System. out . println( " Test 1.1 succeeded "
);
}
catch ( Exception e ) (System. out .p rintln( " Test 1.1 : Should be no exception " }
/ / Non-empty constructor / / Test 1. 2 : Lega 1 co nst ruct io n
);
571
S72
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
RentalTest re nta lTest2 = n... RentalTest ( 1, co n creteRe ntal Customer , concreteR e ntalltem ) ; try ( rental Test2.ch ec k~nvar iant () ;
System. out. println( "Test 1.2 succeeded" ) ; } catch ( Except io n e ) (System. out .println ( "Test 1.2: Should be no exception"
);
}
II Test 1. 2 .1: Legal construction with warning Re ntalTest rentalTest2pointl = n... Rental Test ( 99999900, concr et eRentalCustomer , concreteRentalltem ); try {
rentalTest2pointl.checklnvariant(}; System.out.println( "Test 1.2 succeeded"
);
} catch (
Exceptione)
(
System. ou t. println( "Test 1.2: Should be no exception"
);
}
II Illegal construct ions II Test 1. 3 try {
RentalTest rentalTest3 = D." RentalTest ( 0, concreteRentalCustomer, concreteRentalltem ) ; }
catch ( Exception e) { System. out .println( "Test 1. 3: Exception as expected"
};
}
II Test 1.4 try {
RentalTest rentalTest4 = nu RentalTest ( 1 + HIGHEST.J
catch ( Except ion e ) { system. out .println( "Test 1.4: Exception as expected"
); }
eOOE USTINGS REFERREO TO IN THIS CHAPTER
I/Test 1.S ~
(
RentalTest rentalTest5 = ...w RentalTest ( 1, null, concreteRentalItem ) ; }
catch( Except ion e ) (System. out .println ( "Test 1.5: Exception as expected" ); } II Test 2: of getNextRentalNumber () System. ouc .prin tln( "cur rent integer < -- > " + gecNex cRe ntalNumber()
);
}
/************************************
* Intent:
set the id if the parameter is legal; warn if the number * of rentals is getting close to the maximum .
•
* Precondition: * anId > RENTAL- 10- WHEN - NOT-IN-EFFECT * anId <= HIGHEST- ALLOWABLERENTAL -10
&&
*
* Postconditions:
*
(1) id == anId * (2) i f the rental number is within TOLERANCE_ON_RENTAL_IO of * HIGHEST_ALLOWABLE_RENTAL_IO, a warning is present on the console .
*
* Exception: if preconditions violated
*
* Known issue: method" log() "
to be implemented
*/ pri"atevoid setId( int anId ) throws Exception
/******************************** / ( i f ( ( 10- WHEN- RENTAL- NOT- 1NJ;Fn:CT
( anId <=
< anId )
&&
HIGHEST_ALLOWABLE_RENTAL_IO ) )
(
id=anId; if ( anI d > H!GHEST_ALLO~IABLE_RENTAL_ IO - 1000 ) { /*tbs: Log . log ( " setNumber () i n 'Rental' set ' id ' " + "w ithin 1000 of highest allowed id' , ) ;
*/
System . out .println( "WARNING: Rental IOwithin" + TOLERANCE_ON_RENTAL_IO + " of highest allowed value" ); } }
573
S74
CHAPTER 22 PRINCIPLES OF IMPLEMENTA n ON
.1 •• (
I I do n ot c han ge id
thrown.w Exception( " setNumb er() in Rental tried setting id " + " o u t of bounds: " + anld ) ; } } }
**------------------1
*
• • • • • • •
* I abstract clan RentalCustom.er { }
*----------- -----1*
* • *1
• • • • • •
abstract class RentalItem (
private String title = "RentalIt em title not assigned yet"; public float length = 0; II 'public' for demo purposes
I I Static constants private static final float
MAJCRENTAL_ITEM_TITLE_LENGTH =
20;
/ .**********************************
* Intent:
Requirement http: // tbd.tbd.tbd#3.2.DVD.l.l
*
* Postcondition: *
If' aTitle' consists of English alphanumer ic characters i n lower * or upper case, and punctuation marks!, :, ", or ?, then title == * aTit le i f length of 'aTi tIe' < = MAX_DVD_TITLE_LENGTH * otherwise title == first MAX_DVD_TITLE_LENGTH characters of * 'aTitle'
*1
privatevoidsetTitle( StringaTitle) / **********.*********.*****. / (
I I Check that' aTitle' consists of English alphanumer ic characters in I I lower or upper case, or punctuat ion marks!, :, " or ? bool.... charactersAcceptable
= tzu8; I I
make false when
unacceptable character found char ch = 'X' ; fore tat i = 0; i < aTitle.length(); ++i ) {
CODE LISTINGS REFERRED TO IN THIS CHAPTER
ch=aTitle.charAt( i) ; // temporary nam e for clarity / / !lake ' char act er sAcceptab le' false if 'ch' unacceptable // true otherwise charactersAcceptable = charactersAcceptable && (
( ( ch > = 'a' ) && ( ch <= ' z ' ) ) I I ( ( ch > = 'A' ) && ( ch < = ' Z ' ) ) I I ch == ' !' " ch == ' :' " ch = = .... " ch = = );
, ?• '
}
if( charactersAc ceptable ) {
title = aTitle ; } // (otherwise leave 't itle ' unchanged ) } }
22.15.2 Code Listing for EncounterCharacter Source code for the EncouHI"Cha raC' /(rcias in the Encou nter video game (described
In
t'Cllon
22 I O) is shown
in listing 22 .3. Source code (or all of the Encounter case tud y is available o nline
Ustlng 22.3: Sample code from the Encounter video game implementation paetaqe&ncounter . EncounterCharacters ;
/* Class Name: EncounterCharacter
* Date : 01/13/2000
* Copyright
Notice
: copyright (c) 1999-2000 by Eric J . Braude
*/ import java .awt. * ;
import java . to. *; import Fr . . . .orkRPG . Char.cters . *; • l.mport T•• tOtiliti.s. * ;
/** Base class for the characters of the Encounter game. SOD reference : • 6.2 . 1 •
SDDreference: 6.1.2.1.1 * < p > Invar iants: see the class invar i ants *
Re q uir eme n t s : 3 . 2 . EC . 3 . 2 (pr opor t ions among qual i ty values) * @ret u rn Th e sum o f the player ' s qualities , a value 0 or greater .
*/ publ ic s y n chr oni zed f loa t
sumOfQualitie. ()
{
f lo at suml(= f or ( i nt i =
O. Of ;
0; i
<
qualityTypeS . length ; ++ i )
s . - + = qualValueI tiJ ;
return
aumM ;
}
} // e nd of En cou n te r Character
22.16 EXERCISES I In your ow n ,.,..ord, . des r ibc w hat
1
mea nt I y codt, bl.'lIl g "correc t ..
2 Sup po c that you arc about LO code a method W hat .1fe tI'll' ma lo r .;;ourcc:~ dc . . cnbmJ.: fo r you what
th l< method
IS
to do)
3 Provide an exampl of a domain lac; . a de~ l gn cia.;;,. Jnd an Imp!cmCnt3ltOn ciao;, thal nll gh t be used ,n the Implementat Ion 01 a bank AT 'I applICatI o n E,plalll why yo u t ho," "aeh cia" 4. Spec ify the '" tCOl , preco nd Iti o n" an d pO~lcon dtt1 0 'h
of an tn put pa ram eter x
or J (unCtto n th at
o m pU lt ...
the sqUJrC roo t
581
582
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
5 Explain why Ihe u c of globa l vari.bles works "8alOst the princIple of Inlormatlon hid,ng. C,ve an example of when this can lead to program errors. 6 . The following functIon returns the correct value, but violates one ol tho implementatIon practIces described in this chapter. Which llnpl emen tatl on practice is vio lated, and how mlllht II lead to a problem 10 the future ) How would you Ax the problem)
/ / compute amount of interest and return float computel nt erest ( float balance, float interestRate) {
/ / compute interest earned balance = balance * interestRate; return balance; }
7. Describe two to four advantages and one or two disadvantages of enforcing coding standards. 8. For each of the error handling methods described in Section 22 .6. I give an example of when it is sensib le to use the method. 9. What does the following function compute) How would you modify the function using commentS and more descriptive variable names to make it easier to understand its purpose]
int compute ( int a ) {
int result = 1 , num = 1; while (num < = a ) { result *= 1; num++ ; }
return result; }
II Intent : Compute the factorial of the inp ut parameter /1 Precondition : 0 < - factorialNumber II Postcondition : Return facc o cJalNumber! inc compuceFactorial (inc factorialNumber) (
inc current - 1; factorial - 1 ; klhile (currene <- faccorialNumber) ( factorial -- . current ;
current
I I ,.
)
return factor 1a1; }
10. Describe how the pnnciple of "Enforce Intentions" leads to improved code quality. Provide at least three examples to support your answer.
BIBUOGRAPHY
II . ChOOR thr
which they would not apply
12. Code is rarely perfect. Give thr<e criticism of the code in the case srudies.
Tf".M EXERCISE
Impiementatien Implement key pans of your application to fonm a protOtype.
BIBUOGRAPHY I McConnell. Steve. ~CoJ( Co",pklt A Pru cllclll Haltdboot of ~ff1DQft C (trlSlfllchO,. ... 2nd Ed, MICrosoft P r~s. 7004 2 Horstmilnn. Cay. S . "Pracli(AI ObJfCI-Onrnltd DAAlopmrn l 'ft C++ Q,J JUIlQ ," John Wiley & Son\ 1997 .3 Ambler, Scon. "'J1x Objt I Pnmcr TIx Appl,(D!!O" DnlfWP
583
uality and Metrics in Implementation
Plann ing Maintenance
•
How do you assess the degree of sufficiency of an implementation ?
•
How do you measure the degree of robustne ss?
•
What metrics are there for flexIbility?
•
Reusability melrlcs? Efficiency? Rellab;;;ty? Scalability?
•
How does one assess the degree of security of an Implementation?
•
How do code inspections Improve code quality? What about code revIews?
•
How does pair programming Improve code quallly?
Testing
The Software Developmen t Llle Cycle
Requirements
anatysis
Imple'ltlntatlon
Oesign
Figure 23.1 The context and learning goals for thiS chapter
The qUJ IIl y of an implementation can be mea urcd with attribute,;; SimIlar t those 1I cd fo r asc:;esslI'g J design. The fi r I p.u,- of thl - chapter descnbes these attribute, The second di!. us "-s c de In .. pc lions an c.-rfCClivc qllillllY process (o r discoverin g defects before code 10;; tested A~ u ~lIal . 010 t mctric~ dC'S nbt'd bel \\' are mealllngful onl)' 111 th e context of co mparati ve dal') (rom pa')t proJect'i.. In Jddlt lo n. eac h me tric is most effective whe n used in co njuncti o n with o the r mctncs rJth e r th"n by It elf
QUALITY OF IMPl£MENTATlON
As menlioned in precious chapter<, there are two ides to assessI08 the quality of implementations. One is the IXrifica lion side, in which quality is assessed bosed on looking at the source code. This chapt.. d ISCUSses the ""nfication side. This IOciudes code inspection , the subjeCt of the second part of this chapter. Included in that part is pair programming , a klOd of r.o nllnual inspection favored in agile projects. The other side of Impkmentation quality is an asse sment of the completed code . That side is ualidalioll-essentially, tcstlngwhich IS the next part of this book. 23,1 QUALITY OF IMPLEMENTATION The qualities of an implementation Ca n be categorized as shown in Table 13 I. For each category, the two cxmmes are captured with a rough scale o n whi ch 0 indicates low quailty and 10 high . More precise measu~ments for these categones are dl cussed In th is chapter Some of these qualities support other<, depending on the application For example, robust code is less sensitive to anomalous conditions, and thus makes applICation morc reliable si nce they stay operat io nal Table 23.1 Rough measures o~of an implementation
ro;;;-
of
.. .
IsufIIdency Irobustness
Iflexibility
Rough metric
o ...
10 (maximum score)
Satisfies all of the design specificatIOns for this element Will cause crash on any anomalous event
Recovers from all anomalous events as well as can be expected
IWill have to be replaced entirely if the design or reqUifements change AS easily adaptable to reasonable changes as can be expected cannot be used in other applications
usable in all reasonably related applications without modification Fails to satisfy speed or data storage requirement
satISfies speed or data storage requirement with reasonable margin Obviously won't achieve required mean time between fa ilure
IObviously will achieve required mean time between failure can't be used as the basis of a larger version IS an
MCurity
outstanding basis for a version with much larger scope
~ not accounted lor at a/l
-r,; known manner of breaching secunty IS known
.,
585
586
CHAPTER 23
QUALITY AND METRICS IN IMPLEMENTATION
robuSlness
I I
/
,
/
reliability
seal bility
/
/
_ _ • flexibility
f/
efflclency ~
/--- -- -
-
Key: usually competes: .
Figu re
23.2
-
•
-
• reusability
usually supports:
Supporting and competing relationships among implementation
)
quali~es
lo nger On the other hand, some of these goals compete The I;oals of reliability and Aexibility often compete because flexibility tends to introduce Increased opportuni ty fo r error. It is difficult, frequentl y impossible, for a design to cnJO all of these quali ti es at o nce. Figure 23 .2 shows comm on support and contradictio ns among them oftware engtneers trade off properties by prioritizing qualities Agile development , fo r example. places a lower priority on tlex,btl,ty and reusabi lity than o n sufficiency and reliability ll)c sec ti ons that fo llow claboTOltc upon each of th ese Implementati o n qua liti es .
23 .1.1 The Sufficiency of an Implementation The
suffi
1(tIC)'
of an Implementation measures the pcrccntag(' of th e requ irements and design specificatio ns
(lctually implemented . Although we expect to Implement all requirements, time lim ita tions often force liS to
Implement in order of pnority, omitting some. Th e suHicicncy of an Implementa tio n can be calculated from
the fo ll OWing formula (which req uires us to have a completely speCified li S! of deta iled requ irements). Prr rutnge
of detailed
requirements thtll nrc implcmol ted .
If the SDD IS detailed, the design speCifics classes and methods. Another measure for the . ufRcie ncy of an implementJtlon
I
as follows.
P"cOI'ag , of methods speclfi,d III .he drsig" .bn. arc II"pl",,,,,,,d A rougher m elfiC is (he followi ng.
PercCllfagc oj classes sptciji,d
1/1
.be dCSlgll
fh•• 'lfe IIIIplcmm .,d.
A problem with the laner is how to account for classes speCified in the SDD that arc o nl y partially implemented .
QUAUlY OF IMPLEMENTATION
1
input to the method a Anomalous parameter value b. Anomalou> glob.1 variables c. Anomalous- event variables
2. Asses dependent methods tcas-ure ex tent of compromise FigUre 23.3 ASseSSing the robustness of a method
23.1 .2 The Robustness of an Implementation which it handles anoma lous input ( 1.(, . Input whose fo rm or content IS unexpected). In the final .nalySls, the wo rk of an application is performed by ItS methods However. not every method need to be ro bust ,n every way . Fo r example . suppose that. medicine is highl y An implementation' robuSlu rss is th e extent to
toxic when taken in large quantities. A me th o d that o m pUl es doses for Il must be as Tabu
t
as r>o~s lbl e On
the other hand, • method that takes input and creates a strong for displayi ng an .utomobtle doc> no t need to
be as robusi. There arc tw o
avenu('S
(o r
aSS'C 55ms
th <: ro bustness of a metho d, as listed in Figu re 23 .3
T o assess the robustness of a method relative to It S po tenti al inputs, we in vesti gate th e precondili ons.
Fu'St. we a sess their completeness. In o the r words , we e nsure that every assumption made by the me th o d IS expressed in the preconditions. \"(Ie th e n as ess whethe r the metho d defe nds against possible vIOlati ons of each precondition . ConSider, for example, the Rcc/tlIlg/r closs in Listing 23. 1 Ho\,.' robu l is the method t tArrn () 7 Let's assume that we do not want to restri ct [h e size of the ]Jon l inputs.
Ustlng 23.1: A Rectangle class
----------------------------- --------- / **---------------------------------------
./
poblic: class {
Rectangle
-- - - - ---------------------------------- ---- --------------//VARIABLES ====---float float float
area = 0 ; length = 0 ; width = 0 ;
------------------------ ----//CONSTRUCTORS =====----------------------------/* ******************************** *****
./ public Rectang le () /********************.***************** / { }
587
588
CHAPTER 23
QUALITY AND METRICS IN IMPLEMENTATION
/ *********.****.*********************** * 1 public Rectangle ( float aLength , float aWidth ) / ******************.*******************; {
length = aLength; width = aWidt h; }
II METHODs ------------------------------========== ------------------------- - -- -/ **************************************
* Preo:onditions: * (l) length > = 0 *(2)width > =O
*
* Postcondi t ions:
* (1 ) area == length * width
*1 public void setAr ea ( ) / ************************************** / {
area = length * width; } }
Note I , The first question is whether the preconditions are complete. In view of the stated desire not to restrict the values of 1'''9th and Ividth , the preconditions appear to be adequate. (One is not always com:ct in onc's intentions. bur the point is thal the y are documented and so ca n be revisited . Undocumented intentions,
o n the other hand, lead to confusion and greater errors.) Note 2, Next, we assess whether the method allows a reaso nable recovery if the precondition fails . Since there I no provision for this in the code, the method's robustness is compromised. A check on 1"'9th and width that leaves a'ta unchanged, and that generates reasonable notices, would elevate the method's robustness. listing 23 .2 is a more robust version of RtctaH9l,. It restricts the values of fields to what is intended, a practice that usually makes computing more robust. The objectIon In Note 2 above is also addressed. Nevenheless, listing 2 is still subject to critICisms, which arc discussed below
Ustlng 23.2: A more robust Rectangle class
---------------------- -------------------1* *--------------------------------------------
* Rectangle
*
class, including safeguards for limits on area
* Known Issues: * (1) Limits dimensions to floats, not double.
QUAUTY OF IMPlEMENTATION
• (2) See known issue (s) for indiv idual method (s) •
*1 public cla . .
MoreRobustRectangle
{
----- -- ----- --------------------------------------------II VARIABLES --------------
I I Class invar iant (i ntent: the corresponding area is limited) : I 1 0 <= length && 0 <= width && ( le ngth * width <= Float. MAX_VALUE) private float ar ea = 0 ; private float length = 0 ; private float wid th 0;
=
-_ ._----------------------II CONSTRUCTORS ====-==--------------------------
/ **************************************
*1 public
MoreRobustRectangle ()
/ ************************************** / {
}
/ **************************************
* Intent: Robust constructor * Postcondi t i ons : * ( 1) If the class invar iant is true, length == aLength && "'idth == aWidth * (2) Otherwise * (ilamessagehasbeenloggedtothelogfiledescribedinErrorUtility stating that the class invar iant was viola t ed and * * ( ii I the same message appears on the console
*1
public
MoreRobustRectangl e ( float aLength, float awidth )
1************************************** / { if ( c lassInvar ian tHo Ids ( aLength , aW i1th ) )
{
length = aLength; width = aWidth; }
.1..
I I Postcondi tio n (2 I
{
Str ing error Message= "At tempt i n RobustRectangle ( float , float) " + " to use values that make the ar e a too large . Ignored "; EuorUt ility . 1ogAndRepoltToConsole ( er ror Message ) ; } }
519
590
CHAPTER 23
QUALITY AND METRICS IN IMPLEMENTATION
uETHODS ------------ - - - - - - - - - --------------------------------------// 1'1 / **************** •• *******************.
* I ntent: A single locat ion for checking required class invar iant . * * Returns: true if the class invariant would b e valid after construction
* with length == aLength and width == aWidth; *
false otherwise
* Known issue: Does not deal with aLength > Double. MAX_VALUE * aWidth > Double . MAX_VALUE
or
*/ classlnvar iantHolds ( float aLength, float aWidth ) / ************************************** /
priv.at. boole'n
{
/ / Create Double form to allow check on product of floats double aLengthDouble = ( new Double ( aLength ) ) . doubleValue () ; double aWidthDouble = ( new Double ( aWidth ) ) . doubleValue () ; / / double form of Float. MAX_VALUE double floatMaxValue = ( new Double ( Float. M.l'.)CVALUE doubleValue () ;
) ) •
return (
aLength >= 0 && aWidth >= 0 && aLengthDouble * aWidthDouble <= floatMaxValue ) ;
}
/ **************************************
* Precondition : The class invariant
* * Postcondition: area == length * width */ p"'lic void S e tAr e a
() /**************************************/ {
if( classlnvar iantHolds ( length , width) ) {
area = length
* width;
}
ebe//Postcondition (2) {
StringerrorKessage="Attempt inKoreRobustRectangle .setAreaC) "+ "to use out-of-bound value (s) • Ignored" I ErrorUtility.lOgAndReportToConsole( errorMessage);
QUAUlY OF IMPLEMENTATION
} }
/* •• ********.*.*.********************** * Precondition: The class inval iant * postcondition: length -- aLength
*/ public 9OJ.c:l setLength ( float
aLength )
/ ************************************** / {
/ / Safety check on the precondition if ( c lassInvar iantHolds ( aLength, width ) ) {
length = aLength; } .1 . . {
StringerrorMessage="AttemptinMoreRobustRectangle . setLength() "+ "touseout-of-boundvaluefor length. Ignored"; ErrorUtility.logAndReportToConsole(errorMessage) ; }
}
/**************************************
*Precondition:Theclassinvariant *Postcondition:width==aWidth */ public""ic:lSetWidth (floataWidth ) /************************************** / {
//Safetycheckontheprecondition if(classlnvariantHolds(length ,aWidth ) ) {
width = aWidth; } {
StringerrorMessage="AttemptinMoreRobustRec tangle.setWidth () " + "to use out-of-bound value for width. Ignored " ; ErrorUtility.logAndReportToConso le (e rrorMessage); } } }
591
592
CHAPTER 23
QUALITY AND METRICS IN IMPLEME NTATION
A metric (or each method, No ro bustness = 0, , o me = 05, comp lete = I A metnc (or classes
L
(degree o ( method 's robust l1es< on , ca lc o( 0 to I )
"I/II!III-GJ
Number o( meth ods Figure 23.4 A robustness metriC for classes on a scale of 0 to 1
A metric (or the ro bustness of a block of code IS shown in Figure 23.4 Let's calculate the robustness of tVIortRobll5fRcclaligit This class has six met hods (we Include construe · tors). The null const ructor is guaranteed to leave all va lues zero , so it respect the class In va n anl, and is robust The cbcckiHvariaHI() method is rob ust The r«t of the methods check o n the precondition but do nothing If the preco nd itio n is not valid. We can give these the score o( 1'1 . The formu la In Figure 23.4 thus yiel ds the follOWing robustn«s measure fo r RobllSlRccltmgft.
(I
+ I + 1/ 2 +
1/ 2 + 1/ 2 + 1/ 2}/6 = 67%
It is considerably more robust than RtCldHgit , which has a low score
23.1.3 The Flexibility of an Implementation An implementation isjb:ibft if it can easily acco mmo date new o r chan ged requireme nts. Figures 23 .5 and 23 .6 list impl~mentation techniques that increase Oexi bihty .
I. Document precisely and th o ro ug hl y
• Reason, cannot adapt code that you do n't und erstand 2. Name constant.s • Reason , understandability 3. Hide where possi ble • Variables and methods • Reason: reducing complexity Increases understanding 4. Collect common code • As helper methods and classes • Reason, reduce complexity FIgure 23.5 Factors In Implementation that increase flexibility, 1 of 2
5. Reduce dependency on global variables - and on any variables external to the method • Parameterize methods • Reason: allows method to be usod in other contexts 6. Program at a general level
• Reason: applies to more situations 7. Use understandable vari.ble and ",nction names Flsure 23.6 Factoo $ In
that Increase flexibility. 2 of 2
QUAUTY OF IMPLEMENTAllON
We dlscuSli the~ factors b.:low and subject the code above (or Rob""RtCla"glt to each factor. I. J)ooooo..1. The idea is that the more effectively code is documented, the more easily it can be reused. For example, we can still fault the overall ciass description in MortRobusrRtcla"glt (or lacking su(Hcienl description o( the purpose of a cia ... One could possibly fault the "variables sectIon as lacking a description, .Ithough none is needed where obvious.
2. Na .., CO","'"I> When constants arc named rather than being stated explicitly, the code becomes morc eisily targeted to new u~s . There arc several places in the MorrRobu"Rcc"'"9k code where constants would have improved its flexibility- for example , naming Floar MAX_VALUE as J\W...ALLOWABLE...AREA. As another example, instead of the statements
pr ivate float length = 0; pr ivate float width = 0; we could state the (ollowing,
private static final float DEFAULT_LE NGTH = 0 ; private static final float DEFAULT _WIDTH = 0 ; private float length = DEFAULT _LENGTH; pr ivate float width = DEFAULT _W IDTH;
3. Hid, Wlmt Possiblr. In software engineering, o ur ma in adversary is compleXIty. O nc useful tech nique (or combating complexity is to hide from view the parts that are no t relevant at the time. "Hiding" applies ro code that is not available to other code that should not need it. Class membe rs that are not to be accessed by methods of other classes are thus made l>rioart (or prorrcr,d if inhentance is required ). Cia ses that are not to be accessed by methods of classes outside their package are not made p"hltc.
Cod,. When common code is collected into a meth od, the result is grea ter flexibility ; otherwise the common code would have to be changed in multiple places. Robu,rRtcrml91, doe a good job
4. Collter Commo"
of this by collecting the checking o( the invariant in one place, classlnvaria nrHold50. In this respect, then, the code is flexible. S. R,d." D,p",d",cy 0" Clohal Variahh This means that each method and each class sho uld be self·contained so that they can be mixed and matched . Perusing the methods o( Roh.,rR,c"'ngl" we sec that the o nly method referrin g to an attribute of the class is "fAr,aO, which refers to arta . In pnnciple, we can eliminato arm as a variable, elImInating "tArtoO and introdUCing 9,rArraO that returns the area . This is an improve ment in Rexibility , but it could coll ide with another quality, efAciency . lf the applicatio n requires very (reque nt use ot arta , II may be preferable to compute it once and refer to II often .
6. Program C""rically Here we ask whether the code is at a suffiCiently abstract level to be usable for additional or changed reqUIrements. It is possible to approach thi S at the de Ign level by u ing abstract classes, but our focus here IS o n impl,,",n rafion flex ibility Flexibility depends o n the directron that an application is taking. For example, if this class is to be part o( a 3D appli alion, we ma y want armO to compute the area on the mo nitor o( a rectan gle m space , een at an an!;le-that is, taking perspective into account. Thi s is a rar more generi c computJlI on.
7. U" U"d",,,,"dahl, Varlahl, and Funcrio" Nom" In d,scu sing Rexlbilrty , we indl atcd that vanables and methods must be understandable (or the code to be Aexlble. In f. t, the very name 01 a va nab le or method is an Imporlant way of makIng it under
593
594
CHAPTER 23 QUALITY AND METRICS IN IMPLEMENTATION
Poor
Betler
Bcst
Ome mOO
dally Dosagc
ma xDady D(J,age ", InOailyDosaJ!c o mmonOa Il yDo
Figure 23.7 Naming vanables to Improve code quality Table 23 .2 Metncs for vanous attributes of an Implementation Attribute
Metric
1. Degree of documentation
a) Percentage of comment lines b) Percentage of commented lines
2. Extent at named constants
Percentage of numerals with names (see Note 1) a) Standard deviation of class size (see Note 2) b) Standard deviation of method size
3. Hide where possIble 4. Degree to whIch common code is collected
S. Degree of dependency on global variables
6. Degree of generic programming 7. Use understandable vanable and function names
percentage of repeated code paragraphs (see Note 3) a) percentage of public fields b) Percentage of protected fields C) percentage of unlabeled fields Percentage of generic classes Percentage of names clearly difficult to understand
Memes for ro bustness can be ba
such as " 135" in the following :
final int TANK_CAPACITY = 135; Note 2: H igh standard dev ia ti o n means high deviation fro m the average. Measured over a large number of classes, a deviatio n higher than the usual mean s an unusual variation in class size.
This IS no t necessarily bad , but It docs suggeSl Ihat Ihe largeSi and small«t classes should be reVi ewed, focusing on their size.
NOI" 3: One considers paraKraphs of code, sclecled al random , and delermines the percentage of paragraph that arc repeated al leaS! once (or ., leaS! Iwice, etc.). NOIe 4: The hIgher Ihe perce11lage of public fields compared wilh the normal percentage, the more global the variables.
23.1.4 The Reusability of an Implementation ReusabililY of code is the capacity for ilS use in other applications. Making a componenl more Acxible usuall makes II more reusable. ReusabililY is pOSSIble at the method, class, and package levels, although the method level is usually lOa granula r. To make a class reusable , the follOWing factors are considered .
QUAU1Y OF IMPLEMENTATION
Table 23.3 Metnes for reusability Attribute
Metric
, The matching of classes to a real·world
concept 2 Level of abstraction
Percent of classes that clearly match an understandable concept (see Note 1) Average number of Inheritance levels from a class In the Java library (see Note 2)
3 oegree of desCriptIOn
Percent of classes that are clearly documented (see Note 3)
1 lllC matc hin g 01 the dol" to a rc.,l . wo rld c o n '-.:pt . '" Important, ot h ('rwI<;<; d cveiopcr'!i arc unl,kely to 1I I1d<,'r.;(J nd It
2
n,c levd of abSlroc ti o n ,hould be h Ig·h Cnollg'I
to (OVer many app IK3tlon .. but low enough to allo,",!
sub,tanct' F• r example .f a dev <.:-loplll cnl organ ....... Jtlon c rc;)t cs m,uran C Industry appl, i)llon.;; the: lc.:\c\ of a cia" (IlJtllacEldoradol",,,,,,,,,,Poll . " probahly '00 10\\' and I'0 II t)· ,on h Ig-I1 ali Idr L. Jo;; feU.,a b I I Hy I!lon erne d An A"'omol,,I,Poll~ -J cia ...... , 0 n ,I lC· 01 Iler Ilan d \\ ou I(I b C .. ub ... tan ll VC and probJbl y reusable 3 The reliability of code pr mOlC''' rcu(,Jh.hl}' Olhcrwl'l: "0 nc IS Ilkelv to reu<;(" the Ill". It .. hould contain o mplctc (rror dJeckltl9 . for example In a ') orncwhal Circular proce .. :, c1a"~<..·, that 3re wldc;iy u.. ed
become tN"ted and under-load and thu, morc' wldelv reu:,cd .Metnc", for rt'us(lblilty can he ba,ed on the attnhule, of rcu,anlil tv Onc an mca!>urc them.J!> In Table 23 3 based on an automated process or bv manual random !>arnpk.. takcn from the code bJ~e ( unllng allltnC~ manually IS usually ,mpra IIca l)
late I This an be calculated on a r.lndom sample: bv laking a vote among tnspector~ for example.' Note 2, Thc hI gher lhl' number thl.' more hkel}' th<..' cla~, JI1 be reu!> d NOte 3 The bctlcr a las, I~ descnbed , the mon; Ilkelv It p. to be rCll'loablc Scttlon 23 1 4 dc, nl cd measures of documentat ion , 31ld lho,c can be used here tOO
23.1.S The Efficiency of an Implementation Recall that there an: ,\,' 0 kind, of cfflCl<:nc}' prot.:e." 'peed and ,tOr.sgc U'loC Elhcl<..'nC)' requlrl'ment, Ill:l) or may not be <'peclhc..'d 111 the RS For cxampk. suppo;;;e that on<..' IS specifYIng the reqUirement, lor a Jicndar appltcatton one should "pcClfy tlml· Illnlb su h a, the appllcJtlon wtli reSl.'t all calendar, \\,.th ne\,' apPo intments \'lIlhm V. econd \Xlh en crfIClenc ' n.:qll ...emenl<\ Me not ... pe Ihl'd \vc apply Lommon ..en"c hmns as bcst we can Neither Pi) (' nor runt 15 unlimited In praulce ror (:,,(Jmpk a \'(Ieb '1((: ,hoppln~ Glrt appltcallO.n may not <,pC'clfy maximum d lay . but It I' ommon o,enw that the uwr .. hould nOt walt more than a minute for a c redit card approval. excluding Internet dela s
An appropnau: metriC for ')peed dh I('n )' 10, the fraction 01 the ,peed required For C""(ampll' It .111 appilcatlon I:) requ ired to proc.c" J transaC110n In at I1lO,1 half J , etand but Jctually take ... two !>cc.ond.. ,q: an fairly ~ay thallt<, dr,C lcncy m<'a .. urc 14\ YJ 12 :=25 % It all applicatiOn "cn' t~p;;tcr th an rcqutr ct , \'1.'(.' l,o,' Olild .. lIli hkc to be able t measure Its ')pccd cfl1cll:nt y The sam fOnl1UlJ i.1pplle" ~'I example If du: appJt Jtl 11 prcxC"Sscs transac..tIOI1' In onc quarter second on avcrag<.:, then II'- CfflCI~IlCV mca .. ure wou ld be ~ I/. ~OO''tI It ha~ high 'lual,lY In Ihl,) rc.;pec.t with 100~... being th<: 'UCLe,' ba" Itne An appropnate mctrt<.. (or c;paLC dh lenLY I' Slm.iar l or CXill1lplc .f an appliCatIOn I" required (I') lI'C no mOrt. than 2 Hi o( dlc,k \PilCC hut ust's 5 {\ IB th en we (.;Hl fillrlv .,ay tllill It .. ':!orac..e: cfh ICIlCy I~ 2. 10 . IKe: aJ(aln the (om1ula appll(,'t even If 1I,a~~ excced, requirement .. rorc'(a l11 pll.', If til app llL3tlol1 \,'ere LO U'C onl\
=
1 MB we: would rate " ..
~loraHc u<\c clflLll'n
y a.. 2,' 1
20('''l
595
596
CHAPTER 23
QUALITY AND METRICS IN IMPLEMENTATION
23. 1.6 The Reliability of an Implementation ReliabilI ty j , a quality lhat goe< funh er than sufflclcncy and robu, tnc. <. To ' rel y" o n an ap pl.ca ll o n I ~ to be sure fil"'i t that It docs ,~hat it is supposed to, th iS Include sufn leney, as desc nbed above Rel ,abil ity can be o n
23 .1.7 The Scalability of an Implementation An implementation is .ca fablt if it is sumcient for all reasonably anticipated homogeneous growth (i.e ., growth In the same general direcllon as itS current capability). For example, a melhod that slOres dal. may work well fo r a data rate of one record per second. If the maximum anticipated data rate is 1,000 records per second, the method's scalabrl lty IS effectively its adequacy for Ihis growth requirement. We inspect and test the method With thiS in mind as soon as possible. Inspection and lestlng for scalability have limitations, however. Scalability can be di fAcul1 10 assess through inspections; early testing at the required scale can be expensive or even impracfical because of the work reqUired to create a scaled-up test structure.
Scalability melrics measure speeds and data storage
to
these simulated or accelerated cnvironm~nts
23.1.8 The Degree of security of an Implementation Applications often include or are connected to networked pans. T he parts may be components of the executing code (as with Web Services, for example ), they may consist of distributed data, Ihey may consist of a downloaded Web SIte, or they may simply be accessible through the Intemet or another ne(Work. Often , some of the data are confidential For those reasons, security is a significant co~sideration . Consider the simple example of logging in The application checks Ihe user's 10 and password before allOWing access. We will assume that these data must reside on a Ale situated remotely from the application . This scenario raISes many security questions, as listed in Figure 23 .8. Recall that security considerations can be divided into categories. We can base initia l implementation metrics on these, possibly weighted, as shown in Figure 23 .9, measured for every unit of code for example, • StOre IDs and passwords wilhout allowing unauthorized access • Ensure that data go only to authonzed requesters • Design so that security is easily maintained a application e"olves
• Isolate security-.ffecting c1asses7 Figure 23.8 Security
for Simple Login example
CODE INSPECTIONS AND RELATED QUAUTY PROCEDURES
, ConAdenliality, I\t a ure by degre f d' fA I ' e 0 • cu ty: ga'"'"9 J'lallow,J aem, , onr'Cpu d latlon: rrpud'"li"9 a9""""" ,Integrity, .. IIlrmug Jilin ,. Irll""', u.d"rrI,d ,Authentication· .. urnJY"'9 idnllily 'Authorization. .. 9"i.'"9 di,allowrd IIUns 10 II /ocalio.
o = tasy,
f1Sure 23.9
t
=
!'fol rosy but C'onCtipabltl 2
=
flol
10
i"Jo""allo.
Co"ctivablt
Metrics for security-hlgh·level metric using security attributes
on classes and relevant methods. Although this categorization helps, the nontrivial part lies in assessing the liability of the implementation to each kind of security b..ach. The d ifficulty in assessing the degree of security of an .mplementation is conceiving of breaches. The ' not conceivable" category of Figure 23 .9 does nOt necessarily imply that breaches are impossible merely that the evaluator cannot imagine one.
23.2 CODE INSPECTIONS AND RELATED QUALITY PROCEDURES The tOp.c of inspecting project artifacts was covered in general in Section 6.3. Now we will describe a specific process for inspecting code Code IOspections are an effective tool for producing high-qual ity code. As with other artifacts produced during development , code is reviewed by a team of peers whose goal is to identify as many defects as possible of as high a severity as possible. Inspections are typically conducted after a segment of code is written but before it is unit tested Before code is inspected it should be d"k-ch,ck,d by its author. This entai ls the developer reading the code looking for syntax and other obvious errors. There is no point in having others examine your code if you haven't carefully looked through .t yoursel f. The code should compile with no errors or even warnings; if it doesn't, there arc obvious errors that need to be fixed befo .. inspection . Oner desk-checking i complete, the inspection process commeners. The author distributes the code to a group of reviewers Sometimes an overview mee ting is held before the actual inspoction . The goal of this type of meetlOg is to prescnt an overview of the code, presenting its layout and the overall design This helps orient the reviewers and provide persp
Do variables have mcanlOgful names)
,
Are hard -coded numbers used instead of named constants'
, 1\ a vanable value read -o nl y) If so I~ .t declared const or final ' ,
Are all vanable~ u~ed )
597
598
CHAPTER 23
QUALITY AND METRICS IN IMPLEMENTATION
2 Fun 11 0 m o
Do funclIons have me,nlngful n,mesl
o
Are,1I parameler.; used ?
3. Correctness o
Are all parenlhc es properly matchedl
o
Arc brackets properly malc hed l
o
Docs each ca e in a swileh stalemenl lerminale wilh a breakl Is Ihere a default easel
4. Inilializatl on o
Are variables In ilialized before their flr.;1 use l
5. Loops o
Do all loops successfully terminalel
• If used, do brrak and o
COllfitlllC
statements ,,,ark correctly]
Does Ihe body of Ihe loop modify the loop variablesl
6 D)' namic Allocation o
I every dynamically allocated piece of memory properly de·allocaled l
7. Pointers o
Can a NULL pointer be de·referencedl
8. Comments o
Is Ihe code properly commented ?
o
Do Ihe com menrs accuralely describe the corresponding codel
9. Defensive Programming o
Arc checks made to prevenl error.; such as divide by zero or illegal dala l
Inspector.; should read the code line by line, 10 fully under.;land whal the y are reading . For each line or block of code. skim Ihrough the inspection checklist, looking for ilems Ihat apply . For each applicable ilem, delermine whether Ihe code correctly addres«s Ihe Ilem . If not, write Ihis down , as il is a potential defect. This list is broughl to the inspection meeting for further review. In order 10 make dRcienl use of people's time during the inspectio n meeting, any syntax or trivial errors discovered can be
fonyarded
to the author prior to
Ihe meeling . This way the meeting can focus on more substanlial error.; . During Ihe inspection meeling the facilitator leads Ihe group through Ihe code. As a block of code is ",ached, inspeclor.; raise issues found during Iheir prior code reading. If il is agreed Ihat an issue is indeed a defect, it is duly recorded. An In'portan! point is Ih.t Ihe fault should only be recorded. It should nol be olved , and new code should not be wrillen during the meeting. This Is lefr 10 Ihe author 10 execute at a time subsequent 10 the meeling. During this and all 01 her inspeclions, metrics should be collecled. Example metncs a", as follows , o
Number of defects discovered, by severity and type
o
Number of defects discovered by each calegory of stakeholder inspecllng the artifact
exeRCISES
•
umlxr of def«:ts per page revlc"'ed
• R~ew rate (numlxr of p~gcslhour) The checkhsts and data referenced abDve can b (~arTJngcd .10 a form or 3 C UI for software engineers' us(' and for data collection .
23.2.1 Code walkthroughs and Code Reviews 'any teams emp~oy od, wafktbroughs or od, ,roitws. The meaning of these temlS differs from project to project, but they .Iways mvolve a meeting-perhaps only a synchronous onhne meeting. They cover some of the ground of inspections butar. Ie s fom,.\, For cx~mp l e , participants may no t cover every line of code, and they may not be required to prepare for the meetm!!. A detailed II t of defects may not be compi led. A major difference is that Ivhereas inspection are dedicated to Andi ng defects alone, walkthroughs and reviews are not. In particular, suggesti ng and discussi ng aitematives is permitted sometim es encouraged-at walk. throughs but discouraged for inspections
23.2.2 Pair Programming Pair programming is a process by which programming is perfonned by tWO ;oftwar. engineers Slttmg side by side and usi ng a single computer. Ty pically, one of them enters code while the other inspects contlnuouslyrssentially fo r quality . As a Sim ple example, o ne eng lncer types a method for diViding two numbers whde the othercantinuall y think of things thaI could go wrong (e.g., di VISion by zero) o r Ihal Ihe firsl has mISsed (e.g., documentation giving the context or limits) or left unclear (e.g ., why a stan dard library IS nOI being used ). The pair switches roles periodically. It IS clear that the quality Gf software produced Via pair programming will be higher than thaI produced by a slOglc person. The trade ·offs becomc more complex to asse« when one compares pair programm ing with Single . person programming augmenled by inspec tions.
23.3 SUMMARY In order to assess the quality of an implemenlati on. it is use/ullO categonze ils qualilles In [he >arne way as for a design . The qualities we con idered in IhlS chapter arc suffbency , robustness, AeXlbil,ty, reusability, efficie ncy, reliability , sca labili ty, and security Various metrics are avadable to measure the extenl of each of thrse in the application. Code inspections are a speCific type of art ifact inspection thaI is conducted after a piece of code is wrinen but before it IS unit tested. The goa l is 10 detect and fix defecls in the code as close 10 thelt injection point as possible. Checklists are commonly used to guide revi ewers to the types of errors the y hou ld look for while readln!! the code.
23.4 EXERCISES I . t h e qua IIliC S 1h a t II nplcmcntation< should po'>c". I" your own words, describe the meaning 0 1. L.,.Ist . each quality can >o me t'mes be compe ting Impl ement all o n qual ities .le ICHC')';an d , ,"'abil,ty 2. Ex p Iatn h ow C)J1( I • an example to ,upport your a",wer
599
600
CHAPIER 23
QUAUTY AND METRICS IN IMPLEMENTATION
3 De~cribc SIX factors that increase the flexibility of an Implementation . and prov Ide an example of how each contribut<s to oncreased f1cxibiliry . 4. The code onspection checklist In Section 23 .2 is not an exhaustive li't pecdy three add itIo nal items you think would be useful to add to the checkli st. and cxp laon why you ha ve added eac h 5. Your instructor will pair up student project !eams. Conduc t a code Inspec tI o n of the o the r team's implementation . Usc the code inspection checklist in Sectio n 23 .2 to gUIde you r ons pec tlon . 6. Chapter 22 contains a code listing for a part of the Encounter video gam(' Whe re feasible. appl y the informal and formal metrics mentioned in thIS chapter to measure Its ro bustness Expla In whether the usc of a relevant robustness metric is not feasible in thl case and deSCribe the reliability of the metrics' use on this case. 7. Chapter 22 contains a code listing for a part of the Encounter video game. Where fca ible, appl y the informal and formal metries mentioned in this chapter to assess it< f1exi biliry . Explaon whether the use of a relevant Aexibiliry metric is not feasible in this case and describe the reliabdity of the metrics' use in this case .
8. Chapter 22 contains a code listing for a part of the Encounter video game . Where feas ible . apply the informal and formal metrics mentioned in this chapter to assess its reusability. Explain whether the use of a rclovant reusabiliry metric is not feasible in this case and desc ribe the r."ab ility of the metrics' us(' in this case . 9. Chapter 22 contains a code listing for a part of the Encounter video game. Where feaSible , appl y the informal and formal metrics mentioned in this chapter to assess its reliability . Expla in whether the use of a relevant reliabiliry metric is not feasible in this case and describe the reliabil iry of the metrics' use in this case ,
10. Chapter 22 contains a code listing for a part of the Encounter video game Where feasible . appl y the informal and formal metrics mentioned in this chapter to assess its sca labdlry . Explain if the use of a rclevant scalability metric is not feasible in this case and describe the rel ia bd ity o f the metrics' usc in this casc o
Refactoring
--
Planning
The Software Development LIfe Cycte
•
What Is refactorlng?
•
How does ref acto ring work at large scales?
•
!-tow do you relaelar at the method level?
•
Can you reorg anize classes uSing refactoring? Reorganize data?
Requirements analysis
Design
•
Can you relactor at the module/package level?
•
In what way is refaclonng essential for agile proJects?
•
How is retactoring used in non·a91le proJects?
•
How does relaclOring relate to design patterns '
Figure 24.1 The context and learning goals (or this chapter RdaClonng ., a procc co of J ltcrln~ source
ode .. o
ii'
to It:avc H ~ CX "l1n g fun cti o nalit y lIn c h"n~('d
Moltv~s for refa lOri ng vary , but a pnnc lpa l o ne "to Improve: mainlalilal lill y . espcl.l all
e nhance me nt h.,
I n cc; , cnlIJI p ~lIt 0 1 010" J ~ dc.: approa ht.· .. R.facto n "j( wa, In trod ULcd 10 a wl dc all d, e ncc hy I uw le l "' IllS la'
conc;,dercd ac; 500n as c;oftwarc:: eng inee r, hCg'l n writ ing co de, and
All dc"gn
volve,.
Ie;
and 11,,\ " e'pcc lall y lru" lor , o(l,. arc prO)CC h In lhe pa" " ha, o flen n
t
be n
modify ('od very mu h J~ n~cd, 'vulvt" H owever ohJect-orl e ntJtl on , IInprovl-d dc vl'l opm l"nt enVlfonm nt~. and, f.:\pt: 1;)lIy r diJtlUn rl ~ have m.1 u · d11 \ Incl cil "tlo glv ffCCll vC
dftctJv
li)
P(rhap\
the:
\Imple\l dlU"t tralive e Xil llll11 C QI rC'fa((() lI og I" r(nalll/utl In w hl
'ndu dtn ~ a di1~~ n r pa(,k.a~C' name:
h th e
n J Ol t 0 1 J va n ahl e-
an be ( hange d ~ l n" t devel opm ent cnvlro nmcnh allfo m.1l C n..· n ~ l1\ln ,.; 01 ..
602
CHAPTER 24
REFACTORING
d" u"cd below Whe ll Ihe Ilame i, changed , all rclerc nce> to It except for comment< arc automallcally hanged Jt the ...amc time . Bef ore renamin g be ame Jvailablt", nanling a variable \vas, in practice, an important
declsloll Ihat became hard to aller o nce made and used for a lime If he o r , he wanted a new variab le name, the pros"rammer was often o bliged to alter so man y occurrcn c: o f th e name 111 multipk- classcc; that it was seldom worthwhile 10 carry out for a large program . Naming variables is jus t as important J~ In th e past , bur the ability to rena me vlftually at will has freed some progra mmer time . Ild allowed new flexibililY · What fo llows is " second examp le that demo nstrates the tl.vo r of refacto rin g. It IS called "Promote At'tTibu l C to C lass ," and
I
use d to co nvert a implc attribute in lO a class . To accommodate the increased scope
of an applica ti o n, we ofte n need to introduce ol new class to replace an att ribu te. Forcxa rn ple , suppose that we already have a class Au!omobilr w ith inregcr attribute milragr .
class Automobile {
int mileage; •
•
•
•
}
W e may decide later that "mileage" for used automobiles, however, is substantiall y more involved than a si ngle tnt va riable. For example, the auto's motor may be a replace ment , resu lting in a m otor mileage different (rom a chassis mdeage. In addition , if our application is required to account ('Or fraud , the reported "mileage" would have to be modified by other attributes such as whether the car had ever been stolen . For these reasons, we would consider the "Promo te Attrib ute to a C lass" refactoring. Th is would involve introduCing a Millage class like
L1stl ng 24.1: Mileage class-promotion of mileage field
class Mileage {
int nominalMileageValue = 0; int chassisMileageValue = 0; int engineMileageValue = 0; •
•
•
1/ shown on odometer / / best estimate / / best est imate, account ing for replacement
•
public int computeEffectiveMileage () { . . . } }
class Automobile {
Mileage mi leage ; • • • •
}
/ / to obtain estimate
REFACTORlNG
t
'" r~
Rc"",,"o f Il!ld ,
• · o · q. · n
-.-
1
• __ lie
-.--
ShiftlAIVR •
•
~~ •••
5tr1DQ
.
[ m~lo,ee
I
~;
I
( e.G
fEJ
~n.llM h e ld ~n21 ~ I M~~~~J~
I
_________________________
, • . j...."
(chp"' SDK
!!IUd ·atefewas
O' to''t? tutu.! OCCIITCII"U1 n CGif'!'lel"'(:S 4I'Id st1n;s (forcfS PNIC")
<:. .
~ · o ·
pula..l..l. c:: c:.l..... tl::lp l o yee. I StrlDQ
~_;
I
t PreTES )o
I(
II
C..... I
Figure 24.2 using a refactoring wizard-an Eclipse example
Dependi ng on thc progre s of ,hIS appkatlon , eve n the cia S 1\'11/"'9' could be conSIdered worthy of furth .. refactonng--fo r example . b). extracting ' o me of ItS properties IntO scparate types 0 mdeage classes. Anotherdi reClion for refactoring I to extract Interface< for it so that lienr code (code that u cs It ) can as ume that It possesses a given set of method signaturcs such a compu/,Eff, /Il',AI'/
The rest of thIS c hapter Introduce many of the rdactorings descnbed by Fowler, a well as an additional one, ln/roduCing Mr/iJod, ID Es regularly Include ncw refa tonngs, and" IS a good Idea to explore the e be Id~ the refactorings in [ I ). This chap tN I Intended to !l'VC the reader a ubstantlve taSte for refact o nn g and to place II 10 a ~oftware englOtcnn!; context Fowler or!;a ni zc, hI< rda cto ring as 10 Figure 24 .3 TIll' chapter does not attempt to explain all of Fowld~ refactonngs For example , S,mplifY"'9 LOIIJ,llollal Exp'''!loll and 11101:/119 IIf"J.,d alh ""pI" are n t
603
604
CHAPTER 24
REF ACTO RING
I 1l1~ Ref, lOring> 2. ompo IIlg "'et hods love Features between Obje t, 4 Orga nize Data 5 Dealing with Generalization 6. implify,ng Condi tiona l Exprc sions 7. "'aking methods Calls Simpler Figure 24.3 Fowler's main refaetorlng taxonomy Source Fowler ct 81 , RefaC10nng: ImprCNIng the Design 01 EJustJng COde. Copynghl
Rl'Qfoduced bY
petmL$SlOI'l
1m by Pearsoo Education, InC
f
of Pearson Education. Inc
24.1 BIG REFACTORINGS The refactonng de
Em~yee
rJ0
~
<-r SoftwareEmp
I' FullhmeSoftwareEmp
ClencalEmp
MaintceEmp
t..;,.
-r'
FulllimeMainlceEmp
FulitimeClericalEmp
IParttimeMalntceEmp I IReliredSoftwareEmp I IRetiredM'lnlceEmp I PartlimeSoftwareEmp
IParttimeClericalEmp I
IReliredClericalEmp I
FIgure 24.4 Big refaetorlngs. 1 of 4 Tease Apart Inheritance SOtJIU Fow\ef tt ai , RefactOf'ln8 Improymg the 0es1iJ"l of ExiSting c.ooe. CoPYTCflI Reot'CdUCed by IJe... II"'O"1 or P~r1On EdUCltion. VlC-
I
1999 by
Pearson EOucatloo.. InC
BIO REFACTORINGS
.J-0~ ---_--,
IVldeoGame I
stanGamBO disptayCharactar O moveCharacterQ
I
. '.'
I
GameCharacter
t"
I
u
Figure 24.5 Big refactorlngs, 2 of 4-Gonverl Procedural Design 10 Objects 50cIft f(lV.;ier et Il~ Ref.ctOfIng: InlprcMng the DesIgn of Existing COde, Copynght
f
1999 by PUrson EdlJCauon. Inc
Rt;400""P\d 1:11' !:rIJssioo of Pearson EducatIOn. Inc
shown in Figure 14.5, a designer may usc a clas such as COH ,ro/ to contro l a vrdeo game (Le., to start and stop vanouS element of the game). The problem with this IS that cont ro l classes, when needed, should be used to manage object o nl y by initia ting the" methods, not as a replacement for the work that should be performed "'rthln an object. When an o bject is requi red to con trol, it should be kept to a min imum : usually a simple, s,"glr call to a method in an appropriate object that sets off the entire process. Figure 24 .5 shows how dements of what used to be control, such as mourO, have been relocated to the objects to which they properly appl y The Instances of CameCharactcr now move themselves . Minimal control ma y sti ll be needed outside of VideoCame and CameCharacter, but it would in itiate rh o work rather than doing it. The next "bIg· re(aCloring we'll consi der, Scpnrn tt Domtrlt1 Jrom PrcstH ltJ liotl , is used when a design mixes control with output fonmalS-ln part icular, when C UI code occurs in the same class as the computational algonthms or the data repository . For example, as shown in Fib""e 24 .6, a desig ner ma y use a class such as Accovn' to perform computations but also to produce di pl ay<. Such a design lacks reusability and conceptual
Account name
balance •••
displayStandardO displayHTMLO
: display
0
Account
=>
nlme
balance •••
display ()
Flcure 2.4,6 Big refactorlngs, 3 of 4 ~C4" FQMef 1ft aI
eparate Domain from Presentation
RtfflCtOflna imprOVIng the 0esI(I,n Of (xl,lIna Code, CopyTIWlI , _CG,,"1d Of PI ''''U'On 01 "UfIOtl E.cSuca1JOn, IOC
1m by Peirson EOucatlot\, Inc
605
606
CHAPTER 24
REFACTORING
Project
=>
Figure 24.7 Big refactorings"-Extract Hierarchy Soutce Fowter el ai , Refactorlng' (mOfcMng the Design 01 EX'tSMg COde. COpyright , 19991Jy Pearson Educ.auon. Inc. ReoroduGeClIJy pelTT\fSSlOl"l of Pearson Education. Inc.
simphcity (ConsIder how comphcated it would be to change just the CUI parts or to allow several displays for the same account data .) Figure 24 .6 shows how the o ri gina l des ign can be decomposed into the core part of
A CCOIUlt ,
se parated from classes describing varioLis ways to display the account.
Our Rnal example of a "big" refactoring, Exlmel Hicrarc/,y , applie, when il has become clear that a new or extended hierarch y of classes IS nceded-in particular, when the classes in the existing hiera rchy are not refined enough for the task at hand. For example, as shown in Figure 24.7, a designer may use a class such as PrO)tcl to implement a project management application . We'll presume that the application has become too soph isti cated fo r a generic project. So, for example, quite different functionality IS needed by software engineering proj ects vs . entertainme nt projects. As shown in Figure 24 .7 , cXl.Tacting a hierarchy of classes
fro m the original beco mes a needed rdac torin g
24,2 COMPOSING METHODS The "composing methods" category of rcfactorin gs concerns the process of creating , removing , and combinm8 methods to SUIt an evolving Clpplication . The various rypcs of mcrhod composition examined
by Fowler are shown in Figure 24 .B. They are e.plalOed bel ow. • Extract method • Inllne method
• • • •
Inline temp (re move a temporary vanable ) Replace temp with query (i,e , a function ) Introduce cxplainlOS variable (to replace complicated expressIon) Split temporary vanable (I.e., used more than once)
• Remove assignment to paramel'ers
• Replace method ","h method object Figurl! 24.8 " Compose methods" refactorings Sourw Fowter et at . Rotoctot .!IO Improol!l"l8 the OF r,gn 01 RepOCluc:td I7f ~6ttmssron Of Pearson Educltion.. InC.
ExlStlna ~. COgyr'igtlt
I
1999 by Pearson Eclucation. InC..
COMPOSING METHOOS
Exrracr M,rboJ refers to the process of identifying a block of code and creating a method that serves its purpose . The block of code can then be replaced with a call to that method. One perfo rms such a ,eplacement when the beneRt of redUCing clutter outweighs the penalty of having to look elsewhere for code details. This depends on the sense of purpose of the code extracted, its relative complexity, Its "ze, and how fr
[x(y
+ z) - 'illY - (x - z) + x"yl
(24 . 1)
R,placr Trmp wilh aurry refers to using a method ca ll IOstead of a temporary variable. For example , we might want to save expression (24 . 1) in a temporary variable v and then usc 0 several times, or we mi ght want to dISpense with a temporary variable and call the method that evaluates thIS expresSion each time we need it. This would make sense if the variable we usc takes up a lot of space (true for a large data structure but not for a Aoating point number like the one above). Another factor to consider here is whether or nOt the vanables in the expression change . The penalty for introducing R,plaCt Tnnp will, a"rry is the time It takes to make the • compuranon.
1.',oduCt Explai"i"9 Variablr is the opposite of R,placr Tnnp will, a",ry. It introduces temporary van abies to facilitate working with complicated expressions. Although the hiding quality of R,plac, Tnnp wilh Gurry is usually benencial , it is counterproductive when there is little to hide. Splil Trmporary Variabl, applies when you use a temporary va riable for purposes different fro m its anginal One. It consists of introducing one or marc additional vanables IOstead. Cenerally speaking, it is good practice to us< a temporary variable only for a si ngle purpose. R()IIov, Alsi9"",rnllo Paramd", nxes the problem of changi ng the value of a parameter this is nOt expressly designed to be an in/oul vanable. Cenerally speaki ng, it is poor practice to wri te to a parameter unless the method is speCifically designed for th is, expecting and using the changed values In fact , it 15 usually good pract ice to make methods parametersji"al (in Java notation) to prevent their use other than fo r the value they provide. R,piacr M,'hod W,lh M"bod Objtel is the process of replaci ng a met hod such as dofiliancinlC"lculalionO with a function call on a dedicated object of a specially desig ned class (Fllla"ela/Calcul.llon ) uch asfinancialCalcu. la"onl •.rxcCIIltO. The effect of calling ",te.'cO With object filla"ela l alc"lalionl' of a separate class gains adva~tages when the funCtIonality required has too many effect to be handled conven ie ntly by a simple functio n call ~I one. Another exa~lpfe is when we need to cou nt the number of times thar functionality uch as n"ma lcProfilO 10 class SrockH,lprr IS executcd. Instead 01 si mply making " 'II"al,Profil() a method of SlockHrlptr. we create a class ProfiIE."mnlioli that agsregate SloclcHrlp, •. and we call the method ",mll,O of Projilf>III".'ion A nn.al.example IS when we want an ulldo capability . If we store the object repreSenting the function , there IS a pOsSibility for undOing. Otherwise. we couldn't retrieve the funcllon call that brought us to a urrent state and would be unable to go back.
608
CHAPTER 24
REFACTORING
24.3 MOVING FEATURES BETWEEN OBJECTS Tim C"I
clas'Ol's and recogn Ize beller h o mc~ for existing variables.
Exlr"
allow the softwa re engineer to create a class from a collection of artributes and methods that alread y exist w,th in a class \Vle apply Exlrael whc n such a co llecti on makes log,cal sen e together and tands out from It con tainin g class As an example, an applica"on may be ,mple mented with a Cu,'omer cia" conrain'"g data abo ut books perh.aps because favonte books were Ill itia ll y understood to be a characteristic of a cust o mer. However, if the app" catlon cha nges to one for wh.ch the book no ti o n becomes Significan t, then we would appl y Exl", I C/II" to create a Book class. 1,r/iN' C/IIS' . the opposite of Exira I CIt"" is the ,"corporatio n of a cia s A, let's say, into another. B. delet,n g A in the proce s. In other words, lhere is really no need for A. H,d, Dt/'9"" is us(·d when a class references classes that are supposed to usc it, the dfect being to remove these references. Clients of a class need to refere nce the used class. but the reverse shou ld b. avo.ded. This is expanded upon below . Remo", MiMI, ""Inn is the o pposite of Hid, D,I'9alr. Hid, DrI,gal, is accomplished by introdUCIng a separate class, as hown in Fib'Urc 24 . 11 ; rcver.,lng {he process amounts to removing this "Middle Man." F.gure 24 . 11 ,ho'. Hid, Drlr9alrs in some detail. Method{s) in /i,nl call "ltl/,od2 {) in (server) class C/"SSl. H owever, m"bod2 {) requ"es th e usc of Cla,SI in a way that force C/irnl to rderence C/a,SI a well. An example is the fo llo ,,' .ng, I
/" "
e"IS'
• Move Me th od • Trades off method ho ld.ng v<. usage • Move Field • Trades off hold ing vs. usage • Extract Class • Encapsulate a set of attributes and methods of a class • Inli ne Class • OpPosile of Exlrael Class Figure 24.9 "Moving Features between Objects" refactorings, 1 of 2 SOUIte Fowler ct al... RetiKtCl"II'lg: ImortMng the DesIgn of EXistfng COde, eopJ'l'Iif\l , 1999 by Pe~ Educabon, Inc Reproduced by permlssIon of Pearson Education, Inc.
• H ide D elegate Hide class dependencie from client classes • Re move Middle Man • Opposite of Hid, D",gal, Figure 24.10 "Moving Features between Objects" refactorings. 2 of 2 SClC.TU rOl-.'" f't II .. RefICtOf'll'W" .iij)fO\ilna tho DI : ii' of AlprodlJt:ed Dv pel,,; ' ['on of Pe.-son Eauc:ation. i'IC..
Edsma COde, Cov/f1ItIt,
'999 by PHrson EOlJCauon. IlC.
ORGANIZING DATA
;----1
Class'
I I
Clienl
I
I
----.j
I I I
Class2
I
.. _---
melhod20
delegale
Class2
--------
melh0d20 Key:
0;
changed
delegale.melhod20
FIgure 24.11 "Hide delegates" refactoring ~: Fcw.1e1 et at.. RefGCtoting: ImprovlnE the DesIgn of Exlstmg COde, CoPY'l&ht, 1999 by Pearson EducatIOn. Inc Re1JOlh'ed by peillussion of Pearson Edutanon, Inc
Climl. Tax preparation
Class2 Personal proRle Class!. Employer
m,'bod2(). Prepare summary tax page In summary , Clire l has been saddl ed with unnecessary respo nsi bility. Hid, Dd'9alrs allows Iirnlto depe nd only on Class2 by aggrega ting Class I to Class 2 (making a Cla sS! objeci an attribute of Cla"2 ). A a result, Grel now depends only on CIa SS 2.
24.4 ORGANIZING DATA In the refacto rings of Ih is seclion , Fowler li m Iho e havi ng to do with Ihe location of data in a design o r implementation . S'if Elleapsulal, Fitld c hanges direct access of an attribute (c g., pub 1 ic S t ring name; ) to that via accessors (e.g., pr ivate Str ing name; . . . Str ing getName () . . . ) One would use this refactoring if one forgets to make or postpone, makin g fie lds private, available o nl y via ac~essor methods. Using accessors in 00 is generall y good practice becau e it allows co ntrol such as checki ng an as igned value to ensu re Ihat il is withi n bounds R,pla" Dala V"lu, wilb Obl,el; A an exampl e, c hange the otlribute pub 1 ic S t ring name to pub lie Name nam e . O ne wo uld app ly R,pla" Dala Valu, wilb Ob)tC1here when the idea of a name becomes too complex for Slrill9 . An examp le" whe n it becomes necessary 10 track all parts of a name as well a alia e , matTIed nam e~ , and former unmarned o nes. O,a"9' Valut 10 R,f"rncr b u cd when the va lue of an object's allribute IS beller obtained via a function (typically, because Oblall1 l1l!! the va lue IS complex) ra ther than ,-.,h an expkll instance or with IIull, as III Ihe fOllowing example In th e "" version below, the attribute II slon", has the va lue lIull. In the e ond VCrsl n, II IS a ( " Sl"",,, object created by a "atic mel hod of uSlorna. Thi S ha the adva ntage of entralizlI1l! the rcatlon of "slomtrobjecls. ",hl c h is often desirable T his advanlage be o me clear when severa l different las e need
609
610
CHAPTER 24
REFACTORING
In'I J nll Jt1n~ a defau lt cu\tomer The undC:"lfable
ustomtr objcCl<\ In J standard man ner, such liS w h c Tl
altcmat ive is to repeat the code that rcates such o bJccts for each of the,e dasse. class Order { . • . Cust o mer customer ; •
•
•
•
} •
replaced by
•
•
•
class Order { • • • Customer customer = Custo mer . get Customer ( Str ing • . . . ) ; •
•
•
}
( hul/ge RrfertHce 10 Value IS the opposi te of the previous refacto ring. Thi would be nceded when the machinery of a refeeellce is fo und 10 be unnecessary. perhaps because the program turns out to be less comple x than Jmicipated in thi S respect.
Rrplace Array wllh Obi,CI, Arrays have the beneRt of being standard in form and of ha vi ng random access. However. they arc not as Aexible as specia lly built classes even though both may ha ve essentially the same contents. When the use of an array loses the balance of its advantages. this rdacto ring makes the convers Ion. An example is the fo llowi ng. C hange Company [ ] companiesl . . . . to class Companies{ . . . } . Th is refactor· ing may be benenci al because there are bener way to access companies (e.g.. why should IBM be companiesl [3] in particular)). whereas accessing a compa ny by name (e.g .. Compani es companies2 . . . companies2 . getCompany ( •• IBM' • ) ) may be much morc appropriate . The preceding rdactorings arc summarized in Figure 24 . 12. ( hal/ge Bid""tlonal Association 10 Ullid",clional, We usua lly want the relationship between classes ( , and ( 2 10 be one-way rather Ihan two -way. For example . ( , refers 10 (2 bUI ( 2 docs not also rder to (, . Olherwise. we cannot usc onc in another applICation without the other. Ci rcular references are awkward in an)' ca e.
Elllploy« and Em ployer is an example; if the applicatio n is a corpora Ie a ile, we wou ld pro bably want Elll ployer 10 reference Employer. and there may be no need for the reverse. Tho resull is as fo llows. Em ployer _ Em ployer.
• Self Encapsulate Field • Change: direct acces or an attnbute to accessor lise • Replace Data Value with Object • Change Value to Reference class
,In"
Order ( Customrr cuslOtnt'rJ . O,d" ( pri"at< ( Ul loIII" 9"(""Olll,r(51""g ..
)
• Change Reference to Value • Replace Array with Object Figure 24.12 "Organizing data" refactorlngs. 1 of 4 souru: Foil! - et ai, Relac:toring; II'I'O't1oMg the oestgn of eo.stin& Codt. COp)'flahl Repf'OO'.JCtd
bV LX""h l'on of PeItWl Educ:atJon. WlC.
I..
1999 by P~arson EdlatJOn. InC.
111
°
CI"'"9' tI,udim:lrollnl As inlioll 10 R,d,rtCliollal is the opposite operation from th~ preceding rdactoring. If then: i no clear way to e1.iminate the dual asso iation direction e ntirel y, we typically ny to create a third class to ha.ndle the relat,onsh,p . An example is as follows .
E,llployer ~ EltlploYItI,"IRtlaliol,hip ~ Employtr. However, if this is Aot feasib le, we apply Cbnllg, tI,tidirteilollnl Associalioll 10 Bidirtcli""al by establishing a reference in E",ploy" to Employtr.
R,pla" "Magic Nu",btr" wilb Sy,.bol,e olls lall l is the process of using symbo ls for consta nt S wit h in code . An example is NUM_ WORKING_MO TH S instead of purely " 10." This helps readability, si nce the reader understands NUM_WORKING_MONT HS but not necessa rily just 10. This process also help with maintenance, si nce it allow easy changes-for exa mple , c han g Ing NUM_ WORKING_MONTHS to II instead of hunting for all occurrences of 10. checking lheir context, and changing to 11 where applicable. E.capsulal, Fitld i the proce of c hanging accessible variables to pMn l, ones, supplYlllg an accessor method or methods. For co nvenience, we might intemlo nall y make all variable public when first c reating a class and then apply this relactoring. The pn:ceding set of refaclorings is summarized in Figure 24 . 13. R,plnct RtCord IVilh Daln CIa s is u cd when we need to e"capsu late the data of a class in a database record . In other words, it suits the application better to deal with records as self·co ntained unit . The reco rds become objects with private data ne lds and accessor methods. This is similar to the Replae, Da ln Vnl", wilh Objeel refactoring mentioned above. Replace Type Cod, will, Class is used whe n a group of ~rtributes of a class essentia ll y specify what type an instance of the class is. For cxample, in the class 5/'01, the attributes eo""'ryOj ,"n""jnclure, qual"y, and dcsi9""Name would effectively indica te the type as h igh fashion , IIltem, edia te , or low fashion . Thi s refactoring applies when it becomes advisable to call out a specific type class (SI,oIFnsl,ion Type with at leasl three valllcs for the example). T ypically, the type class is aggregated '"ith the o r;g lOa l class. R,pla t Typ, Code ,vilh Sub Inss, This refactorin g implements the sa me problem as for Rlplnel Type Cod, IV,lh Class hy using inhe rited classe , each a d iffe rent ty pe, as shown in Figure 24 . 15 . The preceding refactori ngs arc ummarized in Fig ure 24 . 14 . R,plact T yp, Code ",il/' Slnlc/Strnle9Y' Thi s refactori ng deals with the same type of issue as that described In R,plact TYPI Code wilh Class/S"bclass but combines classes into a hierarchy . as shown iQ F,gure 24 . 15. The result " the aggregation of a type class, such as AeoulllType and inherited sllbclasses su has Re9"I",Aeeou",Type and IVboltsaleAecounlType. At runtime, the A,outl/Type allribute of Aceo",,1 is instantiated with an object of type
RegularAeeo""ITyp, or WI,oltlal,A ecolmITyp,
• Change Unidirectional Association to Bidirectional • (On ly If necessary), install backpoinlcr • Change Bidirectio nal Association to Unidirec tio nal • Find a way to drop; conS Ider third party. • Replace "Magic Number" with Can tant • Encapsulate Field • public at!rihul~ to ,,,ionlc/newso r
Fl&ur. 24.13 "Organizing data" refactorings,
2 of 4
SOtxu F(M1H et. 81 , Ref3ClO(11l1l: ImproYlng me De51&11 01 tJ(ISllnR cooe, COC)Yrlghl' 1m by Pearson EdUCation. Inc ltapoollCCId 111 Ptfmtsllon of Pe8rsM EducaUOl"l. Inc.
612
CHAPTER 24
REFACTORING
• Replece Record with Dala Class o SlmploSI obJoct with privato data flold. accessor
• Replace Type Code wllh Claa. Accounl
... Iype
REGU' 6R: Aoco..,ntType BIG_DISCOUNT: Aooo!.tnlType
Figure 24.14 " Organizing data" relactorings. 3 014 Source Fow\ef' et aJ• Relactormg: ImprOVing the Design 01 ExiSting Code. COf)'frlght , 1999 by Pearson Education, Inc. Reproduced by peitiilssion of Pearson Education. me..
• Replace Type Code with Subclass Accounl •••
=>
•••
•
type
• Replace Type Code with State/Strategy
Account
... type
Figure 24.15 "Organizing data" relactorings. 4 01 4 SOUrce' FO'N1er el at . RefactOtlng: ImprOYlng lhe DesIgn of Existing COde, copyr.ght " 1999 by Pearson Education, Inc. Rept'oduccd by permissk)r of Pearson Educatkln. Inc.
24.S GENERALIZATION The refactorings in this section exploit inheritance to conven (l deSign and code base from o ne (orm to another that bett~r suits the si tuation . Pull Up Firld is used whe n a field (e .g .• ordrr in Whol,salcOrd" and In R,'aiIOrd,,) occurs In severa l slibel. ses of a class (wh ich we'll call the baS( class). It declares the ,ecurnng field in the base class. helping us to extend the functionality of the design since the base class becomes more useful as a r«ult . Figure 24 16 shows an example. Pull Up MtI/'od is th e same as Pull Up F,,/d except that it refe rs to recurrins methods '""cad.
1
• Pull up field WhoIesaleOrdor
RelollQrder
amount
amount
• Pull up method • Pull up constructor body
o Rep lace by super(. ..) • Push Down Method
o When base class mel hod nol used by mosl subclasses • Push Down Field Figure 2".16 "Dealing with generalization" refactorings, 1 of 5 Source: FoWtef et al . Aefactorlng: Impro¥1ng the Design of EXisting COde. Copynght ReprodUCe
i
1999 by P~arson Education, me
Pull Up Conslructor Body is similar 10 Pull Up M,thod, but here we are refemng 10 a bl ock o f code Ihal recurs in Ihe conSlruclors of subclasses. Th is bl ock i placed in the base cia s co nstructo r. The derived cia s construclors must call supcrO in order to effect it. An example in the co ntext of Figure 24 . 16 is when It lxcomes clear thai there is ubstantial commo n code in co nstruclln!: Whoirsal,Qrd" and R,tmlQrdcr objects. Pull DowlI Fi,/d or IvIrthod is the opposile of P"II Up .... We abolish the field or mel hod in Ihe base cl ass when il is needed on ly once or twice in derived clas es. An example IS when we write a ),,,,dry lass wilh the melhod "timat,Tim,To Cu'O and realize laler that thi app lies to very few ubclassc, - uch as dIamo nds and sapphires and thaI even they do not have a large amount in commo n when it comes to thi s operati on. These refactorings are summarized in Fi gure 24 . 16, where Ihe Iypical mOlive for each is included . Extracl Subrlass is a mo re extensive versio n o f P"s/, Dou>ll . Here , we recog nize pans o f a class Ihat arc specialized and are liable to be used toge ther, and 0 de erve clas ,hood. The process IS exempli Red in Figure 24 17, where we recognize th e who lesale natllre o f man)' orders made to an enterpri se. Ex'ract Sup"c/ass i an oppos Ite version o f P"II Up. Here, we recognI ze parts of class tha. can and should be abstracted into a superclass The process is exempl ined in Figure 24 . 17, where we recog nize a generic "employee' aspect o f manager and en gIneer objecls. [xtraet SubIS"/>"c/ll lS e nable ge ne rali zation b rcRning the cia s model These two rd acto rln gs make It l'asicr to introdu e new kInd o f ca pab ililies g0 ll18 forward beeause general co nce pts arc better defin ed. Extract /"t"jac( arISes fro m askin g how a colle tlo n o f la srs would be u<ed by lients. In the example illuslrated in Fi gure 24 . 18, we ask how a o llecll on of classes, includ ing i\~"lag" and E"!illl"' , would be used TI,e Idea IS to collect thIS inform atI o n togeth er In a convenIent fo rm In till ase , we may come 10 Iht' conclusion 111 the cont ex t of the applicati o n- th at u'e" of the,e las e need only unders tand that thc" functio nal ity IS concerned with the concept' of bil/"bility (lor hargi ng eu tomers) and rtllp/oy,""" TI,e n we crealC an interface thai re nects th ese conce r" Collaps< H,crarcby applle< when we have hudt an inherit. "'.c Sl nl ture that' unne e , ari l refi ned- Ihat " , It ha. too many level s An exa mpl e from llymna>tlC\ I< U""'(JI BarP"jo,,,,,, ~ Gymllll!t ~ /,or,, \\fO'''101 HSSt.J", t - StudtH' - Yo uth - Pmo" Fo r a , mall appl icat i-o n, Ihi< " prohahl y I 0 deep and need, con>nlldatlo n Fo r th is exa mple, ol/"ps< H'tmrciJY CQ nLcrn ' the " cps needed to R'd" C Ih i, to the 10110w II1ll ymna,t
-10
•
tudc nt -
Pe r o n
614
CHAPTER 24
REFACTORING
Order
• Extract Subclass
quantity
Order quantily discou nt
dlacounl
Iype
minimum
• Extract Superclass
Employee name salary
Manager name
salary
Engineer
numSupervlsees
name
Engineer skiUSet
Manager numSupervisees
salary skillSel
Figure 24.17 " Dealing with generalization" refactorings, 2 of 5 Source FOWler at al.. Relactorrng:; improVing the Design 01 lJOsting Code, Copyrfght RepfoOucecl by pefmlsslon of Pearson Education, IIX".
I
1999 OY Pearson EducatK>n, me.
:-i';io~l
• Extract Interface
1-Bln;.bie l IgBlNsmeO I I gBlRB1eO :
Manager name
Engineer
salary numSupervisees billA ale
name salary skiliSel billAale
- -7' IT' I
,I
'_-
-
I{/9tSsiafy{) I
ifI
I
I
I
I I
Manager
numSupeMsels
Enolneer akiuSet
• Collapse Hierarchy o Inherited class not special enough
Figure 24.18 " Dealing with generalization" refactorlngs, 3 of 5 SOUn:e. FOW'ter et al • Refactorlng' Iml)"OYing the ~gn Of EXisting COde, Copyright. 1999 by Pear$O(l EClucatiot\. Inc Reproduced by pefm~lon of Pearson EdUC3tion. Inc.
Fo"" T""pialr Mrlhod applies whe n we no tice a skeleto n algorithm Wi thin a body of code that i common to several algorithms. In effect. we arc evolvi ng a desig n into an applicati o n of the Template design pattern . The example In Figure 24 . 19 shows how the algorithms (o r "",lrBiktl"struclions() and umlrTrlkri"struction,O. which ge ne ra te assembly instruction manuals depend ing on parameters, have 1I CO mm o n illgorithm Core. Th is core consists of pans that can be pulled out as common to both u.rilrBikrl"slrllclio",O and wntrTnkrinstructionsO. IDrll,PrrpO. wrltrSafrtyO. wrilrWrapUPO. and IDrilrMaHua'O. Rrpiacr i"hcriilJ"cr lDith Dr'rgatio". somewhat self.explana tory. usually effects an improveme nt on a desig n. 00 langua ges such as Java d o not allow for more ,han o ne base class, so that there is an advantage to
GENERAUZATION
Assemblylnslructlons wrllePrep() wrileSalely() wrileWrapUp() wnleManual()
,
BlcycleAssemblylnslruelions wrileBikelnslruetlons()
~
BieyeleAssemblylnslruelions wrilePrepO wrileSaletyO wrileWrapUp()
T ricyelaAssem bly Ins I ruelion s wrile T rikel nstruelions()
T rieyeleAssem bly Inslruel ions
wrilePrepO wrileSaletyO wrilaWrepUp()
Figure 24.19 "Dealing with generalization" refactorings, 4 of 5, Form Template Method S«n:e' FCM1er et 81.. Refactoring: ImprOVIng the Design of Existing COde, Copyright Rcpe OduCe<:l by peilhlSSfotl of Pearson Education, Inc.
I
1999 by Pearson Education, Inc
eliminating an inheritance. Fo r the example in Fi gure 24.20, Accou/ll can inh erit from another class once the ..factoring is done , resulting in greater Aexi bil ity . Th e refactoring give a sequence of step that ensure a smooth and safe transition from th e o rigi nal fo ml to th e refactored fo rm . R,p/ae, DtI,galio/l with J/l h,rita/lC< would be appropria te whe n we wanl to repai r a desig n in wh ich code becomes understood as having a gene ralizati o n rciati onship such as Emp!oy"/ Pmo/l . \Vle effec I Ih i in code by mean~ of inheritance .
• Replace Inheritance with Delegation Record lastChangedO
Account
reco rd .Ia stChangedO
record
Account taslChangedO
tastChangldO
• Replace Delegation wl.th Inheritance Flcure 24.20 " Dealing With generaliza tion" rcfactorlngs. 5 of 5 5outu; fO\'t1et
at • Refactor1l'1i' amprO\llng the Design 01 EXlSlJng Code, COPVTIiht ReprO<JU(td by pel lIIiStion 01 Pe&r5On EduUl.lOn. If'\(.. tot
1
1999 by PeArson EduClJtlon. Inc
615
616
CflAPTER 24
REFACTORING
24.6 INTRODUCING MODULES Cood deSll(n requires modul.rozallon , a process of ('paratlng Its es",ntial clement Whenevcr fc.-iblc . th" hould be performed in advance H owe.er, it IS very useful to mod ularize aher thc fact a, well - In other words. to recognize useful modulan Z3 t10n as the appli allon grow..;
Cia se< by them elve, are a mean of modularozatlo n, but an applicatio n can contain huodred, of classes, and so cia. os need organizing to enable designers 10 manage and appl y them . A useful way to handle modularity o n thi sca lc is via the Fa ade dcsign pauern . Impl,(YlOl! m3ue,>, the problem can be reduced to that shown in Figure 2~ . 2 1 , in wh ich the design IOvolves classes U, V, and W, where U references (men lions} classes V and W . An example is U ~ Transaction, V ~ CllSlOme r , and W =Loan pool. Suppose that we want to avo id multiple references like this (think of many clas os instead of Just the twO in this simplification , and you can ImagIOe the re lilting compleXity). la s U must be modified becallse it ,hould no longer reference bo th classes V and W . The rdactoring 10 Figure 24 .2 1 is si mple if U docs not need to instantiate V objects or \VI objects ThIS IS the case when U needs o nl y tatic methods of V or W . (Example, A transactio n needs only a generoc CtlStomer functionality >uch as ge uIOS average assets of all customers, and the IOtal amollnt in the loan pooL ) In that case, U references functio nality in F o nly, and F does th e work of translating slich function ca lls into the static calls on V or W. The situation may be more involved, however. Suppose that U requires V instances In order to operate ( such as is usually the case when it lran action involves a cuslomer). If we want to protect \1 within a package,
then U has to depend on the facade interface F and 11 0 longer on V directly. Figure 24.22 shows how thi can be dealt with . First, V IS proVided with an abstract interface VI (Step I) that abstract its public methods. The Exlrael liller/nrc rdactoring can be used for this. Next. in Step 2, \1 is enclosed 10 a module (or package)
package
,---G
,
@}--- -0- --~
:- -~
Figure 24.21 Refactonng by introducing facade
u0)
Figure 24.22 "Introduce module" refaCloring. 1 of 2
REFACTORING IN PROJECrS
ITmsctn ~
Cust
Agure 24.23 "Introduce module" refactorlng, 2 of 2
• T msctn has attribute 01 type Cust • Replaci ng Cu,' em l ; with ICu,' ell" ; • Cusl has on ly private attributes (, C., usc via metho ds o nl y ) • Tntsctn docs nOt instantiate Cust instances • T m sctn has me tho d wi th parameter 01 type CUSI • Replacing my Method(Cllsl) with myMe thod(JCu.sl) • Cusl has only private attributes (i.e., use via metho ds o nl y) • T"" eln has method returning type CuSI • Replaci ng Cusl mylvltlhod(J; with ICll sl myM, II,od(); • T"'seln has method with variable of ty pe Cllsl • Replaci ng Cu" eIIsl; with ICII, I ell "; Unreso lved as a general mailer
OK if . ..
OK if . ..
OK
Agure 24.24 Types of references of one class to another
with facade F. The class U must now be modi Red so as to refere nce \f / and F onl y. It is far less of a problem fo r a class to reference an interface than !O reference a class. Let's apply thi s to an example , shown in Fi gure 24 .23 , where a transactio n o bject 01 class T",scln depends on a customer clas GISI. We can introduce inte rlace ICuSl, wi th Cusl bei ng unc hanged , but we need !O dea l wit h the resulting changes needed to T"'seill . The de pende nce of T"'selll o n Cllsll re placed with depe ndence o n ICusl. TIlis IS a slg~ificant improvement because II increases modularity. Th ink of it a fo llows: Imagine T "' ,elll as a bicycle pump. Such a pump wo uld be of littl e use If it werc ab le to o pe rate o nly on Ajax tires (no t an interface ) but would be very usefu l if it were ab le to operate o n an y tire sa ti lyi ng the standard va lve interface . Figure 24 .2-1 lists the impl icati o ns of th is c han ge for T ", \Chi and intro duce rem ed ies for most situall o ns.
24.7 REFACTORING IN PROJECTS As mentioned at the beginning of thi S chapter, rdactorlng ca n be profi lably applied a soon as software engineers begi n wri tin g code , Figure 24 .25 was Intro duced In hapte r 4 o n ag de metho ds, bUI With o ur mcreased knowledge of rdilc to rins we now have an o ppo rilinil to reexamIOc it. Re .11 Ih at a~ i l e methodologies repea t the waterfa ll ,cquc nce ma ny time, bUI with eve ral diffe re n c< Eac h Ie beilin, With the (functi ona l) code base ReqUIrements . re us u. lly in the fo rm o f IIser ~torie , . The ex ,,"n g
617
6I 8
CHAPTER 24
REFACTORING
Oblaln high-level requirements
Obtain requirements for noxl perlod's' segmenl
Ref.clor 10 Ref.ctorlo clean up
accommodate
new reqU irements
Modify code and lesl code base to handle additional requirements
• Typically 1-6 weoks
Figure 24.25 Agile methods-cycle of activities
will have been expre sly designed for Ihe eXisting requirements. It is a tenet of most ag ile melhodologies "01 to try to anticipate forthcoming rcqulrtl1lcnt . The existing code ba~c m() y thus be unsuited to th,· additional requirements In one or more ways-and rdactoring wou ld then be clppropriatc in order to accommodate
them . An example is the uscr story for a video Slore applicalion that inlroduces candy sa les (i.e .• nOl just Ihe management of rentals ), A n('\\' module at the architectural level may be required" and this , require pulling contro l functiona lity out in o rder to orc hcsrratc the rentaVsalt::~ actiVities.
In
rurn , may
24.7.1 Refactoring in the Agile project Life Cycle Figure 24 .25 shows an additional refactoring step the ta,k of cleanup. I\·\osr software addilion and modification work leaves a "me s" of one kllld and ma gnitude o r olher. An example i a SCI of displayllcCOI(l110 methods, one (or an existing account t)'PC and two more: for added account types Even If the application docs nor continue to evolve
10
this direction , the disorganization descnbed I\hould be cleaned lip
to make" more reliable and readable . Rdactoring is thus an esse",ial parr 01 agile design . imp lement.tlon. and testlllg. It IS part of the expectation for agile projeclS.
24.7.2 Refactoring and Design Patterns Fowler's refactorlngs, described in [ 11. stand mostly apart from de ign patterns at lea" 111 expilcjl term . However. refactOrlng is really an integral part of all de .. gn and implementatIon In particular. the need for refactoring often poinlS to the need for new de ign panerns The cla<slc source for these is (2). in whICh Kerievsky names most of hIS patterns in one of the follOWing forms . 'Exr~cI
or
< Design Pattern > "
EXERCISES
' Ext..
MoveIReplacc < irua tion > \Vith/to < DesIgn Pattern >"
Our purpose hen- is on ly to dral\' the reader' attent ,on
10
thi s \Vork . H ere arc some example •.
• Encap ulatc Classes wIth Factory. Help the sO(l\Vare engineer recogn ize .. . .. when Factory is a better way to construct o bjects that he o r she is dealIng with, and how about the conversio n • Move Embelli shment to Decorator
10
go
• •
... when the amou nt o( functionality bein g added dynamically to objects of a class is extensive enoug h to require th e use of the Decorator design pallern , and how to go abo ut the co nversio n • Replace State.Altering Conditio nals with State .. . when the State desig n pattern is a berter wa y to handl e eve nts that alter the state of the applicatio n, and how to make the transition
24.8 SUMMARY ' Refacto ring" refers to a d iscipli ne of replacing code in such a way as to Improve the applicatIon but without changing its functionality . The improvement can be o( the following kinds. • A simplifica tio n of th e design and code (removing unneees ary complexity) • An increase in its reusabil Ity (or o the r parts o( the codc base fo r other app li catio ns • Improved preparedness of the desig n and code (or increasi ng functionalit y Refactoring is possible at the archotectural level and at the det.oied code level. II extends the lIfe of applications because it increases their capacity fo r modiAcation in response to changing requirements. Some refacto rings can be done wit h wizards upplied woth devel o pment environment Refacto ring is essenna l to agile devel o pment. This is because It facilitates the evolutio n of applications so as to include additIonal funct Io nality . This chapter has eoted severa l classica l refact orings. There are many more . An a t lve research communI ty explores new rdactoring sec f3], for example
24,9 EXERCISES I. O ne refactoring is to "sepa rate domain fro m prese ntat ion " Explain what this mea ns, and app ly It to a ca lendar applicatIon , 2 Wrote a SIngle that ompute< the roots o( a quadratic cqua tlon Apply "ex tract method" to It. 3. Describe an appl,cation not mentioned In this chap ter- or part o( an application-in wh , h ' Convert Method to Objec t" would he approp roat e 4. Apply ''Extra ct
lass" to the (o llowlng
619
620
CHAPTER 24
REFACTORING
class Rental{ Str ing customer; Stringdvd ; • lnt customerLlcense; Str ing director; Date date; •
•
•
•
}
5. TI, is chapter ci tes the fo llowi ng class diagra m for o,allg, Bid",ctional AssocIation 10 UHld",,'ional:
Elll ploy"
<0---- <> Em ploY"''''t Rtiatio",biP <> --> Em ployer
(see Section 24.4 ). Write code consistent with this model that allocates seven emp loyees among two employers and lists them . 6 . Give an example in which the addition of a meth od to a calendar application would cause the software engineer to apply P"II Up M,tbod. 7. Explain where Inlrod"a Facad, was used in the Encounter video game case study. 8. Section 24 .7 cited two stages at which rdactoring is used in agile projects. Give examples of each in the evolut ion of a calendar application. 9. The introductory section of thi s chapter refers to a class Mil,ag,. Show how the refactoring of it could progress usefully along the directions suggested there.
BIBLIOGRAPHY I Fowlc.-r, M~nln . HRtJactonl'l9 I".",oai"9 ,he Dn'g" of E"u l '~ CoJe Addlson,Wc-sit-y . 1999 2 KcnC""Sky . J<xhu.a .. Rt/acwnf19 fo P.:Jrk"" ~," Addl'>on·Wt"Sley, 2004. 3 Rd~ct on ng http j/~' rdactonng.com! ( Iccc~..ed 1l/ 14/09]. M
Introduction to Software Testing
Planning Maintenance
•
Why test early? Why often?
•
When and why do you retest?
•
W tlat IS the difference between black box and white box testing?
r.stlng The Software Development Ltle Cycle
• Requlremenls analysis
Implementalion
Design
•
How do you document lesls?
•
How do you plan for testing ?
•
How do you know when to stop lestlng?
•
Where does test Inpu t come from?
•
Who Is Involved In lesllng?
•
How much effort does It lake to test?
Figure 25.1 The context and learning goals for this chapter
v~l l datl"n proct<' Execu tll1 g "de (rom th e c u lv "' 1l J"p l l<.~ t lon IS provide I \\ Ith Input, and the (csullln~ output 1\ ompzll cd wI th thl' (('qulI 'd lllPlil i'(l h
622
CHAPTER 2S INTROOUCTION TO SOFTWARE TESTING
Termmology, IEEE Sid 610 121 9 0) a< "an incorrec t Slep. pro e,s. or data dcflnilion In a computer program " "In orrec!" " 'e wiliundersiand 10 mean something Ihat causc< a failure to sallsly Ihe rcquifemenlS In any way The goal of Ie. ling i 10 uncove r as many defecis. al Ihe hl ghesl level of serlou,no", as pOI"ble. It IS nOI posslblc 10 leSI an app licalion wilh every possible "'PUI value duc 10 Ihe extraord inarily large number of combina llon of input values. For Ih, s reason, te ling ca n cstabll h the Pft5(11CC of defctls but Nol Ih,,,.b.rncc (.. o aptl y PUI by Edsgar Dijk tra) In o lher words. for any prac lica l application, Ihe follOWing is a fal« Slatement· "II has been Ihoroughl y lested and Iherefore has no defecls." TIlOrough testing IS nevenhele<s Indi . pensable . This chapter descnbe essenllal principles of software Icsti ng . II also summarizes tesllng practices so that Ihe reader can understand leSling types and their contcxt withour gettms bogged down in details C hapters 26 and 27 provide detads.
25.1 TESTI NG EARLY AND OFTEN; AND THE AGILE CONNECTION Two baSiC principles of software leStmg are "test early" and "te51 often " These precepts havc been respected for man y years and are a pnncipal feature of agile methodologies. "Testing early" means testing pans as soon as they arc implemented ralhcr than waiting for the completion of the unilS they arc part of. In the video store application, for example, suppose that we are constructing a method that stores rental mformation using Vid,o and ( ,,"orner objects as input parameters. 'Testi ng early· Implies testing thIS method alone as much as possible before constructing addilional methods in the class. 'Testing often" means running tests at every reasonable opportunity, including after small additions o r changes have been made. For the video store example, suppose that we add functionality to the rental storage method mentioned above . "Testing often" translates here imo Arst rerunning the prior tests and then testing fo r Ihe new funcli o nality. One reason for testing often is that changes sometimes invalidate code already implemented. \VIe discuss this next. A goa l of modern development methods, and especially of agile methods, is for the application under development to grow only-in other words, not to require any other kind of alteration such as er.sures. Accomplishing this (which is not always easy) means that existing tests continue to apply as new clements arc developed .
25.2 REtESTING : REGRESSION TESTING Suppose that we Ihoroughly tcst part P of an application . Part P necessarily depends on other parts. (If part P depends on no o ther parts, it can be treated like a separale application .) Now su ppose that we add to or alter part Q of the application If P depends on Q , then P should be retested . Retesting software to ensure that its capability has not been compromised is called rtgrtSsio'rl !n tin9 · A rcgrc sion test is de Igncd to aSSure uS that the
code added Since the last test has not compromised Ihe functional ity that was present before the change{s) were made . Such a lest usually consists of a repeat or subset of the tests that were executed on the artifact before changes were made. As an example, we could And that addmg function.lity to DVDRtJllaf to estimate when a Customer will return the DVD (mysteriouslyl) changes the due date. This kind of occurrence is caused by an erroneous addition . a poor design, or an incomplete understanding of the application. Figure 25.2 ummarizes thiS. A problem in regression lestlng Is assessing whether or nOt addcd or changed code affects a given body of already. tested code. Also, we may not always be able to retest every part of an application becau e this sometimes becomes prohibitively time·consuming (an operating system is such an example) Figure 25.3 explains such situations by considering what regression lestmB is necessary aftcr code N has been added or changed.
BLACK BOX AND WHITE BOX TESTlNG
1. Regression Original leSI
lesl (= original
lesl?)
Original Original
code
coda
artifact
artifact
2. Teslof
addition
added functionality
""-
"""
Figure 252 The idea of regression testing
Suppose that C is a body of already. tested code in an applTcation A. Suppose that A has been altered with new or changed code N.
A
• If C is known to depend on N Perform regression testing on C • If C is reliably known to be completely independent of N There is no need to regression tes t C • Otherwise Regression test C
.... N 4ft'I'
$
'woos us
Figure 25.3 Parts to be retested in regression testing
25.3 BLACK BOX AND WHITE BOX TESTING Suppose that we have buill the video to re application and we want to tes t it . We ma y run the application with data like the following , and then compare the app li cation's behavior with Its required behavior.
Abtl
,"" S'Tb, Mal,ix" 0" Ja"uary ,"" S"Gon'
/larry
].
Wilh Ih, Wind" on January] 5
Abrl "'u,,,s 'Tb, Ma lrix" on January ••
)0
•
Thl~ type of test inS i kn ow n.,
black box tesllng because
does not take into a ount the manner in which the application was deSigned o r implemented. ilia k box testing can be performed by
623
624
CHAPTER 25
INTRODUCTION TO SOFTWARE TESTING
Result
Input determined by...
Actualoutpul
compared with
.. . requirements - - -....
reqUIred output
White box ... design elements
Figure 25.4
Bla c~
Va lida lion ot expected
------+-t
behavior
box and white box testing
Black box tes ting is esse ntial. H owever, to uncover as man y defec ts as possib le, we also need to utilize
knowledge of how the application has been designed and implemented. ContInuin g the automobile analogy,
if the
ca r is built with a new design (or its automati c transmission , we wou ld be wise co usc this knowledge ,
srressing multiple gear changes and runnin g rests that foc us on changi ng gears in as man y ways and
circumsta nces as possible. T ests based o n desig n and implementation know ledge arc called wbilt box or glass box tests. Figure 25.4 illustrates th e d iffere nce between black box and wh ite box testi ng. White box testing met h ods arc typica ll y performed during unIt testing , which is described in C hap ter 26. Black box test ing is performed both during and after unit testi ng and is described in C hapters 26 a nd 28 . Tests that focus substantively o n bo th o n the know ledge of h ow an application is intended to operate as well as how it is construc ted are someti mes called gray box tests .
25.4 UNIT TESTING VS. POST-UNIT TESTING Software applications co nsist of numero us parts. As with all constrtlcti o n, the sou ndn es of tho who le depends on th e soundn ess of the parts. This is ill ustrated by the ca nt ileve red bridge in Figure 25 .5. Because of this depe ndence, we test software pans thoroughly befo re- assembling them-a process known as "n il 'tsling . Individual methods arc con idcrcd tmits for tC'sting purposes, and so are clas cs. A part as substant ial as a grammar checker in a word processor is probabl y too large to be conSidered a "un it." At times
we inadverte ntly allow a defect in a unit to remain undetected until the pro duct is compiete. In that case, the cost of isolating and repairing the defect is tens or hund reds of times the cost of doi ng so wit h in the pRase durin g which th e defect was creat ed. In other words, there is a very large payoff in d etecting defects early at the un it leveL
Reliable Reliable? Reliable?
-
-
Reliable?
Reliable?
Agure 25.5 A bridge made from parts depends on their individual reliability
Reliable? Reliable?
TESTING OBJECT-ORIENTED IMPLEMENTATIONS
•
Int~rfac~
testing validates function. expo cd by modules • Int~ration _ _ _ _ _ . combinations of module • S~tem whole appitcation • Usability user satisfaction • R~ression
• Robustness ab.lity to handle anomal.es • Performance
fast enough, uses acceptable amount of
changes did not create defects in existing code memory • Acceptance customer agreement that conlract sal.sfied • Installation works as specified once installed on required plat form F"rgure 25.6 Some major types of post-unit tests
Unit Unit • ••• •
Build
Unit
•• •••
_~)
Modufe
..... --
Application on test bed
Application
-
(n(erface testing
system testing usability testing
• • • ••
Unit Unit
on final
platform installation testing acceptance testing
Module .
testing
• • •••
Unit
Regression testing throughout
FIgure 25.7 various non-unit test types
Various types 01 POS'-""" tests arc al 0 administered . F.gure 25.6 sum marizes some 01 the major types. They are covered in Chapter 28. Figure 25.7 is a summary of when each of the post -unit testing activit.es.s performed during the praces of bUilding an applicalIOn .
25.5 TESTING OBJECT-ORIENTED IMPLEMENTATIONS Object-oriented applicat.ons, when develo ped well . beneA t from thei r organ.zation into c1asse . like an modularozatlOn , this help' wit h testing because the classes ca n often be tested separately froro-and '"
625
626
CHAPTER 25
INTRODUCTION TO SOFTWARE TESTING
add,t,on to- bl. k box functIonality . Prior to the advent of 00, modulanzatlon tended to be in terms of fun tlonalul1Its , deco mposed 1111 0 lowe r leve l functional un its ("stnlctured programmlllg") Thc<e units can be eparo tcl y tested but o nl y when cleanly de igned. As w.l l be >cen in hapter 211, on unIt testlllg , 00 t<stlllS In ludes method , lass, and package te. tin g.
25.6 DOCUMENTING TESTS It require signdkant lime to decide whal lo test, how to lcst , when lO do so, and with what data . In addition, test results must be ana lyzed to determine what defects they uncovered . We therefore treat each test as an item of value Tc 1 procedures, tcst data , and test record arc maintained; tests are reused o r modified where possible . E.xamples of test documentation can be found In Chapters 26 and 27.
25.7 TEST PLANNING T o ma xi mize the effectiveness of resources spent on testing. a systematic approach is required and a plan IS devised . Recall that the goa l is to detect as many errors as poss ible at as se riou a level as possible with the reSOurces available . Typical planning steps arc shown in Figure 25 .8 and elaborated in the rest of (his section .
25.7.1 Organize "Unit" VS. Non-Unit Tests The limIts of what constitutes a "unit" have to be defined by the development team . For example, do they include the testing of packages, or is this to be considered another rype of testlllgi
I . Deflne "units" vs. non-units for testing
2. Dctermllle what types of testing will be performed 3 Determine extent • Do not just "test until time expires" • Prioritize, so that important tests are def1nitely performed 4. Document • Individual's personal document set includedl • How/when to incorporate all types of testing) • How/when to incorporate in formal documents;> • How/when to use tools!test utilitiesl 5. Determ ine input sources 6. Decide who will test • Individual engineer responsible for some (units») • How/when inspected by QA) • How/when designed and performed by third partiesl 7 Estimate resources • Use historical data if available 8. Identi fy metrics to b<: collected • Dc:fine, gather, usc • For example, time, defect count, rype, and source Figure 25.8 A plan for testing
TEST PLANNING
• • • • •
When tester has not been .ble to Rnd anot her delect in 5 ( 101 301 1001) minutes of testing When all nominal, boundary and out -of-bounds te _t examples show no delcct When a given checklist of test type has been completed After completing a series of targeted coverage (c.g., branch coverage for unit testing) When testing "ms out of its schedukd time
figure 25.9 Stopping criWia (or testing
For object-oriented devel opme nt projects , a common sequence of unit testing is to test the methods of each class, then the la,scs of cach package, and then the packagt: as a whole . If we were building a framework , we would test the classes in each framework package first and then move on to the application packages, bt-cause the laner depend on the form er. Once the "units" and non -unIt tests have been identified, they must be organized and saved in a sy tematlC manner.
25.7.2 Determine the Extent otTesting Since it is impossible to test for every possible Situation , the rx ltll l of te ting hould be considered and den ned in advance. For example, if a banking application consists of Withdrawals, deposits, and queries, Untt testing could specify that every method should be tested wtth an equal amount of lega l. boundary, and illegal data; or perhaps, due to their se nsitivity, withdrawal and deposit methods arc tested three times as extensIvely as query methods, and so on . Test cases are se lected both from normal expected operation, as well a from those judged most likely to fail. SloPP;lIg enl,,;a are established in advance; these are concrete cond Iti ons upon wh Ich testing stops. Examples are listed in Figure 25 .9 .
25.7_3 Decide How Tests Will Be Documented Test documentation consists of teSt procedures, input data , the code that executes the test. output data, known issues that cannot be attended to yet, and efRciency data . Test dnvers and utilitie are used to execute unit tests. and these are documented for future use. JUnlt is an example of a unit test utility (described In more detail in Chapter 26). JUnit·like and various profeSSional test utilities help developers to retaIn test documentation JUnit classe . in particular, tend to be maintained along with the applicatIo n.
25.7 _4 Decide How and Where to Get Test Input Applications are developed to so lve problems in a speclRc area , and there is often a et of test data special to the application . Examples are as follows ; • Standard test stock market data for a brokerage application • Standard test chemICa l reactIOns for a hemical engineenng appitcalton • Standard FDA procedures for the pharmace~ltcal Industry • Standard test input for a compiler • Output from prevIous verSIons of the applt atio n The procurement process and usc of su h doma.n-,peCtA
test Input mu t be planned ,
627
628
CHAPTER 2S INTRODUCTION TO SOFTWARE TESTING
25 .7.5 Decide Who Will Be Involved in Testing UnIt t<' slIng i usu,II), performed by develope rs tn. m.nner o f their own cilOoslng T estIn g beyo nd the unIt leve l i, planned and performed by people other than the devel o per- u uall y an tnternal Q A o rganlZ
25.7 ,6 Estimate the Resources Required Unit te ting is o ften bundled with the development process rather than being called out as a separate budget ite m. Good leaders fos ter an altitude that the rcliabiHty o f un its is essential , and they allow developers suf Acicnt time to alta in reliable un its, Testing beyond the unit level is an identifiably separate item , usually assocIated with the project's budget but sometimes a part of QA's whole budget. Employing a third party for teslln g IS sometimes used-including offshored resources-and must be budgeted for.
25.7 ,7 Arrange to Track Metrics The develo pment organ izatio n speciRes the fonn in whIch engineers record defect counts, defect types, and time spent on testing . The resulting data are used to assess the state of the application , to forecast the job's
eventual quality and completion date, and as historical data for future projects . The data also become part of the organization's hi stori cal record .
25.8 TESTING TEST SUITES BY FAULT INJECTION Suites o f tests and test plans can be eva luated, and there arc ways to improve them . MutatioH !(sti"g , in
particular, validates testing sUItes rather than the code under test itself. Suppose that we have developed a suite of tests for all or part of an appl ication . Fo"ft injection is the process of deliberately inserting faults into a program , Mutation testing is a kind of fault injection whereby we change the source code in small , controlled, and deliberately incorrect ways to detennine whether the resultIng mjected errors are detected by the test suite. Examples are changing a true to a Jalst and a ">" to a "> = ". If our tests continue to pass despite fault injections, this exposes weakness In our current tcst suite . We can infer that the test suite is probably failing to
find defects that we did not insert . By working on fault insertion, it is possible to estimate the number of defects that our test suite is faili ng to And. Mutatio n is said to have originated by R_lipton in a J 971 class . It is computationally intensive, which is one reason it took some time to become active as an area of research and practice.
25.9 SUMMARY Software testing is a validation process, the purpose of which is to detect as many defects of as high a level of seriousness as possible , Defects are detected when the software under test is provided with input, and the resulting output does not match the expected output. Two basic principles of software testing are "test early" and "test often," "Test early" means that as soon as a software part is implemented it should be tested. This ensures that defects are detected as close to their introduction as possible, making them easier and cheaper to detect and correct, "Testing often" means
EXERCISES
running ~ts at ~very rea on able opportunity, includi ng after additions or modifications have been made. Updated code may advcrsdy affect the exi ting code , and the errors should be found and repaired as quickly as possible. The testing for capabilities already attai ned prior to update is known as regression testing and is pcrfom1ed throughout the testin g process. There are two basic test mNhodologics, black box and white box. Black box testi ng does not take into account the manner in whIch the software i designed or implemented. Test inputs are provided based on the requirements of the application, and outputs are examined to ensure they match what is expected. White box testing takes the desIgn and implementation into consideration , and inputs are devised with these in mind. Unit testing is performed on the methods and classes of the software. It employs both white box and black box techniques. It ensures that the underlying structure of the software is sound. After some or all ullits are test~d, post-unit test are run that test the larger system . These include interface, integration, system , usability, reglession, acceptance, and installation testing.
25.10 EXERCISES I. Why not wait for many parts to be built, and then test them together? This seems to kill several
birds with o ne sto ne. 2. Suppose that you have a developing applicatio n, tested so far, to which you add code. Why not, as the next step, test the combined result7 3. Explain why (a ) white box resting, by itself, is not enough and (b) black box testing, by itself, is not enough . 4.
Why is unit testing most com monly performed by software engi neers who program and post-unit testing by QA personnel7
5. Why shou ld test planning be speCifically identified as an activity rather than being pursued informall y when the time comes7
629
unit Testing
PlannIng
•
subjected to unit testing?
~
T......
The Software Development Life Cycle
What parts of the code should be
•
How do you go about unit testing?
•
What is statement coverage? Branch coverage? Path coverage?
•
How does equivalence partitioning help in selecting test cases?
•
How do you use stubs when the unl1 under test requires other - but unbuilt - units?
•
How do you use JUnit?
•
What is test-driven development?
•
How Is unit testing done in case studies?
Figure 26.1 The context and lea rn ing goals for this chapter
UIlI" rs''"9 IS the testing of the paris of an app lication In isolation . Typically thesc are the methods and classes. Unit testing.s conducted by software developers c.thcr IJl parallel with implementation or after a part of the appl,cation is coded. In eIther case both white box and black box methods are employed. \""'ite box unit te (5 focus on the unit's Internals such as program logic, branch pOints, and code paths Black box unit teSlS focus on providing inputs based on thc particular reqUIrements of the unll , vahdating that co~ct
outputs arc produced. Once they arc uccessfully tested in ISolation , units are ready to be integrated and
UMTTEST METHODS
Key:
•
·speclfies·
Implementatlon.time specification
Desig n document (SOD) Requirement document (SRS)
·'t
Enmple: shall be possible to add 8 DVO to the vkJeo store's
inventory»
Domain classes
Example: get D VD tlt/e
1i·ltllemlnlatlon unll (cede lor i1i."~ or claD) Examp Ie: void sa/OVON.mel ... )
Example: me/hod addOVO( " . ) ~Pr8condl'ions:
... _
Postcond,llons: ... •
FIgure 26.2 The source of units for unit testing
tested together. This is what we will ca ll pOS I-"IIIllrsliH9 and is covered In C hapter 27 The rest of this chapter describes specific test methods a nd stra tegies employed in unit testing .
26.1 THE SOURCES OF UNITS FOR UNIT TESTING The first step in unit testing is identi fyi ng Units and determining wh al they are intended to do . These arc obtained from the SRS or the SOD . They may a lso be ele me nts 100 minor to specify in the SOD . Figure 26.2 illustrates this for the video store exa mpl e. For units arising from design , we ma y not possess ex pl icit requ ire ments against which 10 perform te ts. An example is a test for the class Cm"rOla,aCIII, introduced for the design of ou r video ga me; none of the original requirements specifica ll y involves CamrChamrlll per se. Separate specifica ti ons shou ld be wrillen for all design classes oncc the desig n is crea ted . When Ihese are nOI wrinen , as is often the co e, lest cases have 10 be devised against the functionality Ihat the class is supposed (by Ihe lesterl lo pos c s Figure 26 3 ill ustrale unit lesti ng agai nst reqUire menls a nd against design .
26.2 UNIT TEST METHODS Both white box and black box mel h ods are ul ili zed during unll Icstl ng Some of Ihe principal te hni ques are shown in Figure 26.4. As described In h ap ter 25, white box testing IS conducted with knowledge of the design and impleme nlatio n of Ihe unit under lesl. The while box unit Ie I fo us o n the Internal cod~ structure, testi ng each pro!:ram statement , every deCision point , a nd each indepe ndent path Ihrough th e code. Black box mel hods focu nn tesling the unit w lthoUI u"ns its IOternal structure Tc hniques u. ed 10 conduct black box unit lest' Include eq uiva le nce parllt ionlng and boundary va lue ana lysi<, IOP'C Ihat are explained In detail below There has been , and con tinue, to be, resear h o n Ih e relations hi p alilong these te tlOR Iyp<"> SIO c they often overlap a nd a lso leave va n ou' ki nds of gaps An examp le of p. t research is dc, nhed by Rapp' and E J. W "yuke r [ I J. '" which paths are selec ted on Ih ba<;' 01 w here v.nable, are deAned vs. where Ihe are u$ed . Nevertheless, the types d,scu,sed form a Rood , tart ins point and pra tica l ba
631
632
CHAPTER 26
UNIT TESTING
i2} Design 3.2.EC.l .2 Dualities of ElKX>unler
GameCharacler: An abstract class with attributo name ... ,
chsracters
"- "- \
Every game character has the same set of qualities. Each quality shalt be a nonnegative fica ting point number with at teas tone decimal of precision . . . .
Test this class ... .,. against this requirement
j
Characters
\
GameChsfscter
"- .....
--
Test this method ... ... against thIs require ment
L
"-
\
I -j
"
EncounterCharacters
, "-
EncounterCharacter
t.. adjUS1OuaJityO
Figure 26.3 Relating tests to requirements and design
26.2.1 Statement Coverage At a min imum, every statement in a program must be executed at least once during unit testing.
Ir a line of
code contains a defect, tests that nev", execute the line will not detect the defect. Untested statements are thought by many to be a major cause of latent defects. Consider the function co",p.t,Fi", 0 shown in listing 26. t . We will usc a directed graph, ca lled a progra", (0""01 graph , to graphically represent the control paths of the program . Figure 26.5 contains the program conrrol graph of comp.tcFi",O, where each node in the graph represents an executable line of code, and each
White Box Methods • Statf:ment coverage
Test cases cause every line of code to be execllted
• Branch coverage Test cases cause every decision point to execute • Path coveragr Test cases cause every independent code path to be executed Blad Box Methods o
o
Equivalence partitioning Divide input values into equivalent groups Boundary value analysis Test at boundary conditions
figure 26.4 Methods for unit testing. categorized by black box and white box types
UNIT TEST METHODS
1
False
False
Figure 26.5 Control flow graph of computeFineQ, with numbers keyed to Listing 26.1 edge represents the transition between lines of code. In the graph we repre e nt decision poin ts uch a or for statements as a diam o nd, and all other executable statements as a ci rcle.
If, ",/,il"
Ustlng 26.1: COmputing a fine for a late rental
int computeF ine (int daysLate, boolean pr intOn) {
1 2 3
int MAX_FINE_PERIOD ~ 21, fine ~ 0; i f (daysLate < ~ MAX_FINE_PERIOD ) { f ine ~ daysLate * DAILY_FINE; }
4 5 6
logFine ( fin e) ; i f ( printOn~~TRUE ) { printFine(fine); }
7
return fine; }
In order to satisfy statement coverage, tes ts are devised ,,, lth Inpurs that e nsure eo h linc of code IS cxecutcod at least once As s hown in Tab le 26 I , o nl y o ne tes t is nece>'"!)' to sa ti sfy sto te mc nt co crage 01
",..p..kFi"t() (but not truly comp le te overage , as we shall eel .
633
634
CHAPTER 26
UNITTE5T1NG
Table 26.1 A test for computeFlneO Test Case ,
,
daysLate
,
pnntON
path
TRUE
' ·2-3-4-5-6-7
26.2_2 Branch coverage Statement coverage is satisfactory for determining whether a particular line of code has an error, but it will not catch all ty pes of errors by any means. In facl , computcF""O does ha ve a defec t: the vanable fi., shou ld be initialtzed to MAXJINE on line I, not to O. The defec t will mani fest if day,!..le is input with a value g reater than MAX_ FINE_ PERIOD . Th is was not detected in the statement cove rage test because, although the if statement on line 2 was execu ted, the branch for daysLate > MAX_fiNE_PERIOD was no t tested . A stro nger fonll of test coverage, one that includes statement coverage and detects this ry pe of defect , is branch cov(ragt , which means that for every decision point in the code, every branch I S executed at least once. listing 26.2 contains an updated compul,Fi",O function , with the aforementIOned defect repaired-the variable fi., is now In itialized to MAX_FINE on linc I .
Ustlng 26_2: An updated computeFineO function
int computeF ine ( int daysLate, boolean pr intOn) {
int MruCFINE_PERIOD = 21, fine = MAX_FINE; / / defect fixed i f ( daysLate <= MAX_FINE_PERIOD) { fine = daysLate * DAILY_FINE;
1 2 3
}
4 5 6
10gFine(fine); i f (pr intOn == TRUE) { printFine(fine); }
7
return fine; }
To satisfy branch coverage , one or more tests are run with appropriate inputs to ensure that every
statement is executed at least once and every branch decision is executed at least oncc. The two test cases in Table 26_2, for example, satisfy these conditions . The execution path of each test case is shown in the program cont'rol graphs 01 Figure 26.6 , with the bold arrows depicting the contTol Aow.
26.2.3 Path coverage An even stronger form of test coverage is path coutrage, in which all distinct code paths a", executed by at least one test case. By distinct code paths we a", rderring to the complete set of sequences of branches and loop
UNIT TEST METHODS Table 26 -2 Tests SUfficient to sa tisfy branch coverag Test Case •
daYSLate
printON
Path
I
1
TRUE
1-2-3-4-5-67
2
60
FAlSE
1-2-4-5-7
e
Test Case #1
1
False
False
False
False
FIgure 26_6 Branch coverage of computeFmeO. with numbers keyed to Usting 26.1
traversals, even if the y d iffer by just o ne small part of the path . This type of testing detects errors that only occur if a speciRc path is executed . Path coverage subsumes statement and branch coverage. As an example, c","puItFi"r(J contains two If statemen ts, each with two branch decisions · true and false . Therefore compu/rFin,(J has four distinC1 paths through the function as Illu trated In Figure 26.7. Four test cases would be reqUIred to test all the distinct paths of compu/rF,",O, one fo r each path , as shown in Table 26.3_ As the number of branches and loops increase, the number of distinct paths grows exponentially. It qUJckly becomes impractical to test them all. Fo r exa mple, the number of decision poi nts IS 30, the number of distinct paths is over 1 billion . It is therdorc necessary to limit the number of paths to test_ A commo nl y used method of maklOl! the tests Viable whde gal nln !! IgniAca nt conAdence is to compute the number of linearly independent paths, or baSIS paths, through the code under test ThIS can be thought of a the minimum number of paths that can be combined to generate every po Sible path , and i the minimum number of paths that hould be tested
.r
63S
636
CHAPTER 26 UNIT TESTING
Path #1
Path #2
Path #3
Path #4
1
1
1
1
False
False
False
False
False
False
False
False
Figure 26.7 Distinct paths of computerFineO, with numbers keyed to Listing 26.1
The Il umbe r of basis paths ca n be ca lculated by computing the cye/omnlie eompltxity [ 2]. which has its roots 10 graph theory. The Am step in computin g the cyclomatic complexity is to represent the code with a program conrrol graph. Then the cyclomatic complexity (CCl is calculated w ith the fo ll owi ng fo rmula: CC = e - n
+2
where e = the number of edges, and n = th e number of no des. As an example , listlOg 26.3 contains an upd ated vers io n of eornpulrFi""O that has input an array containing the number of days late fo r a list of DVDs. In o rder to process the list, afor loo p is introduced, adding an addi ti onal decision POlOt in th e function Figure 26.8 shows the corresponding program conrrol gra ph for this eompul,Fi""O.
Table 26 • 3 Test cases for all tile distinct paths of computeFine() Test case •
, 2
daysLate
,
60
prl ntON
path
TRUE
' ·2·3·4·5-67
FALSE
'·2·4-5··7
3
,
FAI SE
' ·2·3·4·5·7
4
60
TRUE
'-2·4-5·6·7
UNIT TEST METliOOS
1
3
5
8
10 F"lgUre 26.8 Program control graph for computeFinesO. with numbering keyed to Listing 26.3
26.3: updated function--computeFinesO int computeFines ( int d a ysLate[], int numDVD, booleanprintOn) {
1 int MA>,-FINE_PERIOD = 21, int cumF ine = 0; 2for (i=O; i < numDVD; i++) { fine = MAX_FINE 3 if (daysLate[i] <= MAX_ FINE_PERIOD) { 4 fine = daysLat e [i] * DAILY_ FINE; 5 }
logFin e ( fi n e ); i f (pr i nt On == TRUE) { pr i ntFin e (fine);
6 7
8
}
9
cumF i n e += f i n e ; }
10 r et urn c umF i n e ; }
637
638
CHAPTER 26
UNIT TESTING
To cal ulale thc cyclomalic COIl1P!cXIIY of comp"'cFiHtS() , we rcrcr to Ihe program co ntro l graph Figure 26 .8 and no te thaI Ihere arc 12 cdges and ' 0 node$ Therefore, C IS ca l ulaled as follows ;
In
C = 12 - 10+2 = 4
Tills lell us Ihal Ihere arc four basIS palhs. To ge nera le a spe lfic scI of basIs path< , Ihe foll o wing SICPS can be foll owed. I.
tart wilh Ihe stralghl path Ihroug h Ihe code (all cond i\l ons lrue).
2. SCI Ihe firsl cond 'lion 10 fa lse, kee ping all Ihe re I lrue. 3 Resel Ihe firsl co ndillo n 10 lrue, Set Ihe second condil io n 10 false , keeping all the rcSI lrue 4. Continue, se lling Ihe next cond itio n false with all the rcst true. 5. Stop aftcr the last condition has been set fal e. ThaI IS, each basis path varies o nly o ne of Ihe conditions at a time. Note that the condition nodes in thiS function are 2, 4, and 7, which arc the for statemenl and the IwO if stalcments. Usi ng Ihis algorithm , the four baSIS paths for (omp"'cF,",,() arc as follows ; Basis Path # 1; 1· 2· 3· 4·5·6·7·8·9· 10 all true Basi Palh #2 ; 1·2· 10 for Slalement false
if statement false second if statement fal se
Basis Path #3 ; 1·2·3 ·4·6·7·8·9· ' 0 first Basis Path #4 ; 1· 2·3·4·5 ·6-7-9· 10
The corresponding program control gra phs arc shown in Figure 26.9. Four test.s arc then devised with appropriate inputs to ensure that each baSIS path is executed once, as
shown in Table 26.4.
26.2.4 Equivalence partitioning The challenge of testing is the selection of a test sct. For example, a funclion such as (ompuI< Fi"c(), which takes a simp le integer parameter day,i.A'c, ha s all of 2" = 4 bill ion possible input values . Any test SC I IS a truly \ln y subset of the collection of all possi bilities. and so we want il to bc as represe ntative as possible. EqUivalence partitio ning IS a black box test method in which paramcter values arc divided into nonovcrlapping selS that constitute the complete set of possibilities (" partitions"), with the values in each partition expected to produce similar rest results . (( we can identify such a partitioning, we ca n have some confidence in a test that selects one value per equivalence partilion as test input. Equivalence panitloning i
also used in system testing, which is discussed in Chapter 28. The potential input values for a test can be thought of as points 10 para",clcr space: an "-dimensional pace
with one dimenSIOn per parameter. For example, if we arc testing a method intended to compute the area of a rectan gle, the parameter space is two -dimensional, each widlhnCHglh pair is a point in two-dimensional spact'. As another example, suppose we want to test that the video Store function discussed above COII«:tiy
computes the flne on late movies. Suppose that the store's penalty depends on the number of days late. usual but also on whether the movie is a new release, old release, or ·one·of·a·kind: The parameter space
Basis Path #1
1
1
5
-
Figure 26.9 Basis paths for compuleFinesQ
1
1
5
-
c:
z
=<
§ 3:
~
~ 0W
'"
1>40
CHAPTER 26 UNIT TESTING
Table 21> • 4 Tests that cover a ll basis pathS Test Case I
daysL.ateO
numDVD
pnntON
Basis pat h
1
11,5,141
3
TRUE
1-2·3·4-5·6-7-8·9-10
2
11 ,5,141
0
TRUE
1-2·10
3
11 ,5,601
3
TRUE
1-2·3·4-6·7-8-9-10
4
11 ,5, 141
3
FALSE
1·2·3-4-5·6-7-9·10
can be thought of as consisti ng of the poi nts shown in Figu re 26 . 10. The parameter space is not limi ted to kgal va lues; it incl ude values that are no t perm itted F'gure 26. 10 lIggem the shape of this pa rameter space. uppo e rh.:n th(" store's Rnc calcul ation requiremt'nt is as (ollows: The Rne shall be $2 per day fo r the firs t 5 days and $ 1 per day after that, up to th e value of the movie. The value of all new releases shall be taken to be $20, o nc-of-a·kind releases $ 15, and old releases $ 10
The parameter space decomposes into correspo nding regio ns such as "new re lease between 0 a nd 5 days late," each haVing the fo llowing pro perty .
1lJ( applicallo" b,hautS in
II
similar
marHl(r
jor nil lJalu(5 hI web r(9,on .
The-se are ca ll ed r4u ilmlmcr partilio"s, o r cc[uil1alrll ct cln sses.
C rea ting equivalence classes ca n be demanding. T o (ocus o n onc region In Ollr Vi deo sto re example, we expect that the algorithm behaves in the same way fo r all of the paramete r points in the ' I(W "fcasr/6- 15 days Ia/, part ition shown in Figure 26. 11 .
Each element represents a pair. (Days late, Movie name)
new releases old releases
....·1 1111111111:"::111111 ::::: •• ::::: 111111111111 :.:: 111111 ::::: • • . ..!~ 111111 ... ....· 11111111111 ... ••
,,, ,,,
• one-of·a-k1nd •
,, ,, ,
••• • • • ••••
• •••• • • •• • • • • ••
•• • ••
...-....-..- ..................._.- ........... -5 o 5
~
•.g., (6 days late, "Casablanca-)
fl&un! 26.10 Parameter space for COIllputeFlneso
,, ,,, ,, , , ,
•...... -........ -................. .......:>10
•,
15
Days late
UNIT TEST METHODS
•• •• •• •• •• •• •• •• •• ••
new release .-. ~ ~. - . -
._......I.... _--_...- .. __.---_.._-- - .-,
o
5 Days lale
RlUre 26.11
One equivalence partition of COmputeFinesO
I new release old release one-of-a-kind
•• ••••• ••••• •• ••••• •••••
•
•••• • •••
•• ••••• •••••
I -5
o
5
I 10
15
Days lale New release DVDs 6-15 days lale
Agure 26.12 Equivalence partitions of computeFineQ method
A full parameter space equivalence partition for this example is shown in Figure 26. 12 To identify equivalence par1itions , determine the limits or boundaries on the individual variables or combinations of variables. These limits can be seen either in Ihe code itself or in the requirements that the variables reAect . Often , the relevant requirements are in the form of bUlinm ",ItS . The ~ne policy of the video Slore example is a good example of a rule for doing Ihe business of renting . Once the equivalence partillons have been determined, we creale test cases as in Figure 26. 13.
26.2.5 Boundary value Analysis Many errors occur at the boundanes between equivalence classes . As an example , co",pultFillt(J contains a boundary between 5 and 6 da ys late , because at 6 da ys a nne slarts accruing . A common coding error might be
Test '"
•
•
• •
•
•
•
values strictly within each region values at region borders
NOles: • Includt aI/ II/,gal "!I'OIlS • With," tach conslralnl, " ltCl randomly • For "",,,,pit. "/Ih "ntw "leaSt" inpIII,
,tlrel laltn rsl
d.Y'
al
random brlwtt" 6 ,/lid ' $, rxc/lldill!l 6 "lid
IS
641
642
CHAPTfR 26 UNIT T.ESTlNG
u e ">;· 111 lead of ·~· when checklll S for a boundary condillon For example , th e ode Ihat c heck. (or the PlnD "lr,rsd6- IS tiny 'nlr equivalence clas in rOlllplllrFIPlr() sho uld read as foll ows 10
i f (( numDaysLat e > 5)
&& (numDaysLate
<= 15))
H owever, a common error IS to wnte code like the (allOWing
i f (( numDay sLate > = 5)
If we were to
uSe
&& (numDaysLate
o nl y a value of 6
10
<= 15) )
lest this equivalence class, Ihe boundary error would no t be
delected. Values equal to and o n cilher side of a boundary hou ld be lested . In Ihe example above, we arc tnlcrested in leSi ing the eq uivalence class wilh values in Ihe range [5 .. 15 ], inclusive. Test cases shou ld be executed Ihat include the following values for PI"tnDaYSu,lr as inpul ' 4, 5, 6, 10, 14, 15, 16 In ge nera l, one identifie boundaries as follows, the principal sources for unit testing being cia s Hwananrs and method preconditions.
1. Identify all of the variables involved , global and local.
2. Identify their limits, individually and in combination (example, the co ndition 2< x+y<7 identifies 2 and 7 as boundanes for ny). 3. Test for combinations of these variable/combination/values. Testing all combtnations is ideal but when this is Impractical , wc select those that appear most likely to fail or we select combinations at random or
bo th. NOle th.t 2 betng a boundary for x+y implicales the straight line x+y; 2 in the x-y plane as a boundary.
26.3 TESTING METHODS Unit testing typica ll y stans by teSiing the melhods of a class. In this section we discuss how to carry this out in an orderly way. incorporating the methodologies covered in the prevIOus sec tio n.
26.3.1 Checklist for Testing Methods Humphrey [3] recommends the checkllSls in Table 26.5 for perfo rming method tests.
26.3.2 organizing Test cases By now you may be overwhelmed by the sheer number of different types of tests . Several t t over l ap. cs types For example, a test with normal inputS may have statement coverage branch cov-rag d h ,. . . .. . .... c, an pat coverage. One way to Slmpltfy and organize the Untt tests IS to lISt the testin g types as in Table 266 d L _ h " d I d' I . , an to numucr t e In d IVI ua tests aceor Ing y .
26.3.3 Stubs A method frequently depends on class« other than the one containing I't Th' • IS pre ents no probl 'f h needed c1ass« have already been built and tested. Otherwise, we use stand. ' . h L em I t e inS Wit tnc same name but with
TESTING METl100S
TIllIe 26,$ Humphrey's unit-testing checklist, categorized black bOxor Whlte bOx In the context 0 f a me!hod test
operatIOn
Comment
1. verify operation at normal parameter values
a black bOx test based on the unifs requirements
2. verify operation at limit parameter values
black bOx
3_verify operation outside parameter values
black bOx
4. Ensure that all instructions execute
statement coverage
5. Check all paths. Including bOth sides of all branches path coverage 6. Check the use of all called Objects
white bOx
7. verify the handling of all data structures
White bOx
8. verify the handling of all files
white bOx
9. Check normal termination of all loops
white box: part of a correctness proof
10.Check abnormal termination of all loops
white bOx
11.Check normal termination of all recursions
white bOx
12. Check abnormal termination of all recursions
white box
13. verify the handling of all error conditions
gray bOx
14. Check timing and synchronization
gray bOx
15. verify all hardware dependencies
gray bOx
just enough substa nce to support the method under test. These are call ed slubs. For example. suppose that we want to test the ,,,,'0 method in the R",lal class of the video store application framework . It depends on the classes R",'alI'tm and R,"laICuslomtr as shown in Figure 26. 14. \Vle therefore create stubs for these two classes as shown. Simple stubs like these are not .ufAcient beyond the method-testing level. As we will de cribe in Chapter 27. in that case we require artifacts known as "drivers" as well.
26.3.4 Exam ple of a Method-Level Unit Test As an example of a unit tcst . we will test for the fo ll owi ng detai led requirement for the Encounter cas. study. 3.2.EC. I.2 Qualities of Encoun ter characters. Every game character has the same se t of qualities. Each quality sha ll be a nonnegative floating POlOt number with at least o ne decimal of precision These are all initialized equally so that the sum of their values is 100. The value of a quality can not be both greater than zero and les. than 0.5 For the Am release the qua lities shall be (Oil tt,lmli" • • sl'''''M. ,."I/'9mCt. palltllrt . and sl""'9 Ih . An approp"ate test ,et for a method adjusIQllalily(Slrlll9 4,mlilyP. floal vallltP) , gIven next Thi method sets the qualtty named by 4ualiryP to valutl' and ad;u IS the rema ,n ing qualt ties so that the proportIon of the remaining avaIlable points rema,ns the sa me Within each of the "on ranKt boundnries: ' Ollts d~ rang~:
'43
644
CHAPTfR 26 UNIT TESnNG Table 26.6 Checklist lor unit tests an example showing which tests fulfilled each question Tests
Test type 1. Within bounds?
1, 12, 14, 15
2. On boundary?
12,3,5
3. Out of bounds?
6,3,4
4. Covers all statements?
9
5. Covers all branches?
1 1, 10
6. Covers all paths? 7. ASsertions tested?
12
8. Use all called objects?
6
9. verifies handling data structures?
8, 7
10. Handles all flies?
12
11 . Tests all loops with normal terminations?
12
12. Tests loops with abnormal terminations?
7
13. Tests all normal recursions?
N/A
14. Tests all abnormal recursions?
N/ A
15. Tests all error conditions?
11
16. Tests all synchronizations?
N/ A
17. Tests all hardware dependencies?
N/A
Rentalilem neededByRentO
-----
Rental
- -----
RentalCustomer neededByRentO
./ ........- - - - - - - dependence
Rental
. . . . --------<'0' ,estin~g;---------// stubbsd
fl&ure 26.'. USing stubs to test a method
resnNG METHODS
Unit test 01 sdjustOuafllyO
Within range
fIIU/'I! 26.15
On boundary
Out of range
Partitioning iJdjustQualityO at the top level
Within range
Does not result in zero
concentration
stamina
Results in zero
concentration
•• •
stamina
•••
FIgure 26.1 6 Partitioning adjustQualityO-" within range"
and ·within range" categories, we try to obtai n systematic coverage by seeking represe ntatives of eaeh equivalence partition . Figure 26. 15 is typical of a systematic deco mposi tio n of the input space into equivalence partitions. The next levels of partitioning are shown in Figures 26. 16, 26. 17, and 26 . 18, and the actual test ca es are listed below. A resulting test suite is s hown in Table 26.7.
On boundary
Parameter:;:; total current points
Parameter :;:; zero
concentration
stamina
concentration
•• •
stamina
•• •
Fl&ure 26.17 Partitioning adjustQuality(}-"on boundary"
Out 01 range
Below lower limit
Above upper limit
=t CXlI1Cantration
stamina
...
26.11 Partitioning adjustQuallty(}-" out of range "
concenlration
slamlna
...
U5
~6
CHAPTER 26 UNIT TESTING
Table 26.7 A test suite for adjuSrQualityO Key to unit tests of adjusrQualltyl} (Details for each test follow this table) 1. Within range
1.1 adjustQualiry(} does not result In a zero value 1.1.1 quality parameter ;; "concentration"
..
' " 1.1.2 quality parameter ;= stamina •
•
•
1.2 adjustQualiry(} does result In a zero value 1.2.1 quality parameter = '"concentration" 1.2.2 quality parameter ;= "stamina" • • •
2. parameters at range boundaries 2.1 zero parameter
2.1.1 quality parameter == "concentration'" 2.1.2 quality parameter ;; "stamina'" • • • •
•
• •
2.2 parameter value = current lotal points
2.2.1 quality parameter =; " concentration" 2.2.2 quality parameter ;= '"stamina" •
• •
3. Parameters outside range 3.1 Above upper limit of parameter values
3.1.1 quality parameter = "concentration" ; total points ; 100; parameter 101
.. . 3.2 Below lower limit of parameter values
3.2.1 quality parameter = '"concentration'"; total points = 100; parameter -101 .. .
The following a", th e details for each of the tests. Test 1.1.1
1"""" (Ideally, choose these at random between 0 and 100 to sum to an amount les than 100.) Concentration 10, Sl
TEST-DRIVEN DEVELOPMENT
&".<11'1/ .... ,""" Concentration 20 + 10 = 30, Stamina 70/4 = 17.5, (Note, remains 1/4 of the non ·concentration" points), Intelligence 70/ 4 Tests 1.1.2, 1.1.3, '"
= 17.5, Patience 70/ 4 = 17.5, Strength 70/4 = 17.5,
are similar, using the other qualities Instead of concentration.
Test 1.2. 1
I'PIII, Concentration 20, Stamina 20, Intelligence 20, Patience 20; Strength 20, adiustQualiry('"conC"rtltmtioll". 99) Exprcl
Tests 1.2.2, 1.2.3, ... are similar, using the other qualities instead of concentration . Test 2. 1.1 I.pu" Concentration 0, Stamina 25 ; Intelligence 25 ; Patience 25, Strength 25 , Exrcu't , aaiu"Qualiry(",lamilla", 7' ) Exptclta outpu" Concentration 0; Stamina 99; Intelligence 0 (result of 1/ 3 is set to zero), Patience 0 (result of 1/ 3 is set to zero); Strength 0 (result of 1/ 3 is set to zero) Tests 2. 1.. 1.2, 2. 1.1.3 , ... are similar Tests 2.2, 2.3 , . . . pertain to other extremes. For example, 2.N aaiu"Quality() called with parameter equal ing a current value Input, Concentration 0; Stamina 25; Intelligence 25; Patience 25; Strength 25 , EXtcutt, aaiu,tQualiry('", lamina ". -25) Exptclca ou'put, Concentration 0; Stamina 0, Intelli gence 33; Patience 33; Strength 33-, Test 3. 1.1 Input, Concentration 20, Stamina 20, Intelligence 20; Patience 20, Strength 20, Extcu't, aaius,Qualiry("conctn'ration". 81) Exptctra output, Message to error log stating that adjlls,Qllaliry() was called with out ·of·range input; Concentration 100; (20+81 set to 100); Stamina 0; (after concentration is set, there are no remaining quality points to distribute); Intelligence 0; Patience 0; Strength 0 Tests 3. 1.2, 3. 1.3, ... arc sim ilar Tests 3.2, 3.3, ... are similar to test 3. 1 Test 3.N . 1 Input: Concentration 20, Stamina 20, Intell igence 20; Patience 20, Strength 20; Ext, u't: adill s,Qllal,ry('"conctnlralion". -2, ) Exprcltd OI'P"t: Message to error log stating that IIdjllStQ llalily () was called with out-of·range input; Concentration 0; (20-2 1 se t to zero ); Stamina 25; ( 100/ 4); Intelligence 25 ( 100/4); Patie nce 25 ( 100/4); Strength 25 ( I 00/4). The remaining test set is ge nerated in a sim ilar manner The relevant partS o f the code fo r adi llslQ llaliry arc part o f th e class EncolI,II"Chllracfcr , give n in listing 26 10 found in Sectio n 5. 1
26.4 TEST-DRIVEN DEVELOPMENT All dfective me thod for pe rform,"!! un it testin g IS to co nduct te nng in par.tllel with implementatio n. In fact, in dfective way to "Ulld qualllY in to an impleme ntation i< to specify the tests that an implem entation mll t pass be/orr writing the cndc After wnlln j.( u h a test, o ne add. to the impl ementat ion lIntil the teSt '" ceeds
647
648
CHAPTER 26 UNIT TESnNG
Th" " called ItS l-dmlCll droc/opm"'1 (mDl TDD is ofte,; a"oclated with ag ile devel o pm e nt, but ,t w, lh,n any developmenl process The general sleps Involved in TDD arc as follow s: I.
IS
useful
Write a leSI case for some code lhal " yet 10 be IInplcmcnled Envi ion what lhe code is suppa cd 10 do. Dependlllg on how tho roughly this part of th e code was previously designed , a bit of dCladed de
2 Run the lesl case to verify it, which fa ll . The first nln of the Icst shou ld always fai l, since the code to make it pass has yet to be written . If it does pass, there Iii; a bug in the tcst case and It needs to be fixed . 3 Wrile only as much code as necessary to make the leSl pass. In th is wa y
il
clean implementation emerges with minimal extraneous code.
4. Run the lest case .
lf il slill fail s, go back to Step 3 and fix Ihe problem in the implementallon. It il passes, the test ca e is complete. If there is morc Implementation to be done, repeat these (our steps .
Figure 26. 19 summarizes this process . There arc many advantages to mD, includi ng Ihc following : Stalement coverage-A natural by· product ofmD is thaI after the lests arc wrilten and pass, every line of code is executed by al IcaSl one tcst . Thus sta tement coverage is satisfied . Cleaner code-As we men tioned previously, only as much code as necessary is written to make a tcst pass. TI"Iis results in an implementation that tends to be clean and contai ns little extraneous code.
Rapid feedback-Once a seclion of code is wrillen , it is immediately tested , providing instant feedback as to its correctness. TI"Iis leads to quicker development time a,s bugs are easier to identify and correct.
Suite of unit tesls-After a test is wrillen and passes, It is saved along wilh olhertests being developed. In this way a suite of unit tes~ iscreated and can be used for huurc te sting activities uch as regression tC'Sting.
II is common to perform mD within a testing framework such as JlI"'t, which we describe next.
, . 2. Write a test case (wiliiall)
_-+I rest falls
3 . Wrile/flx code 10 pass test
Test passes. more tests to be written
4 . Run test case Test passes, no more tests to be written
FIgure 26.19 Test·drive developlilent-the activities
TEST·DRIVEN DEVELOPMENT
26.4.1 using JUnft for Unit Testing ]U.1t is a public·domain te t framework widely used to "wnte and run repeatable tests" [4]. It is implemented In and u ed for testing Java programs It supports lInit testing with tools lor test result executio n, reporting, and error handling . uppose, lor example, we have a Calculator class and we want to write a test lor a yet.to·be coded ubtract method. 11 we are uSing TOO, the Rrst step is to write a unit test lor the enVisioned method. By convention. when testing a clas X, tests arc placed in a clas TtS'X and every method perlorming a test 01 method mmmm {) is labeled ItSlMmmm O. listing 26.4 is a Teste alew/ator class that co ntains One test called IrslSub'racl.
26.4: JUnit class for testing Calculator ~rtjunit.framework.TestCase;
public: c:l . . . TestCalculator extends TestCase { public: void test Subtract () { Calculator c new Calculator () ;
=
/ / Test 1: Nominal Case double r = c. subtract (2.0000000001, 3.0000000002) ; assert:Equals ( -1.0000000001, r, 0) ; / / Test 2: Corner Case r = c. subtract (Double . MA)CVALUE , Double . MA)CVJlLUE) ; assertEquals (0.0, r, 0) ; •
•
•
}
}
By ~xamining testSubtract we can imagine the code we must wntc to pass the test : I A subtract method that takes two double arguments and returns a double result.
2. An implementation of a subtract method that subtracts the second argument from the Rrst and returns the result of the subtraction . To fulfill our envISioned method, we write a subtract method such as in Listing 26 .S.
Llltlna 26.5: Building subtractO method for the class Calculator package EB . calc I public class Calculator {
649
650
CHAPTER 26 UNIT TESTING
public double subtract(do u ble n1 , do uble n 2) {
ret u r n n 1 - n 2 ; } }
, ..'
nrrul
-----_. ----- -
.. -
1I!I . . . . ~R2',.
I
-
Figure 26.20
I
•-
•
u '"
Outp~t of JUnir for a simple test
The result of runn ing T estCalcul ator in J Un it is the wi ndow in Figure 26.20 showi ng a g reen bar (for "passed") . T o illustrate what hap pens when a tes t fails. we wi ll fo rce a d efec t with a new subtract that erro neo usly converts to float , as in Li sting 26.6.
Ustlng 26.6: Example of a test that will fail
package EB. calc; public class Calculator {
public double subtract (double n1, double n 2) {
float subtract ion = (f loat) n1 - ( f loat) n2; return subtraction; } }
TEST·DRIVEN DEVELOPMENT
~;;;;; e~e" ed ... , 000000000 1" butwa s '- I 0' al EB calc TestCalcutalor.testSublr.ut(TestCalculalor Java.! ' ) at sun retlect.Nallve MetnoClACcessorlmpl tfft'OkeQ(Nattve MethOd) at sun reneclNatJvelrllettlOdA.ccessorlmpl lnvoke(lJnknown Source)
Figure 26.21 Junit display for a failed test
Re-executing the testSubtract unit test from Listing 26.4 results in aj Uni t response like that shown in Figure 26.21 , with a red bar indicatin g failure . In o rder to run multip le unit tests, j Un it imp le ments th" TtSrS",r, class. Suppose that in additio n to the T,srCa/cuiaror/Ca/cu/aror pair we also have a T,srCo"wr,,,"rorICo,,cnrttl" ror pair, as shown in Listings 26 .7 and 26.8, respective ly. If we run j Unit us ing t he TtS rAll class show n in Listing 26 .9, bo th of these tests will be execu ted .
Ustlng 26.7: Test for Concatenator class
import junit.framework.TestCase; public class TestConcatenator exte nds TestCase (
public void testconcatenation() (
Concatenator c = new Concatenator () ; Str ing str ing = c . concatenationOf ( " abc ". "def " ); assertEquals ("abcdef ". string) ; }
}
651
652
CHAPTER 26
UNIT TESTING
Listing 26.8: Concatenator class public class Concatenator {
public Str ing concatenat ionOf (Str ing as t r ingl , String aString2) {
return aStr ingl . concat (aStr ing2) ; }
}
Listing 26.9: A TestSuite example, combining tests for Calculator and Concatenator import junit . framework . Test ; import junit . framework . TestSuite ; public class TestAll extends TestSuite (
public static Test suite() {
TestSuite testSuite = newTestSuite ( " A simple test suite example " ) ; test Sui te . addTestSuite (Test Calculator . class) ; / / Add all test s from TestCalculator class test Sui te . addTestSuite (TestConcatenator . class) ; / / Add all tests from TestConcatenator class return testSuite ; } }
26.5 CASE STUDY: ENCOUNTER VIDEO GAME 26.5.1 Code Ustlng for Encountercharacter Class listing 26. 10
IS
the class EncolmtrrCbaractcr from the Encounter video game.
CASE STUDY: ENCOUNTER VIDEO GAME
10: EncountefCharacter class from the Encounter video game
1* Class Name:
EncounterCharacter • Date: 01/13/2000 • Copyright Notice: copyright (c) 1999-2000byEricJ. Braude * Edit history: * 24 Dec 2003 Er ic Br aude Edited to simple stand-alone version to show unit test of adjustValue () * 24 Jul 2000 Tom VanCourt Cached character image rather than * recreating it on every repaint. * 13 May 2000 Tom VanCourt Moved saveQualityValues , getOldValue * and oldValueI from Player Character
•
*/
ioIpOrt ). ava. aw t . * ; . . *; ioIpOrt)ava.l.o.
1** Base class for the characters of the Encounter game. * * * * *
Design issues:
Requirement
3 . 2 . EC. 1. 2
*/ public atatic tlnalllo.t OUAL_TOTAL_INIT
= 100. Of ;
// Symbols used when other classes refer to specif ic qualities.
/** Symbol f or one of a charac ter ' s quali ties * / publ.1c ataticflnal String
OUACCONCENTRATION=
"concentration";
653
654
CHAPT1:R 26 UNIT TESTING
/ **
Symbol for one of a character's qualiti e s */ public static lind Str ing QUAL_INTEL LIGENCE = "in te lligenc e " ;
/ ** Symbol for one of a character's qualities * / public static lind Str ing
QUAL_PATI ENCE =
"pat ience" ;
/** Symbol for one of a character's qualities * / public static final St ring QUAL_STAMI NA = "stamina" ; /** Symbol for one of a character 's qualities * / publl.c static final String QUAL_STRENGTH: "strength";
/ ** Qualities that each Encounter character possesses.
*
Reg: 3.2. EC. 1. 2
*/ protacted static final Str ing [1 qualityTypeS = (
QUAL_ CONCENTRATION,
QUAL_STAMINA,
QUAL_INTEL LIGENCE,
QUAL_PATIENCE,
QUAL_ STRENGTH
) ;
/** Root directory for graphics files. */ static find String
FI LE_ROOT
= "edu/bu/braude/SWEngExample/";
/*
INSTANCE VARIABLES * / / ** Values of the qualities.
Requirement 3.2. EC. 1. 2 protectad float[ 1 qualValueI : n•• fIoat [qual it yTypeS . length 1 ;
*/
/** Quality values before the last engagement *
Requirement: 3.2.AR.4.6
*/ protectad float [ 1 oldValueI = n•• fIoat[qualValueI.lengthl;
/** Name of GIF file containing the character image. * The character in this image is assumed to be facing left. * Select this character's height, relative to heights of other * char acter s, * by padding the to~ and bottomwith transparent pixels. No padding gives * the tallest posslble character.
*/ prohct.ad String imageFileNameI: null;
/** Displayable image for the character. Initialized when used. */
pri.Yata Image chImage I = ma.ll;
/*
CONSTRUCTORS
*/
CASE STUDY: ENCOUNTER VIDEO GAME
655
/ ** Allocate initial total qualitv oints
. . "
Requ irement . 3 2 E - p . equally among the quall.t:les. "/ . . . C.1.2 (qual:ltyvalue initialization)
~uct.1
{
EncounterCharacter ()
Lupn ( ) ;
for( int i = 0 ; i < quali t yTypeS . length· ++ i) qualValue I til = QUAL_ TO TAL_ I NIT / qu'ah. tyTy peS . length; . saveQual:ltyValues() ; }
{"* Construct a new character using the given name .
Requ:lr emen t : 3 . 2 . EC . 1 . 1 (char act e r naming ) * @param nameP Printable name for the character .
*/ Encount erChar ac ter (St ring nameP ) this (nameP, null ) ;
protected {
}
/ ** Construct a n ew character using the give n name and i mage file . *
Requirement: 3 . 2 .E C.l.l (c haracter naming ) * @param nameP Pr intable name for the character . *@param imageFileP Filename , relative to docume n t base, * f or the character image file .
*/ protect.d {
Encoun terChar acter ( Str ing nameP, Str ing imageF ileP )
thia ( ) ;
setName (nameP) ; imageF ileNameI =
FILE_ ROOT +
imageF ileP;
}
/ * KETHOOS * / /** Adjust qual ity values , normally retaining a co n stant total. * Synchr o nizat ion holds qualityValueI constant even with other * threads running . ..
Invariants: see the class invariants ..
Preconditions : qualityp is in qualityTypesS [1 .. ANO q ualityValueP >= 0 .. AND qua lityValueP <= the sum of the quality values *
Postcond itio ns: qualityp has the value qualityValueP .. AND the rema ining quali ty values ar e i n the same proport ion as pr ior to .. invocation , except that values less tha n some tolerance are zero . ..
SOD : 6 . 1 . 2 . 1 . 1 ..
SRS : 3 . 2 . EC . 3 . 2 : " Conf igurab ili ty of Encounter character qua li ty .. values. " "@param qualityp Quality whose value is to be adjusted .
I
656
CHAP! fR 26 UNITTfSnNG
* @param
qualityValueP
The value to set this quality to .
*/ public ayncbronizad void adjustQuality (Str ing qualityP, float qual i tyValueP) { / / Value of the quality to be changed float quali tyValueM = qual Value I [indexOf ( qual i tyP) J ; / / Save the sum of the values float or iginalSumM = sumOfQualit ies ( ) ; / / Set the stated quality to the desired amount, / / adjusted to the threshold value. setQuality(qualityP, qualityValueP); / / If the caller adjusts the only non-zero quali ty value, / / divide the adjustment amount equally among all other quali ties. if (or iginalSumM == quali tyValueM ) {
float quaU tyDiffEach = (or iginalSUmM - quali tyValueP) / (qualityTypes.length - 1); for(int i = 0; i < qualityTypes.length; ++i ) if( ! qualityTypeS[ iJ . equalsIgnoreCase ( qualityP ) ) setQuality(qualityTypeS [ iJ, qualityDiffEach ) ; } ala. {
/* Compute factor ("proportionM" ) bywhich all other qualities must change. * Example: if the valueswere 1,3 , 5 (i . e . sum9) and the first * qualities changed from 1 to 2, then "3" and "5" change from B/9 of * the total to 7/9 of the total, so each should be mul tiplied by 7/B , * Le., by (9 -2 )/(9-1).
*/ Coat proportionM = (or iginalSumM - qualityValuep ) / (or iginalSumM - qualityValueM ) ; / /Adjust remaining qualities, retain i ng their mutual proportion for(Uiti=O; i
/** Get a copy of the list of names of quality values. *@returnworkingcopiesofnamestringsr eprese ntingqual . t ' */ ~ ~es public aUtic Str ing[ 1 getQualityTypes () {
.
CASE STUDY; ENCOUNTER VIDEO GAME
Str ing ' [] r eturnListM = // Copy the s t rlng . . array . IIZ1I St r l.ng [ quaIl tyTypes . length J ; for(1Ilt i = a'; i < ~ali
/* * Returns the value of the specified quality . quali tyP is a valid member of qualityTypeS [J *
precondit ion: * @param qualityp The quality we want the value for. • @return The value of the specif ied quali ty .
*/ pablicf!olt
getQualityValue (St ring qualityp)
(
return qualValueI [ JndexOf( qualityp ) ] ; }
/** Quality values below this threshold are set to zer o to * avoid having the game go on for an indeterminate amount of tim e . *
Requirement:e.g.3.2.EC.l.2 ( 10werlimitonnon- zeroqualityvalues ) *@return Tolerancevalue
*/ atat.icflndfioatgetTolerance () { HturnO. Sf; }
/** Returns the index of the the specif ied quality . •
Precondi t ion: qual i tyP is in qualityTypeS [ ] , * give or take capitalizat ion . *@param qualityp The quality we are searching for . *@return Thequalityindex.
*/ protlctlcl.tatic int
indexOf ( Str ing qualityp)
(
//Default to "missing" value. iIIt r e tur nlndexM = - 1 ; // Search quality name table and not e t ,he i nd ex value. fo,. (illti =O · i < qualJtyTypes . length; ++1.) 1f (qua l1ty~s [i] . equalSlgnoreCase(qualityP» { return lndexM = i; } zoetum
}
returnlnd e xM;
657
658
CHAPTER 26
UNIT TESTING
/ ** Set default max imum number of characters in names of charact e rs . *
Requir ement : 3 . 2 . EC. 1 . 1 (1 iroi t on char acter name l e ngth) *@return Maximum number of characters allowed in a character name
*/ protect odint maxNumCharslnName () {
return
15 ;
}
/ ** Preserve the current quality valu es . * / publl.csynchronizedvoid saveQualityValues ( ) (
(i nt i=O ; i < qualValueI . len gth ; i++) oldValueI [i) = qualValueI [i) ;
for
}
/ ** Set a quality value without regard to the values of other qualities . * Truncate any value below the threshold value down to zero . * Synchronizatio n prevents cha nges to qualityValueI while other * threads ar e using it . 3 . 2 . EC . 2 ( l ower limitonnon- zero qualityvalue s ) , *
Requirements : *
Precondition : qualityp is a valid member of qualityTypeS [ ) *
Postcondition : Quality values are greater than to l eran ce or are O.
*
*@param * @param
qualityp valueP
The quality to s e t the val u e of . The valu e to set t h e qua l. ity to .
*/ publicayncbronizeclvoid setQuality (Str ing qualityp, Coat valueP) { i t (valueP
< getTolerance ( ) ) qualValueI[ indexof (qualityp») =O . Of ;
.1_
qualValueI [ i ndexOf (qualityP) I =valueP ; }
/** Computes the sumo f the quality values . * Synchronization mak es sure t h at a n other thr ead wo n' t c h a n ge * qualityValueI wh il e th is th r ead ispart -way thro ugh computing the * total . *
Requireme nts : 3 . 2 . EC . 3 . 2 (proport ions among quali tyval ) * S RS 3 .2. EC .3. 1 Ll.vl.ngp0l. ., . nts ues , * @return The sumof t h e player ' squalities , a value 0 or great */ er . publ1cayl>cbronlzodfloat sumOfQualit ies ( ) { float sum!! = O. Of ;
CASE STUDY' ENCOUNTER VIDEO GAME
forCint i=O; i
} / / end of EncounterChar acter
26.5.2 Unit Tests for the Encountercharacter Class ote to the Student: The format of this docllm ent is derived from the IEEE Standard lor Software Test Docu mentation This document applies to the tes t· ing 01 one class. JUnit was not lIsed in tillS case but could have been .
For si mpl,ci ry , thi s unit re t includes teS t data with the method . Normally , ho,,'cver, the Input data and the expected output are rc · tri eved from a Ale .
3. Test Procedure Specification TI, e unl! test' for E"co",,'rrCbnfllCltr arc IOltiated by execut ing the ",mil O method of EncounlrrClJn rncttr
The parameter su pplied to mni" O speCifiC the fl le
UNIT TEST FOR THE
to wh ich th e rc ult are wnncl1
ENCOUNTERCHARACTER CLASS
1. Test Design Specification The unit te~l (or Eli collnlerClJnraclrr co n
1St ....
of rwo
public methods as follows.
This is a si mple procedure . H owever, the procedure becomes can iderably more complex when sourCe flies and u er interaction arc involved For example , this will be the case in unit tes tin g the class E" o""'trG",",
ItSIE"co""lrrOlflracltrM"hod.O teSt- cach of the methods in rurn
ItsIE"co""'trChararl,, 1a sO test<
4. Test Results Documentation The test re lilt documentatio n o n"5r, of the te t log , tt·
The,c methods ca n be executed by E"co",,',,Cha"",d, mamO method or by an external ob)cLl
4.1 Test Log
2. Test Case Specification The i.est cases for £"(0""'''( /",,"(/tr are bu d t
1111 0
InIEHco""'trCha"'
IrP( 1us.(J
Till I< an ac ount of the tt' 1', result. eX' l1lrle helow
et, the
65.
660
CHAPTER 26
UNIT TESTING
1l\1~ IS co ntained in RIc Etlcolmlcr bllradt,_
4.2 Test Incident Report This Includes any occurrences or noteworrhy ~vc:nrs that occur during te ting Sec the exam-
ple below
In
file E",oulllrrCl}fIrtlClt,_Ttsl_
1n""Jntf_da)' _molll" Jcnr doc
4.3 Test summary Report This
IS
contained in fi le
f" co,m l,rCharael"_T",-Sum'M'Y_R,porCdQ)'_ lI1otllh-ywr. doc EX
< < <<
1234567890 12 345 < - - Obtained 1234567890 12 345 < - - Requ ired Expect one name
rOT
each charactcr
Querry defaultName 1234567890 12345 » » i ndexOfO Test I: valid quolity nome ««< Actual tntc:gcr
=
I
nominol volue
««< Ac tual Ooal = expecled Aool. » » selQuolityO Tesl 2: nominal value
Tnl_Lo!l_dllY _molllh-J,tnr doc
Thi s IS co ntained
» » setQuoIIlYO Test
««< Actual Aoal = expecled Aoal. > > > > adj ustQuahty() lest 0: verify that values add 10 100 « « < AClual Aoat = expected floal. > > > > adjustQ uali tyO lest 1: ve ri fy values sum to 100 afrer adj u l,ng « « < Actuol Aoat = expected Aoar. > > > > adjusrQua l,ty{} tesr 2: verify values adjusred as commanded « « < AClual floal = expected Aoar. » » adjusrQuo li ty() tcS! 3: verify low va lue reve rts to zero « « < AClual Aoat = expected Aoal. > > > > odjustQuality() ICS! 4: veri fy values sum 10 100 ofrer odJusring < < < < < ACluol Aoat = expected Aoat. C lass test : » » Class ICS! ge-aq-so « « < 100.0 < - - Ob lained 100.0 < - - Required » » Cl055 test ge·aq·aq-gq ·so: part I «< « 20.9876 < - - Obtained 20.9876 < - - Required » » Closs test gc ·aq-aq-gq-so, part 2 «< « 100.0 < - - Oblained 100.0 < - - Required » » Class lest for Ihe invariant '_q uaIValue [iJ >= 0'« « < true < - - Obta ined tn'e < - - Required The leS! log example doc:s not show failed t~ts. These can be delailed in Ihe log, transmitted 10 a separale fi le, and con ge nerale monilor leXI.
expected in teger.
» » lndexOfO Test 2: volid qualilY name ««< Actual Integer = expected integer.
Example of a Test Inc,dent Report ( eelion 4 2 of the Pe"onal Soflware Do ume nrion ): f"co.,.;"
Cbarael"_T" '_/lIcidtlll_26_Jul_199. dO<'
CASE STUDY: ENCOUNTER VIDEO GAME
Th( test was allemptcd With version 7.2. I of &. o"."rCbarael" using version 2.3 of the TrslUliiilits package . On th e first try , the test fa ded to run . We think that t his wa due to the fact that we did not really have version 2.3 of Ttl/liIiiilit! . When we ~Ioaded this package , the test ran without Incident. This is a good place to mention mistakes made dunng testing. These are particularly prevalent when user actions are required, and it is impractical to rerun the e ntire test.
Example of a T est Summary Report (Section 4.3 of the Personal Softwa re Docume nti o n): Elleoll.'''' CbaraeICT_T lSI_Summary _26_111'_' 999 doe This test was executed by Joh n Jones at 2:00 P.M. using release 1. 1.6 of Sun's virtual machine . Subject to the anomalie in the test incident report , the results were 100 percent pass o n the bui lt -in unit t<st methods. These met hods were inserted by
E. Braude in version 6.5.2. They are due to ~ expanded in later versions of EHeO"HltrCbaraCltr. Example of Unit Test Source Code: The fo llOWi ng code, for the EHcowHlrrCharaCltr class, includes self- test methods. The class TtslEx
listing 26.11: Control for testing EncounterCharacter
1** To test th is class
* @param
argsP destinatian .of methad test lag, class test lag * respectively *l public static void main ( S t ring [J ar gsP ) {
II Default files an which ta write test .output
run tests Str ing methadOutputF ileNameM = "methodOutput. txt" ; Str ing classOutputF ileNameM= "c lassOutput. txt" ;
i f (argsp !
= null
&&
argsP . length == 2)
&
I I use defaults if input
• lmpraper { methadOutputF ileNameM = argsP [OJ ; classOutputFileNameM = argsp[lJ ;
}
I l l . EXECUTE TESTS WHICH DO NOT REQUIRE HUMAN INTERVENTION I I Test methads individually , then test class try
{
testEncounterCharacterMethods(methodOutputFil eNameM);
661
662
CHAPTER 26
UNITTESTING
testEncounterCharacterClass(classOutputFileNameM) ; } catch (IOE xc e ption eP) { System . out . println (eP) ; }
//2 . EXECUTE TESTS WHICH DO REQUIRE HUMAN INTERVENTI ON Frame [) imageTests: { // Display test cases new testCharacterImage ( // Missing image new Enc o unt erChar acter ( " GuyWi thNoImage" , null ) ) , new testCha ra cterImage( // Image is present new EncounterChar acter ( "E lena ", " e lena . gif " ) ) } ;
for( i nt i = 0 ; i < imageTests . length ; i ++) (/ / Display each t est window image Tests [i) • setSize (400 , 250) ; // Adequate size for char acter imageTests[i) .setVisible( true ) ; imageTests[i) . show( ) ; }
try {
// Let user examine windows Thread.currentThread() .sl eep(30*lOOO ) ; } catch ( Exception exc) { }
for ( int i = 0 ; i < imageTests.length ; i++) imageTests[i) . dispose();
// Shut the windows
System.exit(O ) ; }
/ ** Tests this class by executing its methods in combination * @param destinationP Location to write results * @exceptio n IOException I f there's a problem opening or accessing * destinationP
*/
Class testing is covered systematically in Chapter 27. It consists largely of testing
combinations of methods The code testing EncOImrtrCbarncftr is given in the cas< study th
26.6 SUMMARY Unir .r"ring ' e IY J fte ' f is conducted by softwa .. develop<" either In conJ'unction w'I th or .1m m ed lat I . a Unit 0 code. Units are typically Ih< methods and cla"es of t L • soft B L L r Imp <menll ng ,,wa.. . Ot" W",re b · d bl k b methods are utilized. ox an ac ox
EXERCISES
Thl! Ilrs! tl!P in unot testmg is Identifying units and dl!termining what they arc intended to do. This comes from one of several sources, the SRS, the SOO . or else a motivation tOO minor to specify in the DO. For methods arising from design, we may not possess explicitly stated requirements against which to pl!rform tests. A systl!matic approach is required to effecti vely implement unit testing. In this way, as man y errors as possibll! at as serious a level as possi ble can be d iscovered within a practical time period and usi ng a prac tical amount of labor. The Arst ste p is o rga nizing the testing-typicall y methods are tested Arst, followed by classes and packages. The extent of testing should be considered and defi ned in advance. Test cases are selected from one or more categories of tests, both fro m no nnal ex pected operation and those judged most likely to fail. Stopping criteria are established in advance; these are concrete conditions at which point this particular testing process will hi! considered done. Depending on the problem space of the software , there is ofte n a set of test data that is pecific to the application . If applicable, obtaining and usi ng this data must be planned . Unit testing is typica lly conducted by deve loper , as they arc the most fa miliar with the structure a nd organization of the code under test. H owever, un it testing is sometimes conducted by a separate organizat io n such as QA because of their object ivity . Th is requires extra time fo r the new o rganization to learn the software desig n so they can successfully executed the tests . As with other phases of development . metrics are co llec ted during un it testmg. Metrics collected include number of test cases, number of tests per test ty pe , a nd percentage of fai led teSts. There are several d iffere nt types of white box and blac k box testing metho do logies empl oyed during UOit testing. White box methods include statem e nt coverage, branch coverage, and path coverage . Black box methods include equivalence partilionin g and boundary va lue analysis . When testing the methods o f a class. a strategy is required to ensure proper test coverage. Humphrey recommends u ing a checklist that includes Ite ms such as usi ng no m1al parameters, parameters at their boundaries, illegal values, handling of error conditions, path coverage, loop termination , timing, and hard,,'are dependencies. After the individual metho ds of a class are tested , the class as a whole is tested . All of the class methods are tested in combina tio n. Th is is because the methods of a class are freque ntl y interrelated as they may alter the values of common class attributes. Focus i placed o n eque nccs likely to be comm o nly used and sequences that appear most likely to contain defects. If an ohject of a class transitions th roug h several states, s!ate·based testing is emp loyed . An effective method fo r performing unit testing . a nd to build q uality IO to a n Impleme ntation, i to specify the tests that an implementation must pass btforr wri ting the code After " 'fi ting a te t, one adds to the Implementation until the test succeeds. This IS called ',s ,·dr",,,, dwt/op,""" (TOD ). T OD IS ofte n associated wi th agile developme nt, but it is usefu l for a ny deve lopme nt p rocess.
26.7 EXERCISES t. In your own words, d escribe t he difference between white box and black box te ting . Why is each Important and ncccss ary ~
2 Why do you think unit lesting is u,ually co nduc ted by lhl' d~vcloper ,vho Impleme nted the unit] 3 a
What is eqUiva le nce pa rt lt ionlng~ \~hy I It Im portant to partitIOn th e te t ,po e into eqUivalence cla sses ~ rlease usc your own wo rd, in re<ponding
b For lhe followll1 /l fun cll o n, de "be five d iffe re nt les t a,cs Jnd for ca h des nbe the type 01 test case II represents The applica tio n i, ha,cd o n Myer, tn ang le prohlem [5 ).
663
6~
CHAPTER 26
UNIT TESTING
Il x, y and z are the lengths of the sides of a tr iangle . This funct io class if ies the Iitriangle and returns either ' ' scalene " , , isosceles" (two sides
Il equal) or "equilat eral "
(all sides unequal ) ,
( all sides equal) . If x, y and z don't
form a tr iangle
II (Le. either (a) x, y or z is <= zero, or ( b) ( x +y ) < z) the null string is returned IIAssumption: x,yandzareinascendingord er ( i.e. x <=y <=z) soyou do not need
li to test for this char. triangle ( int x, int y, int z) { •
•
•
}
4. Explain why testing every line of code for correctness (i.e., 100 percent statement coverage) is generally insufficient for ensuring that a program is bug-free . Give an example of a defect that can go undetected by tests that have 100 percent statement coverage. 5. Why is path coverage a stronger form of testing than statement coverage7 Give an example of a defect that would be detected by path coverage but not by statement coverage. 6. Draw a program control graph for the method adju' IQuality() of listing 26 .4 in this chapter. What is its cyclomatic complexity' Explain your response .
7. Write the code for a class Accou"t with attribute balan", accessor methods, and method add() . Assume that Account has states Sound, Empty, and Arrears, and that these are implemented using the State design pattern . Write a complete set of unit tCSlS for Account, including statc·oncnted tests.
8. In test·first development, why is it imponant to execute a unit test to ensure that it fa,l s before the code it is testing is actually written ]
9. You intend to implement a Recta"gl, class using test-first development . Suppose the class is defined during design with the following characteristics, • Constructor with parameters length and width • Methods getL..:ngthO and getWidthO to retrieve length and width • Method to calculate area of rectangle Write. unit test class to test the as yet unwritten class Rt
BIBUQGRAPHY
unit Tests Perfoml full unll te ts on two signi fica nt methods of your applica ti on. State how long individuals and th~ whole team spe nt o n de velo ping eac h part of these tests. and how the proce s yo u used could have been improved. Evaluation criteria, ( I ) Degr~e of clarity of th e plan (2) Ext~nt to wh ich the plan and test include all relevant aspects of the unit tests (3) Realism of the self·evaluatlon data and improvement plan
BIBLIOGRAPHY I Rapps, Sandra and Elaine
J
W(:yuk~r. "SclC'C IIIl ~
Software Test 1)313 Usmg Datil Flow In (o rm all on," IEEE Trnnsnctto"S on SojlJD,m
&.g'''''"''9. Vol. II . no. 4. 1985 . pp 367-375 1 McCa~. T J.,·A CompleXity Measurc,- IEEf Tr"tI~lCllOtl5 "n 5"jlll.tI(( E"9H1etrltl!/. SE·2, no .. ( 1976), pp 308- 20 3 Humphrey, WaItS S , "MtJI'I49 1119 rl,( Software P'ocr<~ (SEI Srnri m SO/IU)n rc £"9'"(("" 9)," Addr so n·Wt."s lC'y. 1989 4 jUnll org
WW'W
S Myers Gle nford
jun.t org [acccs.:.ed 12/ 14/09 J
J 'Tht
Art of SO/I U1.trt TrS fm9." John Wiley
&
So ns. 1979
665
Module and Integration Testing
Planning
Maintenance Testing The Software Developmen r Ule Cycle
•
How do you test a class?
•
How are stubs and drivers used for testing?
•
What are attribute-oriented lests lor a class? Class invariant-onented lests? State-based tesls?
Requirements analysis
-
Impleifbl nt8tJon
•
What
•
What is big bang Integralton? Incremental? Bottom-up? Top down? Continuous?
•
How do dally bu ilds facilitate
Design
IS
mtegratlon?
continuous Integration?
•
What is interlace testing?
Figure 27 .1 The context and learning goals for this chapter
This chapter dlscuo;",co; tes ti ng beyond Unit IC')llllg-to the module level and to the Inl cgr\luon of modules. Vil e bc:glll by discussing class tl.-sung. Cia'S tc')tmg I con,\1dcred by some to be beyond lImt It''Stln~
and by o thers not so Integration IS the process of assembhng partS to (om, a whole As
3
phYSIcal illustration of thl< o nn.pt .
consider Flgur( 27.2, which IlIuslra tC' the Integ-ration of J ~uspcns l o n bridge . The order of Inlcgr.1tlon and the
STUBS AND DRIVERS
Assembling Ihe parts inlo a whole
Figure 27.2 The meaning of "Integration" -an analogy from bridge·building, steps 1 through 6 manner In which rhe part are te red toget her IS critical for rhe co n,tructio n of the bridge For exampl e, as cmbling ir in the wrong order wdl lead to longer construcrion times, o r worse, a defecti ve bndge u h issues are equally important for the integration of sofrwa re sy tern, likeall engineering artifact , software systems must be bui lt fro m parts. Each part is deve loped and unit · rested separately. The whole i then assembled , /''',gralloll is the process of assembling these parts and te ting the result to ensure that they work together correctl y. A part of a software system to be Integrated can con ist of several lines of code, a whole method . a class, o r an en tire subsystem Aglie melhodo logies use co nti nuous integration and dail y budds as much as possible. We dIScuss th ese on this chapter. An example of a class tc t IS provided In ne case study sectio n. In ano ther, an integratio n plan" descnbed. Both of rhe'e apply to the Video game example u,ed ,n thIS book.
27.1 STUBS AND DRIVERS Consider the coordination issue, a,sociated w,th Integrati ng the parts of an application show n in Figure 27 . ~eral of the part depend on each other yet mu'i be put together ,n some order. \Y/e u'c ,rub, an d drivm for thiS purpo e Simple stubs Were Introduced ,n haptn 26 We e 'amine th em ,n more depth here for Integration t"'"ng, and we also int roduce drivers The left·hand co lumn of F'gu re 27 4
..7
• 668
CHAPTER 27
MODULE AND INTEGRAnON TESTING
Home Office Use
Computes pariS 01 a tax return associated with the use 01 pari 01 the home (or business purposes
uses
uses
Tax Retum Creates an entire tax relUm for many kinds of personal and business situations
Computes the depreciation on various types 01 equipment
Depreciation
Figure 27.3 Stubs and drivers-motivation from a tax return example
Eventual conliguration
Boltom-up
:
Top-down
development or integration
I
development or integration
I
I I I I I
I I
I .------, I
Item 2 __- .... BU-b
Item 2 :
driver
I
Item
1
uses
I I I
I I I
I
I
uses
I I
: I I
'-~-::l
I
I I I
I I I
--' -.., Item 3
I I
I I I I
uses
Item 2 stub
'--
Item 1 TD·C
I I
BU·A
Item 3
I I
•
I I I I I
TD·a
Item 3 stub
•
Figure 27 .4 using stubs and drivers for integration and testing
TI,,,,c remarks appl y just as much to the development of items In the first place as to their integration and lesting .
27.2 TESTING A CLASS Ah'er testang the individual methods of a class, we can move on to Ie ling the class as a whole. This amoun ts to executing tts methods in combination or subjecting: objects of th(: class to event such as mouse action. Rt"Call
that the method of a class are frequently interrelated because they may alter the value, of commo n variables For example, in an Aceo",,1 class, the methods J,posil () and Ul.lhdw wO would both alter the Imlun , van.ble. If
TESTING A CLASS
I Exercise methods in combination • 2-5. typica lly • tcst moSt commo n equence Arst • include sequences likely to cause defects 2. Focus tcsts on each attribute • IOitialize, then execute method seque nces that affect it 3. Verily that dass invariants are unchanged • verify invariant true with initia l values • execure a method seq uence
• verily invariant still true 4. Verily that objects transition among expected states • plan the state/transition event • set up the object in the IOitlal state by setti ng variables • execute event and check that transition occu rred Figure 27.5 Performing class
tests-variou~
focus
dtpoiilO "ere coded in terms of flool , for example. but uJi,/,drauJ() in terms of doublt , the tester may not notice anything "rong in testi ng each indiVidually. For this reason . It may not be sufAcient to know that each method has been individually unit·tested . nlere are several complementary ways of tes ling classes, as shown in Figure 27.5. Each is discussed in this seclio n, and several are illustrated in the case stud),.
27.2.1 Example of a Class Test Each method combination test consi sts of a seq uence of function calls. For the class fll eouHltrebornCI", for example, the methods in Table 27. 1 would be tested in sequences. We concentrate our testi ng resource o n the following : I. Sequences likely to be com mon ly used
2. Sequences that appear most hkely to harbor defect Table 27.1 Example of a class test- labeling methods for use in combination Abbreviation
Method prototype
aq
adjustQuality(String qualityP, float qualltyValueP) deleteFromEncounterCharacters(EncounterCharacter encounterCharaC1erP) EncounterCharacter getEncounterCharaC1er(Strlng nameP) float getQualltyValue(Stnng qualityp) float getSumOfQualitlesQ float getTOleranceQ Int IndexOf(String qualltyp) throws Exception InsertlntoEncOunterCharacters(EncounterCharacter encounterCharacterP) Int maxNumCharslnNameO setQuallty(Strlng qualityP, float valuep)
d
ge gq gs gt 10
II
m
sq
669
670
CHAPTER 27
MODULE AND INTEGRATION TESTING
The follow.ng sequences arc common in playing the gamc.
gc-aq-gs /I get character - adjust quali.ies - get sum of qualoties gc-'q-aq-gq II get character - s
g'-"l -aq-'q-aq-gq II g" characler -
sri
a quality - adjusl qualilirs -
sri
a quality - ad!,'" qua/.Urs - g" quality
\'(Ie will assume that the methods have been tested IOdividually, and we'll concentrate o n sequences of methods that aflect the others. Figure 27.6 shows how the methods in the example chosen rdate to each other through their effect on variables. Steps I and 2 affect the value of the conw,'rolion vanable. Step 3 affects the value of " ""gl/'. In Step 4 . the "amina variable is an input to the adju"Qua/ity() method, which uses this value (and the current value of co"crJltrntio~l ) to change the value of Cotlct'llration . Thus, each method in the
sequence sq-aq-,q-aq affects the outcome of a later method. The interaction among seemingly simple method.s can be quite complexi The case study of Chapter 26 shows these tests in action . The sections that follow discuss ways to tame this complexity 01 choices.
27.2.2 Attribute-Oriented Tests Attribute -oriented tests focus on variable changes, and create method sequences that effect them . A simple example for an Acco""t class is to have the balance grow and shrink to zero. To do this, we could execute t he sequence ",Ba/aH"( 50); addToBalan,,( 70) ; d,ducIFromBa/a"er( 120); g,'Ba/aller() . \'(Ie va lidate the predicted balance. The example in Figure 27.6 can be designed as an attribute test, focusing on the variable (O"'"ltraflon .
1. ge: c = getEncounterCharacter( -PlayerCharacter")
3. agoc.adjusIOuaiity( "concentratlon-l 0 )
concentration
4. 5g: c.setOuatity( "stamina"40 ) 5 . agoc.adjustOuatity( "concentration"10 ) 6. gg; c.getOuatity( "COncenlration")
Figure 27.6 selecting melhod sequences ror unll lesting
--retrieve data to validate
TESTING A ClASS
27.2.3 Testing Class Invariants As described in Chapter 22, class invariants are constraint among the attributes of the class that must remain nut alter the execution of every method. A class invariant te t conSists of executing a seque nce 01 methods and validating Ihat the invariant remains lrue. For example, suppose that a rule of the bank is that overdrafts ~re capped at $1 ,000, including the assets in the customer's avings, and IOtal assets per regular account are capped at $10,000,000. The invariant of the Accolml class would be something like the lollowing.
-1000 <= checkBalance + savingsBalance <= 10000000 We would initially set the variables to amounts that honor this invariant, such as chrckBalanCf = - 3000 and SQvin9sBalanCf = 2500. Then we would execute a sequence 01 methods such as deposl( 300); wilhdraw(500 ); deposil(50) and check that the invariant is still true. Languages such as Eillel and Java are equipped With functions that test the validity of assertions. An assertion is a statement that can be true or fa lse: lor example , "x = = y." Assertions are often invariants.
27.2.4 State-Based Tests As we have seen, the instances 01 a class ca n often be usefully thought 01 as transitioning among states in response 10 events. We should therefore test such classes in terms of' their state. For example , let us test the class Enco,,"lrrGame. Figure 27.7 illustrates the first steps In the testing of the application's state transHions . The complete state· transition test is shown in Figure 27.8. The numbered steps denote a typical event sequence for causi ng a meanin gfu l sequence of events. One lest would thus consist 01 sti mulating the system so that it transitions through thi s sequence. The tester would also introduce events that do not apply for panicular Slates 10 ensure that indeed they do not affect the application . To design and execute state·oriented testing requires significan t time, especially because extensIVe user inputs are required. Tools arc available that record user interactions with the system and that can reproduce
test step 1 Preparing
Player dismisses qualities menu
Verify that the game is initiallv in Preparing state (by checking on the class member gameS/a/e/).
Wailing
flcur. 27.7 State-transltlon test sequences, 1 of 2 seve. A5'<WtJon 10( Compuong Madtinery, nup'VIww acm orll... pe(lmarVQUOSliOn cgmorm. PUTQ
671
672
CHAPTER 27
MODULE ANO INTEGRATION TESTING
test step 2 ........... .--/ Dismiss the quality menu, and verily that the game Is in Waiting slale.
"-
test step 3
Preparing
I~
Player dismisses
test step 1 Verily that the game Is Initially In Preparing slate (by checking on the class member gameStatel).
qualiries menu ,./
Move the player character to an adjacent area, and verily that the game is still in Waifjng state.
Move to adjacent - - -
area
---'
Figure 27.8 State-transition test seQuences, 2 of 2
these actions In addi ti o n, assertion checkers ca n be embedded ,n the code to verify that the system is in th e
slate it is supposed to be.
27 .3 INTEGRATION Thi s section discusses and compares various types of Integration , and is summarized in Figure 27.9. It starts by co mpanng b ig bang inlegration with the inc remenlal style that IS generally recommended ( when it's po sible), The extreme (orm of Incremental integration is COll titlU OUS integrati on. The last c1assincl:Ition d iscussed is between to p · down and bottom · up sty les. Projects o ften mi x these ,"teg rati o n and testing styles, depending on the n3rure of rhe projec t
Big bang integration
Test
Incre".entallnlegration
modules IndMdually
Figure 27.9 Module and integration testing
INTEGRATION
IApplication I
'/
Module
Unit
c-
Unit
Unit
Module
Module
• ••• •
• • • ••
.....
Module
•••••
• • •• •
Unit
Unit
Unit
figure 27.10 Big bang integration
27.3.1 Big Bang Integration Big ba.g
integration consists of creating modules in parallel and th en assembling them in one operation . A form of this is illustrated in Figure 27. 10 Although big ban g testing redu ces or eliminates the need for test
drivers and stubs. thi s beneAt is usuall y far outweighed by the complexity and co t of fault isolation. Since many modules are integrated at o nce. i t IS frequ ently difAcult to locate the source of defects . As an example, consider a sys tem that moni tors th e health of at ·ri sk patients as th ey go about their daily lives. As illustrated in Figure 27. 1 I . the application ca n be th ought of as deco mposed into a m odu le that
Individual Health Monitoring Applicalion
Health Data Transmission
Unit
Mobile
Diabetic Analysis
• • ••
• • •••
Cardiac •••••
Analysis
• ••••
Phone
Fleur. 27.11
Big bang Integration of a health monitoring system
Unll
Emergency Notification
Ambulance
Unil
673
674
CHAPTER 27
MODULE AND INTEGRATION TESnNG
Module 1
uses
uses
Module 4
Module 3 uses
uses Module 2
Figure 27.12 Module sell-dependency-conslder Its effect on Integration
handle the collection of data fro m patients, o ne that analyzes data for sp('ci flc diseases, o ne that handles emergency notiRcations such as calls to the po lice, and a o n. it makes a g rea t deal of sense to develo p these modules separa tely For example, \\'!hy no t develop th e diabetic analysIs in an orga nizat ion specia lizing In that
Acid, an d ha ve emergency no ti fica ti o n d eveloped by a company with expe nence in writing such software reliably Some modules may be effectively written b), skilled teams worklllg anywhNe , geograp h ica ll y speaklllg. Although continualllltegra tion , described below, is preferable in gene ral , it ma y not be practical in a case like thi Each h ig h · level mo dule and its subsidiaries ma y ha ve to be devel o ped separately, and then IIltegrated III big bang fas h io n. The Integration and .estin g of mo dules illustrates the wisdom t,f desig ning so that dependenc ies arc noncyelic. In o th e r words, we try to avoid architectures in which a mo dule depe nds o n itself. Figure 27. 12 illustrates suc h an architecture. We can't fully test an y pair of mo dules al o ne, O ur o nly c ho ice is to use stubs or to test all of th em together, which multiplies the po tential for hard· to·R nd and hard -to-Ax defects.
27.3,2 Incremental Integration owa days . software integra tion typica ll y proceeds 10 an incrcmt. ntal manner in whIch softwa re modules are
developed and assembled into progressively larger parts of the system, This is known as i"a"""".1 i""gra'io" ( I ). Gradually building the system means complexity increases incrementall y, making it easier to isolate integra tion problems Incre men tal integration ommences when the first tWo pans of an application arc developed, and continues until all its part s have been integrated into a complete sy tern , at which time system testi~g
comme nces. Stub and drivers arc employed during this process. Throug ho ut th e integration process, software "builds" may be crea ted that foml the e merg ll1g ystem , as Illustrated in Figure 27. 13. Befo re adding new mod ules, integratio n tests arc executed agai n t each build, ensuri ng th at the build ",arks correctl y. Figure 27.2 Implies that mo dules arc developed and integrated in some o rd er, but does no t sugges t how the o rder is determined , We u ually determine the Integration order b)' ba ing it on the desig n of rhe sy tern . Two common met ho ds are bOl/om-up and lop-dOlPH , and eac h must account for dependenCies between the modules mak ing up the desig n.
27.3.3 Bottom-up Integration Suppose that an application consists of the modules and dependenc.es as hown III Figure 27, 14. In bottom-up Integration , modul« that are most depended o n are developed and inte"rated •nrsl. Th en ., the modules that depend on t h em are integrated next, .nd so on In FIGure 27, 1-1 , this implies th.t Module 3 i< developed first , si nce it is at th e "bottom" of the dependency tree Modules I and 2 arc integrated nat with
-. ,. .'. . ~-'~ .•. ~. ; ••.h-
~ "
.... .. RII!'d
BuIld
Un!!
. ....
Uni!
.. ....
Uni!
• •• • •
Figure 27.13 Incremental integration with builds
Module 4
\ uses Module 1 uses
uses
Module 3
Module 5 uses
Module 2
FIgure 27.14 Example of module dependencies
Module 3 since they depend o n II. Modules 4 and 5 arc integrated lasl. Integrating in thi s manner is illustrated In Figure 27. 15. An advantage to th is approach is that It reduce< the need for stub si nce dependent modules are available when needed for integration Let's consi der how we mi ght perform bottom ·up integrat ion testing o n the Encounter vi deo game. Figure 27. 16 shows the relationship among rhe objects of the Encounler ",chlleC[ure , We have three modules (package ) to Int<:grate. and need to determine which modules depend on which. The direction of th e aggre!;ations uggesr an appropriate order, 0 show n in Figure 27. 17. Figure 2718 Ihows the resulllnK "using" reiatlon,llIp between the po kases .
676
CHAPTER 27
MOOULE ANO INTEGRATION TES TING
Third or fourth Module 4
Module 5
usos
Third or fourth
uses Module 1 Module 2
uses
uses
- -I
First or second
Figure 27 .15 Bottom-up integration
EncounterGame EncounterGame .. Iacade ..
--<
Er'I»'Hlt&rChar8cters
c
lr EncounterCast .. facadegetTheEncounterCastO getThePlayerCharacter() getTheForeignCharacterO
getTheEncounterGameO getStateO setStateO handleEvent()
1
EncounterEnvironment
I*EncounterEnvironment .. facado ..
setLocationO
Area
Figure 27.16 Module relationship in Encounter
X depends on Y 50 create and lest Y first Figure 27.17 Dependence and Integration order
INTEGRATION EncounterGame
uses
uses EncounterEnvironment
EncounterCharacters
__------ uses
F"tgUre 2.7.18 Module dependencies in Encounter
Second
EncounterGame uses uses
EncounterEnvironment
uses
EncounterCharacters
F"rgure 27.19 Bottom·up integration testing in Encounter
Next, we apply the principle of bottom · up integration to derive an integration order. Th.s tell s us to firs t te5tthe integratio n of EncoII"'trEnoiromn,,,' with E" Oll"'tr /larnrlcrs , and then to integra te E"colln'trGmnr. Thi s is .lIustrated in Figure 27. 19.
27.3.4 Top-Down Integration Top ·down Integration is the opposite of bottom ·up, Modules at the top of the depende ncy tree are developed first, with integra t.on proceed.ng down the tree . Th.s rype of Intq;ranon requires a cons.derable use of stubs since dependent modules are nOI yet ready for Intcgrallon . The advantage of top·dow n '"tegTalion i that modules at the top of the dependency tree arc typ. ally h.gher level fu nctiona hty of an aDpl. allon , su h a user interfaccs, and are te ted early in the .ntcllratlOn ~y Ie. n,i< prov.des an early fee ling for the appli ation , 1110lolin8 time for .mportant mod.f.cation,. F,gure 27 20 shows the lop ·down .ntegration order of En ounter. Th.s tell s u to Ar t te t the .ntcgrallon of EnCO""'rrG"mr w.th E.ICollnlrrEnviro","tIll , and th en to .ntewale E"(Ollllln Ch"", 1m.
6n
678
CHAPTER 27
MODULE AND INTEGRATION TESTING
EncounterGame
Ar51
uses uses EncounterEnvironment
uses
( second)
EncounterCharacters
Figure 27.20 Top·down integration testing in Encounter
Top-down Implementati on . '"t
,'ruc'u"a
,h,
27.3.5 Sandwich Integration Sandwich Integratio n is a process by w hich o ne integrates from the bottom and to p more o r less at the same time , introduci ng stubs for the intervening classes as o ne does this Suppose. fo r example, that we wa nt to integrate (h e class Forri9nCharacttr, which is at the lowest level in Encou nter, and EnCOUHltrGamt, which is ar the
highest, without havi ng to worry about the intervening components for now. T o have FO"'911Charac1" and E"colmkrG~mt coexis t, we can introduce stubs (or the intervening classes. For example, in Figure 27.21 , we Ars t have Fortl9n Cbaracttr work with a stub (or EncolmlrrCbaracttrs , then one (or E"CO,mlrrE,1IJi,."mmcH', then E"coulflcrGatftt. We don't count the Introduction o( stubs as true integration, so the only step th at's trul y integration i n this
exa mple is the last. It integr.ltes from th. top and bo tto m Simultaneo usly.
27.3.6 Continuous Integration (oll ,illuou, ;II" 9ral;01l is a ty pe of .ncremental integr.ltion in which small amo unts of code are added to rhe baseline (the currentl y state of the application ) on a very freq ue nt basis. Intervals arc often. freque nt.s da.ly (see Section 27.4 ), and the newl y integrated code does not neces arily correspond to a completed met ho d or
DAILY BUILDS
EncounterGame
uses uses \
EneounterEnvlronmentSTUB b
.- uses
EncounterCharaetersSTUB
a
uses
>1ForeignCharaeter I
Figure 27.21 sandwich integration testing in Encounter, in order a, b, c
class but can be smaller. As long as the code is unit-tested and does not introduce errors in the baseline , it can ~ integrated into the baseline. Continuous integration is one of the twelve practices of Extreme Programming (XP), as we described in Chapter 5. However, it can be utilized even if a non-agile process is being followed. 27 ,4 DAILY BUILDS
During incremental integration we build the software and regressio n-test it at regular intervals. Regression testing is designed to ensure that recently added code does not compromise preexisting functionality . Depending on the phase of the project , builds ca n be created weekly or even as often as da ily. Daily builds are often used at the tail end of projects when last·m; nute additi ons and changes are required. They are also used during mai ntenance . Figure 27 .22 shows an example schedule of overnight regressio n testing for an application approaching release . Figure 27.23 illustrates the da ily code integration process. This kind of daily integration and regression teSt schedule was reported by Cusumano and Se lby [3] as being utilized by Microsoft, for example. Referring to Figure 27.23 , a daily code freeze time of, typica lly, 6 PM is established, after which no new code is accepted for that day. The software system is then bUilt and run , and regression tests are executed on
biweekly
weekly builds
week 23
24
25
26
27
28
29
30
3'. release
Key:
'f= overnight regression test
fl&ure 27.22 Example frequency of overnight regression tests
679
680
CHAPTER 27
MODULE AND INTEGRA nON TESTING
Run Regression tests development
development
Confirm baseline or rever! /0 previous baseline
Freeze /0 baseline
Figure 27 .23 Daily builds the new budd between 6 I'M and 7 AM . If a problem is found with the ne'" bui ld , it is assumed the defect lies in the code that was checked in during the previous da y. This makes the job of problem isolallon and resolution easier than If a longer time Interval had elapsed between bu ilds.
27.5 INTERFACE TESTING
l"'''facr
validate the interface of each module from the viewpoint of the ir usage by a client. These can be conducted, to the extent possible , prior to the in tegratio n of a module (with necessary stubs); and then after the integratio n of the module (With, typicall y, a reduced set of stubs). The Facade desig n pattern can be used to faCilitate Interface testing. A faca de object IS created for each class o r package , provi ding an implementa· li on of its public interface . Each method in the facade checks its input pa rameters to e nsure they are passed ItS ls
correc tl y and rc turn ~ a predetermined response. Thu s, the ca ll er can test its interface with a module without
knowledge of whether It is usi ng the facade or the rea l implementati o n. This makes problem discovery and Iso lation easier Let 's n:turn to the: Video store as an example. Figure 27.24 shows the module decomposition
for this appitcation .
DVDs DVDRentals DVDAccess .. f8csde -
VideoStore
DVDsRented
VSCustomers
DVDCustomerAccess
.'.c.,OO,.
Figure 27.24 Video store module interfaces
fE-
o ..n
IPflERFACE TESTING •
Now we will perfoml an interface t h OV a Ii arion ) can be exercIsed by mea n est 0 11 t .e Os module. Its usage by clients (I.e., othc~ pans of the PP L d clas DVDA I s of the facade object o nly. Thus, the interface tests conSIst of testIng thc raCa e s rerss . t exposes meth ods ' uch as t h eo f II oWing: . :1
voi d stockDVD(String aDVDTitle) ; Rentalltem getDVD ( int aDVDID) ; Rentalltem getDVD (S t ring aDVDTitle ) ; StrJ.ng des cr ~beDVD (i nt aDVDID) . . . ' Str~ng descr~b eDVD(String aDVDTitle) ; Note that the metho d griD VD() returns a Rnllalflffl1 o bject. The Rn.tnlItcm class is a public fram ework class, and so IS accessIble to all o bjec ts. Th e9ttDVD() method ca nnot return a DVD object because the DVD class is hidden fro m clie nts of the DVD, package. The interface test executes interface methods with test cases. An example is the fo ll owi ng,
•
DVDgwtw=newDVD ( "Go neWithth eWi nd" ) ; / / Get access to the facad e obj ect DVDAccess dVDs = DVDAccess . getTheDVDAccess ( ) ; / / Now run the tests dVDs. st o ckDVD ( gwtw ) ; Rentalltem rentalItem = getDVD( "Gone With the Wind" ) ; / / Report discrepanc ies between str ings (assume a "compare () , , test utility ) compare ( rental ltem.getTit le() ,gwtw.getTitle () ); / / etc.
For the DVDRnl tais package, which does not use Far(/d, . the interface is the collectio n of meth ods of member classes. For example , the class DVDR,ntnls expo es me thod such as the following fro m the DVDRtntal class.
DVDRental createDVDRental(RentalCustomer aDVDCustomer, Rentalltem aDVD) DVDRental [) getDVDRentals ( RentalCustomer aDVDCustomer ) RentalCustomer getDVDRentalCustomer ( i nt aDVDRe nt alID ) void removeDVDRental ( RentalCustomer aDVDCustomer , Rentalltem aDVD) void r emoveDVDRental( int aDVDRE'ntalID) float getFin e ( RentalCustomer aDVDCusto mer , Rentalltem aDVD ) float getFine( i n t aDVDRentalID) The Interface test IS ,urn marized In FIgure 27.2 .
611
682
CHAPTER 27
MODULE AND INTEGRA nON TESTING
An Interlace Test:
DVDs DVD gwtw • new DVDI "Gone With 'he W.ncf"):
DVDAccess -facade-
1/ GOI access 10 the fO~8de object
DVOAccess dVOs '"' DVOAC.0e55.getTheOVOACO)ssO:
void stockDVD(StringaDVDTilie ): Rentalltem getDVD( intaDVDID): Rentalltem getDVD( StringaDVDTilie ): String describeDVD( IntaDVDID ): String describeDVD( SlringaDVDTnle ):
II Now run the tests dVDs.stockDVDI gwtw ):
AontalUem rentalHem ~ ge,DVDI
"Gone With the Wind") :
/I Report discrepancies between strings
/I (assume a ~compare W test utility) compare( renlall lem.gelTIll eO.gwtw,gotTiUeO); II etc.
Figure 27.25 Interface tests of DVDs package
27.6 MODULE INTEGRATION Once In terface teSlS are completed , we ca n feel conRden< about th e interface between modu les. We are then ready to test their interaction more completel y wit h in tegration Itsts . An integration tcst focuses on the additional functionality gained by assembling modules. Now let's i,llegrate fully functional ve rsi o ns of the DVD, and V5Customm packages . To perfo rm integration tests , we identi fy the added functlonaliry that thi s integration provides-in thi s case, the
additional functionality that the DVD, and V5( ullo",,,, package< provide . In parti cular, the methods of DVDRrnla', wh ich were using stubbed facade meth ods in DVDAccm and f)VI)CullomcrAcctSs , now use fu ll y fu nctional versions . The methods of DVDRtIIln' ca n now be fully tested . The same app lies to all classes in DVDR,"'a', . listing 27. 1 is an example of a met hod in DVDRt>ltn' that IS part of thi s integ-ration test
Ustlng 27.': The getDVDRentalO method, which becomes more operable after some integration Rental getDVDRental ( Rentalltem aDVD . RentalCustomer aDVDRental Customer) {
/ / Check that aDVD is in the inventory DVDAcc ess theDVDAccess = DVDAccess" getTheDVDAccess ( ) ; i f ( ! theDVDAccess" islnlnventory ( aDVD ) ) return null; / / or some other error indicator
CASE STUDY: CLASS TEST FOR ENCOUIIITER
II Check that aDVDRentalCustomer is an actual customer
DVDCustomerAccess theDVDCustomer Access = DVDCustomerAccess getTh e DVDC t () • ( I h . us omerAcce ss ; ~f . t eDVDCustomerAccess . verify( aDVDRentalC ustomer) ) return null; I lo r some other error indicator
I I Check that aDVD is rented to aDVDRentalC ustomer . . .. .
I I Retr ieve and return th e rental . . . . }
27.7 CASE STUDY: CLASS TEST FOR ENCOUNTER Usting 27. 2, whic h fo ll ows, Chapter 26 .
IS
a test fo r th e Enco"n ler llaracler class and comple te the Encou nter case study in
Ustlng 27.2: Tests for EncounterCharacterclass testEn counterC hara eterClass ( Str ing destinationP ) IOExcept ion
public static void throw.
(
/ * Prepar e for the test * / Pr intWr iter outM = new Pr i n tWr iter (new F ileOutpu tS t rearn (destin ationP) ) ; System . out . println ( " \ nEncounterCharacter class test results on " + dest i nati onP + " \ n" ) ;
/* * The f ollowing methods will be tested in sequences :
*
* a . adjustQua lity( Stri ng qualityP , float qualityVa lu eP )
*d . deleteFr omEnco unt erCharacters(E ncount erCh aractere n count erCh aracte rP ) * ge . Encount erCharacter getEncounterCharacte r ( Str ing nameP ) * gq . float getQualityValue ( Stri n g qualityP ) * gt. float getToleranc e() • io . int indexOf( Stri ng qualityP ) * ii . i n sertl ntoEncounterCharacters(EncounterC ha r acterencount erCh aracterP) • m. i nt maxNwnChar sI nNarne ( ) • sq . setQuality( StringqualityP , float qualityvalueP) * 80 . float swnO£Qualities()
• •
The f ollowing seque n ces occur commonly:
683
684
CHAPTl:R 27
MODULE AND INTEGRATION Tl:STING
ge - aq-so qe-sq-a-qq
" "
•
•
•
•
• •
The following sequences have a high potent ial for defects: ge-aq-aq-gq-s
*
"
•
• • • • •
"I I *TestCl:ge-aq-so"1 En counterCharacter eCIM = new
I I method "ge" EncounterCharacter ( "CharForTestCl " ); Il aq eClM. adjustQuality (QUAL_STRENGTH , 40.0f); TestExecution.printReportToFile(outM, "Class test ge - aq-so", eClM. sumOfQualities ( ) , 100.Of ) ; Ii so
I " Test C2 : ge-aq-aq-gq-so" 1 EncounterCharacter eC2M = n."
EncounterCharacter( "CharForTestC2"); Il ge eC2H.adjustQuality (QUAL_STRENGTH,40.0f); Il aq eC2H.adjustQuality(QUAL_STAMINA,20.9876f ); Il aq TestExecut ion .pr intReportToFile ( outM, "Class test ge-aq-aq-gq-so: part 1" , eC2M . getQualityValue ( QUAL_STAMINA) , 20. 9876f ) ; I I gq TestExecut ion .pr intReportToFile ( outM, " Class test ge-aq-aq-gq-so: part 2" , I I so eC2M. sumOfQuali ties ( ) , 100. Of ) ;
1* INVARIANT-ORIENTED TESTS "Check for the invariant "qualValueI [i) >=0 " * -- after executing the sequences of methods executed above
"I bool.'n truthM ::t.l:Uei ~or( in.
{
i = 0; i < qualityTypeS .length; ++i) I " Set trClthM false i f any entry in eClM. qualValueI not >= O· I truthH=truthM&& (eCIM.qualValueI[ij »=O .Of ) ;
)
TestExecution.pr intReportToFile (outH, "Class test for the invar iant qual ValueI [il >=0 I truthM tzue ) ; I
II ,
I
It Cone lude "I outM. close () ; System. out .pr intln( "\nClass tests of EncounterChar class concluded." ) I } II end of testEncounterCharacterClass
I " Tests all the methods of this class one at a time
CASE STUDY: CLASS TEST FOR ENCOUNTER
-@par_ • tellcept ion
dest inat ionP IOException
Location to,",r ite results. If there's aproblemopening or accessingdestinationP
*/ JIIIIb11cI.tatt c oid testEncounterCharacterllethods ( Str ing destinationP ) tlhos. IOExcept ion (
/* Prepare for the test */ PileWriter outM=nzwFileWriter( new File( destinationP) ) , System. out .pI intln ("EncounterCharacter method test resul ts on " + destinationP + " \n " ) , / *TestsforgetEncounterCharacter() */ EncounterCharacter eCNorM = n.wEncounterCharacter ( "qwerty" ), // normal TestExecution.reportToFile(outM, "Get Character Test 1: nominal value", eCNorM . getName( ) , "qwerty" ) , EncounterCharacter eCNullM = new EncounterCharacter (null ) , // null TestExecution.reportToFile( out II , "GetCharact er Test 2 : null parameter" , eCNullll.getName(),GameCharacter . DEFAULT_NAME ) , StringtooLongll="12345678901234567890 1234567890 1234567890 ", EncounterCharacter eCTooLongM= n•• EncounterCharac ter (tooLongM ) , //t oo long TestExecution. reportToF ile ( outll , "Get Character Test 3 : Limit parameter values , " + "max name len = " + eCTooLongM . maxNumChar sInName ( ) , eCTooLongll.getName () , tooLongll.substring (D , eCTooLongM.maxNumCharslnName(») , EncounterCharacter eCZeroM = new EncounterCharacter ( ,," ) ; // zero-len TestExecution. reportToFi1e ( outll , "Get Character Test 4 : zer o- length" , eCZeroM .getName() , GameChar4cter . DEFAULT_NAME), // bad chars EncounterCharacter eCPuncM= new EncounterCharacter ( "a +b" ) , TestExecution. reportToP i1e ( outM, "GetChar acter Test 5 : bad char ' + ' " , eCPuncll .getName() , GameCh a ra cter . DEFAULT_NAME) ,
/* Tests for indexOf ( ) for every valid quality name . */ for ( in~
i= 0, i
/* Tests for indexOf () for an i nvalid quality n a me . */ tcy
{TestExe c ution.r e portToF~le(
outM , " inde xOf () Test 2 : i nv alid name: zorch ", i nd e xOf( " zorch " ) , --1) 1
615
686
CHAPTER 27
MODULE AND INTEGRAnON TESTING
} catch ( Except ion eP )
{TestExecution.reportToFile( outM , "indexOf () Test 2: valid name: compare " , l'indexOf (\ ' 'zolch\ " ) ", , 'with expected _1"
);
}
1* Tests for setQuality () *1 II Set up for test EncounterCharacter hank = new EncounterCharacter ( , 'Hank"
);
II Nominal value hank.setQuality (QUAL_STRENGTH, 10.3f ) ; TestExecution.reportToFile(outM, "setQuality (} Tes tl:nominalvalue", hank.getQualityValue( QUAL_STRENGTH), 10.3f ) ;
II Out of range value hank.setQuality ( QUAL_PATIENCE, -6.2f); TestExecution.reportToFile(outM,"setQuality () Test2:nominalvalue", hank. getQualityValue (QUAL_PATIENCE ) , O.Of ) ;
II Value below close-to-zero threshold. hank. setQuality(QUAL_STAlIINA, getTolerance () * 0.9f); TestExecution.reportToFile(outM,"setQuality()Test3:valueclosetozero", hank. getQualityValue (QUAL_STAMINA) , O.Of);
II Tests for adjustQuality() . II Set up for test and verify: Values should be 20 each. EncounterChar acter harvey = n.. Encounter Char acter ( , Harvey' , ) ; TestExecution.reportToFile( outM, "adjustQuality() test 0: ver ify that values add to 100' , , harvey. sumOfQualit ies ( ) , 100.0f ); II Nominal adjustment II strength 30 rest 70/ 4 each harvey. adjustQuality (QUAL_STRENGTH , 30.0f ); TestExecution.reportToFile(outM, "adjustQuality() test 1: values sum to 100 a£ter adjusting" , harvey.sumOfQualities(), 100.0f ) ; TestExecution.reportToFile ( outM, "adjustQuality () test 2: values adjusted as commanded' , , harvey.getQualityValue(QUAL_STRENGTH), 30.0f); I
II Adjustment resulting in a zero value harvey.adjustQuality( QUAL_STAMINA, 99.0f }; TestExecution.reportToFile(outM, "adjustQuality(} test 3: ver ify low value reverts to zero' , , harvey. getQualityValue ( QUAL_STRENGTH), O. Of ) I
CASE STUDY: ClASS TEST FOR ENCOUNTER
// Conclude outM . close () ; System . out .p rintln( " \nMet h od tests of EncounterCharacter class conc luded . " ); }
/ **Classtotest repainting of characters. Createsawindow, whichwillcontain * * several copies of the character image .
*/ pd.... t.e .t.atlc cl ••• testCharacter Image eztend e Fr arne {
/** Instance attr ib\lte that remembers which character image to display. * / pri_t. EncounterCharacter characterI;
/** Basic constructor -- cr eate a window for test ing some char acter ' s image . *@param characterP Character whose image is to b e tested . */ testCharacterImage ( EncounterCharacter characterP) {
"ljor (c haracterP.getName()) ; characterI=characterP;
// Do all normal Frame initialization. // Rememberwhichcharacterwe ' retesting .
}
/ ** Repaint the display areaof the frame . *@param drawP Graphics context for drawing the c haracter.
*/ public ..oidpaint (Graphics drawP) {
Dimension frameSizeM = getSize () ; / / Size of the window area . / / Co nv enient divisions of window . iJlt widthUnitM = fr ameSizeM . width / 5 ; iDt heightUnitM = frameSizeM . height /5 ; character I. showChar acter ( this, dr awP , / / Dr awn small , fac ing right . n •• Po int (widthUnitM , heightUnitM) , heightUnitM , tab. ) ; char acter 1. showCharacter ( thio, drawP , / / Dr awn large , facing left. now Point(widthUnitM*4 , heightUnitM*3), heightUnitM*2 , tru. ); char acter I . showChar acter ( thia, dr awP , / / Dr awn lat ge , fac ing right . now Point (widthUnitM*2 , heightUnitM*2), heightUnitM*2, lala. ) ; character 1. showChar acter ( thi., drawP, / / Dr awn small. facing left . n •• Point (widthUnitM*3 , heightUnitM*4) , heightUnitM , tru. ) ; }
)
/ / End of tcstCharacterlmage inner class
688
CHAPTER 27
MODULE AND INTEGRATION TESTING
27 .8 CASE STUDY: ENCOUNTER INTEGRATION PLAN APPENDIX FOR ENCOUNTER SCMP: INTEGRATION PLAN
Note to the Student, We need to de eri be the order il1 wh ich the applic.'ltion is to be IIltegr.lted . The S MP is an appropnate location for this descnption , since it describes configurations of th e itera· tions and builds. ThIS could be placed in the SPMP, but it contains design and implemen · tation detail, which are nor rea ll y projec t management irems It could be placed in the SDD , but the integration plan is nOt a design but a way to get to the implementation of the design . A document o n implementation issues alone is a possibi lity . Another possibility is the SCMP , si nce it is concerned with conRgura· tions a the produc t comes toge ther. The Encounter case study selected this optio n.
The irH cf,( ratlon lC tlOg a.;sociated with thiS
Integra ti on plan a urnes that the Ind,yidual c1asse, have been tested (as above ).
2. Construction of Integration Baselines
Referri ng to the va rious integration techniques
discussed aboye, which o ne IS th is, It is largely bOllom · up if you take Ihe ",tS relationship for the hiera rchy. The til o""lrrGo"" package IS then at the top. If the integration process we re to be co ntinuous, a descnption of a dail y build pro· cess would be prOVided , perhaps along with some sense of the order of the integration. This is normall y associated with an agile process.
TIl e three successive bUIlds fo r re lease 1 of Encounter arc show n
In
Figure 27.26. TIle first
budd conS ist of th e GamtC/ulrn Irrs fra mework pack ·
Hi story of versions of this document:
11 / 1/98 E. Braude, Initia l Draft
Jgc and th e Ell cotmtrr bartlctrr5 package . Th e second
build uses rhe fir.; t build. It consi ts of the E"co""I"E"· 11irolUllf l11
pJckagc, irs corresponding fram ework. and
the ("St build . The third build refers to budds I and 2.
4/4/99 E. Braude, Re vised
It
8/23/99 R. Bostwick, Documents reviewed and
consi"it
of
th e
EllcolmlcrGamc
its corre ponding framewo rk, budd
I,
pa ckage,
ond build 2
rccomm enctJtions made
8/ 24/ 1999
E.
Braude,
Recommendatio ns
integrated
8/26/ 1999 E. Braude, Reviewed , comme nts exponded
1 . Introduction Dunng the integration process , the softwa re for
Encounter is co nstructed in sta ges or builds. Thi s
appendi x describes the configuration of the first three builds . Integration testin g i. b •.sed on these builds The last build i the basis for sy tem testi ng .
2.1 Integration Build 1 Build I i illustrated in Figure 27.27. Budd I imple. ment. the Gam,Charnel", frame work pockage and the EII Colmter Imractcrs package.
Imc rfacc testing (see Sectio n 27.5) is performed on this module by identifying all of the methods that its classes make public. (1\·lethod not needed by other modules should be made private to avoid unneeded te. rs of th, kind.) The design is such that these methods are ,,11 p.rt of the f"CO""lrrC,,,, cia ..
CASE STUDY: ENCOUNTER INTEGRATION PLAN
Build 3 EncounterGame
>l EncounterGame
Build 1
-'
EncounterCharacters
EncounterCast
j Build 2 •
./
EncounterEnvironment
I;
\
EncounterEnvironmenY1! .
""
Figure 27.26 Integration plan
Inlegratkm Plan
r,
0
1
GameCharacters
Err.;Q.ltlt~
«framework package»
r _"""
GameCharacter
e,"'(J'''o{",N'''''',.r\~2 -'
&...-....e-,."..Q" . ... I
Encounter Characters
EncounterCharacter
EncounterCast
~
PlayerCharacter
. facade - singleton -
Figure 27.27 Build 1 for the Encounter game
ForeignCharacter
619
690
CHAPTER 2;
MODULE AND INTEGRAT ION TESTING
Integration
r'>L!( . ...
1
~ I
GameEnvironment
(J'!CO 'IW C
Pip" I A
•
,.
GameAreaConnection
•
;<;
t
GameArea I~ 1< L
GameCharacter
~
GameLayout
~
~
Area EncounterEnvironment
~I
«facade » ~
EncounterCast «Iacade~'
EncounterEnvironment Figure 27.28 Build 2 for the construction of Encounter
2.2 Integration Build 2 Build 2 is shown in Figure 27.28 . Bu dd 2 conSlSlS of the
EH CO lltlltrfu pjrollmhlt
0"'"'''/
package and the GtlmtEIIIJlr-
framework package . logelher wil h Ihe first
At Ihe conclusion of build 2, Ihe framework! application decompOsi tion is show n in Figure 2;.29.
The fll CoIIII,,,Gllm, package and its Ro/,P/ayillgGarro, framework package arc no t present because the
a~
part of budd 3.
build. The GamcEHPlfoHmcnt and the En Co lmttrEtlVirorl ,""" packages use the build I Gam,Charac'tr and f" colm'"Cas' classes, respective ly. Courtyard, dun -
2.3 Integration Build 3
geon , and liVing room are examples of areas. Some of Ihesc areas are connecled . For example, there is a connection between Ihe dressing room and Ihe courtyard
The fi nal build, build 3, IS illuslraled in Figure 27.30. Budd 3 consi Is of Ihe fllco""" re""" package, ItS Ro/,P/aYIHgGmnt framework pa kage, build I, and bUIld 1_
CASE STUDY: ENCOUNTER INTEGRATION PlAN
Characters
GameEnvironment
. framework package _
- framework package.
EncounterCharacters
EncounterLayout
Figure 27,29 Status of Encounter after build 2
~--------------------1
L-f!ol~~~~ng~arn~~ _____ _____ ______ __ ____ _______ ________________________________ _' ____ , I
I
RPGMouseEventListener notifyOfEventO
I
I
P>--
RPGame handleEventO
;
i
£
I
GameState handleEventO f\
~
I
I I
«singleton» Engagement
EngagementDisplay
I
--------- --- -"l
Engaglng '
Wal'tl' nn ~
I
handleEventO
handleEventO
I
----'
I1_ _ _--...: '---_ __
I !
__ _ _ __ ______ ____________ •
-~-----=-_£".:==~-=-=-:...-=.:=~---=--=~:.--=--:.==--.:.===--.::--== II~
1 !
I
__-L..._--, ! Reporting handleEventO
Preparing handleEventO
I I
I I
I I
,---;---------------. . --1 - .--- --.- -,,- - -- - ----- - ----- : EncounterGarne : L ____ __ ___ _ ____ _ _ _ _
I
Key: Domain class Figure 27,30 Build 3 for Encounter (Includes bulla' and build 2, not shown)
I
691
692
CHAPTER 27
MODULE AND INTEGRATION TESTING
27.9 SUMMARY Int08"'tion rders to the process of assembling the pans of an app licatio n and testing their Interactions 10 ensure that they work tOKether correc tl y . The parIS that arc integrated can be as small as a few IIIK'S of code or as large a ;} subsystem. Two overa ll strategies for integra ting th e parts are IIIcnlrlrntal and
big bmtg
In incremental integrati o n, th e
system is built step by step in relatively small increments. As soon as a part of the applicatio n is developed it is Integ rated into the basel ine. In big bang integration . the parts of the system are developed first and then are ",tegrated toget her in o ne tep. This approach ca n lead to man y problem s and i usua ll y avoided if at all possible. A com monl y u ed tech nique is to build and test the entire code base on a reg ular basis. Earl y in projects the interval an be weekly, but atthe tail ·end it can be daily. Co nducting daily builds ensu res that any problems that arc uncovered can be isolated to recentl y added code . si mpli fying defect isolation and reso lution The Facade design partern can be used to facilitate interface testing between modules . A facade stub object IS created that implements the public interface of a class or packa ge O ther modules test their interf"ce wi th that module, and the facade object checks that it is being ca lled correctly and retu rns a predetermined respo nse. Once the interface is tested, the faca de is replaced wi th the real modu le and the modules are tested further.
27.10 EXERCISES I . In your own words, describe incremental integrat io n. Name and explain two ben el1ts of
incre menta l integ'ration .
2. In your own words, explain how a project schedule is affected by the method of integration used on the projec:. 2A. Consider the health monitorin g application described in Figure 27. 11 . Describe wit h examples how yo u would integrate it bo tto m· up and how you would test the integra tion process. 3. In yo ur own words, describe how boltom·up integration works. list and ex pl ai n two advantages and dISadva ntages of bottom·up integration . 3A The case study in Section 27.8 does not deSCrIbe a continuous integration process-but suppose that the document did prescribe one instead. What would that document say7 4. In your own words, describe how to p·down integrati on works. list and exp lain two advanta es and disadvantages of top ·down integration. g
5. Consider a poi nt·of·sale system th.t is under developme nt. Assume that th-.... h ard ware p Iatfarm an d device drivers that control it are brand new. The rest of the software 's b . d fr . . Wh " I emg porte am an eXlStmg system . at appropnate method of mtegratio n might you rec d be om me n used and wy7 • h 6. In your own words, explain how daily builds facilitate the isolation
f d ( . a e ects In a build.
7. Figure 27.31 shows the architecture outline of an application th t ' I h . b k P 'd I fo .. a 51 mu ates t e movement of customers In a an . rovi e a pan r bUilding and integratin g th O I" IS app ICtltlOn .
BIBLIOGRAPHY
BankSlm
BankCustomers
I
~
.facade-
BankCustomer
I
Pending Events executeNextEventO Number
~ ufacade» getNumberO
BankLayout
BankLayout -facade » BankEvent
Teller
BankEvent
IQueue I
ccfacade'l executeO
Figure 27.31 Architecture of bank simulation exercise
TEAM EXERCISE
Integration Obtain proj ect speci ficati o ns from two other team s in the cia . s. Speci fy informa.lly a new appl icatio n that contains significant cl ements o f these applicati ons. SpI' cify an integratio n plan to build thi s new applicatIon . Evaluatio n cri ten a: ( I ) Degree of clan ty of th e pl an (2) D egree to which the pl an conlaln an appropriate o rder
BIBUOGRAPHY I
2 i
I>czu . M auro, dod Mlchill l Y(JunH, ., 0/111'£'" Tl\l'''!/II''11 ;\~U lyfl' p ' ()( t1 C, Pm,,,,,,,, jlllJ Trdmlllun," John \'(' ,I c)' ~ S('IO, 2008 U.,kstra, Ed'8C'r, - ( ,I') To t .. teme n, on" den:d " "rm(u ' " COWI III'HIlj, dhOn( 0/ ,/'t AeM Vo l II no 3, I (\8 Pf' 1-t7- 1"1l t...J,."m. no. M . ~ Ild R W Selby. ~ llow M. ro<\oit nUl ld~ ~oft .....arr .· ( O,"I'Ut" '( ""O"~ o} I/It Ar M v I 40 no O. 1997, PI' . l - b l
693
Testing at the System Level
Planning Maintenance
Testing The Software Development Ule Cycle
Require: 118"15 analysis
•
How do functional and nonfunctional lesting differ?
•
How do you conduct performance tests?
•
What is load I stress event testing? ReliabilIty and availability testing? Recoverability testing?
•
How do you lest usability?
•
How do you validate secunty?
•
How do you test when requirements are
sparse or even Ronexistenl?
•
What Is acceptance testing?
•
How does one lesl In agile processes ?
•
What are compatibility, installation. and serviceability testing?
• • Figure 28.1 The context and learning goals for this chapter
How do alpha and beta releases relate to teshng? When Is testing automated?
TESTING AT THE SYSTEM LEVEL
• p~rfonnance . .. Tcst peed of appl,cation
• LoadlSli <55
..•
Test against heavy event Ira ffic • Rdiability and Availability ' " Determine percenlage up · lIme • Recovcnbility ... Test ease with which application recovers from cra h • Usability ... IXrermine degree of user sa ll sfaclion . • Security ... Determine susceptibility to intended and unintended breache • Compatibility .. . Application compatible with ot her systems as required • [nslallability . . . Test ease of installation • Serviceability . . . Test ease of keeping up· to-date at customer si te FIgure 28.2 Principal system tests SySltm Irs ling follows integration teslIng . It consists of black box test. that vali date the en tire system
against its requirements. Once all other system tests arc successfull y com pie led, Ihe application is deemed ready for the customer's acceptance testing (Section 28.4 .2). These are related to the requirements and to metrics in that each test measures one or more metrics. System tests are most often conducted by an independent group such as Quality Assurance . During system testing, compliance with both the functiona l and nonfunctio nal requirements is validated. Recall fro m Chapter 10 that functional requirements specify services Ihat an applicatio n must provide (e.g., ''fhe application shall compute the va lue of the user's tock portfoliO .") . Nonfunctional requirements, o n the o ther hand, descnbe a quality or behavior an application must possess. Examples of no nfunctional requirements include performance , usability , and compatibility . Figure 28 .2 summarizes various types of nonfuncll onal systems tests. Since system tests ensure that the requirements have been mel , the y mu t systematically validate each requirement specified in the SRS , including each of the usc cases. Whenever possible, system tests are performed on the applkation "Inning in its required environment This is not terribly complicated ('or an application that is intended to run on a PC, such a a ca lendar program , although even for simple platforms we sti ll have to be concerned with complicating issues such as the versIons of the operating system . However, many applications ca nnot be fully tested in their eventual environments. This certainly applies to space-based applications, for example, with somc times d,sastrous consequences The Mars Climate Orbiter spacecraft i a case In point. It veered of( course , resuillng In a lo -s of hundreds of millions of dollars. According to Cable Network News, the Investigatin g board's chairman reported that the root cause o( the loss of the spacecraft was a laded tran,lat ion of English units into mctTlc units and a segment of g round . based , navIgation . related nll' ion so ftware . T csting for thiS and other requlreme nls had to take place o n a grou nd -b.-cd Ie t bed. In analogy to the two pronc lpal forms of rcq ulre m c nt ~.f'lll Iiollallnis leSt the fun 1I 0 nai rcqulrtmcn!> of the system, and nonJullclionll/ INl s the qua"lle, and behaVIor o( the sy
695
696
CHAPTER 28 TESTING AT THE SYSTEM LEVEL
the- req ui re ment ha ve been ful fl llcd, makc up th e 111 311'1 functiona l tes t
~ct. The main nonrunctlonal tests arc
In luded in the lon te
28.1 FUNCTIONAL TESTING Functional system tes ts focu o n ho w custo mers will use th e pro duct in real li fe Use cases a rc a primary source of functIOnal requirements As an example of testing a usc case. reca ll the fo llOWin g Encounte r usc case. EHgag(
For(igt'
ClJart1CI(r , from the customer req uirements.
I . Encou nter displays th e fo reig n charac ter in the same area as th e player's.
2. Encoun ter exc hanges quality values between th e two c harac ters. 3. Enco" nter d isplays the results of the engagement. 4. The user h ilS the "OK" buno n. 5 Encounter di plays player's charac ter in a rand o m area. To test th is. we may begin playing the ga me unt il an engage ment tokes place and is o bserved. as In Figure 28.3.
Currenl lif e 001,'11, !IT !I
Test Slep
-.:....:..2.:.•:. .:. :3. and
CUl1'entonJue
so ~ 80fof, lasl encoul'ller" 10 0
-
Step 5
Figure 28.3 System testing of Encounter video game Engage Foreign Character use case
FUNCTIONAl TBTING
As p.111 of te ting thi Us" case, we <eo that In tep 2 quality values are exchanged. We tum to the detailed requirem e nt< (or qua lity va lues and va hdate eac h. The (ollowing is an example , taken from the Encounter SRS . 3.2.EC.1.2 QUALITIE
OF ENCO UNTER C H ARACTE RS
Every game c harac ter has the sa me sct o( qualities. E.ch quality shall be a nonneg.ti ve Aoa tingpoint number w ith at least o ne deci mal of precI sion . These a re all initialized equally so th.t the sum of their values is 100 . The value of a q u. li ty ca nnot be bo th grealer than 0 and less lhan 0.5. For the firs t release , the e qualities wi ll be CO)Jn'" frallotl , mttlligttlct, patitllct, sfa1tlHltl , and
strmgth. This can be decomposed as fo llows, 3.2.ECI .2 . 1 Every ga me charac ter has the same se t of q ualities. Each quality sha ll be a no nnegative Aoati ng ,pOi nt number with at le.st o ne decimal o( preCISion . 3.2 .ECI .2 .2 Th ese a re a ll initial ized equally
0
that the urn of thcir val ues is 100.
3.2.ECI .2 .3 The va lue of a qua lity canno t be bOlh gTeater than 0 and less than 0.5. 3 .2.EC I .2 4 Fo r the fi rst re lease, these qll.1 itie wi II be (Olletll lrali oll , ;IItrlligrllcr, pal;ntcr , ,'amllla , and
strmglb. • 3.2.ECI .2. 1 is validated by goi ng through each quality o n the srI quallf;'S ,,' indo,,' and ensuri ng th.t each has a deCImal value , as shown in Figu re 28.4 . • We validate 3.2 .ECI .2 by c hecki ng o n Ele na's quahties as the game begi ns
; Elena quality uJldate
.'~"\'~
Total life points: 60.0
Concentration Stamina
120 .0 OK
Fl&ure 28.4 System testing of Encounter Video game
, testing with GUI for setting qualities
698
CHAPTER28 TEsnNG AT THE SYSTEM LEVEL
. Elena quality update
I
'
I
Total life points: 25.563635
~
. fiend status
)(
I
I
Curre nt life POints 25 16364
Current value:
1
Concentration
0.0
Con centration
1°.4
1
-
•
-,
I
Inte lligence Patience
Done ' ~ Before last encounter: 1.3454546
lL _ _ _ _ _ _ _ __ __ __ _ _ _ _ . --
Figure 28.S System testing of Encounter video game testing via GUI for setting and viewing qualities
• Validatin g 3.2.EC. 1. 3 ca n be do ne by redllCing Elena's poin ts o n a quality to less than 0.5 . The result of se tting stamina ( 0 0 04 and showrn g thal Encounter actu all y sets th is imcrnall y to 0 is s(--e n in Figure 28 .5 .
• \VIc validate re qui rement 3.2.EC.I .2.4 by e nsunng that all pro mised qualities arc present and th at there are no additio nal quali ti es. We co ntinue testin g in thi s manner for the res t of the use cases and functional requ iremen ts.
Met n cs fo r fu ncti o nal testing are lIsually based on the requirements, and include the fo ll owing , • Nu mber/percent of detaded req uirements partially, and no t fu ll y real ized •
umber/percent
or detailed
requirements no t realized at
ell!
• Number of hi gh ·level req uirements no t implemented, as pe rceived by th e Custo me r • Number of detailed reqll1remenl not implemc!llcd, as perceived
by
the customer
28.2 NONFUNCTIONAL TESTING Thi s cction dcsuibes several common types of nonfuncti onal testing : performance, load/s tress, reliability
and availability, recoverability, lIsability, security , compalibili ty , installation, and serviceability test ing.
28.2.1 Performance Testing Perfonnance testing vahdates that a system meelS Its specified perfonnancc requirements b b h y 0 servIng t e throughput, or speed of the system. Throughput rerers to the number o f transactions that can be _" . Th e meaning . 0 f a transaction . d epen dson t h c: type of .lpplication that 's L- . procesScu · given amount a f time . d F 111 a • • 1 UC:Ing tes te . or our Video SlO'" apphcatJon, speed could be measured by the l1umbe r of-vldeo rentals th.I can b- P d ' .... rocesse per mmute.
NONFUNCTIONAlTESnNG For a ~31 · tim~ communication system , peed nllght be measured by the number of data packets that can be p~ and forwarded ~r econd. Good requi~ments w,lI have avoided vague statements about ~rfonnance such as 'customer ,csponses should be acceptably fast ' uch vagucness causes problems because the stakeholders can harbor very different interpretation of ' fast : For the video store application, a well·wronen ~rfonnance requirement is 'The appl, ation hall be able to successfully handle a load of 1000 rental requests per minute.' Te t environments such as Eclipse's Test and Performance Tool Platform ( ee Section 28.6) identify the packages, classes, and methods with high execution times, as well as those invoked frequently . Mernes for performance testong are u ually based on perfonnance requ,rements, and include the fo llowing, • Number/percent of speed requirements not satisned • Number of memory use requirements not satisned • Number of s~ed requirements not sati sfled, as perceived by the customer • Number of memory use requirements not sa tisned , as perceived by the customer
28.2.2 load/Stress Event Testing The purpose of loadlstress testi ng is to subject a system to incrcasi·ng loads and to tress it in various other ways to detennine its breaking point. Another way of stating th os is 'under what load does the systcm start to breakt Examples ofthe types of loads used are maximum number of users supported , maximum number of transactions ~r second, and maximum data transfer rate. Once the points of failure are determ,ned we can understand whether the system meets its load ·related requirements. Knowing these limits also allows us to examine the system desi gn to understand those pans of the architecture that arc susceptible to stress, and use this for future plann,ng. A good requirements document speCifics the performance of the applicati on under precisely stre ed circumsta nces. As an example, suppose we have the fo ll owing performance req uirement. Th, sot, shall halldl, custOll"r v,sits with a maxi",,,m of fD stcollds wait "m, "ndtr th, followillg conditions. VISIts occur in a Pois son (probability) distrih,,"on with at, avtrag, of fDO ptr IIIill"t, Each ordtr is ai' avtrag, of 2 books, distrib"t,d IIonllally with a stalldard dwia tion of 1 . An example of a loadlstress test based on th is requirement is the fo llowing. Visit th, sil, for 10 mill"ttS with an aotrag' of 100 c"stomm ptr mill "t,. Each ord,rs at, a"trag' of 2 books, w,tb a standard dwiation of L Rtcall that the Poissoll distrib"tion si mul ates arroval times at a queue, the st""dard dwiation measures the extent to which data varies from the mean . For examp le, a variance of zero ,n the orders of the above requoremen! would mean that exactly 100 customers ca ll every minute O nce we va lidate the system ca n handle this load , we increase the number of cu tomer vi it ~ per minute to determine the point at which the application exhibits a probl em. In many cases, loads and strcss limit arc no t ex ploc,t1}' spe oil ed in a requirements document In th,s ca e, the project manager, QA, o r management decides o n the rargets to be attained based o n the lollowing factors • User and customer ex pectations • Technical lim'ts • Costs of improvement
699
700
CHAPTER 28 TESTING AT THE SYSTEM LEVEL
• Le8~1 advice •
larkct
ond ili ons
• 4xpt'ncncc with past products • Comparisons Wilh competitors' products
T ools such as Eclipse's T est and Performance T ools Platform (TPTP
see Section 28 .6) provide the
number of objec ts rca ted at nlntimc and the amount of memory they consume. V arious gra ph ica l devIces art:
prOVided th.t sho" a "thermometer" reading o f memory consumption (min to ma x) by mo uSing over a sequence diagram of h.nction Invoca ti ons. Tc'S tcrs seck ma ximum and near·ma xlmum rea dings . The sequence diagram
can be ge nerated fro m the test execution . TPTP shows how many objects refere nced a give n object at runtime. MetriCS for loadlstress testin g include the fo llowing , •
'umber/ percent of load/stres requirements not satisfied
•
umber/ perce nt of loadlstress standards (industry or company) not satisfied These can be decomposed by types of loads and stresses.
28.2.3 Reliability and Availability Testing It IS an implICit requirement fo r every application th.t it be available for usc! Sometimes it is acknowledged that the system will have defects or th.t it wi ll not be able to survive defects in its environment (e.g ., the opera ting sys tem) and will crash at times. Rtliabi/ity "lid a"ai/ability assess and measure the extent of this. Relia bility and avai lability arc ty pically measu red by the mean time between fa ilures (MTBF). T o obtai n MTBF, a defillition of "failure" is first specified-for example, a crash of the appl ication that requires its reload. Several different levels of failure ma y actually be defined and used. To compute the MTBF. a tester start.s the application and notes the time. He orshe then executes the appl ication using, ideal!y, random scenarios until the system fa ds. The elapsed time is computed. This process is performed repeatedly; the MTnF is the average of these times. Obtai ning a very reliable value of MTBF involves hiring people to use the applicatio n according to some controlled rules and procedures. Gathering these data for man y hours requires significant compensatioA for testers. Naturally. one tries to gather the data while users are using the application for another purpose. However, the other purpos~r purposes cannot be permitted to bias the results. A related technique is to have a large body of users exercise the applICation in advance of its official release (see Section 28.4.3 concerning alpha and beta releases). To obtalll an MTBF, it is necessary then to estimate the number of users and the lime they spend using the application. As many know, the gathering of this kind of data continues even after a prod uct is shipped. as in the pop·up message "Please send us notiRcation of th is fail ure . .. •
28.2.4 Recoverability Testing Many otherwise excellent applications crash from time to time, The reasons may be beyond the control of developers, such as power outages. A good SRS specifics what should take place when an application crashes. A common require ment is that, whC'n restarted , the application returns to its state at the time of tht: crash. This is a rrc01JfI'ab,lily rcqul,,,"ml. Anothercommon requirement is for a designated log ~Ie to conta',n a . I . f h .
.
n exp anahOn 0 t C
crash s cause (ratherlike an airplane s black box). As an example of a recovery techn 'Ique con d h"b k • • $1 C'f( e ac StOP technique employed by Tom VanCourt on the Encounter video game The code ,' s ho . L' . wn In I tlllg 28. 1.
NONFUNCTlON.Al TESTING
28.1: Recoverability in Encounter video game
INbliC: .tatic: void main( Stringl] argv) { try {
// Create the main applicat ion wi n dow . 1!n&1 GameMain gameFr ameM = new GameMain ( ) ; g ameFrameM . addWindowListener ( new windowAdapter () { public void windowC losed ( WindowEvent e ) { Sy s te m. exit(O) ; } public void windowClos ing ( WindowEvent e ) { gameF r ameM . dispose ( ) ; }
)
} ;
// Set frame to a workable size . The size given here is only // approximate , since the frame can be resized and the layout / / manager can adapt the content over a wide ran ge of sizes . // Ad d in approximate amou n ts for window frames , etc . gam eFr a meM . resize ( GAME_AREA_WIDTH + 25 , GAME_AREA_HEIGHT + THUMBNAIL_HEIGHT + 25 ) ; gameFrameM . createGameUI ( ) ; // Set up the user interface . gameFr ameM . show ( ) ; // Display the win dow . gameFrameM . validate () ; /1 Display the win d ow co n te n ts . gameF r ameM . toFront () ; // Start in front of other wind ows. } catch ( Throwable thrownException ) { // Backstop exception handler : Catch any exceptions not already I I hand l ed elsewhere and try to get debug informatio n fro m them. / I Runt imeExcept ion obj ects , in part icular , can be thrown by // any method wi thou t hav ing been dec lar ed in a ' thr ows ' clause . System . err . println( thrownException . getMessage() ) ; thrownException . printStackTrace( System . err ) ; }
}
The effect of this odc i to trap excep tion, not hand led elsewhere and report them before the applicataon stops. One can tc~ t for thl at :hc system leve l by entering ill ega l valell's suc h as 10 '0 for strength value of a qlll1lily . M e trics for 10acVs tre.- tc ~ tin g include the fo llOW ing: • Number/ percen t of rc ove rabil,ty reqUireme nt > nOt
701
702
CHAPTER 28 TESTING AT THE SYSTEM LEVEL • Frequcncy of auto· recovery compared with thc deslrcd auto ·recovery frequency •
tcan recovery time
• Mean r('S tart time
28.2.5 Usability Testing U,./lIlily ''' 1119 va lidates an application's acceptability to Its users. Thc primary goa l 01 u ability testing is to ensure that the application sa tisfies Its stated u ability requirements. These should be provided in the SRS In quanrified tem1 S, toget her with the manncr in which the deSIred quantities arc to be measured. Kit [ Il lists the overa ll critcna in Figure 28.6 as csscnrial lor usabi lity tcsting. For example, wc might reqUirc rhat a random sample of 30 users of our home finance application rate the application o n a scale of 0 to 10, as shown in T ablc 28 . 1. An inspection of the accessibility results shows that our application scores about 12 percent lower than the industry average-some cause (or concern . Our va ri ance is lower than that found In industry, however, which means that the sampled users agreed more on
• Accrssib,/,ly How easily can users cnter, navigate, and exit ' • For example , mea ure by average time laken to ... • RcsponslIJnltss
How rcady IS the application to allow the uscr to accomplish specified goals? • How often IS CUI display accurate (pe rce ntage)? • How quickly arc user actions ack nowledged? • How oftcn is the application rcady for user actio n? • EfficifflCY Degree to which the number of required steps for sclected functiona lity is minimal • "Minimal" calculated theoretically • For example , measure
by
minimal limclav('ragc time
• Compr
Figure 28.6 Key attributes sought in usability testing so..n-to. Kit. &1Waro. SOftware Testing in !tie Real Wor1O Impn:Mng the PrOCt"SS. Addlson·Wesley, 199$
Table 28.1 An example of usability scores
Score
Vat1ance
Industry average score
Accessibility
8.1
2.1
8 .2
3.5
Responsiveness
9.3
3.2
5.0
3.0
7.2
1.1
6.0
0.3
Quality
Efficiency COmprehensibility
5.6 2.3
2.0
O.S
+
Industry average vat1ance
NONFUNCTIONAl. TESTING
thIS seo"' .than u ~rs t pically as",e on the usabiloty of a UI. This tell< us thot a smaller percentage probably acru.lly dl Ioke uson g our applocatlon than i u ual. The appropriate ample sIze depends On the desi red probability of an erroneous conclusion. If we want a smaller probabiloty o( Cllor, we need a large r sample. Usability data can be collected on a controlled or uncontoolled environment. In a contro lled envi ronment , subjects arc o bserved and data like the following are obrainerl: • Average time for the u er to comple te deSig nated functI o ns • The rate of user errors on desig nated interactions • Average time take n to learn new function • Average time taken to complete d eSignated tasks (e.g., crea te a letter in a word processor) • The results are compared with required , compan y, and industry no rms. Users arc very sensitive to applications with which the or experience deviate much from what they arc used to . In designing usabili ty questionnaires, the challenge is to obtai n data that enable engineers to remedy the most serious shortcomings without exceeding the lim its of user ' time and patience Alling out questionnaires. Usability data can be expensive to collect because users often expect compensatio n fo r the time and trouble of providing detailed feedback. For example, a client of o ne of the authors develops software for a device used by physicians. The company provides a free dinner and signiAca nt mo neta ry compensa tion in return for viewing and commenting on screen sho ts and demonstrati o ns Turning now to uncontroll ed environments, Figures 28 .7 and 28 .8 show the beginnings of the Purdue Usability Testing Questionnaire [2], which provides useful data from which to assess the value of and potential improvements in a set of CU ls.
28.2.6 Security Testing Security testing co nsists of id enti fy ing securi ty defects and measuring the extent of an application's security . Recall that some princi pal aspect of security are those Ii ted in Figure 28 .9. We can base securi ty testong on these. The I.esting ca n be performed by using or imulating interception of traffic (called "sniffers"), usi ng software that attempts to break systems, such as sc rip ts that repea tedl y try pa<sword break -ins, and by uSIn g people of varied skill leve ls to try delibe ratel y breachong the desig nated security aspects . At the hig h end of this spectrum o f skills are people wi th experie nce '1, acking." A hi gh leve l o f Sc urity clearance i< required fo r them . Usi ng hacker ca n prese nt majo r problems whe n an external co nsultong company i the o nl y alternati,'c and especially when the experie nced people have bee n invo lved in unautho ro zed activi tIes in the pa t The OPtto Sou,Ct Security Testooog Methodology Mml u"' (OSSTMM ) is an Opell standard me th od o logy (or performing secu ro ty tests [3]. OSSTMM focu<es o n the technica l detail . o f which Iteon need to be tested , what to do during a sccuroty tcs t, and when dlffcrent type< of securi ty test. shou ld be plTformed. A checklIst for confide ntia lity testIng in in forma tio n secu rit y, parti y ada pted from OSSn,1M , includes the fo llOWIng actions_ o me arc part of non -securot y lest lng as we ll , a o ne co ntlnue< to re ognize thnt many se urity breaches SImply exploit a defect In the ohware • Validate conflde nlo al d atabase 10 alo o ns • Scr e n all dat.bast:s for co nfide ntoal co nt en t
7Cd
"g n
Purdue
~
Questionnaire 11><>1111'/7 ofDf6
"""on.
oCpE.nU
g1 '" '"
iil :;j
Z
"~
PIe ... raIe th. u.ability of the system.
J!
m
II>
Try 10 respond 10 all the items. • For Items tlw ate not appbcable. use NA o Make run: the •• 6elch are 61!ed in. System: Email I. :
-< ;ri
o
II>
;:
t2
• Add a cOUlment about an dem by c~cking on its II Icon, or add comment fields for aU items by cbckmg on Comment All.
To mail III your result•• chck on: Mail D.,.
o
J
Syrtam.l_
-. ..".-, -- ..--.,....
-~
.
.
..
"'~'-'~-~'-
r
j-
r
Email I,,, r~_ _ _ __
commenlS and your et:naJl address
r/.
m
to the bOK
_,",.",.~
~~;'.;..t.1- . .",,_r~ RF:TURN TO REFERRINO PAOE
1. \,;um rAU"",u:1' - - - - --
I. Is the control of cursor compatible with movement? 111
bad
2. Are the results of control enb'y compatible with user expectations? GIl
bad
3. Is the control matched to user skill? ,.
bad
4. Are the coding compatible with familiar conventions? lD
bad
5. Is the wording familiar?
bad
FIgure 28,7 Purdue usability questionnaire fragment. 1 of 2 Soufu Plldue usability T6 Ung Qu
1 1 3 4
5
6
7
r r r r r
r r r r r
r r r r r
r r r r
good
('
good
r r r r r
r r r r r
r r r r· r
NA good good good
r r r r r
6. Is the assignment of colour codes conventional? C
bad
r:
2 11 S J[ ot u-S II'! 0 0 () (j 0
7. Is the coding consistent across displays. menu options? C
bad
0
0
0
0
(j
8 Is the cursor placement consistent? C
bad (j
(j
(j
(j
0
9. Is the display fOllllat cO!lS1stent? C
bad
0
0
0
0
0
10 Is the feedback consistent? C
bad
0
C· C 0
0
11. Is the fomlat within data fields consistent? C
bad (J
0
r
()
C
12, Is the label format consistent? C
bad (J
0
C
(J
C
r o good 0 r C good C ('. r good r 0 r good C r C good 0
13 Is the label location consistent? C
bad
r: 0 0
r·
()
r. C
14. Is the labelling itself consistent? C
bad
0
0
0
0
r: c
C good C
15 Is the display orientation consistent? -- panning vs , scrolling. C
bad (J
0
()
()
0
16 Are the user actions required consistent? C
bad C
0
0
0
C 0
17. Is the wording consistent across displays? C
bad
0
0
C
r
C 0
18. Is the data display consistent with entry requirements? C
bad C
(",
0
0
0
(",
19. Is the data display conSiStent with user conventions? C
bad C
0
0
0
0
0
r o o o o
20. Are symbols for graphic data standard? I::J
bad
0
0
0
(",
0
C- O good 0
21 Is the option wording consistent with command language? I::J
bad
0•
0
0
0
0
0
22. Is the wording consistent with user guidance? C
bad
0
0
0
0
0
0
--
Figure 28 ,8 Purdue usability questionnaire fragment. 2 of 2
.source
P\KOue vsabdity Tescng QueslJoMaire. httDl /WYM acm Ofg!- perlmanlquestion cgi1form",PUlQ
"
C good ()
C C
~
0
o o
C
good
good C
good
r
good () good
0
good
0
good
0
good
0
good
0
-
z 0 z ."
c: Z
!:l (5 ~
r-
~~
~
706
CHAPTER 28 TESTING AT THE SYSTEM lEVEL
• ConRdenti.lity • ",ffers vahdate that d.ta passed not vi sible to unauthonzed p.rtles • Hlrc profession. 1 hackers] • Nonrcpudiation • Experiments to va lidatc • Integrity • Alter data .nd validate consequences • Authentication • Hire profeSSional hackers) • Authorization
• Hire professional hackers) Figure 28.9 Testing (or security
• Valid"te cookies •
Content, types , expiration , and encryption
• Check for buffer overflow protection • Check for memory leaks • Test for illicit site navigation
• Validate Sign -inS • Include default IDs and passwords • Check protection against illegal and out-of-bounds input (not necessarily input that allows breaches) Merrics for securiry testing include the following . • Number/percent of specific security requirements not satisfied
• Number/ percent of security standards (industry or company) not satisRed • Confidentiality: Average time required to gain disallowed access to informa.tion • at a specified level of security • by testers of a specified degree of training and expenence • NonrcpudiatlOn: Average time required to repud iate agreements • Integrity: Average time required to alter data in transit , undetected
• Authentication; Average time required to verify identity • Authorization : Average time required to gain disallowed access to a location
28.2.7 Compatibility Testing Many applications arc designed to work with other applications. For example a word pro h II . . . . . Ceisor t at a ows the Insemon of a ~prcadshcet must be compatible With the spreadsheet application Anoth I . . . fr I -h . . . or examp e IS an application that obtainS data om peop e Wit mobile deVIces of variou.s brands Com 'b ' I' . _ ,
patr
I
Ity testing
IS
NONFUNCTIONAl TESTING
s.milar to integrat.on te ting III that it tests the interactions between parts of an application. The difference .s that the Interfaces are typ.cally developed by different organizations, and developers normally can't change the applications with which they mu t be compatible . An important subfield of compatibility testing is assuring that the application operates w.th deSignated past ver<.ons of software on which it depends . This includes versions of the operating system. An example is an online learning env.ronment, wh ich must work with various versions of Windows as well as with UN IX. Compatibility with future versions can be planned for to some extent, and it is sometimes possible to si mulate upcoming changes. Testing must include combonations of versions. Metri~ for compatibility testi ng include the following , •
umbe r/percent of speCific compatibility requirements not atisfied
• Number/ percent of compatibility standards (industry or company) not satisfied
28.2.8 Installation and Installability Testing An installation test validates that an applicati o n can indeed be install ed. An instal/ability te t is a more general concept in that it tests via installation test cases whether an applica ti o n can be installed o n a va ri ety of configurations. Installation tests whether an appltcation ca n be successful ly .nstalled o n its targe t system . These are binary canlcan't tests Many types of errors can occur during insta llatio n, espec.ally du c to the djfferences in hardware and software platforms. Applications are often required to execute o n multiple hardware and software platforms. Multiple platforms typically require separate tests. For example , .f our v.deo store app lication were required to execute on Windows and Macs with Internet requirements, we wou ld devise tests that ensure the satisfaction of the requirements on each of these platforms. Although we try to develop applications that arc plat fo rm independent, thi s has limitati o ns. Fo r example, we may need to te t with separate bar code readers for Windows and Mac platfo rms . Installatio n tests would be ide ntica l for the most part but would contain Windows·specific and Mac·specific parts. Once we have tested that an appltcation can be installed correctly, we run a second tier, co n ISting of installability tests that measure the level of d iffiwlty of installing the application . As computer u ers we are all too famdiar with how easy or how hard it is to install an app lication . Installability tests thi s proce S and the aspects of the application that make this easy or difflcult. Metrics for installation and insta ll abilty testing include the fo llowing , •
umber/percent of speCific in tallability requirements not sa tisned
• T.me required to install o n deSignated platform by custo mers with designated amount of expert en e or education • Time required to co nnrm installation intcgrity via a standard test seque nce • Number of d e fec t~ found durtng .nstallation, with "defects" carefull y defined
28.2.9 Serviceability Testing Serv.cing an applicat.on .s the pro css of repainng or enhanci ng it This could include visiting the itt and sending a full or partlal replacement ovcr the Internet. An applicatjon '~ strVlCcah,lity refers to the ease or dtlfi tllty w.th wh. h it an be kept opera t.o nal In the face of changes to .ts envlfonmcnt. For example, an expert system appltca t.on reltes o n Its knowledj:e base typ.cally in the form of a \et of rule., whKh may be straightforward to moddy Another exampl e b the ca<e
7m
708
CHAPTER 28
TESnNG ATTHE SYSTEM LEVEL
with which an appJ. Juan that nlns o n o ne versio n of an opcra tlnH sys tem can be made to run on Its successor
umber/ percent of spcCllk scrviccab.!lty requirements not 311shed
• Number/ percent of serviceability stand ard (,nduStry o r ompa ny) no t allsf,ed • Time reqUIred
to
sC r"\' lce
actions on deSignated platfo rms
28.3 TESTING WITH LIGHTWEIGHT REQUIREMENTS Th is secrion di scusses tc tln g in the co ntext of requirements that range from being not written duwn at all (Section 28 3. t) to betng o nl y partially expressed in writing via the user stories of ag tl e processes (Secti o n 28 .3.5 ).
28.3.1 Testing in the Absence of Requirements i\4ost of the softwa re engineenng literature emphasizes the importance of requirements a nd the execution of testing against th ose requiremen ts. Hi g her CMM levels arc bestowed only on those organizallons that wnte down reqUirements thoroughl y (see Chapter 6 ). However, man y real · world applications have Incomplete or even nonexistent requireme nts docume n ts. Our concern in thi s chapter is how to rest such applications . Even when requi remen ts do exist in written form , the)' generally cannot prOVide a very good feeling for [he apphcation compared with running code. This is like the dif fe rence between drawin g detailed plaAs for a house and living in the house after it is built-they arc simpl y not the same. In fuct. if we want to determine whether a hou.se that is already built satlsnes needs, it is more useful to ask the occupants thaa to inspect the architect's drawings. Figure 28 . 10 summarizes the reasons for res't ing wit h little or no reference to a re::quirem ents document .
Suppose that yo u have been asked to test an applicatio n for which there is no requirements document. Where do you begin ) In the next sections, we'll describe a starling poi nt, a h,haDiora' ",odel of the applica ti on .
• PrOVides a "feel" for the application Even complete , wnnen req uirements do not accomplish this effectively • The Requirements document omits implicit ones
• The ReqUirements may - be incomplcre - be inco nsistent With the code - be missing - never have been written down at all • You can't access the requirements because the product is from Vendor software that you must test before using
d
third party
Figure 21.10 Reasons to test without basing the tests on written requirements
TESTING WITH LIGHTWEIGHT REQUIREMENTS
28.3.2 Models for Software Testing To tcst an applicatIon 10 the ab cnce o( \vell -wrltten reqUIrements, the tester needs a .cnsc o( how thc applicanon is meant to beh. e and how it actually behaves. ThIS IS ca lled btl,.1IIo",/ moddillg . Mo t o( us have alread had a behavioral modehns expericn e In dealing with an unfamdl3r application. Although we may road the manual or follow a tlilo nal , we often si mpl y ' play around" with the application . Th, s cCtl on conCerns dLClplined ways to "play around" with the goa l of fi ndlOS as many defects, as serious as po sible, in as little nmo as possIble. ThIS is not the black·and -white proces of requirements-based tesllOg, and it is someti mes called 3n "arl: Good artist . however, arc extremely well -dis iplincd, and good testers are too. Onc approa h to forming the concepts of an as· built (already constnlcted ) applicati on is to u e the software design models that we covered in haptcr 15 These are the uS! .It modds, clnss modds , dtllnJlow ,"odds, and slalt mo.lds. These arc valuable (or creatIng desi gns o( applicat Io ns yet unbuilt , but they are less 0 (or modeling already -built applications. Table 282 indicates whcn these deSIgn model could apply to behavioral modeling of already-bu ilt applicat Ions ThIS suggests that a different or modified model shou ld be soug ht , as di scussed next. Table 28.2 Applicability of various deSign models to black box testing of as-built applications oeslgn Model
Applicability to As-Built Black BOX Testing
use case Model
Apply use cases to identify the main, unbranching behavior Typically not especially useful for black-box testing Possible if the tester recognizes principal functions Possible if the tester recognizes states that the application transitions through
Class Model Oata Flow Model State Model
28.3.3 Constructing Directed Graphs for Black Box Testing
w. will
use the concept of dlrtcltd gmpiJS in what fo li o"" . A directed graph is a Rgure consi ting of node , together with arrows between certa in nodes, called tdglS , illustrated in Figure 28 . II The meaning o( nodes and edges depends on the conlext in which they art app lI ed
node
edge
Figure 28.11 Directed graphs
709
710
CHAPTER 28
TEsnNG AT THE SYSTEM LEVEL
3 ~---
1
4
Actions • Launch text document processing • Enter leX1 • Hit liIe / save • Enter a file name and press save
An action
Edge Indicates sequence (only one in this case)
Figure 28.12 Initial directed graph for OpenOffice
O ne approach to modeling as· built applications is to sta rt from what appears best to be a beginn ing point of th e application , and then keep track of the paths from th ere In directed gra ph form . Each node represe nts an act io n performed by the user o r the appli cati o n (someti mes a seque nce of such act io ns instead). Each edge leads to the next possible act io n. Edges arc labeled ",hen necessary to distin gu is h options. This use of nodes and edges IS neither data flow nor state/ transition. It can be tho ug ht of as a control flow in that each node represenlS a point at which the applicarion i in control.
As an exam ple, let's perform th is for the word processor of the open source ofRce suite OpenOfRce. Besides servi ng as a means forblack box testi ng, a directed graph is a means of ge tting to know the application. Figure 28. 12 shows the ~glnning of a directed graph for executing OpenOfRce's "Writer.' its word processor. Si nce thero is no branching in the example o f Figure 28 .12, there is no need to label the edges to understand the seque nce of actions. In Figure 28 . 13, o n the o ther hand, there is such a need. Branch points aro labeled as nodes like any other (which makes these diagrams different from o thers we have studied in this book). Figure 28 . 13 shows a continuation o f the graph ing process. The numbering serves o nl y to label the nodes and docs not denote an o rder. The la~ls on edges are used to assist in d ifferentiating among branching o ptions.
1\-----
s:::- savebold
Actions 1. Launch text document processing. 2. Enter text 3. Hit file I save as 4 . Enter a file name and press save 5. Convert 3 line to headings at levels I .
save
4
headings ~
[Pred icate
nOde)
7
F
2. and 3
T
6. Bold some lext 7. File exists? 8. Hit save ' "already exists" pops up ,
FllUre 28.13 Elcample of a directed graph for OpenOffice
yes
8
TESTING WITH LlGtfTWElGHT REQUIREMENTS
- - -1
-
. save -
"
Palhs:
--- - -~
- ->
·• .. headings •
bold " " '"
Actions '. " 1. Launch text document processing. 2. Enter lext 3. Hil file ' sa VB as IPredicate 4 . Enter a Ii Ie name and press saVB node] 5. Convert 3 line to headings at levels ' . 2, and 3 6. Bold some text 7. File exists? 8. Hit save '"already exists' pops up ' yes
save / /
F T
8
f"tgUre 28.14 Using a directed graph for testing-openOffice example
• The most .,xpected path s with no e rror o r a no maly condit io ns • Th., most expected paths with error or anomaly co nd iti o ns • The paths most likely to Yield defects Figure 28.1 5 Selecting paths in directed graphs for testing
28.3,4 Using Directed Graphs in Testing Tests are de igned via sequences that traver e mult ip le no des. A reasonable goa l is to crea te enough of these to cover all nodes. (Attempting 10 cover all pnl/, co .. blllalioll' exposes more defects but usually leads to a combinatorial explosion in the number of poss ibilities.) Figure 28 . 14 sh ows Ihree paths that cover all nodes , The number of eque nces made of these path s ca n be extreme ly large . The tester can be elective among these as in Figure 28 IS , h owever.
28,3,5 Testing for Agile Processes As mcnlloned in previou c hapters, continual tes ting IS an IIlteg ral part of agi le proces os, especiall y via utilities such as JUnll and N Unit Allh oug h suc h tests focu, on a method under constnlction , a growing , cumulative set of unit tests ca n e ffe c ti vely te,t large parts of an app lica ti o n as it grow . A sU ite of jUnit te t , grown mel hod by metho d and class by la, (as In hap ter 27), rn a be part! usable for functional testing ( , e , to check that the rcqullcme nls have been . at"Red ) H owever, Invariab ly there will be reqUirements for whl h th 'yare not a pp ropria te , uc h a th o.e that reqUire user intera tl On The follOWin g kinds of teS lin g arc ca rn ed o ul for a!,l dc rroJ,:c t\ In the sa me wa y a, for non . ~gdc ones
•
onfunctlona l tcst lll g (pe rfo mla nce, 10aeVs trc", cvcont, rc ovcrab ,hty, lIsab ili! , SeCliftry, o illpatibil itv ,"stallatlon , servlceabdit y)
• Accertancc tc,tlng (a cnlr. I part of Ih ' a~ d c approa h )
711
712
CHAPTER 28
TEsnNG ATTHE SYSTEM LEVEL
28.3.6 Qualities of a Good Tester - g 0 r 's bu I It applicallons. A good tester, We have described various tcchnlques fo r t hc blac k' I)OX te.Sttn however, goes well beyond them In hIS or her efforts In tryi n!: to ferret out defect that could be encountered _.,111 an t time ' ., per. Il aps In u nant, c,pated ways. He orsh. .shou. ld w hen many people usc the appilCJllOn ror J sign U
·
be an Independent th,nker and should not be part of the tea m that deSIgned or ,mplemented the appllcat,on under test. Thi
IS
bcc~u~c ('ven
the most Independent pc:r o n involved
a vlS,on of the app hcall o n that , eve n when excellent " following arc o rne of the qualities of a good tester:
In
dcc;lgn or
Implemcntatl~n
develops
likel y to overlook or misunderstand ISsueS . The
• Willingness to learn goals of applica tio n • Wdlingness to pu t self in uscr shoe< • Dcterrmned • Dogged • Fearless • Imagi native
• "Outside the box" thinker • Curious
• Meticulous
Let's translate these qualities into the testing of OpenOfr,cc. T o fi nd as many defects as possi ble within a fixed amount of time , the tester would need sufficient detenninatlo n to go beyond the obvious ways of using the application This is because the com mon procedures will probab ly have been exercised many times and thus have been debugged . The tester would need dogged nes< to stay with h, or her intuition concerning lurking bugs even when it yields few initial bug finds . In the nonnal usc of an application , users tend to be relatively gentle . For example, the y avoid hitting a cont ro l-X butto n while a fi le is bein g saved, o r pressing many keys in rapid succession, including functio n keys. A tcster, on the o ther hand , need the fearlessness to stress th e application In such a manne r.
There is another sense in which testers need to be dogged: ge lling actIOn on the defects that they And. Kaner [5] notes that Anding 'lnd obtai ning action o n discovered defects i significantl y mo re important than simply fi nding them. H is pOint i that the time spent discovering a defec t i wasted if the defec t is never repatred. It is certainl y the task of QA to ensure that qual iry is present. and this includes en uring appro priate actio n o n def(·e ts.
T t'Sters need enough imagination to think of many different ways of usi ng the appl ication . The)' need to · think out ide the box· because defects arc usuall y found in execution paths that arc not obvious. For example, in testing the OpenOfAcc word processor, a good tester would pursue sequences very different from the nln ' of·the- mill opm fildtdillsavt sequencc_A more de111and ing sequence is opm fllrl..,ld 10 1i""ISt' Somt Ii"" '" II
TESTING SHORTLY BEFORE RELEASE
28.' ~STlNG SHORTlY BEFORE RELEASE Every project ha, a hi tory of testi ng lasti ng almost as lo ng as the projec t Itself. H owever. the period JUSt pro or to relea,ing the appll aloon has specia l testing characteristics. which are described in thIs sectIon.
28.4.1 Soak Testing h is common to conduct loak 1<s/on9 ncar the end of the system testi ng phase. During soak testing the applicaroon IS executed In an environment that simulates as closely as pos ible the way a tYPIcal customer WIll use the sy tem under no rmal load . The soak lest is conducted for an extended penod of time for eX.IIOple , twO weeks. rest scnp~ are used so that the testing can continue for the entire duration wilhout intemoption . The purpose i to uncover problems such as memory leaks and timong.related is ues that only manofe
28.4.2 Acceptance Testing In principle , the customer contracts with the developer to build an application . At ome POonl, the developer claims to have fulfilled his or her part of the contract, the cuStomer validates this , and then pays for the application if satisfied . The customer performs thl validation by means of ncaplalla 1<sls In pnnclple , these arc most important for all concerned . Acceptance tests can be executed by the custo mer, or by the development organization-in ome sorr of clearly demonstrable manner on behalf of the customer. Acceptance tests arc lYpically driven by the SRS . A subset of the system tests i selected that valodate maJor funerional requirements and selected nonfunctional requirements. It is a realiry of software de velopment that deli ve red applocatlons contaIn defects. If a con tra t were to stale that software will not be paid for if a defect IS found , very few compan Ies would ro sk deve loping software. Defects therefore have to be factored into contracts There arc several ,,'ays to deal WIth this, mostly legal In nature, that relieve the devel opment orga nIzati o n of a degree of responsibility . Recall that soltware ~an meet all its requireme nts ye t nOt meet the II"dl of the custOmer. o ntrac ts attempt to navIgate the gap between customers, who want appl, cation . that arc satISfactory to them (" ' rot te n or not ), and developers, who need to work WIth wcll ·dcflllcd ends. Acceptan c testong IS planned and tonducted accordingly. Metrics for acceptance leStong are a subse t of those covered so far In thIS hapter, by mutual agreement between the customer and devel oper, made In advance.
28.4.3 Alpha and Beta Releases Th,s sectIon concerns ap pll ato o ns Intended for usc by a large number of pc pic A oftware product versIon I rtl"",d when it os officially turned over to CUStomers. This usually take. place dorectly after a ceptan e te
713
714
CHAPTER 28 TESTlr.jG AT THE SYSTEM LEVEL
/"-/'0"" a"d
hig/I/Y !M"J
"sc,..
• Multiplies tes tlll g • Prcvlcw~ custo mer rea c ti on
Alpha
• BeneAts thlrd -pany deve lopers • Foresta ll co mpetitio n
c/ected cU5tomers • Multiplies testin g act ivity • Obtains c usto me r reactio n
Beta
Figure 28 _16 Alpha and beta releases
give n to part of the custo mer co mmun ity wi th th e unde rs tandin g that they re po rt defects fo und . Alpha and bet. releases are also used to co nv mce potential custo mers that th e re rea ll y is a product behind th e vendor's pro mises. A prinCipal motiva tion to be alp ha testers and beta testers is to gai n advan ce know ledge of the product. Developers can gam informati o n about the appl ication (typica ll y its AP ls) so that th ey ca n begin to d evelop applications that use It. Users can begi n to fo rm decisions abo ut purchasing the application o r gai n •
•
t!xpen(" ncc uSing H.
Metncs fo r alpha and beta testing include the metrics mentio ned so fa r 10 th is c hapter, in principle. Alpha and beta tesllng are generall y not focused o n particular attributes. ll,ei r products are bug reports, which arc ge nera ll y ca tegori zed Metrics include mos t of those already mentio ned in thiS c hapter, as well as th o se with a simpler ca tegorization such as the fo ll owi ng: •
umber of majo r defects detec ted within the firs t x days/weeks/mo nths
• Number of no n-major defec ts detec ted within the Arst x days/weeks/mo nths
28.S CASE STUDY: ENCOUNTER SOFTWARE TEST DOCUMENTATION'
Note to the Student: Th is document describes the overall testing of Encounter. The document uscs the IEEE Standard 829- 1998 Software T cst Documen tation (STD ) headings (in'roduc'ion. plan. ttSt JrsigH. Icst CdStS, Itst proceJwrn . trst .ttm rro"slIIillal "port. ,,,' log. incid.. , "port. ' UIIIlIIary ) and refers to the various particular t~sts (i ntegnUlon tests, system tests, acceptance tesfS, etc.). These, in fum , are described using th~ same IEEE SID headings. Thos~ involved in testing appreciate fhe documentation a
'tS'
'tS' 'tS'
g reat deal since it improves their ability to make applications more reliable .
H IStory of version of th is document: 1111 /98 E. Braude, In itial Draft 4/4/99 E. Braude: Revised 8/23/99 K Bostwick· Documents reviewed and recommendations made I R(produced wit h permiSSion ,
CASE STUDY: ENCOUNTER SOFTWARE TEST DOCUMENTATION
8/2411999
E.
Braude:
integrated
Recommendations
Status: to be completed
game. IEEE standard 829- 1998 for Software Testing Documentation is used at every I~I of testing. The test philosophy for the Encounter video game is summarized in Figures 28. 17 and 28. 18.
1. Introduction This document contains the STD for Encounter and its role-playing game (RPG ) fra mework. The categories of testing addressed in this document include unit • integration, system, acceptance, and installation test. ing. This document describes the testi ng required to validate the nrst three builds of the Encou nter video
Although the SOD is not explicitly a requirements document, it efkctively imposes requirements on the implellientation. Sometimes these requirements are spelled out in a separate document. The case study in this book does not contain such a separate document.
Test Type
Unit
Integration
Approach White and black box; method and class tests, tcst agai nst detailed requirements and design. Gray box; mostly package· level; orien ted to builds ( I, 2 , and 3), test against architecture and high-level requirements.
Corresponding document sections SRS scction(s): 3.2 Classc.IObj,el. SDD sectio n(s): 6. D,'ajt,d dt<jgll
•
SRS sectio n(s): 2. Outrall dt
quirements in 3.2 Classr.IObj,cls SDD sectio n(s): 3. D,compo.ilioll dt
System
Black box, all packages; whole system (Build 3); test against nonfunctional requirements, . r· chitecture and hi gh-level requiremen ts.
quirements in 3.2 Classt
mluirrmruls, 3.4 DrsigH constra;,ds, 3.5 Sofllva" allribult< , 3.6 Olh" "4I1irr",,,,', t
,y,'tm
SDD ectio n(s): 3. D,composlljoll dtScriPllolI , 4 _ D,pmd
Figure 28_17 Approaches to system test and their documentation, , of 2
Acceptance
lostailation
rt:qUlremenrs.
SRS scction(s): 2. Outrall drsrn'pljoll, 3.2 Clams! Obi' Is
Black box, ail packages; whole
SR section(s): 2 Ol'(rall dt
Black box, all packages: whole system (Build 3), test against high-level requirements and detai led
Fleur. 28_18 Approaches to system test and their documentation, 2 of 2
715
716
CHAPTeR 28
TeSTING ATTHE SYSTeM LEVEL
2. Encounter Video Game Test Documentation
n,e5 I 0 for En
<>tin ter and th e RPC f", mewo rk covers
pa koge and the Encoun ler harael'" package It de · scribes how to verify thai the player and foreign c haracters Ca n be retrieved . modi(,cd, and dIsplayed thro llg h the singicton Enco""I"C"" object
lCSt planning. speCifica tion, and reporting . TI'\crc arc
separa te tcst plan for unit, mt'cgnm on, ystem , accep -
2.2.1.1.3 Test Items The classes and method< '"
tance, and ",stallatio n te ling. Each test plan reference< its test design, rc t case, and test procedure spc IRca· lions. The' tcst reporting documen tation consists o( the
th e G",", harael", a nd E"cou",,,Ch.,. I", packages arc te. ted throu g h the EncountcrCast sIng leton .
tCSt 108, incid~nt report , and summary report.
2.1 Unit Test STD Refer to th e separate
UOit
test document .
2.2.1 .1.4 Features to Be Tested The features tested by the tes t desig n speci ftcation Budd 1_ TD ar" based o n the reqUIrements with", the SRS and SDO, as listed in Figure 1810.
2.2.1 .1.5 Features Not to Be Tested See the case srudy in Chapter 17.
2.2 Integration Test STD
•
The 5 I 0 fo r Integration testing consists of the separa te STDs for budd I, build 1, and build 3, as described next. Refer to Appe nd IX A in the SCM P fo r an expla natio n of th e construc tio n of th e build in tegration baselines. T csts will be Ident iRed acco rd · Ing to the convc: ntlo ns shown In Fi&'Ure 28. 19 .
Inevitably, infinitely many points simpl y can't be tested for. but identifying particular issues that will not be tested for sometimes helps to clarify the test ing process.
The testing of th e feature s associated with th e EncoutlltrEnu"onm mt and EncounlrrCamt packages and their fra meworks is deferred until the build I and build 2 integra tio n testing .
2.2.1 Build 1 STD
2.2.1 .1.6 Approach The approach to the ve rifica· 2.2.1.1 Build 1 Test Plan 2.2.1.1.1 Test Plan Identifier Build 1_ TP 2.2.1.1.2 Introduction This test plan covers the integration test for the G. ,",Ch. ,.cl'~ framework
tion of build I consists of verifying that the characters of the ga me can be ret rieve d and displayed through the Si ngle to n EncounterCast o bject. Th e method and interface tests verify that the re quire d (public) inter. face methods of th e Encounter Cha racters package are av. dable from the EncounterCast si ngleton.
Test Document Identifier
Test Document
Document Identifier
Build Build Build Build Build BUIld Build
Build 1_ TP Build 1_ TD BUIld 1_ TC I toBu ild 1- T C .. Build 1_TP I toBuild I TP . .. Buildl _ LOCI to Buildl _ LOC " Build UnRep I to BUilcMJnRcp . .. BlIIldl _SlImRepl to BuildiSumR"p ...
I T est Plan
I Test Design Spocificallon I Test Case Specifications I Test Procedure SpeCifications
I T est Logs I Test Incld"nt Report I Test Summary Report
Figure 28.19 Test document file Identification
-
717
CASE STUDY: ENCOUNTER Document
Section
Requirement Title
SRS
2. 1.2.2
User
3. 1.1.2
User interface for sening quality values
3.2.EC
Encounter characters
3.2 .FC
Foreign characters
3.2.P
Player characters
3.2 .PQ
The player quality window
3. 1.2
Characters package
5.0
Interface description
3. 1.2
EocounterCharacters package
4.2
Interprocess dependencies
5. 1.2
Interface to the Enco"PlltrCharacltrS package
SOD for RPG framework
SOD for Encounter
interf~ce
for setting quality values
-
--
Figure 28.20 Features to be tested in build 1
2.2.1.1.7 Item Pass/Fail Criteria Pass/fail criteria are based upon satisfying the corresponding requirements in the SRS and SOD. 2.2.1 .1.8 Suspension Criteria and Resumption Requirements (N/ A) 2.2.1 _1.9 Test Deliverables The documents listed in Figure 28 . 19 are to be delivered to the conRguration management group at the completion of the build I integrati on test. 2.2.1.1.10 Testing Tasks The testing tash sisl of the foilowlIlg steps:
on -
I. Load build I and Ihe pa ka ge Build_ I. 2 Execule build I Ie I procedures from Ihe malllO mel hod of Bu ild_ ITest ,n package Budd_ I 3 Wme lest report documentall on wllh Sect,on 2.2 I I 9
In
accord.nce
4 Slore ail te
2.2.1.1.11 Environment Needs Depending upon equipment avaiiabil.iIY, either an IBM PC, Sun SPA RC workstalion , or an Apple iMAC hardware configuration can be used. The Eclip e In te · graled Development Environmenl (IDE) should be used for Ihe build 1 testing. 2.2.1.1.12 ReSponsibilities Sally Si lver and Jose Hernandes from the SQA group are responsible for managing. preparing , and execullll8 Ihe bUIld I integrati on test. In addition , the Encounler development group addres es lechni cal quest,on and respond to teSI inCldenl reports. o nAguration ontrol stores aU te st documentation and data.
2.2 .1.1.13 Staffing and Training Needs The SPMP speciAes the ovcra ll stafRnl( and tra,ning need, for integration rel.i tln g
2.2.1.1.14 Schedule The chedul e for lIlle!(ratiOI1 tcstlng ,S 111 luded ,n the P"IP, 'uion 5 VC,",'OIl
and hi gher (
t"Ct!CH\
Iq
d"
tI",CI\
(lu.'
718
CHAPTER 28 TESnNG AT THE SYSTEM LEVEL
upd~tlng
of the
2.2.1.2.3 Approach Refinements
PMP to rene t the arc hitecture
• •
selected ) 2 .2.1.3.2 Test Items The functlonaJ.ty to be te ted is conta ined ,n the pcone.tlons for the follow ,n g publi c met hods of fl1 CO""ltrCasl.
TI,e ca e studies in this book do not include the updated SPMP.
E"co""ltr asl g"n"fl1coll11 I' rCns l()
Gam,(I,a,acltr 9"Th,Player(haracl, )
2.2.1.1.15 Risks and Contingencies
If the SQA
Ga ,",Characler g" Th, FortigllChaTaCI,r( )
tcam is unable to execute tests, or the numberof defects
causes an unacceptable number of system failuTes. then Alfred I\lurray of the Encounter development team w,lI be aSSIgned to the budd I integration test.
void stlPlay,rO,. ,acl,rQual,ty(SI,illg 4",,[ity,jloal oa[.,) oo,d stIFortigllC/UI,"clerQ""I,ty(SI,,"g qua[ity, jloal oalu, )
2.2.1.1.16 Approvals The completion of this test requires the approval of the SQA Manager, the Encounter Development Manager, and the CCB Representative.
jloal geIP[ayerC/'araCltrQlIa[,'y() jloal 9" Fort1911C/,aracl,rQ"al,ty()
2.2.1.2 Build 1 Test Design
ur~
These arc tested in accordance with Fig28.21.
2.2.1.3.3 Input Specifications: see Figure 28.21
2.2.1.2 .1 Test Design Specification Identifier . .
2.2.1.3.4 Output Specifications: see Figure 28.21
2.2.1.2.2 Features to Be Tested The test for build I w,lI get the f llco""lerC,,sl object and the player and foreign characters, change the va lues of various quahtics, get these va lues, and (hen verify their
2.2.1.3.5 Environmental Needs ThIS testing is performed with the Gam,Cba ,acl,'S and fll co,ml,rCbar·
co rrec tness.
actcrs packages alone.
Qu.llry
Phytr input
Foreign
v• .luf:
v.lut
Inp ut
Othu
Action
InCCBr3t1on
Tnt. 81.1
N/A
N/A
N/A
Bl.l
IA
N/A
NlA
Vcnfy by n.lmc
Get
fortlsn
char.lcte r
Verify by name
BI.3
Conccntr.ltlon
30
40
N/ A
Venr output valun __ Input v.llu('<.
B1.4
Sloamlnoa
30
40
N/A
Verify OUtput .".. Iu« •• InflUt valuC'S
Bu
•
•
•
Figure 21.21 Integration test Inputs, outputs, and actions
•
•
CASE STUDY: ENCOUNTER SOFTWARE TEST DOCUMENTATION
2.2.1.3.6 Special Procedural None
Requirements:
2.2.1.4.4 Procedure Steps Po pulate the Ale Build I_test_data with input data and expected output values fo r Ihe qualiti es in the following fonna t.
2.2.1.3.7 Interface Dependencies: None < quality name > < illput > < expected output> This section dcscri~s the ",Iarion hips among lhe various inlerfaces . This becomes signin . anI for fulUr., bUilds, but is not an ISsue for build I.
< quality name > < input>
•
•
There is no additio nal begi nning o r e nding text.
2.2.1.5 Build 1 Test Item Transmittal 2.2.1.4 Build 1 Test Procedures
Report
... . ..
2.2.1.4.1 Test Procedure Specification
2.2.1.6.3 Activity and Event Entries
Identifier
The ' defect rderence" is the number used by the defect tracking system for Ihis defect
This identines the class/method from wh ich Ihe test is executed.
2.2.1.7 Build 1 Test Incident Report Inregration_ Tests/Build I_T est in package T ests
2.2.1.7.1 Test Incident Report Identifier
2.2.1.4.2 Purpose T o sct up a tesl of build I wilh
Bu ild U cst3
a minimum o f o ther parts of the appl icati o n
2.2.1.7.2 Summary see Figure 28.22 .
2.2.1.4.3 Special Requirements The test hal"
2.2.1.7.3 Incident Description Ed Blake wa d is-
ness in Integrati on TestslBuildl _T esl, m nsisting of a class with a si ngle method, mainO, is to be co n· structed . and tests 1, 2, 3, . . arc to be executed and the results compared.
tracted during the execulion of tesl 3 by an alann in the building, and could no t record the re ui ts It was decided no t to inte rrupl or repeat the test seq uence, and to conducl test 3 as part of Ihe tesling for bui ld 2.
Defect reference
Result
Test
*
Build I Te
t
Log
I
Passed
N/A
2
Fa il ed
1823
3
Dala 10,1 - T o be repca led
N/A
Lost 01prec Isio n in re lu rned value
2872
s
• ••
••
Figure 28.22 Build 1 lest log (summary)
•
•
••
719
720
CHAPTER 28 TESTING AT THE SYSTEM LEVEl
repe t, tlon of lh b lest.
d "played th roug h the Enco"n ltrEnviro",mml object, an d Ih ,1' the o nncctlon< among them arc con ,sLent wi th the SR .
2.2.1.8 Build 1 Test Summary Report
2.2.2.2 Build 2 Test Design T hese teSts first will
2.2.1.7.4 Impact It \ ,s d~c ldcd th, t the Irl IdcnL(s) repo n ed above were n Ot serl ou enough to rcqum.: a
ve rify th at the correc t Etlfo lHllrrEnvironmCJ1 t object ca n
2.2.1.8.1 Test Summary Report
be obtai ned, and the n wdl show that the Arca o bJeclS
Identifier
and Art'(/ COPlllrclioll objec t ca n be re tn eved as req uired.
... I t~Sl passed wi th
2.2.2.3 Build 2 Test Case The func tio nality to
the exceptIon of the defec ts noted . TI, i wi ll be h,ndled by the regula r defect repair process.
be tested is co ntai ned in the fo ll owi ng publ ic fun c·
2.2.1.8.2 summary TI,e bud d
2.2.1.8.3 variances
tio ns of
GnmcArm 9c1TI"DrmillgRoomO
co build I teq incident re port.
2.2.1.8.4 Comprehensive Assessment
Ellcolm f(rEIIVffOtHlltn l .
GnmcArm gCIThcO""9tO" O •
• • •
•
•
•
Enco ll PlltrEnvi rOl' ,"ril l 9(1 ThrEt'ICO UH IrrEllvi r(l",molr()
Add itional remarks supplyi ng details c an be placed here.
2.2.2.4 Build 2 Test Procedures: To be 2.2.1.8.5 Summary of Results
supplied •
•
•
•
•
•
•
2.2.2 Build 2 STD
2.3 System Test STD This (annat is similar La the fo rmat in Lhe build I S I D.
2.3. 1 System Test Plan Th ese lc t5 arc pcrfo m1 cd agai nst lhe arc hitec ture, as
2.2.2.1 Build 2 Test Plan These tests will ve rify
described in Figure 28.23 . TI,e tests verify that the effects of game actio ns
that th e areas of the game can be re trieved and
in
Eu oUl1ttrCa mr
corrt"ctl y manifes t them selves as
EncounterGame
EncounterGame EncounlerCharacters
-'.c.de·
EncounterCast -'8PcM _
EncounterEnvironmenl
EncounterEnvlroniicent ott.c •••
Figure 28.23 ArChitecture and modularization for Encounter video game
CASE STUDY: ENCOUNTER SOFTWARE TEST DOCUMENTATION
nlO~nl~nts of EH
O".t"
chara ters
wllhin
the The integralion leslS verify that the require· ments of Encounter, as stated in the SRS, have been satisAed.
~nvlron",ent .
2.3.2 System Test Design ~ syslem lests are designed to verify the
The acceptance te IS arc slored in the Accept· package, and include the usc cases. The Initialize usc case IS sh own In Figure 28 .24 and is executed by the mai"O method of the class Initia lize in the Acctpt."erTts' package.
architecrure by executi"g and verifying se. quences of "'Ierface methods
."crT",
2.3.3 System Test Cases Syst~m T est I
The E"rounltr Fortig., CJJarn
use case is shown in Figure 28 .25 and is executed by the ",.i"O metho d o f the class Acctpta"ctTts t l"itia/izt .
I. Move player character into dllngeon .
Itr
2. Move foreign character into courtyard. 3. Move foreign character into dungeon .
2.4.2 Acceptance Test Design
4. Execute an encOllnter in the dungeon .
The use cases indicated in Section 2 4. 1 are to be executed in sequence severa l times, in accordance wilh the lest case in Section 2.4 .3.
System Test 2 •
•
•
2.4.3 Acceptance Test Cases
2.3.4 System Test Procedures
2.4.3.1 Test Cases for Initialize Use Case
• • • •
2.4 Acceptance Test STD
The lests are instances of the Initialize use
case, also known as "sct"narios."
2.4.1 Acceptance Test Plan
:Encounter· Game
main player character: Pia er Character
User
1a· .
:Player quality window .. create"
dress ing room:
Area
I
1 b. -create .. ~
2. -create-
'y
I la . onter quality valuo
Jb. • etOuolityO 4. select exit tor character
,
5. moveO
• Numberlng key ed to uH case
Fleur. 28.2.4
Sequence diagram for Initialize use case In Encounter
.,.,
721
722
CHAPTER 28 TESn NG ATTHE SYSTEM LEVEL
:Encounter arne
:Encounter Cast
freddie: Foreign Character
1. 1 displayForolgnCharO
:Player's main character
1.2 d,splayO
~
engagement: En a ement
1.3 .. create ..
2 execuleO
I
2. 1 S.IP~ye.aua ll1yO
I
2.3 selForolgnOualityO
2.2 seIQua/l1yO
2.4 selQuall1yO I
:Engagement Di~a
3. 1 .. create ..
r 3.2 dispiayAesul10
Figure 28.25 Sequence diagram for Encounter Foreign Character use case in Encounter
2.4.3.1.1 Initialize Acceptance Test 1 1. S1~n up game
2. Supply main characte r wi1h 1he fo ll owi ng qual. ity values ,
In
2.4.3.1.4 Initialize Acceptance Test 4 . .. 2.4.3.2 Test Cases for Encounter Foreign Character Use Case
the order show n:
Strength , 30, then Conce ntratio n, 20. 3. Move the main character to the counya rei
2.4.3.1.2 Initialize Acceptance Test 2
2.4.3.2.1 Encounter Foreign Character Acceptance Test 1 I. Set the main chara cter's "patience" va lue to 30.
2. Set the foreig n c haracter's "patience" value to 20. 1. Start up game.
3. Move the main c haracter to the draWing room. 2. Supply main character with the foll owing qual· ity values.
10
the order shown:
Strength , 30, Concentrati on, 20, and Patience, 30. 3. Move the main c haracter to the courtyard.
2.4.3.1.3 Initialize Acceptance Test 3
4. Cause the fo reign characte r to enter the drawi ng room.
5. Ve rify that an e ngageme nt has taken place 6. Observe the e ngageme nt window showing the results .
1. Start up game.
(The players patience value should be 40. and the foreign c haracter's 10.)
2. Supply main character with the following qual · ity values, in the order shown, Strength, 30 and Concentration, 20
2.4.3.2,2 Encounter Foreign Character Acceptance Test 2
3. Move the main character to the dungeon .
I. Set the main character's ' stren<»h" o~ va Iue to ;.'0.
CASE STUDY: ECUPSE
l . Set the foreign c harac ter' "strength" value to 20. 3.
love the ma in chara ter to the dungeon .
The installation tests shall consist of the accep· tance tests conducted o n all of the above platforms,
4 Cause the fore'g n character to enter the dungeon .
5. Verify that an engageme nt has taken place.
28.6
6. Observe the engagement window showi ng the
W e continue to use Eclipse for a case study, as in past chapters. There are many systems for automating tests; and to appreciate the kind of capabilities that they provi de, we focus o n the Eclipse Test and Perfo rmance Tools Platform (TPTP), The fo ll OWi ng is quoted and adapted from the o nline documenta· tion for TPTP [ 6), TPTP is a sui te of "test, trace and monitoring tools ," It addresses the "test and performance life cycle , fro m earl y testing to production app lication mo nito ring, including test editing and execution , monitoring, tracing and proAling, and log analysis capabilities." TPTP addresses many of the issues di cusses in th is chapter, includi ng the col lection of metrics , The TPTP profili ng tool can be u cd to profile a Web application , including memory use and exe U· tio n time (the two ma in performance metri cs), The ize of the hea p as the execution progresses is an example, TI,e profiling process all ows the user to select parameters as well as output formats such as graphs, TPTP can be used to record trafAc at a Web application, In particu lar, it e nables loops within which a test engi neer ca n embed a test . te t parame · ters varying fro m pass to pass, TPTP has built · in facilities for maki ng logs of the te t re ult for exa mple , a grap hica l output showi ng reque t that take the longest time.
resul~ .
(The player's strength va lue sho uld be 40, and the foreign character's 10 .)
2.4.3.2.3 Encounter Foreign Character Acceptance Test 3 '" 2.4.4 Acceptance Test Procedures Acceptance tests shall be carried o ut with two desig. nated representatives of the customer present These representatives shall carry out all testing wi th the assist.ance of the vendor. Whenever possible, events should occur as a result of the random processe of the game instead of being sti mulated. An example of th, s 's the arriva l of the fore ig n character in an area , A log of all tests shall be maintained by the customer repre· sentatives and ig ned by all panics; an y sig natory can enter dissen ting statemen ts in the log ,
2.5 Installation Test STD These are tests verifyi ng that the applicatio n executes correctly in its required hardware and ope'f3,ating system environments,
The installation test s for Encoun ter co nsist of executing the system tests on the fo ll owong hardware conAgurations, 1 IIlM .compatible PC w,th at leas t 32 megabytes of RAM and 100 megabytes of d, sk space
2. SUN SPARC mode l mmm with at lea t 32 megabytes of RAM and 100 mega bytes of disk space 3 Apple ,MAC mode l 1234 or later w,th 32 mega · bytes of RAM and 100 megabyte s of d, sk space
CASE STUDY: ECLIPSE
St.'vc:ral "agents" ca n be set to monitor various
aspect of the execu ti o n, These ca n be thollgh! of as processes a tong in para ll el with the executi o n of the app lication under scn,tiny. Besides heap and stack usage data , TPTP ca n be used to vie,,, the II age of objects l-rom varoous cia ses. It can account for all of the objects of a class that come onto being dllron!! execution, allOWing a trace into th e exe lIt ion TIm can be di splayed ,n the fo rm of r an of a ,cqut'nct' diag ram For example , ,t may happe n that 0 man ,n stances 0 1 the 'm'9 cia s exis t at runtim e that the applicat , n' performance i, compro mISed
723
724
CHAPTER 28 TESTING AT THE SYSTEM LEVEL
n,e key to man y analy <5 I the Iden Ion of unll
It includes monitori ng (or "method
entl)', method exil, ca tch/ fi nall y block . and cia s loa ding," \X/ ith sla'lC instrum entation. probe
arc
Inse rted before execlltion. These have 10 be rem oved often by hand-before the application ca n be deployed . Th is can introduce errors via
Method Invocallon, ca n be compared, as In Figure 2826. In thIS exa mple, dI splay parameter< have becn chosen so as to aVOId dISplaying methods invoked a negligIble nllmber of tImes (7]. Method execullo n limes ca n be displayed as In F,gure 28 .27. TPTP includes the abilll)' to generate test cases and test procedures from higher. level descriptIons, as wel l as the ability to record CU I interactions. In o ther words. the application is execu ted and the user interac ts WIth CU ls. When the application IS exe· cuted again in plnyba k mode. the user's same CUI
pro bes Inadvertently left in the code. With d)'llnmic inslnlmcntation, moddled cia scs can be ubstllutcd
actions arc automatically performed .
(or unmoddi c:d ones at runtime . This avoids the manual c1can ·up process, but the application must
example, to test a word procc sor, we would test
T ests arc often o rganized In hierarchies. For
be execuled in a speCIal mode to use il. Listing 28.2 is example output from a class Order that has been
"child" teSts for Rle handling capab,lit,es, editing capabilities. display capabilities, and ot hers. The Rle handling tests break down into subsidial)' tCSts, and so
taocally Instrumented with method entry and exit
on. Managing tests within such hierarchies is a signif.
probes [7)
icant challenge, and tools like TPTP lacilitate this.
Listing 28.2: TPTP output trace of entry and exit of Order class
Entered: Order.main Start Entered: Order.
CASE STUOY: ECUPSE
"" .000 ....
Method Invocltlons
........-
llS,ODD
•0c
" .... "'0_
.... .s- ..... -• ' .000 , ..... ' .000 ' .0lIl ,11
~
0 0
Q
E
'.000
Z
.'.000
Methods
Figure 28.26 A comparison of method invocations In Eclipse
source. Eclipse Test and Performance ToolS Platform ProrecL reprOduced WIth permISSIon, htt+fJ /WNW edipse.orgItptplplat1omv document!JprObeklvprot>eklt.html
Method Execution Time (In seconds)
Figure 28.27 Graphical comparison of methOd execution time In Eclipse ~ [dipse Test
and PtriOf'lnance 10015 PIilUOfm PfOjOC.t. JopI"oducca wlUl permISSIOn, I'&UlTJIWww.edipse OfIll~platformidon'menIJlPfoDelllliptObekit hlmt
725
726
CHAPTER 28
28.7
TEsnNG AT THE SYSTEM lEVEL
CASE STUDY: OPENOFFICE
need
n."V I('"W , I t
is pO~ltive progrc!)s that is cs~ntja l to
keep th is projcc i moving lorward • Note to the tudent, QA for o pe n source project' is characterized by user involvement, as exempli Red in this case tudy.
The OpenOfRce teSti ng missio n tatement is at httpilqa.openofRee.org/, ''To provide an easy way for voluntee r to find , update and bettcl' de Rne issues. and to deBne tc"t processes to validate a build 01 the Olfice SUIte."
28.7 .1 Open Contribution to Quality Assurance 1ueh of this section is quoted o r adapted from h up';I q a .openof Rce .org/hel pi n g. h tm I. Th,' latter "describes ways in which anybody ca n he lp make OpenOffice.org better, even no ndevelopers. OurCUTTcnt focus isonconAnning issue that an: marked WIth the Aags 'unconfirmed' and 'defect.' O ur goal is to r<-"Spond to new Issues po t<.°d by users a soon as possible
as we ll asclcarout the backlog of unconfirmed issues that currently resides in thc IssllcZilln database. However, we recognize that there is a lot m OTC to Quality Assura lKe (QA) than just reviewi ng and i o lati ng is u(s. In the future , OpenOlfice.org (000) QA will invol ve te
cases, regression tests, QA spccifkation documentation . or any other idea you think wou ld be val uable to Improving the qualIty of 000.
It IS indicative of the scale of OpenOfRce that settling 100 issues a day (over 36,000 per yea r) is considered "insignificant."
EveI)' little bit 01 contributio n counts and is in· valuable. For example, if we have 100 Interested volun· teers, and thcya ll work o n o ne issue per day, we would be able 10 cover 100 issues per day. As insignificant as that may seem ""hen compared to the number of issues that
28.7.2 Smoke Tests Smo ke tests arc superficial tests c hecki ng that c hanges to the baseline ha ve no t resulted in cataserophic errors. A smoke lest is a reduced regression test. "Insta llatio n tests" here are no t fu ll inscallation tests
The fo llOWIng is quoled and ed ,ted fro m the si te give n at [ 8]. "Smoke Te ts (a lso ca ll ed Shakedown tests) va lidate a build of 000. These arc not fu ll y . fled ged test CJses, but \'Ie may use them to create (est cases in
th e future , Your ideas are welcome." The c consist of the fo llowing, quoted fro m th e reference . Insta llatio n T es ts. In ta ll 000 in both sta nd · alone and ncrworked environments
File type Test. T es t th at 000 can open and correc tl y display specified fi le types. Ca n open! execute a Java app let (sa mp les avai lable ). File Actions. T est that 000 can create and save different types of files . Ca n sen d mail using an external mail program .
Insert Actions. T e t that 000 can insert spec. iRed ac tions into a text document.
Edit Actions. T es t that 000 edit actions func. tio n as speCified with a text document. T est that em and paste integrate with ex tern al editors
and 000.
View Actions. Test that 000 view actions ftlnction .s specified . Format Actions. Te t that 000 fom» t ac tio ns funCtion as pecified . Tool S/Options . T est that 000 tool. options fun tion correctl y. Print . Test that 000 Prints, text do ument to a default printer. Hdp . Test 000 help Content. and fu nc llo n<.
CASE ST1JOY: OPENOFFICE
28.7.3
QA Priorities
~ proce:du ~ de:scribed here ,s designed to en$U~ that t he: most ,mportant issues are woritcd on first. Its somewhat mechanical fonn i n~essary in aD open·source environ. me:nt since no single manager i making con. tinual decisions.
Table 28.3 reAects the OpenOffice QA pnorit .
,es (taken, with
minor editing , from the source given
The following is quoted and adapted from [II ]. 1ne qadcvOOo project proVides a te t harness to execute test cases wri l len in different prOgr.Jmming languages, like + , Java, Python, or BaSIC. These test cases are responsib le for validating the functionality and reliability of speCified APls. The test harness
ac+
(written in Java) is responsible: for setting up, running, and controlling the test processes and threads: "The test harness and a nearly complete set of Java and Basic ICSt cases for the OpenOffice.org API are at [ I I ] as well as the desired value set for the test runs and a set of test documents used by the test cases "
in [9J. QA contributor procedures are given at the source in [ 10].
28.7.4 Automated Product Source Code QA This section d escribes a test harness for exe cu ting OpenOffice tests.
28.7.5 Automated GUI Testing 'The automated C UI testing provides a test frame· work with test scripts and an application (TtsrTool) to test alm os! the w hole of~ce application automati · cally. The TtsrTool scripts are wrinen ,n BAS IC with some additiona l functions especially for the o ffice . The TrsrTool communicates via TCP/ IP with the office app licatio n." [ 8 J
Table 28.3 Example of priorities in Open Office Rank
Task
IssueZilla (lZ) Search Tips
1.
New issues posted for the current month or today.
Look at the 'Untouched" issues hnked at http://Qa.openoffice.org/issuelinks.html Also try searching IZ with Issue Type set to "Oefect" and Status set to "Unconfirmed," where the fiel d(s) is set to "[Issue CreatlOnl" .. .
2.
Follow up on unconfifmed defect issues with the "oooQa" keyword . Ideally. start with the oldest "oooQa" issues and work your way to the most current. If the issue is older than 3 weeks and the Issue does not follow the guidelines listed in the "How you can help?" page, leave a comment to the user Indicating you are clOSing the Issue for now. but If they can provide more information to help reproduce the issue, they can reopen the Issue at their convenience.
Try searching IZ with only the following fields set: Keywords set to " oooqa" ... Limit the search to a particular time frame .. . .
3.
Close out issues reported against versions of 000 that are no longer current. Do a Quick check to see whether the issue is verlfable. If the Issue cannot be verified, send a message to the user to see whether upgrading to the latest version of OpenOfflce.org resolves the Issue. II upgrading 10 the latest version resolves the problem, close the Issue. If the upgrade does not resolve the problem follow the 000 QA " How you can help?" guidelines.
Try searching IZ with Issue type set to " Defect." Status set to " Unconfirmed," and the Component and Version fields set to your choice.
727
728
CHAPTER 28
TESTING AT THE SYSTEM LEVEL
28.8 SUMMARY nee integratio n tesling is omplclcd, th e appli ca ti on a~;) w hole I ~ tes ted T hi s i~ known as system testi ng. y
Appl icatio ns arc freq ue ntly distributed in-hou c fo r te ting (alpha t es t in~ ) and 10 partt ci patlng usto mers to try o ut with a lear unders tand ing of liS
system tesrs. j\~a ny rca l· world appl ica tiolls have incomplete or even nonexistent requin:mc nts documl"nts. T c:sting in th e Jbsencc of well -wrin en requirements requires th e tes ter to obtai n a sen c of ho\,{ th e appl ica tio n behaves and how it i meant to behave. This is called bt'haoioml modtlmg . A n approac h to tes tin g in thi s srtua tio n is to
S'art fro", wha, appea r; best to be a beginning poi n' o f the applicatio n, and th e n kee p ,rack o( ,he fun c ti o nal path s fr o m th ere . Directed graphs arc used to document ,hese path s. Te t, are devised to execute a set of pa,hs ,hat altai n a kind of coverage In o rd e r to be effec ti ve at Rndin g defec,s, a good software tes ter mus' be de termined , dogged, (eariess, imaginati ve , curious, meticul ous, and must think "outside the box ."The les ter's gOoll is to discover ddects that c.a n mani fes t wh en an appl ication is used (or a significant tim e
by user , perhaps In unanticipated ways.
28.9 EXERCISES Answer th e following exercises in your own words. I. Why arc black box ' cS tS (rath er than white box tests) used in system testing )
2. What is th c purpose o( acceptance testin g and wh y is it nl'cessary 7 Cive an exa mple o ( an applicatio n and a defec t that co uld go undetected in system tes ting yet be c au g ht by acceptance tes ting .
3. A compan y is develo ping an applicati o n, and th inks it has d iscove red a novel way to speed up its tes ting cycl e. It decides to dispen se with sys tem testing, and in tead deliver th e appl icati o n to customers just after integrati on testing
is complet ed. The company will lherefore rely on its
custo me r; to discover problems in the appl icatio n. Wha, arc the ad vanta ges a nd d i ad vantages of this approach) Be speCi fic and ex plain your answer. 4. What is the purpose of soak testing) Gi ve an exa mple o f a defect thi s ty pe o f tes tin g is likel y to uncover.
5. Load and sfrtS5 tC'sting is often conducted on indiv idu a l units dllring unit and in,eg~ t Ion ' . I testin g. n •
. •
•
•
IU
thIS teslIng, unllS are subjected to hi g h levels 01 stress [ 0 e nsure ,hat th ey do h 'b' . . no t ex I It an y problems. Why IS It necessary 10 conduc, system-level stre« 'c, ,, even if all of ,·h e '"'' t t'"'-'SO t e IS . are success1uI7
6. Describe the various levels of testing to whic h you wo uld sub)'ec t ,he' I' . d . . . .. "pp Icallo n escnbed In E-xerclse 7 In Chap,er 27. Indicate which o f the clas es and pac kages ( ho . h fi wn In t e gure ) would be
BIBUOGRAPHY
involved in each. (Many more classes wi ll be involved in buildi ng the completc application. but you are not required to show these.) 7. For Nch of the black box testcr qualities listed in Section 28 .3.6. give an example of how that quality could be counterproductive if take n to an extreme.
BIBUOGRAPHY t
2: 3 ... 5 6 7. 8 9. 10. 11
Kit, Edward, £JjlfL.'\Qft Ttjtlrtg ,PI II" Rcal World l,"pro,,,,,; ,Ix Proem, Addison. Wc:sley. 1995 Purdue Usab,hcy T CUing QuC'Stlonna ire, hnp Jlold"ww.acm ,orglpcrlma nlques llon ,cgI1form . PUTQ [accessed 121 15109] Herzog. Petcr, OSSTMj\'I - Open Source Security Tc:stlOg ''''!ethodalat,,), Manual httpJlwww.lsccom org/projcctvOSSlmm shlml [accessed 12I 15109 J. Snnlv~san Deslkan , and Goplllaswamy Ramc:sh. Software TCStHlg. Pnnclples and PraCtiCes , Pearson Education. 2006 Kiner, Cern, J;ICk. Falk, and Hung Quoc Nguyen, T Nli"g (olllp",'tr SO/IIlIQrc, John Wiley & Sons, 1999. EclIpse T~, t ~ Performance Tools Platform ProJect . hnpJlwww.cc\lpse.org/lpt.p/ [accC..Sscd 11 / 11 /2009]. Eclipse T e"Sl & Performanc~ T 001<; Platform Pr.ojecL htlpJlwwwed.psc.o rg!tptplpladormldocumentslprobcklvprobekit.html [accessed 11/ 1112009J. OpenOfAc~ Project. hakedown Test SUlle · hllp J/qa opc nofAcc.org/tcstcasc:/mdc)(.html (.lcccsscd 11 / 1112009]. O~nOfAcc Project . · 000 QA Issue Revl cw PriOntl~." hnp j/qa opcnofficc o rg/ prio rltlcs.hlml [accessed 11 / 11 / 20091 O~nOfficC' ProJect. "A Quick Stan CUlde to contributmg to this prOJeCt. ~ hltpJ/qa .openorAce.org/W'W"Wslagingil askslqlllckstan . html [.ccess.d 11 / 11 12009J OpenOfS« Project. "Automated product source code QA: hupJ/qa.openofRcc orglqadcvOOo_dodi ndex.html (accessed 12I IS/09}
729
Software Maintenance
Planning
•
What are the units of software maIntenance?
•
What are the differences between corrective , adaptive , perfective , and preventalive maintenance?
•
What are some management challenges in maintenance? Process challenges?
•
What are the rna," technical Issues?
•
What is the maintenance process ?
•
How do patches work?
•
What standards are lhere for software maintenance?
•
What is reverse engineering? Reengineering?
•
What maintenance metrics are available?
Testing The Software Development Ufecycle
Raquir8J'L8nt& analyaIs
Figure 29.1 Tlle context and learning goals for this chapter
Software systems continue to evolve after their initial release. The l'ttainlt'HflH Ct o f a software sy trm consists of those activities performed upon it aftcr it ;s released. The IEEE glossary [ I ] deAne< ofcware maintenance as follows:
TYPES OF SOFTWARE MAINTENANCE
TI,. proctSS oj mod,Jyi"!l a SOJlwart 'y,'m or eo,"poHrnl afler d,/i",ry 10 corr,el faults , impro", p,rjO"",,HCt or olb., a/lnb.ttS, or adapi 10 a eha"9,d ,H"oroH,"rnl. Maintenance is an activity of trul y il!nincant proportions, consuming an estimated 40 to 90 pe,cent of the total life cycle co ~ of applocations (see, for example [2] and [3]) . Perhaps the most famous maintenance effort involved the year 2000 (Y2K ) problem, for which maS
As
software systems evolve over
tmHo",
the y require co ntinuous ma intenance in order
[0
remain useful.
Lehman ([ 4] and [5]) claims the existence of several laws of software evolut,on borne out by extensive experience. The nrst, eOH IoHu iH9 ehaH9', s tates that if a program IS not cont,nually adapted to ongoing needs, it becomes less and less useful over time . According to the second law, "'Crta''''9 eomp/"",y, as a program is changed over time, it complexity increase unless ,,,ork is done speCifically to alleviate this. An example is a maintenance action that increases coupling between modules . Lehman's two laws are relaled . As oftware evolves, it is modined by engineers who may be competent to make each change but may not completely understand the overall desi.g n and implementation . TI,is is not surprising, give n the sheer magnit ude and complexity of many applications, As a result , the applicat,on's structure and maintainability decline. Il is for these and other reasons lhal software maintenance of several varielles is necessaty ' The addition of new features and functionalilY to an application is n::a ll y a kind of dcvc1opmenttypica ll y of the application's next release . Nevertheless, the process IS somelimes included in the "mainte · nance" rubric , especially when the new features are very much ,n the spirit of the application's curre nt functionality and when they are small by comparoso n. This type of mainte nance i explained in this chapter. In many ways, agile projects can be viewed as being In "maintenance" mode from the beginning . This i because agility relies on adding to a code ba e a procc s that has much in commo n with ma,ntenance
29.1 TYPES OF SOFTWARE MAINTENANCE This section introduces the unit of maintenance . It also names and describes vanous type of m.,ntenance activities.
29,1 ,1 Maintenance Requests Maintenance organizations manage lheir work by identifying task . Ideally , the c sh ould be of comparable magnitude (imagine the Inappropriateness of a li st of c hores that Inc ludes "buy bananas" and also "build house"). Each such unit of maintena nce is ca lled a MaoHlrnaH" Rtqutsl (MR) in IEEE term inology We try to ize MRs to be of a regular mag nitude , but the amount of code needed for each ca n vary and the Impact can vary as well. A phYSICally small code c hange may have a major effect on an application . One way to keep MRs at comparable effort is to decompose them into c hild MRs . An MR is either a "paor or an ".hmoe''"tlfl It IS a repair when it co nce rns a defect relative to the existing requirements, An enhancement MR is one of two types. The first in troduce a feanlre no t called for in ,he requirements at dclovery t,me, the second type of enhancement c han !!c~ the design o r implementation , wh,le keeping the functionality unchanged. ThIS is known as refactori ng , as Introduced in C hapter 24 . Refa tonng usually improves the deSign ,n order lO redu ce comp leXity a nd Increa e efficiency , and it is a re pon e to Lehman's seco nd law of Increasing co mple Xity Figure 29 .2 summan zes these distinctio ns. A common categorization of MRs IS defined by L,cintz, Swanso n, et al (6). (7). who reRne the,e twO types of malntenan e IntO twO .ubcategories, a' ,ummarized ,n Figure 29 3 and explained ,n the rest 01 this seCtion
731
732
CHAPTER 29
SOFlWARE MAINTENANCE
• Repair • FIXing defec t (relative to existing requirement s)
• Enhancement •
•
cw reqUIrement
• C hange desig n o r Im picment atio n (no func to onal hangc ) Figure 29.2 TYPes of mai ntenance Corrective
Repair
- defect identificatio n and rem ova l Adaptive - changes resulting fro m operati ng system . hardware, or DBMS chan ges
Enhance
Pc rfective - changes resulting from user requests Preventi ve
- changes made to the software 10 make it more maintainable Figure 29.3 -:)Ipes and subtypes of maintenance SOUrce Uentz. Benmltt P., E. (CACM),
no
BUitOrl
SWnnsoo, and Gerry E. Tompl(J1"IS. "Chat<1cterlstlcs 01 Applications Software Maintenance," CQmmunlcaUons of the ACM
21 . 1978, P 406 471 .
Maintenance Reguest 78 Problem When the player changes the va lue of a quality, the computatio ns are specified to keep the total invariant , but they do not.
Exa mple. If the qualities arc
' 1""9Ih = 10, pa,i",ct = 0.8, and ",du,anet = 0.8 (sum = 11 .6 ), and the player adjusts "''''9 ,h to I I , the result is slrclIg fh = 1 I, palimcc = 0 and mduranct = O. These do not sum to I 1.6. Figure 29 .4 Example of corrective maintenance request
29.1.2 Corrective Maintenance Correc tive maintenance is concerned wi th the repair of defec ts relative to exist ing req uirements. These
defects are typically d iscovered b y CUStomers as they use a software product. Each defect must be analyzed. priOritized, and repaire d, and fixes incorporated into new sofh\>'are revisions. As an example defect, consider
th e MR for the Encounter case study show n in Figure 29.4. MR 78 requi res the maintainer to determine th e cause o( the defect. One possibility is an error on the code, such as in the method adJustQu.lityO, which is responsible for adj ustong quality values when one of them is changed b y the user. Another posSibi li ty here is that eXIS ting requirements (or Encounter characters are defect've. Actually, th e latter is the case, because the requ ireme nts mand.te the follOWing ,
TYPES OF SOFTWARE MAINTENANCE
• The user hall be peml ined to sel any Quality qualitic .
10
any va lue les than or equa l to the curre nl ,um of the
• The remaining qualities retain thdr mutual proporti on:,.
• No qualit
shall ha ve a value both grealer than zero and less Ihan 0.5 ,
• The sum of the qUJ.litte~ remains Invarianl.
can be Seen in the example in MR 78 , Ihese ca nnOI all be salisfied Since the defect is in the ~quirements , ill S the cu lo mer's preroga live to make o r permit the c hange, O ne wa y 10 do th iS is to relax the last ~quircment to the followin g , Isum of qualities - 0.5
* (N - 1)1 <= (sum of qualilies)' => sum of q ualities
where N i the number o f qualitie and x'
IS
Ihe va lue of x after Ihe adjustmc nl proce
Th is modiAcation keep Ihe effect of di _cou ragi ng the player from changi ng quali ry va lues too many times becau e point ma y be 105 1 wheneve r Ih,s is Gone ,
100
muc h o r
29.1.3 Adaptive Maintenance Adaptive maintenance i concerned wllh ada pIing the software
10
changes in the operating envi ro nm ent uch
as a new operating system relea se or a new versio n of hardware. As oft'\"arc system s evolve ,
It IS
inevitable
that changes in their externa l environment will take place. An example i if '\Ie were to port o ur Encounler video game caSe study to an iPhone. It ma y seem awkward to classify adap ti ve ma intenance as a kind of re pai r, bur this is appropriate
if o ne views an app lica tio n as a liVing cntity . In ordt'r to r('mam
leg itimate, the
application must adapt to rea o nabl e chan ges in its e nviro nment.
29.1.4 Perfective Maintenance Perfective maintenance is the develo pme nt and Im plementallon of u er reqllesl suc h as new feature enhancements. Recall Lehman's Rrst law- Ihat ys tem s mu t con tinuall y adapt to o ngoi ng needs o r become less and less useful. As an exa mple of a perfecti ve maintenance reque
Figure 29.S Example of a perfectIVe maintenance request
733
734
CHAPTER 29
SOFlWARE MAINTENANCE
29.1.S Preventive Maintenance Preventive mJlntcnan c cone<; ,c;;ts of c hang ing J c;;oftwJrc applt a ll on
In
order to m&lke It eas ier to maintaIn
'n,e need for preventive maintenance can be deduced from Lehman' <econd low As
program evolves over
0
lime, hange made through correc ti ve , adap ti ve, and perfective millAlcnancc requests cause the system to become Inc reasing ly compl ex unless action
rakcn to prevent it. Preventive maintenance Involves proactively rdaclonng the sy'\tcm to reduce its comp leXity. It IS Jlway~ a good Idea to pe rform preventIve IS
maintenance on an ongoin g baSI An example preventive mainlcnllncc is to recog ni ze and anticipate Industry trends Suppose, (or
or
exampl e, that we sell a Windows ·based word pro cssor ond that we reco!: nl ze that word proce sors arc likely to m1grare, In pan , to the \'(Ieb, A preventative maintenance action would be lO alrcr th e word processor's architecture so that selected pans arc mo rc readily moveab le to the Web Metncs can be used to identify lIrcas thilt need improvement. For example , by examining ddect mc(rics It may be determined that a certain software modlilc has a hig h number of defecrs reported agalOst it After flirt her inve tlgation It may be detem,ined that many of the defect are a rc ult of changes made wh,le prior defects were repaired This might lead to a conclusion that the desig n of that modu le IS 100 complex, and thus not ca, ily modified. As a result , mointenance work moy be perfom,ed to redesign the module to make it Simp ler and morc mainta inable, without changi ng its hlOctionaliry , Subsequently , we would expect fewer defect to be filed ogainst the refactored module.
29.2 ISSUES OF SOFTWARE MAINTENANCE Software maintenance preseOls a unique set of cha llenges. Ben nett [8) has categorized them as manage· ment (what to do and who wi ll do it), process (what procedu re to fo ll ow), and techOical (design and Implementa t ion).
29.2.1 Management Challenges Senior management tends to focus o n delivering new products, which are a Ou rce of revenuc (or COSl savi ng if internal) and provide a quantdlablc return on investment. Funds spent on main .. enance , however, are usually not si mple lO justify. The cost of maintenance is high , and unless the maintenance organization ca n charge for their services, th e return on investment IS much les clear than for delivering new products . As a resllit, maintenance teams can often be understarred and lInderfunded . maklOg an already dtfficult job even harder. oo ner or later, the need for organized maintenance i recognized by management and resources are allocated !o it. Sometimes an. individual or a group or is assigned to repilir tasks ;lnd a se . pal'are group to en hancements, Incorporated In new update or releases As software moves from shnnk . wr. ppc d d eI'Ivery and big -bang integration to online deli very, cont lnuOliS '"tegratlon and security upd,tcs tlle tr:cn d h as be en toward more frequent version updates ra ther than major releases_The management of rno fr d . . " re cquent up ares IS more demanding thon that for major relcoses Simply because !he act of relcase . freql1ent Th'I .IS I more analogous to thc difference between managing a daily newspaper and a monthly magazine . The management of maintenance involves the assessment of benefits the calc I ' f ' u atlon 0 cost and the allocation of rcsourc~s, mainly pcopl~ . Table 29. 1 how examples of COSts MRs .. ' " . a r~ p non II zed bose
,
ISSUES OF SOFTWARE MAINTENANCE Table 29.1 Example of an es~mate for Implementing a maintenance request Estimate
Estimate ActMty
1. Understand the problem and Identify the functIOns that must be modified or added.
Actlvlty
(person-days)
2- 5
(person-days)
6. Compile and integrate Into baseline.
2-3
/-
2. oesign the changes.
HI
7. Test functionality of changes.
2-4
3. Peliorm impact analysIs.
1-4
8. perform regression testing.
2-4
4. Implement changes in source code.
1-4
9. Release new baseline and report results.
S. Change SRS. SOD. STP, and configuration status.
2-6
TOTAL
1 14-35
29.2.2 Process Challenges Process issues-the procedures to be carried ou t can also be a challenge. Extensive coordination is required to handle the inAow of MRs. T ypica lly , numerous maintena nce requests flow cont in ually through the organization. Some economy of sca le can be achieved , reducing the cost of cach change, but a stream of maintenance changes places a sig nifican t burden on the process. Programmers , tester , and wnte rs have to be coordinated. To take an example, shou ld the SRS be updated as soon as the customer indicates a Aaw in a reqUIrement , only after thorough testi ng , or o nl y when grouped with o ther maintenance actions) Each of these options leaves the documentation and source code in an inconsistent state for periods of time. Without careful management, these supposedly short· lived inconsiste ncies ca n multiply and the documen tation get out of control. The re ult is that it becomes difficult to know exactly what the application does. If a Single , focuse d change were the only o ne we had to handle, the n our process problems would be minor. However, source code changes in re ponse to an MR typically cause a ripple effect in the deSign , documentation , and test plans. An impact analysis (described in Section 20) determines the extent of the ripple effect, and a cost analysis determines the cos t of implementation. As an example of a COSt analysi , let's imagine that the Navy has inform ed us (a military cont ractor) that the algorithm for reconciling three independent sources of shipboard navigation data is Rawed. An e timate i needed of the cost of making thiS repair. Our calculation cou ld be performed as shown in Table 29. 1, which shows that the co t of making this change at $400 - $800 per day of loaded labor (i.e., Including benefits, etc. ) IS $5 ,600-$28 ,000
29.2.3 Technical Issues Maintenance ca n be thought of as a repetition of the de vel opment process but with a major additional constra int · that eXisting reqUired fun tionality of an eX isting code base i~ preserved . This Impcb 11< t ellher add onto the eXisting deSign o r 10 redc>lgn the app lication Maintenance actions that are repairs usually result In stayinll with the curren t dc,,!(n An e CC ptlor. to thi s is where the eX isti ng de ' Bn it<elf is a source of the proble m. Add,nll to an eX lstln!l de ign has th e adva nt age of not perturbing ,.hat already works but the pOte ntial disadvant'f(c of reatlng an lIna ~ cptablc overall de illn . Redcsllln has the OPPosite advantafje, and d"adv. nta!(c, T he rede
735
736
CHAPTER 29
SOFlWARE MAINTENANCE
A~ an exa mple, "UPPO)C
that \'\fC \\IJ llllO ('nh.mel'
~he F n toulllt: r video ),(Jmc with
tht: p rco;cncc of \cvcral
mon""" rJlher Ih an JUSI o nt oWe wo,dd prohably kee p Ihe Lurre", overa ll dC
rl' m a ll) S
th e
)JI1l(' In
SPirit ilnd
h CGlU"C
th t·
urrCJ11
archltc
II
because the
capJbk· of Jbs.orblng the
lUre "
add itio nal apal>dity . O n th e o lher hand . If we arc reqUired to rurn Encou nter 1111 0 J rea l' lIme 31) game In w hl h Ollr cha rJclt'r engages In v;:mouS "'Jy4; with the monster u~'ng wcapon) and they arc: Jblc to pursue each o th er wllhm area, and from area to arca , we would reexa mine- and pr bably alt('r- thc c:xl) lIng arc hitecture This IS because the COmbJl aspec ts wuuld domi ni.lt e the cXI"lIng ) la lC a~pcc{)
Tesllng IS a sig nl ficJ llIlechlll ailS ue Si mpl y focuslOg tes t on changed or added pans takes time enough because pecial ttst plans l1Iust o ften be devised for this purpose. But fo u cd te'ling IS no t enough . The posslbdl ty of npple e(fecls reqUIres th at we execute exte nsive regressio n teSlin g to cn, ure th at changes have not compromls(.'d th e app lication's preexlsllllg funct ionality Thi s i a major factor In th e hi gh CO'Jo l mai ntcnance
or
29.3 MAINTENANCE PROCESS A ","i"lnl""e, pro css dennes Ihe flow of MRs through an orga nlzallo n Figure 29.6 dlustrates a tYPica l ma intenance process in J large project, where the th icker lines indica te th e nominal path The additional
(thin · lined) paths show o ther ways In which MRs ca n be generated and retired. In th e process shown In Figure 29 .6, customers prov id e co mments on enhancements and defect
through the help desk . Th ese are wrillen up as MRs. O rga l1lzatio ns ha ve a limited number of resources to work o n IR, . mean ing that some of the proposed enhancements and repo n ed defects are eit her delayed or nevcr implemented . .vtalOtenan cC' engi neers must therefore priOrit ize;.: i\1Rs. A Inag( proc(ss IS ofte n empl oyed [9] th at includes the: re-vic\" of all proposed ffi (l/ntcnJncc reque sts and the prioritization of their importan ce to th e bU. ln ess and to customers. Triage starts with an ofRc lal orga nizall o nalun il, wh ich may be
- - - Marketing
nominal
Written
MRs Proposed MRs
MaIntenance manager
Customer
Help desk
MaIntenance engineer
Approved MRs Current source & documentation
Change control board Modified SOurce & documentation
Figure 29.6 A typical maintenance process for a large project SO'lf(e GtaQnk.s reprMQ'd wlltl
~
Irom COrm
Rejected MRs
MAINTENANCE PROCESS
a single person or a committee. deciding which MRs will be Implemerned and aSSIgning them a relat.ve pnority . This unIt is often referred to as a Cbal1g, COl1lrol Board (CCB) ( 10). It co nsists of stakeholders. selected from various organizations such as development . user documentation . marketing , quality assurance (QA). and customer uppOrt . Each organization brings its ow n perspective, and collectively they decide on MR priority. The group conducts an Impaci a,,"lysis . which as esses the scope of the changes to the product's artifacts that are necessary in order to Implement the MR. Each group represented by the CCB provides input into the impact analysis. Maintenance engineers prepare an estimate of how long it will take to implement the MR. and its impact on the system. including code and system spccl~cations . The user documentatIOn group determines which user manuals, if any. are affected and require updates. QA determines how much testing is required to validate that the MR is implemented correctly. and also to validate that problems aren't inadvertently introduced into other parts of the system. In the case of repair MRs. customer support may need to determine the impact on customers of the MR and whether there are any possible workarounds that can be employed in lieu of repairing the defect. Using all this information as input. the CCB estimates the number of resources required , the cost. and the risk of implementing the MR. It then decides whether to accept or reject it; and if accepted. assigns it a relative priority. MRs approved by the CCB are then retired by technical maintenance staff. New software versions and documentation are generated and available for customers. For efficiency reasons. multiple MRs arc often grouped together and released as part of a single maintenance release . The number of artifacts affected by the implementation of an MR is va riable . Figure 29.7 illustrate two extremes. At one extreme , the defect is in a requirement that requires changes in the SRS, the architecture. and so on, all the way through to the code that makes the system operable in its intended environment. At the other eXITeme. a defect could be present in the code for a method and the MR could affect that method implementation but nothing else. The minimal · impact case occurs, for example, when the programmer has failed to follow a standard i~ naming a local variable, o r when an unused variable is removed. In the worst case, however, every part of the process is affected. Even for a defect in the code o nl y, the impact can range from minor to major. A seemingly Maximal impact Requirements Df1f8C1/nlected 116'8
Maintenance: I mpact a I Del ect MR
,1 Architecture
Minimal impact Requirements Architecture
"
"
Detailed design
Detailed design
Interface specs
Interface specs
Function code
7
Function code
Defee. Injected 116,..
Module (e.g .• package) code
"Module (e.g" package)
System code
Key 5 I"""",
denoto.
Fllllr. 29,7 The Impact of a maintenance request- two extremes
System code
code
7T1
738
CHAPTER 29
SOFTWARE MAINTENANCE
-----
Requ irements
Arch lleclU",
__ - -
Oetalled design
--
--
Interface specs
~/ Function code
Accommods/e ability /0 change
:::.
g/obalappearanC6:
USB
Abstract
Factory dsslgn par/em
--- - --
- - - - - --
Module (e.g .. package) code
System code
Add: ·chsnge app6srsnC6 when plsyer achlaves new levels·
Add Interlace me/hods for Layout package
----- as --
----- --- -
Add classes and methods per de/ailed design
Modify gameplay ----control code
Figure 29.8 The impact of a maintenance request-a n example
SImple change such as an increase," the SIze of a compile-time C ++ array could have major ripple effects throughout the application. Maintenance Request 162, described ,n Figure 29.5 , aHects ewry aspect of the process, as shown in F'gure 29.8. Recall that this new requirement-t he concept of mu ltiple game levels-is a signiRcant addition . It leads to changes in every phase in the process_ When an application is designed with traceability in mind, the documentation of maintenance actions
can be manageable. Otherwise, the consequences can be extremely expensive.
29 .3.1 Root-Cause Analysis After a defect MR is repaired, a process sometimes known as root-caust aHniym is sometimes conducted. This is an iterative, problem-so lvi ng process ai med at determining the underlying reason Ihat a defect has occurred. Once the root cause is understood , process or other improvements can be implemented to prevent similar
defects from recurring in the fueure . Root -cause analysis is performed via the change control board or its d~ignee as part of the maintenance process. For each defect , the team asks a series of questions to narrow
down the root cause of the problem. As an example, suppose that after an initial investigation it is detennined that the reason for a particular
defect is due to a requirement being missed by the test plan. The roOt -cause analysis process is then invoked to determi ne the unde rlyi ng reason that the requirement was missed , and once determined, to ensu~ that
other requirements are not omitted in the future . The following series of questions illu trate the iterat,ve narure of rOOt-cause analysis (9), [II]. I. The requirement is no t t<sted for in the test plan .
2. Why? It appears that the requirement was cha nged after the SRS and test plans were completed. 3. W hy? The customer communicated wit h the product marketing group their desire for the ch.nge, but th is was commun icated o nl y to development. The rest of the tea m was unaware and therdore didn't update the SRS and test plan .
MAINTENANCE PROCESS
~ . Why~ Product marketing thought this was an .solated change that wouldn't affect product te t.ng, so they communicated it only to development. S. Why) Product marketing didn't underst:and that all changes to leatures must be communicated to the entire team .
Once th. root catlse is understood , the product marketing department can implement appropriate changes to its proc ..ss that prevent th.s type of problem from recurring . As root causes are detemlined, metTics are recorded to keep track of them . To provide consistency and make it easier to track and ana lyze, it is helpful to deRne a list of root causes from which the team can choose . Rakitin [9] suggests the fo ll owing list. 1. Function was missing from SRS 2. Function was incorrectly specified in SRS 3. Design problem-design was inadequate or inappropriate 4. Design problem
design review didn't catch it
S. Code problem
code was inadequate
6. Code problem
code review didn't catch it
7. Inadequat .. Untt testing 8. Inadequate system testing 9. Installation/e nvironment/versio n compatibility issue
A metrics analysis is periodically performed to identify the most common root cau es. The result are used to create a plan of action to eliminate these types of defects from recurring For example, if it is found thaI many defects are caused by Cod, prohlrm cod, rwi,w d.d" 'I ca lch iI, a review of and improvement to the code review process can be implemented.
29.3,2 Patch Releases Patches are used in two ways. The Ar t way concerns gelling new or replacement software vers.ons or parts to users. The second addresses delay< in impleme nt ing an MR . In Ihe first way, patches arc permanent replacements of parts of the application. They often take the form of a set of fi les, sent via the Internet. that replace object code already written . In th.s case, the challenge are for the customer's organization to ensure that patches arc appropriately installed. Many customers conduct their own system tests of patches that ' 5, 111 their ow n environment. The second way concerns the handling of defect MRs thot require s.gnincant time to remedy It al,o concerns defects that hamper a customer's use of the ys tem and so must be remedied quickl . A rap.d Ax is not always possib le. To take an extreme example , in a m.lirary application with which one of the authors was once involved , nine months cou ld elapse between the .dentiAcation of an MR ond it complete implementation and docume ntation l l n these case patches are modifications or addition s to the object code that either nx or work around a defect. FiBure 29 .9 showl a way .n whic h the'" patche an be organ.zed w.th.n the develop me nt orga ni zatio n It demon strates the nom.nal , "ofAcial" path taken for a pat .. h on the
739
740
CHAPTER 29
SOFTWARE MAINTENANCE
1. Get malntenance-!r8Quest 2 . Approve changes
:r 3. Plan changes
Assess impacl
Coordinate
Execute with patch
I
4. Change code and documentation
4
Implement.J
Release
Test changes
Document
Update documentation
patch removal
Figure 29.9 Patches In maintenance workarounds
Advantages
Disadvantages
• May be a complete solutio n to the problem • Keeps customers satisfied
• May duplicate work - patch a"d final fix both implemented
• Enables continued operati on and testi ng
• Temporaries sometimes ne ve r replaced
without prese nce of th e defect • Avoids masking other defects • Enables test of fix
- pro per fix deferred fo reve r • Complicates fi nal fix (where appltcable) -
must rem ove
• Complicates documentation process
• When too ls used for insertio n, ma y com .
promise code base Figure 29.10 Advantages and disadvantages of maintenance patches left-as well as an informal process f.or ge uing the patch into the application on a temporary basis on the right of FIgure 29 .9 . The advantages and disadvantages of patches include th ose li sted in Figure 29. 10. The comment about "masking" refers to the fact that allowin g defec ts to remain can make it difficult to detect other defects whose effects arc hidde n by the effects of the nonrepaired defect .
29.3.3 Software Trouble Reports, Maintenance Requests, and COlTection Reports It is simplest when a single test leads to an MR that is worked on as a SI ngle ac tion , but the proce s is often not so simple. Mai n tenance requests emerge fro m reports of trouble experienced with the application (often called sofl ware tro"bl, reports). There may be several pieces of evidence for a si ngl e MR or, Conve rse l)" several MRs th.t grow out of a single trouble report. E.ch part of the work on an MR that IS worth d ocumenting I recorded in a so ·called correction rtport . To deal with the prol ifera tio n of correction reportS, We may need to identify a child MR of the MR under conSideration . This organIzation is shown In Figure 29. t I.
IEEE MAINTENANCE STANDARDS
::t,
-;.,
Malnlenance
I,
~
Request
Sollware Trouble Report
1293
STR 902834
Correction
Correction
Correction
Report
Report
Report
1293.1
1293.2
1293.3
Maintenance Requesl 1293.1
Maintenance
Malnlenance
Request
Request
1293.2
1293.3
Figure 29.11 Software trouble reports. maintenance requests, and correction reports
29.4 IEEE MAINTENANCE STANDARDS The IEEE ha published standard Sid t 2 19· 1998 [ 12], which descri be. an iterallve process fo r managi ng and executing software maintenance activities. It is gea red to large projects. but it is instruc ti ve to examine this sta ndard as a speCific and de tail e d example o f a mainte nance proce s for projects o f a ll sizes. Its table of contents showing the pertine nt secli o ns I Ii sle d In Figll": 29. 12 .
I
Prob lem ide n tifka tion
1.1 Input 1.2 1.4 1.3 Contro l 1.5 Quality faclo rs 1.6 Metrics
4 Proce ss
4. I
Input
O utpul
4 .2
Proce ss
Codill9 and It lill9 4 .2 .3 Risk alialysis alld rroirw 4 .2.4 Tts l-rtadillfSS rwiw> 4 .2. I
2 Ana lysis 2. I Input 2.2
Imp le me ntatio n
4.3- 4 .6
Process
2.2. I Fea sibility analysis 2.2.2 Dtlailtd analysis 2.3-2 .6 Con lro l, o utput, quali ty factors, metncs
3 Desig n 3. 1-3 .6
fac to rs, rnerrics
5 System tes t 5. 1-5.6 6
7
SoIXGf"1EE£ l td ~'994 Reptoouced WlUl "cumtSskln
Inpll !, proce. <, control, Ollrpllt , quahlY fa tors, melnCS
Delivery
7. 1- 7,6
Alure 29.12 IEEE 840-1994 "Soltware Maintenance"
Input, process, control, output, quahty fa tors, metncs
Acceptance test
6. 1-6.6 In put, proces', contro l, output, quahty factors, me ln s
o nlro l, O"tp"! , quality
ta ble of contents
In put , process, contro l, output, qua hty fac tON, metnc,
7.1
7.2
CHAPTER 29 SOFTWARE MAINTENANCE
The sta ndard deA ne. seve n p hases t hat an MR flow< th roug h . each
orrc pondlng to a scction '"
Figu re 29. 12. as fo llows, I . Problem/mo d iRcatio n id ent iRcati o n . classiRcation. and prioritizatio n 2 Analysis
3. Dcsign 4 . Im plemen tation
5. Regressio n/system tcsti ng
6. Accep tance testi ng 7. Delivery Note th at th cse ph ases are si mila r to the phases of th e develo pme nt p rocess. Eac h of th e phases has six attribu tes th at desc ribe th e actio ns and data associ ated w ith th e m, 1. In put
2. Process
3 Control 4 . O utput
5. Q ual ity fac tors
6. Me trics Figu re 29. 13 su mma rizes the relationsh ip betwecn t he p hases and attributes. The foll OWi ng sectio ns describe how a mai ntena nce req ucst flows thro ugh each phase.
Phase
1. Problem identification
2. Analysis 3. Design 4 . Implementation
ANributes
a. Input 1I1e cycle art~acts lor this step Process required for this step c. How the process is
controlled 5. Syslem tes!
d. Output I~e cycle
6. Acceptance
artifacts
PrIX
7. Delivery
.s.
quafl1y
lactors Involved
Metrtcs lor this FIpue 29.13 Six attribUtes 01 each maintenance request phase
IEEE MAINTENANCE STANDARDS Table 29.2 IEEE 1219·1998-Malntenance phase l '• problem Identification
a. Input
• The Maintenance Request (MI\)
b. Process
• "ssign change number • Classify by type and severity. etc. • Accept or reject change • Make preliminary cost estimate • Prioritize
c. Control
• Identify MR uniquely • Enter MR into repository
d. Output
• validated MR
e. Selected quality factors
f. Selected metrics
• Clarity of the MR
• Correctness of the MR (e.g., type) • Number of omissions in the MR • Number of MR submissions to date • Number of duplicate MRs
• Time expected to confirm the problem SOUrce: IEEE Sld 1219-1998. Reproduced WIth permIssion
This section describes and explains Steps 1-4 in Figure 29 . 13. Steps 5-7 arc si milar to the regular testing and delivery process. Testing in particu lar emphasizes regressio n testing to ensure that exi stin g functionality has not been compromised.
29.4.1 Maintenance Problem Identification In this initial phase, MRs arc identified . claSSified , and assigned an ininal prio rity ranking . Table 29.2 summarizes the process (or the identification phase of maintenance requests "Problem Identi fication" In the Encounter case study, for exampl e, wa perfom,ed by the marketing department. They solicited and exam ll1ed user complain ts about the co mpl icated way In whi ch Encounter game characters exchange quality va lues as a result o ( engagements
29.4.2 Maintenance Problem Analysis Table 29.3 summarizes th e ana lysIS phase (or maintenance req ue ts. Maintenance problem s range (rom the Simple to the deeply halle nglng. Fo r example, suppo e that we want to provide the En ountcr ga me player with addin onal image op tl on< (or the main playn This appears to be a straightforward request, however, the ex tent o( mainte nance request> like thi S is often underestimated The ana lys; process is deSigned to uncove r the rca l work 111 ca rrying out modifica tio ns and additions For example, we might dete rmine that the InCrN cd number o( Image opti o n, req Ulf(: a o mple tc reworkll'lI o( the way In whic h th e Images arC di
/1".,,",
59
60
CHAPTER 3 SOFTWARE PROCESS
A~,/, pro e"e< arc 1"8 hl
itl'raII ve , and elllphas,ze workln~
ode Ih roughout, as wel l as frequent
,ntcra tinn.; with th e U\lOIlU.:r.
A PllllolyPt ' a partia l lI11pl emcnlallon of the largel app licali o n u clu l ,n ,dent"'}'ing and re llring rISky part> of a projc 1. 11 can
3.S EXERCISES 1. During whi ch process phaseCs) would each of the fo ll owi ng aClivities occur;>
a. Creating a project schedule b. De leml irlin g Ihe need for a bar code reader c. Req uestin g the additio n o f a fi le backup ca pability d. Performi ng a feasibility ana lysis e. Documenting the software interface to an SQL database
f. Acceptance of the softwa re applicallon by the customer 2. G ive an example of a software project that wou ld beneAt much mo re hom usi ng the waterfall process than fro m using most of the alternative processes. Explain your reasoning. 3. Describe the d ifference between iftr.,i., and incrt",,,,,., development. Describe the ways in which they arc related. 4. Give an example of a software project that would beneht mo re fro m usi ng an iterative and .ncremenlal process than fro m using most of the alternati ve processes. Explain your reasoning. 5. a In your own words, explain hmv the spiral model utilizes risk anal ysis and risk mitigation. b. Exp lain why Ihe o uter spiral of the spiral mode l utilizes Ihe waterfall process , and how the spiral model miligates the inherent disadvantages of the waterfall process. 6. Give an example of a software project that would beneR t much mo re from usi ng the spiral process than from usi ng most of the alternalive processes. \'(frite a paragraph explain ing yo ur answer. 7. How do the phases of the unified proce .. (UP) differ from the pha es usually deRned for oftware processes' 8. Describe Ihe pros and cons of each va lue listed in the Agi le Manife
EXERCISES
Communication For the following exercises, consider as a group how you will perform them , check the hints below, then carry out the assignments . TI . Decide who your team leader{s) will be . Note that being team leader provides you with practice that may be hard to get otherwise. T2 . Decide how your team will communicate, specify your communication tools and methods, and test your communication methods. Be specific: YOll may change the specifks later. T3 . Search the Web for the latest mfomlation on a topic determined by the instructor (e .g., the TSP). Note at least four of its basic goals and at least five of the techniques it uses. Post the references to the course forum or \'(feb site If there is one. and annotate your posting with the name of your group . State individual or gTOUp opi nio n of the topic or issue. Your team respo nse should be 4-7 pages long .
Hints for Team Exercises TI hints: To distribute the beneRts of team leadership practice, It can be beneficial to swap team leadership about halfway through the semester. Both team leaders ca n be chosen up fTont , and they can back each other up in case of emergency. Such backing up is a good practice in any case, because the probability of a team leader having to quit a project o r a class can be high . ote that the second half of a project typically requires the team leader to make decisions more quickly than the first half T2 hints : Examples are telepho ne, meetings, e-mail , forums , chat facilities , and Web sites. I. Schedule regular face-to-face meetings at least once a week, if possible It is hard to convene an unscheduled meeting but easy to cancel a scheduled o ne . 2. E-mail is an essential tool. but can be problematiC due to unpredictable delay . Messages can become unsynchronized, damaging the threads (subjects) of dialog . This is espeCially senous near the end of a proiect when communication is frequent and of immediate Importance . 3. Use a shared Web si te or chat.type facility . Free services are available at hnp://groups.yahoo. com!, for example . 4. Do not merely state, 'We will use Superword for word processing ." Specify a version number, and exchange a few messages to be sure. Don't c hange versions dunng the project without ensuring compatibility Rrst. 5 Try out all the standards and methods you have chosen . Throughout this program of study, validate your plans and inte"tions with practical tests whenever possible. Try to u e at I~ast two independent tests. In genera l, assume that your project Will be much more demanding In the future than it is at the beginning . T3 hints: Usc th is activity to strc ~ your communication system . Forexample , you may want to set up a Web site to which team members are to add new TSP mformation How will you orllaniu thi random actlvlty7 How can you obtain a useful rc. ult In tcad of a conglomeration of unconne ted text7
61
62
CHAPTER 3 SOFTWARE PROCESS
BIBLIOGRAPHY I. Ro "O c, \: " ·M~n"t4lng the DC'v(lopmcnt o r Large Sohw3 rc YS It'lm o ncc:pts 3nd Tt'chnlquc'l: IEEE WESCON "70 , Aul\Kt 1970. pp 1- 9 2 BluMer, Kurt , .lnd Spence', I • 2007, "Mmt4~t"g hffolljW So/tuum DwdopMmf P,o), 's:' Addjson -Wc~IC)" , Peirson EduC1tlon, Inc. kbum. Alistair · Unr.wdlllM I nc ~m('nl
Agile Software Processes
Planning
..... The Software Development Ufecycle
•
How did agile melhods come about?
•
What are the pnnclples 01 agility?
•
How are agile processes carried out?
•
Can agile processes be combined with non-agile ones?
Design Figure 4.1 The context and learning goals for this chapter
In the t9905, agile softwa re development came In lO being as an a ltern ",ve to the existing classl al approa hes to ofrware engineering that were percelvt·d to be too · pro ess·heavy · TI,e e claSSical approaches emphasize the need to plan projects In advJncc, cxpn:s, requirements In writing, provide: """tten deSign sa ti sfYi ng the reqUIrement , wrlle odc ba ed o n these de\lgn' an,fying the written requiremcnts, and fina ll y 10 test the results A we ulstll<>ed in hapt er I and 3. how<'Vcr, Illany prOjects (ollowlng the e steps exh ibit major prol lem, A primary rea,on I< that >takeholders do not ~ uallv kn w at the mCeptlon of a proJeu entirely ,,,hat they reqUire Ag"e process!:, addre" thl< shan oOllng Thl' hapter dc(,n~s w hat" meant by as"e dewlopment, des nbe< ,evera l peclfic softwa re proce"e. that adhere to allile pnnclples and arc thus ons ldered procc"e" and d"Lu ses h ow all " e and non -ag ile pr c'>es can be coOlhtncd
.B"e
6.
CHAPTER 4 AGILE SOFlWARE PROCESSES
4.1 AGILE HISTORY AND THE AGILE MANIFESTO gro up of II1du, try ex perl, me t "' 200 I to d l cuss way' o f Improv in g on the the n wrrent
",St.
• Clo<e co lla boration betwee n prog ramm ers and busi ness experts • Face · to·l-ace communi catio n
Individuals and Interactions (over processes and tools) For decades, manage ment practice has emphasized the hi g h value of commun icat io ns. Agile pract ic~s emphasize the Sig nifica nce of hi g hl y ski lled ind ividuals and the enhanced expertise that emerges from '"teractions among them . Altho ug h processes and tools are Important, skilled people should be allowed to
We are uncovering better ways of develop ing software by do ing it and helping others do it Through this work we have come to value:
1. Individuals and interactions over process~s and tools
2. Working software over compre h e nsiv~ documentation
3. Customer collabor.ation over co ntrac t negotiation 4 . Responding to change over following a plan
That is, while there is value in the items on the right, we value the it~ms o n the left mo~ .
FIlii" 4.2 The AgIle Manifesto
AGILE PRINCIPLES
adapt the proce5 and modify the tools as appropriate to ge t their job done as efficiently as possible. As suggested III [ 3J. agile ",ethods offer generative values rather than prescriptive rules, a nllnimum set of values. observed in all IllIation , that generate appropriate practices tor specia l situations . Individuals and teams usc these rulC'S when problems ari c a a basis for ge nerating soluti o ns that are appropria·te for the projecl. ereali iry IS emphasized as a major means for problem solving. Thi s is in contrast to more rigid sofrware proce e , whi h pre cribe a set of predetermined rules and force teams to adapt themselves to these rules. Agile practices uggest that the laner approach is not effective and actually adds to the risk of project failure .
working Software (over comprehensive documentation) orking software is considered the be t indicator of project progress and whether goals are being mel. Teams can produce pages of documentation and supposedly be on schedule , but these are really promises of what they expect to produce . Agile practices emphasize producing working code as early as possib le . As a project progresses , sofrware functionality is added in smalllncremenlS such that the softwa re base continues to function as an operatio nal system. In this way team members and stakeholders always know how rhe real system is functioning . Although Significant, working software is of greatly dimin ished value with out reaso nable documenta · tion. Agile practices emphasize that project teams determine for themselves the level of documentation that is absolutely essential.
Customer Collaboration (over contract negotiation) This statement emphasizes the fact that development team arc in business to proVide value to cuSlOmers. Keeping as close as possible to your customer is a long-established maxi m of good business practice . Many programmers are disconnected from the cuSlOmer by organizational layers and intermediaries, It is highly desirable to remove this barrier. All stakeholders, including customers, should work logether and be on the same team. Their different experiences and expertise should be merged with goodwililhat allows the team to change direction quickly as needed to keep projects on track and produce whal i needed. Contrac ts and project charters with customers are necessary, but in o rder to adapt to inevitable change, collabo ration is also nece sary [3].
Responding to Change (over following a plan) Producing a project plan forces ream members to think through a project and develop contingencies . However, change is inevirable, and agile practit ioners believe that change should no t only be planned for but also embraced_ Very good project mana gers plan to respond to change, and rhis is a reqUirement for teams operatlllg at the most effecti ve leve ls, as you will see when we discuss rhe hi ghest capabi lity levels of the CMM I in Section III of this book. As changes to the plan occur, the team h ould not tay focu 'ed on the outdated plan but deal instead with the changes by ad.ptlng the plan as necessary [3). Agile practices rely on short iterations of one ro six weeks to prOVide timel y project feedback and IIl fo rmati o n necessary to as ess project progress and respond as necessary.
4.2 AGILE PRINCIPLES In addItion to the va lues dcscnbed in Figure 4.2, Ihe aUlhors of th e Agile Mani!e to oU llined a se t of ~uidi n g prlllcipies that ,upport the manifesto. The,,, arc quoted from [ I) (bold added ). • "Our nIghest priority .. to sa tisfy the custo mer through early and con tlnuo u. deltvcry f valuable suftware • Welcome changin g requi remen ts, even lale In development. Ajlilc pro esses harness OJstomer's competitive advanta~e .
hange for the
65
66
CHAPTER 4 AGILE SOFTWARE PROCESSES
• Deliv~r working software frequently , from a couple of weeks to a o uple o f mo nth •. with a prefer nce to tI,. shaner timesca le. • BU5mess p~op l e and developer must work together dally throughout the prOject • Build projects around motivated ind ivid uals. C,VC them the e nvironment and support they need, and trust them to get the job done. • The most effiCient and effective method of conveying Infonnation to and With," a development team IS face-to-face conversation .
• Working software i the primary measure of progress. • Agile process. promote sustainable developme nt. The sponsors, developers, and users should be able to maintain a constant pace indefinitely. • Continuous attemion to technical excellence and good design enhances agi li ty . • Simplicity-the art oJ maXi mizing the amount of work not do ne-i s essential. • The best architectures, requirements, and designs e merge from self-organizi ng teams. • At regular interva ls, the team reflects o n how to become more effective , then tunes and adjusts its behavior accordingly." Many of these principles are implemented in prac tice by the agile methods de cribed in the next section .
4.3 AGilE METHODS This section describes some of the methods by which many agile processes practice the principles in the Agile Manifesto. Figure 4.3 shows the manner in wh ich agi le methods implement the Agi le Manifesto, a. fo ll ows. Agile processes common ly employ small . close-knit teams; periodic customer requirements meetings; a codece ntric approach ; documentation on an as-needed basis (e.g ., high-level requirements statements o nl y); customer representatives working withi n the rcam ; rcfactoring; pair programming; continual unit-testi ng" and acceptance tests as a means of setting customer expectations .
We next e laborate on the topics not already explai ned above. Pa" programming is a fo nn of continua l inspection by one team member of the work of a teammate. Typically, while one programs, the other inspects and devises tests. These roles are reversed for periods 0 time that the pair detennines. Documenling 0" an a5-ntcd,d basi, usually ,"valves writing some high -level reqUirements but not detailed requireme nts. These arc freque ntl y collected in the fonn of '"'' 5/0ries . A user story is a Slgn ltkant task that the user wants to accomplish wit h the applicatio n. According to Cohn (4), every II er story consists of the follOWing; • A written description • Conversations with the customer that establish a mutual understanding of • T eslS intendcd to validatc that the user story has been implemented
It
purpo e and content
-
1. Individuals and interactions over tools
-
--
and
2. Working software over comprehensive documentation MANIFESTO _
3. Customer collaboration over contract negotiation 4. Respond ing to change over fOllowing
RESPONSES :
a plan
a. Small, close-knit team of peers
y
b. Periodic customer requirements meetings
y
c. Code-centric
y
y
y
y
y
d. High-level requirements statements only
y
y
e. Document as needed
y
y
f. Customer reps work within team
y
y
g. Refactor h. Pair programming and no-owner code
y y
i. Unit-test-intensive; Acceptance-test-driven
y
y
j. Automate testing
y
y
Figure 4.3 ways to address the principles of the Agile Manifesto Examples of user sto ries fo r a video sto re applica ti o n are as fo ll o ws, • "The use r ca n search for all D VDs by a opve n d irecto r." • 'The user can establi sh a n acco unt tha t re me mbe rs all tra n ac tions wit h the c ustomer · • 'The u. e r can view all ava ilable in fo rmatio n o n any DVD " o"lI"unl i"llractlo" a nd contac t With the cu to me r is ac hi eved In twa wa ys. Fi rs t, the wo rk periods ( 1- 6 wee ks, usually ) in whic h the each batc h o f reqUire me n t arc to be flll Rlled are speciRed With a tea m that Involves the custo me r ('co nd, a cUSto me r re presenta tive I< e ncouraged to be part of the tea m. TI,e e mphaS IS o n worki ng soflwart is rea lized by mea ns o f coding versio n o f the applica tio n a nd sho '"lng them to the custo me r. These arc usually clo el y tied to corres po nding test< Indeed , Icsl-dnvOi drvclop",mt an allile a pproach , actua lly has devel o pers wfIte test< even before devel opi ng the code
68
CHAPTER 4 AGILE SOFTWARE PROCESSES
Oblaln requirements for next perlod's' segment
Obtain hlgh-tevel requirements
Relector to clean up
Relactor to accommodate new requ irements
Modify code and test code base to handle additional requirements
• Typically 1-6 weeks
Figure 4.4 A typical agile development iteration
Rcfa
1011"9 is a process of altering the fonm of a code base while retainin g the same functionality . The
usual goa l of a rdacto rln g is to make the design amenable to the addition of functionality , thereby satisfying the agile deSIre 10 respo nd "'CillO c hange. The very fact that the discipline of rcfactoring has been developed IS a majo r f.clO r mak ing agile methods possible This book covers rdacto ring in Chapt.er 24 . Although refactorin g is discussed latcr in the book , much of it will be useful before then and can be referred to throughout the book. Agile metho d. employ the developmen.t cycle shown in Figure 4 .4 . T y picall y , the requirements are expressed in terms of lIser stories . Past experience in the project allows the team to assess its _docily , an assessment of the relati ve diCficulty of tories and the rate at which it is able to implement them The schedule effects of agile me thods can be seen in Fib>tJre 4.5 . Planning is attenuated because there is less to plan . Requirements analysis, design, and testing are often conRned to high levels. The emphasis is mostly code ce ntered .
4.4 AGILE PROCESSES "Agi le developmen t" isn't itself a spe iRe process or methodology Instead , it refer.; to any software proc('Ss that captures and embraces the fundamental va lues and principles espoused in the Agile Ma.nifesto. The following sectio ns illustrate and describe three agile processes as repre cntative examples. • Extreme programming (XP) • C rystal
• Serum
AGILE PROCESSES
• Time line Plan lor agile methods
C,"'X <,-. " '~I-. ...........~ ..........:.~;.o..~...... ""\"'~J:1: t
" . .'
-_.
' ••
Implement in agile fashion System tests not covered by agile method:
Figure 4.5 The agile schedule
4.4.1 Extreme Programming In 1996, Kent Beck and co lleagues bega n a project at DaimlerC hrysler [51 using an approach to software development that appeared to make marters muc h simpler and more efficie nt. The methodology he developed and used became know n as Exl""" Prograrnrni>lg (XP) [6]. Beck [6] cites fo ur "values" gUidi ng extreme programmi ng, communication , sImplicity, feedback , and courage. These are summarized in Fig,,"'s 4 .6 and 4 ,7. XP programmers communi cate continuall y with their customers and fc ll ow programmers. TI,ey keep their design simple and clean , They obta in feedback by testing their software, starting on day o ne. They deliver parts of the system to the customers as early as possible and Impleme nt changes as suggested , With this foundation , XP programmers are able to ·courageously· respo nd to c hangi ng requi rements and techno logy [5]. XP was created to deal effectively with projects in wh ich requirements c han ge . In fact , XP expects requirements to be modified and added , O n man y projects, custo mers start with o nl y a vague idea of what they want. As a prOject progTesses and a customer sees working software , specifks of what they want become progressively firm .
I. Communication
• Customer on site • Pair programm Ing • CodIn g st.1ndards 2, Simplicity
• M e taphor: e ntity names drawn from COmm o n met"phor • S,mplest d eSIg n (or c urrent reqUIrements • R.efac tOnng
Figure 4.6 The "values" of extreme programming, 1 of 2 SOuru- 8.:;)'... YMYt, •.~ PtOSfMlming Eltplak'wl EmbrAce Chang.," ~ddl50n·w8S1BV. '000
69
10
CHAPTER 4 AGILE SOFlWARE PROCESSES
I Feedback alwa y, a u!!hl
• • •
onlJnual l c..~ "tln g Ol1tll1UOU' 'nlegra tl o n (al leasl dad y ) mall ",lease (small e' l usdul feature ,el )
2 Courage
• Planning and esti matio n with • a llectlve code owner-hip •
u ~ t O lll cr
use r stones
ustain ablc pace
Figure 4.1 The "values" of extreme programming, 2 of 2 SOUtre. Beck.. Kenl "Extreme Programming EkJ)Ialned' Embrar.e Chango," Addlson·Wesley, 2000
XP projecls are divided inlO ilerations lasting from one
to three weeks . Each iteratio n produc~s
soft ware that is fu lly tesled . Al the beginning of each , a planning mecli ng is held to determine the COQ t~nts of the iteration . Th is is "just · in . time" planning, and it facilitates th e mcorpora ti o n of changing requirement s.
As code is devel o ped , XP rel ies o n continual integrati o n ralhe r that assembling large, s~ parately developed mo dules. In the same spint , releases are modest in added ca pability . The idea is to bite off a small amount of new ca pability, integrate and lesl it thoroughl y, and the n re peal Ihe process. EXITeme prog ramming recog nizes Ihe all . loo . frequent breakdown in c usto me r devel o per reiationsh ips, w h e r~ eac h pa rry de velops a scpa ralc concep l of what's need ed and also h ow much th~ features will cost to devel o p. Th e resull of Ihis mi smatc h is , all too often , a mad dash for deadlines, including lo ng workin g ho urs and a n un suslainable pace. In respon se, eXlreme progTamming promot~s a modus vive ndi thaI's susta mable in the lo ng term . In addition , it requires every developer to acknowledge up front Ihat all code is everyo ne's commo n property , to be worked on a the project's needs require . In o lhe r words, no code "belo ngs" to a prog rammer. This is in keeping wilh engineering practice , where a bridge blueprint , fo r exampl e, is the product of an o rga nizalio n and nOI the personal property of o ne desig ner. XP is unique in usin g twelve practices Ihat dicta le how programmers should carry out their daily jobs. These twel ve practices arc summarized next (7). I. Planning Process . Req uirements, usuall y in Ihe form of user stories, are deR ned by cuslomers and given a relative priority based o n cost esti mates provided by the XP team . Slories arc assigned to reieases, and Ihe team breaks each slory into a set of tasks to imp le ment. \Y/e described user stories in Section 4.3. 2. Small Releases. A si mple system is buill and pUl inlo produclion early Ihat includes a minimal set or useful reatures. The syslem is updated frequentl y and incrementally thro ughout the deveiopmenl process. 3. Test-Driven Development. Un il tests are wrinen thaI functionalllY is aClually wrilten .
10
leSI funclionality, before the code to implement
4 Refactorlng . Code is regularly modi fie d or rew ritte n 10 keep It simple and mainlainable Chang~.~ Incorporated as soo n as de Acie ncies are idenlified. We ,"troduced rdoc toring in S~tion 4.3 and cover It in delail in C hapter 24 5. Design Simplicity. Desig ns are created 10 solve the known reqUirements, not 10 solve future rcqui~ ments. If necessary, code will b~ refa lored to implemenl fulure dcsisn needs.
AGILE PROCESSES
6. Pair Programming . This was described in Section 4. 3 7. Collective Code Ownership. All the code for the system is owned by the entire team. Programmers can mod,fy any pan of the ystem necessary to complete a feature they're working o n. Th ey ca n also improve an part of the system . S. Coding Standard. For a team to effectively hare ownership of all the code, a common cod,ng standard must be fo llowed. 11,is e nsures that no matter who writes a piece of code, it will be easi ly understood by the entire team . 9. Continuous Integration . Code is checked into the system as soon as it's comple ted and tested. Thi s can b" as freq uent as severa l tim e per da y. In this way the system is as close to production quality as possi ble. 10. On-Site Customer. A customer re prese ntative is available full · tim e to determine requirements, sct priorities , and answer questions as the programmers have the m. The effect of being there is that commun ication improves, with less hard -copy docume ntati on-ofte n o ne of the most expensive parts of a software project. I I . Sustainable Pace. XP tea ms are more productive and make fewer mi stakes if they're not burned out and
tired. Their aim is not to work excessive overtime, and to keep themse lves fresh , healthy, and effective. 12. Metaphor. XP teams share a common visio n of the system by deR ning and using a commo n system of describing the art ifacts in the project.
4.4.2 Serum Serum is an agile methodo logy deve lo ped in the early 1990s . It is named after the part of a rugby ga me that , in U.s. foot ball terms, is a cross between the kickoff and a quarterback snap . As deRned by the Merriam Webster dictionary, a scrum is "a rugby play in which th e fo".ards of each si de come together in a tight fo rmat ion and struggle to gai n possessio n of th e ball using thei r fect when it is tossed in among them ." In o ther words, scrum is a process that follows "o rganized c haos." It is based o n the no tio n that the developme nt process is unpredic table and complicated, and can only be deRncd by a loose set of activities . Within this framework , the development team is empowered to de Rne and execute the necessary tasks to succes fully develop software. The flow of a ty pica l sc rum project is show n in Figure 4.8. A project is broken ,ntO teams, or scn,ms, of no more than 6-9 members. Each team focuses o n a e lfcontai ned area of work . A scrum master is appoi nted and is responsi ble for conducti ng the daily se rum meeti ngs, mea uring progress, mak ong decisions, and clearing ob tacle that get in the way of team progress. The daily scru m meetings shou ld last no more than 15 minutes . During the mee ting the Scrum master, allowed to ask team memb"r< o nly three questio ns [8]: I. What ,tem< have been comp leted since the last serum meeting: 2. What issue< have been di covered that need to be reso lved) 3. What new assignments make sense for the team to complete untol the nex t scrum mee ting) At the begonning of a projec l, a lost of cu
71
72
CHAPTER 4 AGILE SOFTWARE PROCESSES
every 24 hours l S·mlnute dally meetings 1) Done since laSt meeting?
2} Have any obstacles'?
Sprint Backlog 01 assigned features ••••
Backlog items expanded by team
3) What will
30 days
Product Backlog
you do belore next
meetrng?
New Functionality Demonstrated at end of sprint
Prioritized product features desired by customer .
Figure 4.8 The serum work flow SOUrce: QuoteCI and edited from t\rtf)'jfWvrIW coouolchaos.com/aboul
control of how they are to successfull y complete the spnnt. At the e nd of a sprint a customer demonstration is conducted for the cuStomer. It serves several purposes, including [8],
t . Demonstrating to the custo mer what has been accomplished . 2. Giving th e develo pers a sense of accomplishment . 3. Ensuring that the software is properly integra ted and tested 4 . Ensuring that real progress is made o n the project.
At the co nclusion of the dem o nstration, the leftover and new tasks are gathered, a new backlog is created r and a new spri nt commences.
4.4.3 Crystal Crystal is a family of agile methods devel oped by Alistair Cockburn . Each Crystal method shares common characteristics of "frequent delivery, close communication, and reRective improvement" (9 ). ot .11 projects are the same , so differe nt Crystal methodologies were crea ted to address differences," project size and critica lity. Figure 4.9 shows the different methodologies and the size project they are best suited to. Crystal methods are characterized by a color, starting at clcar for smaIJ teams and progressing through to or""9'. mi. and so on as the number of people increa ·os. For example, Crystal lear IS geared for smaIJ teams of approxima tely 6 people, YeIJow for toams of t 0-20 people; Orange for teams of 20-40 people , and so o n, The other axis deRnes the critica lity of a project, where L IS loss of life, E IS loss of es enllal monies. D IS loss of discretionary monies, and C is loss of comfort . Note that the row for los of life" nOt shaded in Figure 4.9. This is because Cockburn had no experience applying Crystal to the e types of projects when he .... ated th...
AGILE PROCESSES
L6
,,,
............. , E6
Clear
loss 01 life E ; loss of essential monies D ; loss of discretionary monies C ; loss of comfon
L;
Figure 4.9 Coverage of various crystal methodologies SOUrce; Adapted trom CocXburn. AlistaIr, "Crystal Clear A Human-Powered MethodOlogy for Small Teams," Aadlson-wesJey, 2005
chart. Crystal Clear doesn't explici tl y suppo rt the E6 box, although Cockburn no tes that teams may be able to adapt the process to accommodate such projec ts. Ano ther restrictio n of Crysta l is that it is al'plic2ble o nl y to colocated teams. Cockburn believes that deve lo pers do no t read ily accept the demands of fl"Y process (docu mentatio n, sta ndards, e tc ). H e strongly recomme nds accepting thi s by Introduci ng the most limited amou nt of process needed to get the job do ne successfull y, ma xi mizing the likelih ood that team members will actua ll y fo llow the process. All Crysta l methodo logies arc built around three commo n pri o rities (9} I Safery in the project o utco me.
2. EffiCiency in development. 3. Habitability of the conventio ns (I.e ., the ability of devel o pers to abide by the pro es itself) . Crystal projects exhib it seven prope rti es to varyi ng degrees (9) I
Frequent delivery .
2 Reflective Improvement. 3 4.
lose commun ication
P -"ona l safety.
5 Fow, 6 Easy a"ccss
to
exp rt use rs
7 Technical ~nvlronm""nt With au to mated t('''tln~ , con If.:ura ti on manage men t, and Ircqllcnt In H:..:ratl n.
73
74
CHAPTER 4 AGILE SOFlWARE PRO ESSES
III
n,e I1r,t three p,opertl '~rc commo n to the ry\tallJmlly The others Cdn be ad ded ,n any order to rc."c the I'Ke llhood o f 1)l'o)ec t ,afety and SULtesS.
4.5 INTEGRATING AGILE WITH NON-AGILE PROCESSES Th e advantage. 0 1 agile meth ods in lude the abll,ty to adjust eas ily to emcrlling and c hangi ng rC'Iu".ment' n,c d,sadvantage in lude awkward ro le for de iBn and dowmentat, o n ockburn's Crystal fam,ly 01 meth dologies alrcady acknowledges that different k,nds of appllcallons must be treated d,fferently . L"Ven when the metho ds are ag de . oft",.re pro e. s, after all , oncerns the order in which we perform act,vities' Fo r example, deSigning Ars t and then coding from the des'gn One extreme IS the waterfall process. As we have seen, there are many IIm,talions in our ab d,ty to thorough ly perform the waterfall sequence:' o nce, or even a few times, 'terat,vely. hangea ble and unknown requirements are a principal rea on Regardless of the development process we use, we must make trade ·offs in deciding ho w ex tens,vely to pursue a phase befo re movlO8 to ano ther phase. o nSider, for examp le . the issue of how much effort to spend on planning a software enterprise. One extreme project situation is when we are certain of obtaining all of the requirements of the end date , of the high ·level deSign , and of who wi ll be working on the job. In that case, we can and probably should devel op a de tailed plan . The other extreme prOject ,tuation is when ,_e have little idea of any of these factors , believing that they wdl beco me clear only after the project is under way . In that ca e, planning at a detailed level would be a wa te o f time at best becau e it could not be even nearl y accurate, and would probably even be misleading. We ha ve no choice in this case but to begin the process , and revi sit the plan as required. The extremes are Illustrated In Fi gure 4. 10. Agile methods provide beneAts bur also costs, and these depend o n several factors . Some are shown in Figure 4. 1 I. In order to gain the advantages of both agi le and non·a gile' processes, we try to integrate them . The means by wh,ch this can be performed depend on several !actors, but particularly on the size of the job. As of
100%
---------------------• Can obtain all require",sntSr
• Certain of end dale • Certain of hlglHe.el design Advisable delallievel 01 plans
.-
• Certain of personnel ~HIGH
DETAIL PlAN
~LOW
_ _ _ _ _ _ _ _ _ _ _ _ Extent o(
0%
knowledge
•
' .' .., "
,, ,
,, ,
, ,, ,, •
100%
Figure 4.10 HOw detailed should plans be? Some: authors c haracterize n n 'JKilc processes For C'x.lmplc. one practice j, to 311 them "plan ~based ." The- autho~ do not believe ,n a I\lOglc Ch"fiJcteri zatlon like thi~ of non-agile proc~s~C's; hence thc= blankf!'l tenn -non.oglle · I
•
INTEGRATING AGILE WITH NON·AGILE PROCESSES
Benetlts 01 Aglig
Costs 01 Agile
@ Motivates developers
® Hard lor new panlcipants
@ Thoroughly tested. usually
®Sensltive to individuals
@Easler to estimate each cycle
®Hard 10 estimate lull lob
@ Responsive to customer
®Umlls learn size
©Always demonstrable sohware
Figure 4.11 Trade-ofts between agile and non·agile processes
2009, the conventional wisdom concerning the agile/non .agile split is shown roughly in Figure 4. I 2, The larger the job , the more non-agile process is required. Agile processes empha ize code first, whereas non.agile ones advocate coding on ly from well· documented designs and designing o nl y from well·documented requirements. These approaches appear to be almost contradictory, so combining (hem requires substantial ski ll and care . We will co ncentrate on methods for doing this in large jobs, where th e c hallenges are greatest. We will ca ll the two options "oll-agiledrivrn and agile-driu
4.5.1 A Non-Agile-Driven Approach A common non·agile-driven approach is to initiall y approach the job without agility , then fit agile methods Into the process after sufficient work has been done to define the agile ro les and portions. We develop a plan , create a ca rehll high. level design, and decompose the work into portions that can be implemented by teams In the agile manner. One can superimpose upon each agile team a process by whic h the accumulating Percent agile vs. non'agile
t
100%
.,-
C>
,
'c" 0
..
Z
i
I SmaJ/
Large
Job slzo
Figure ' .12 conceptual agJle/non-aglle combination options: some conventional wisdom, circa 2009
75
76
CHAPTER 4 AGILE SOFTWARE PROCESSES
- - - - - - - ; : : : : : - - - - - - -•• rima I
Requirements documentation 4
Design documentation
._--......-
2
... .
Coding and testing
System testing
", .
-
-
--
3
6
• High level Figure 4.13 Integrating agile with non-agile methods, : time line for a single iteration
requirements are gat hered . and placed wit h in a master requirem e nts document. The sa me can be do ne with the accu mulati ng design . Domg thi with design is mo re d ifficult because design parts may actually be replaced a nd mo dified as rd.ctoring takes place. Requirements tend to accu mulate as much as they change. The seque nce of eve nts is as fo ll ows, I. Hi gh . level requi re ments are developed for the first iterat ion .
2. A I" gh .level design is develo ped based o n the h igh .level req uirements. 3. Agile develo pment by tcams begins. based o n these hi gh · level docume nts. 4 . Full require ments documentatio n is ga the red fro m the wo rk do ne by the agile tea ms as it progresses
5. The design documentation i ga thered from the agile teams at regular interva ls to update the design document.
6. System testi ng not covered by the ag il e process is performed at the end . if necessary. 7 . The process is repeated fo r eac h iterallon . This is illustrated for o ne watcrfailiteration in Figure 4 . 13. Figure 4 . 14 shows thiS for multiple iterations.
4.5.2 An Agile-Driven Approach For an agile .driven approach to large jobs. a (small ) agile team can be set to work o n signincant a p«ts of the project until the o utline of an architecture appear. At that point . non ·agile methods are used. This ma invo lve reintegrating agile programming again as described in the no n·agi le ·driven approach above. This has muc h In common with building a prototy pe . H owever. the differe n e IS that the initial work i performed larl!cly to develop an architecture rather than retire flSks . In add itio n. the work I no t planned a throw.away cod e. One agile -drive n approach is shown in Figure 4 . 15 .
SUMMARY
Time
M I L E S T 0 N E S First /teralion' completed X
Product released X
SCHEDULE Iteration number
_.
•
'
1
.
•
d ocumentatlon
---
'- -
oeslgn _
.-
_ _N _
Coding and t estlng
- -.----
•
l'
-
•
"Tf _. - .- -
.
•I
d ocumentallon
3
w_._.
•
Requlrements •
2
--
--
• ..
._._- --t•
-
s ystem testing
,
'-•
--
• ....i.
---t-'
-
--
-,
I 2
I
3
'High level Figure 4.14 Integrating agile with non·agile methods 2: time line for multiple iterations
Initial agile development
I--~
I
I \ /~
Requirements documentation Design documentation
\
f
\
'i
:
I
\ \ \
' ''iL_ _.....J1
Coding and testing (Including agility?) Figure 4.15 An agile-driven approach to large jobs
The case sludy sectio ns fo r Ihis part o f the book (wh ich ap pear in Ch apters 5 and 6) ca n lai n two case studies thaI combine agil e and no n·agile methods.
4.6 SUMMARY Agi le software develo pm e nt was crea ted as an allernative 10 exi ling plan. based approaches thaI were perceived 10 be too process heavy and ngid. A gmu p o f industry ex perts mel in 200 1 to share the. r v. io n fo r an alternative to these types o f pro esses. They crea ted the Agi le Mani fes to to ca pture their Ih ollghls fo r a process th aI wa~ ada p ta ble, lea n, and as d".
77
78
CHAPTER 4 AGILE SOFTWARE PROCESSES
• TI,e need to collaborate close ly wilh cm lomors and other ,takeholders •
omtl'lUniCJIIOI1 over
do umentatlon
• Frequent delivery of workll1!; software
•
elf orga niz II1g reams 4
• TI,e need to embrace and plan for changing requirements Any process that embraces Ihe fundamental values of the ag ile manifesto is considered an agile process. Examples include extreme programmll1g , scrum , and Crys lal. E '\Teme programmIng is ba ed o n four prin iples : communicat Ion . feedback , simphclty, and courage. It promotes practices such a lest-driven development, refactorl ng, pair· programming , collective code owner· ship. continuous integration, and on·sitc customer.
Serum deAnes a framework , o r a loose set of activIties Ihal arc employed by the crum team . At the beginning of a project , a btl klog of work. or requirements, is identified . Deve/opers work on a subset of reqUIrements in the backlog in 30-day Sprill!S . Once a spri nt begins, the team is gIven the freedom to employ any methods deemed necessary to complete their work sucLessfull y. A customer demo occurs al the end of each sprint. A new set of work is defined from the backlog fo r the next spri nt and the cycle continues. Crystal is a fam ily of methodologies that address projects of differe nt size and crit icality . Crystal methods share the following characteristics: frequent delivery, reAective improvement, close communication, personal safety, focus , and easy access to expert users, and a lechn ica l e nvironment with automated teSling, configuration management, and frequent integrati o n. Agile and non· agile process ca n be integrated o n projects in order to gain the advantages of both . The means by which this ca n be performed depend o n severa l factors but particularly on the size of the project. One approach IS to Initiate a job without agility, then incorporate agile methods into the process after enough work has been accomplished in defining agile roles and responsibi lities. Another approach is to initiate a job with an agile approach until the outlines of an architec!l;re appear. At that poinl , non ·agile methods are used_This may involve reintegrating agile programming again as described in the no n.agi le-drive n approach above.
4.7 EXERCISES I. The Agile Manifesto favors working software over exte nsive documentation . Under what circumstances can thi s calise problems if taken to an extre me]
2. . . In your own words, explain how agile processes adapt to and embrace cha nging requirements. b. Describe a scenario in which this mi ght be counterproductive 3. Name three benefit of the XP practice of testi ng oftware from "day one," always having working software available. 4. During the daily IS -minute scrum meeti ng, the leader is only allowed 10 a k the same thlee questions . What two additional questions mig ht you want to ask] For each , explain lIS benefit toward achieving the goals of the meeting. 5. In your own words, explain how Crystal adapts to various types 01 projCCts.
79
I Bcd. K
uality in the Software Process
The Software Development Ute Cycle
•
Whal are the principles of managing quality?
•
How do you plan for "quality?'
•
Whal are inspections and how do you carry them out?
•
How do you carry oul reviews and audits?
•
How do you measure and improve sohware processes?
•
In wi1at way does CMMI assess organizational quality?
•
What does a sohware quality plan look like?
Figure 5.1 The context and learning goals for this chapter
This chapter discusses the manner in which we integrate and manage quality throughout the software development process. ThIS is an integral part of project planning. and it affects every phase of development. As part of planning, documents are produced detailing the quality approach to be taken, including specinc quality goals. techniques 10 be employed, melrics 10 be collected, tc~ts to be run , and t he manner i n which
PRINCIPLES OF MANAGING QUAUTY
• Quail! princIples --
•
uality planning --
• In peetlon -peer processes focused on Quality • Reviews and audits -~extcmal Quality as essment • Defeet manage me nt -identiRcatlon , tracking, and resolution of defec ts • Process improvement
--
Figure 5.2 Quality in the software process
defeets are to be handled. All of these contribute to an effective development process with a focus o n qual ity, result ing in the development of a high .quality oftware product. The integration of Quality in the software process is summarized in Figure 5.2. Each topic mentioned in the figure is described in thi s chapte r.
5.1 PRINCIPLES OF MANAGING QUALITY An overall approach to quality is guided by several principles . The planning and practIces described In thIS chapter are implemented WIth these principles in mind, as follows . F,rst and foremost , quality IS something the entire devel o pment team is responsible for . not ju
I. Focu. c.ontinuously on qualtty .
2 A qualtty assurance proce" must be dcAned 3. The or8aniz~tion must follow its qualIty assuran c process 4 . Ftnd and rcpair defec ts as early in the development pro
Asur. 5.3
Key prlnciPles of manag1ng quality
CS<
a\ po<>lble
81
82
CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS
If defect found . . . Reason (by one estimate):
... soon after creatIon
. . . at IntegratJon time
Hours to .. .. detect •
.. repa ir Total
0.7 to 2
0.2 to 10
0.3 to 1.2
9+
1.0 to 3.2
9.2 to 19+
Figure 5.4 Cost to repair a defect. depending on time elapsed since injection
roo
that developers write tests befo re co d ing, and then write code to pass their test . is discussed in more detai l In C hapter 27 Q ualit y assuran ce (QA ) refers to actions taken to assure that a product under construction attains reqlllred levels o f quali ty . The second and th ird principles listed in Figure 5.3 state that a QA process must be defi ned and fo ll o wed. Thi s IS ho w so much quality has been encouraged by the International Standards O rga nI za tIo n (ISO ) standard 900 I "Quality Systems-Mode l for quality assurance in d esign , develop· ment , productIOn . in talla ll o n, and servici ng." Many compani e have c reated documents describing their offiCIal Q A process. ISO In SIS ts o n the exi stence of such documents for companies seeking its certification. H oweve r, I 0 recog ni zed that a do cumented procedure is only a part of quality assurance. In practice, do um ented quaht y procedures are often ig nored wit h impunIty; hen ce ISO's second principle, which e nsures that empl oyees actua ll y fo llOWIn g qua lity procedures. Quality planning is discussed in mo re detail in Secti o n 5 3. The fourth softw are quality principle listed in Figure 5.4 is to find and fix defects as early as possible: i.e .. to prevent them from persisting for more than a sing le phase . Figure 5,4 provides dara fro m one of the author's clients o n the relative cost o f allo wing a defect to persist. Many organizations have rried to measure the difference in cost. and It is always found to be very large . A rule of thumb sometimes used is that a defcet costIng a do llar to fi nd and repair soon afte r its creation costs a hundred do ll ars to fi nd and repair if del ivered to the customer The main consequence of this principle is that it most often pay to spend significant resources findin g and fi xing defects as earl y as possible rather than allOWing them to remain undetected and active.
,
5.2 MANAGING QUALITY IN AGILE PROCESSES Agile and non ·aglle projects arc equa lly concerned with producing quality products. but agile methods go about this in different ways . In particular, agile response to t he prinCIples of Section 5. 1 are as follows: I Focusing continuously o n quality Agile processes fulfi ll this principle by creat Ing increments from close customer contact , b testIng th¢m during development, and via prearranged customer acceptance tests.
QUALITY PlANNING
2. DcAn.nll a qual.ty as,uran e proces Ag.le proccs rdy On rhe activities jll t listed for a QA pro ('55 , rather than o n documentation ueh as the IEEE ·tand~rd di IIssed in this c hapter \'ifhcther th. .s sufAcient , especially for large projects, remains 3 subje t of debate. 3. follOWing the organization' quality ",surance process Whether or not one doubts the adequacy of agil.ty for quality .n large prOjects, team members arc generall ",dl motlVilted , and they usually follow agreed· upon methods very faithfu ll y. 4. Finding and repairing defects a early in the development proce" as possible
Here, agile methods show their greatest stre ng th , s.nce they are code centric and thus try out implementation and testing of the pieces as soon as II is possible
5.3 QUAUlY PLANNING We begin planning for qualoty early in the development Iofe cycle . Documents arc written that denne an overall approach, including quality goa ls and techniques for every deve lopment phase (the Software Quality Assurance Plan ), how the product will be verified and va lidated (the Software Verincation and Validatoon Plan ), and how testing is planned , specined , and reported (the Software Test Documents ). Th e Software Quality Assurance Plan (SQAP) is desc ribed below, the Software Verification and Validation Plan (SVYP) is described in C hapte r 9, and the Software Test Documents (STD ) arc descri bed In the testing chapters of Part VII .
5.3.1 Software Quality Assurance Plan The Software Quality Assurance Plan (SQAP) specines the overa ll quality plan , policies, and procedures that will be followed by the team It provides guidelines so that quality aClions are nOt an afterthought but something conSCiously and deliberately stnven for and practiced throughout the development proce s. It orients the project toward prevention denning procedures for proactively mo nitorong and improving processes and quality, ensuring that qualoty practices are defi ned and implemented, and ensunng that problems are identified and resolved as early as possib le. T o do this, the QAt> answers the questions posed .n F.gure 5.5 The rest of this section addro<se< these question in turn .
1. Who will be ReSponsible for Quality? An ond.vidual or group is .dent ified as be.ng responsible for as
2, What Quality DocumentatIon Is Generated? The SQAP spec.f.es the docun1~n t s tt) be generated for a prOject and how they ar to be he ked for a ura y Examples of do um~nts are the
o ffw ar
Requirement, . peclOcut.on (
l.
oftwar
Des.!!n Document
13
a.
CHAPTl:R 5 QUAUTY IN THE SOFlWARE PROCESS
I
\xfho wi ll he rc>pon,ible (o r qualhy)
A PC:f"\OI1 , a
O1 anJ~('r. J group, an organiza ti on , etc.
2 ~ hat doc umentalion will be ge nerated to guide developme nt, venRcation and va lidat ion, usc and malOtcOJn (' of the o ftwilrc7 3
~
h at standards will l>e u<ed to e nsure quality)
D ocumentatio n tandards, codlllg tandud , e tc 4. \\'lha t metrics will be used to mo nItor quality) Pro duct and proces, metrics
5. \\'lhat procedures will be used to manage the quality process) Meetings , audi ts , reViews , etc.
6. What kind of testing will be performed) 7. \\'lhat quality as urance techniques will be used) Inspections, proofs of co rrec tness, tests, etc. 8. H ow will defects be handled) Figure 5.5 What's needed from a Quality plan
(SOD), Software VeriRcatlon and Validation Plan (SVVP), User Documentation, and the Sohware Co nRguration Management Plan (SCMP). The SRS deRncs the requirements (or the software, and the SOD describes how the software is designed to meet the requirements. The SRS and requirements are covered in Part IV. The SOD and software design are covered in Part V. The SVVP describes methods used to verify that the requirements speciRed in the SRS are the right set of requirements, that the requirements arc correctly implemented by the SOD , and thai the design in the SOD is correc tl y implemented by the code. VeriRcati o n methods include inspection , analysis, and testing. Inspecti o n is described in detail in Section 5.4 . User documentation describes how the sohwarc shall be successfully and correctly used . It also describes error messages and corrective action to take as a result. The SCMP detai ls how changes to software and documents are managed , and is described in greater detail in Chapter 7.
• I QA person per 3-7 developers • Excludes developer testing counted as developer time • Includes post-developer testing • Ideally performed by external QA per onnel FIgure 5_6 Typical estimate of QA requirements per developer
QUAlITY PlANNING
3. What Standards will be Used to Ensure Quality? Adopting consistent document templates contributes to the production of quali ty documentation. The use of IEEE tandud documents as outlined in this text , for examp le ensures that documents contain all the necessary Content and can be easily rcad and unde rstood by team members. Coding standards dictate such things as variable and module naming , commenti ng, and logic structure. Consistently developed code aids in different team members being able to better understand it and make updates.
4. What Metrics will be Used to Monitor Quality? The SQAP deAnes the quality metrics to be coll ected and ana lyzed. Examples of quality metries ,"c1ude defect den ity, mean time to fa ilure, customer problems, and customer sat isfaction. Metrics are dIScussed in detail in C hapters 3 and 9, among orhers.
5. What Procedures will be Used to Manage the Quality Process? Meetings, audits, and reviews are some of the techniques employed to manage the quality process. They are described in more detail in Secrion 5.5.
6. What Kind of Testing will be Performed? Both the Software Verincati on and Val idation Plan and the Software Test Documents specify the tests to be executed.
7. What Quality Assurance Techniques will be Used? Inspectio ns, proofs of correct ness, rests, and so on are all techn iques used ro assure product quali ty. Secrion 5.4 in particular describes the inspection process in greater derail. Proofs of correc tness and testing are described in this book as well.
8. How will Defects be Handled? As denned in Chapter 2, defects arc devia tio ns from requiremen ts. Procedures for ident ifyi ng and managing them are deAned in the SQAP. Defect management is covered in detail in Section 5.6.
5,3.2 IEEE Quality Documents The IEEE has publ ished several standards related to software qual ity, as fo ll ows, • IEEE 730· 2002: Standard for Software Q uality Assurance Plans • IEEE 10 12· 2004, Standard for Software Ve rincation and Validatio n • IEEE 829· 1998, Standard for Softwa re Test Documentat ion These documents relate to the software developme nt pha es as hown '" Figure 5.7. Figures 5 II and 5.9 summarize the contents of IEEE Standard 730 ·2002 Standard for oftware Qualit Assurance Plans. The case study se tion ncar the end of thl< c hapter con!>ins a ample QAP r r the Encounter Video game.
as
86
CHAPTER S QUAUTY IN THE SOFTWARE PROCESS
Projoct Management
IQ. PIIn 7ID I
"
r-----__.: ,-EXPlains quality policies ,",' ', ....... \ ......... ""
Requirements Analysis
.....---_--, I
I I
~v.v PIIn 1cn2~
t-•
-
Design
Explains verification and validation procedures ......... __
----
,
_.
........
\
' II
Implementallon
.........
-- ---- -1L _
=--_.......J1
li _.... _....: ..
Explains plans, procedunts, and test cases
Figure 5.7 The main IEEE software quality documents
6. Reviews
I. Purpose
2. Referenced documents 3. Management
6.I
Purpose
6 .2
Minimum requirements
3. 1 O rga nization 3 .2
Tasks
3.3 3.4
Responsibilities
QA estimated resources
4 . Documentation
4. I
Purpose
4 .2
Minimum d.ocumentation requirements
4 .3
Other
5. Standards,
practices,
conventions,
and
6. 2 . I
Software speci ficatio ns review
6.2 .2
Architecture design rcvie,,'
6 .2 . 3
Detailed design review
6 .2.4
V&V plan review
6 .2.5
Functional audit
6 .2 .6
Physical audit
6 .2 .7
In -process audits
6 .2 .8
Managerial review
6.2 .9
SCMP review
6 .2 . 10
Post-implementation review
metrics
5. I Purpose 5 .2
o ntent
6.3
7 .- 15. See next figure
Figure S.B IEEE SOftware Quality Assurance Plan table of contents 1 of 2 Sourer. IEEE Sid 730-2002..
Other reviews and audits
INSPECTlONS
7 . T est may rde re n e Softw are Test Documentation.
S. Problem reporting and corrective action
9. Tools, t",chniques, and methodologies may reference SPM P. 10.
Media control
I I.
Supplier control
12 . Records collection , maintenance, and retention 13 . Training 14 .
Risk management may relerence SPMP.
15. Glossary 16. SQAP change procedure and history Figure 5.9 IEEE SOftware Quality Assurance Plan table of contents 2 of 2 Scuce: IEEE Std 7.30-2002.
5.4 INSPECTIONS An i"Sp,elicm is a quality technique that locuses o n review ing the details of a project art ilact (requ irements, designs, code, etc .) in an organized and th orough manner. Inspectio ns arc perlormed pen odi call y duri ng all software e ngineering phases by the artifac t's autho r and by o ther e ngineers. The purpose is to assure the artifact's correctness by seeking delects. A meeting 01 inspectors is held at wh ic h ddects arc ident ified . The repair 01 defect is the author's respo nsibility . The Inspectio n concept was develo ped by Michael Fagan [ I Jwhile he was at IBM He obse rved that the author o f a wo rk IS usuall y able to repair a deiect o nce he recognizes its prese nce. Thus, a process is needed whereby the delec ts in a wo rk arc ca lled to the author's attenti on as ea rly as possi ble. Thi implie that inspections should be a peer process beca use inspec tions arc perfo rmed o n work in process rather than on fin ished product. ince inspectio ns we re o riginally introduced to improve code, the y arc often referred to as ·code inspections," but thei r value has bee n shown 10 bc grea test whe n used earl y in thc process , lo ng be fo re code is produced . They arc used proA tabl y a< soon a~ the firs t project documents are produced. For example, requirements speCIfica tio ns, project management, and configuratIo n rlans should all be inspected.
5.4.1 Inspection Principles GuIding prinCIples lor conducti ng inspectIo ns arc It . ted below. The
17
CHAPITR 5 QUAliTY IN TIlE SOFTWARE PROCESS
I
PCCO' pro eS5
2. pe IRed rob 3 Delcc t dete tio n i" lead of defee l repair 4 U se of heck!'sts
5 Arlif" t readiness 6 . Adequate preparallon 7 . Metrics COllec lio n 8. Time limll
1. Peer Process Inspecli o ns arc co nduc lcd by a group of individual; who are familiar with the artifact under reView They may be software engineers, members of other departments such as softwa re quality assurance, marketing, sales, or cu tomers. The inspec tion is a peer process with an overriding goal of discovering defects The work ,n progress is under inspection , not the performance of the author, and therefore it is not a supervisor· subordinate process. An author is responsible mainly for the product he or she submits aJttr inspection, not before. The work brought 10 the inspection should be the author's best effort, not a draft .
2. Specified Roles Inspections work bcst whcn speCific roles arc assigned to each participant . The moJrralor is responsible for leading the inspection and seeing that it is conducted in a productive and ef~cie nt manner. The moderator schedules the meeting and ensure that it starts and ends on time. with the latter bems accomplished by maintaining an appropriate pace throughout. It is very easy for participant.s to get bogged down in details and to try to solve problems during the meeting. It is the job of the moderator to prevent this from happe ning and to keep Ihe meeling moving along . However, the moderator must 31so ensure that the pace is not 100 fast as to miss defects. When defects are identified, the moderator is responsible for e nsuring that there is consensus from the team . Thu , to be effective a moderator should be: technically competent The modera tor is also an inspector. TI,e job can sometimes involve sensitive issues,
such as having to moderate among hostile participants wilh differing opinions. As de robed by Wiegers, "Moderators hould be trained in how to conduct inspections, including how to keep p3rticipan~ with strong technical ski lls but low socia l skills from killing each other." [2J The a""hor is the person responsib le for the work product itself, and repairs all ddects found (offline). The author is also an inspector, looking for defects along with other inspectors. In order to avoid bias, the author should not serve in any other role. Authors must remain objective throug hout the inspection and not become defensive. This ca n be hard as others arc ~nding "faults" with their work. The record" is responsible for writing down descriptio ns and classifications of th~ defec~ found, and for recording the action items. If the inspection team is very smali, the moderator could also take on this role, but it usually is best to have someone else assume this responsibility . The recorder is also an inspector.
A "aJ" is responsible for leading the team through the work In an appropriate and thorough ",anner. This person selects the most effective sequence for presenting the work product and answer qu~stions ~ by the in
INSPECTIONS
All particIpants on an Inspectio n act as inspecto~, In addition to any other rcsp'onsibil,ties they may have. It i important to invite people who can make a significant contribution and have the expertise to identify defect to the in pection. Examples of people who should attend arc other prOject membe~, those responsible for testing o r maintaining the product, and depending on what artifact is being develo ped, customer and busi ness repre,entatives. Depending on the artifact being inspected, there may be a requirement for specia lized inspectors. For example, a Joc""d ,"spec/or inspects for a specific criterion (e.g., rellabiliry). A sprcial;z,d ;IIspec/or is a specialist in the area covered by the artifact under onspection (e.g., a radar expert for a radar contro l applicatio n).
3. Defect Detection, not Defect Repair Inspections should focus on identifying defects, and specIfically excl ude any discu sion of their repair The repaor process is left to the autho r, and no time should be spent durong inspectio ns even suggesting repai~ . All repair suggestions should be made offline. This is rypically one of the hardest things to control-many partIcIpants love to discuss potential solutions and it is quite easy to fall onto intemlinablc tcchnica l discu sions regarding the best approach. This IS where a strong moderator i essential. It is key to not let this rype of d,scuss,on continue and instead to remind people that the goal of the meeting is to identify defects, not repaor them .
4. Checklists A checklist can be very useful in providing gui dance to inspectors, describing specific areas to pay attention to. Each rype of artIfact such as project plan , requirements peci~cation , design peclncatlon , configuratio n management plan , source code, and so o n should have its own check lost, as each requires dIfferent areas of focus . Example questions to ask when examining a requirement speci fica tIo n mig ht be as follows : Is each requirement verinable by testi ng] Is each requirement uniquely identified] For code inspecti o ns, ques tI ons to ask might be: Are there any variables that are unused or rcdundanols the code adequately commented] Good examples of checkl ists can be found In (3).
5. Artifact Readiness The artifact under review should be in the best sta te of readiness that the author IS capable of. For document there shou ld not be many , if any , sections with "to be determined : Code should compi le cleanly \'(fhen a group of people takes ti me to ide nt ify a defect that the author would have fou nd wi!h reasonable effort , a significa nt amount of time is wasted .
6, Adequate Preparation Inspections are not the sa me as reviews, manage ment overviews, or education sessions Inspectors have to
work. at the same level of detail as the author. (This is what make, inspections time ·consumong and thus expensive.) The artifact under review is distributed several days before the meeting, all owi ng inspectors adequate time to study the maten al, identify defec ts, and prepare questions to ask at the in pectlo n Inspection.aidi ng software can save time by allowing inspectors to enter de criptions of defect they discover while preparing The recorder accesses and ed Its these at inspection meetongs
7. Metrics COllection During inspectIons, metrics arc collected and analyzed Examples of metries to colic t arc a fo ll ows: • Number of defects discovered , by severiry and type • Number of ddcc t ~ dl .covcred by each ca tegory of stakeho lder Inspe ting the artifact
89
90
CHAPll'R 5 QUALITY IN THE SOFlWARE PROCESS
•
umber of del cet< per r~!!e rev Iewed
• Revle
rotc (number of pOHe ho ur )
For , everi ty , a Impl e lo,,,f,ca ll o n su h 0' l' IIIWI , ",,"or, and lev'" ~o n be used For Iy pe , ca tc/jo " es such as 1l11 '3,m g uncti on, Inco rrect JlInctl o n, pcrrorrn ancc , il nd usabil ity an be used Thl ~ class ificat ion tOpIC IS d,sc u,sed In e tl o n 5,6. 1 The me trl , w ll ec te d fro lll in pc li o n, arc analy zed and th e resu lts used lo r seveml purposes First, they arc use d to pred, t th e dnc,e n y of future review If a company h., ", formatIon o n th e rate 01 rev,cw lor a part ,cul ar am /oc t, ,t can u'e th at to predl t ho w lo ng to , hedul e lor a luture review of a SI mIlar art ,/a t e o nd , co untin g the number 01 defec ts discove red dUrin !! each sto ge o f deve lo pment is useful ,n pred,c ting th number 01 defe t, rn hllurt proJectS Even Illo rc spec d, c , o untln!! th e number 01 defects d,scovered by a p,rrhC'lllnrslnkrholdtr «- .g ., marke tIn g , cuSto lller, QA ) is also usefu l. For exam ple, dunn g a req uire me nts revIew lewe r than ex pc ted ddc t are d, scovered by the customer represe ntative , ,t could rnd,ca te e Ither a lack 01 preparation o r 1111 und ers tandrn g 01 requirements by that perso n . In ei ther ca e , this would mise a red Aag and a lollow-up Ill eeti ng WIth the custome r wo uld e n ue to und ersta nd the cause lor the discrepan cy .
.r
8. Time Limit InspectIO ns sho uld not be Illorath o n 'cssions, wh ,c h ca n occur if the mo de rn to r docs not keep th e meeting mov ing along. After a certain am o unl of lime , participants will nOt be as foc used a needed_ Each sesSIon shQuld be kept to a ma xi mum 0 two ho urs, and il it is no t completed by then a follow -up session should be rescheduled
5.4.2 Inspection Process The inspecti o n process loll ows an o rde rl y flow 01 steps, each adhering to th e princi ple described above. The steps are ummanzed in F' gure 5. 10 .
1. PLANNING
- - - .j Overview I }
Non-nominal process
/
_-- - -
2_ PREPARATION .......
--
Nominal process
4. REWORK "- -
-
Causal Analysis
--
5.
Figure 5.10 The parts of the Inspection process, emphasizing the main sequence of actMtles
INSPECTIONS
1. Planning. The process begins w.th planning . Th.s oneludes decidong which inspecrion mttries to collect , identifying tool to be used in recording and analyzing these dara, dec.ding who will part.cipate on in pect.ons and wh"n they w.1I take place, and distributing the materoals s~veral days prior to the meeting . Typically, the moderatOT is re ponsoble for thcse tasks. LA. Overview meeting . If necessary , an overview meeting can be organized to explain the artifact under Inspection. Since meetings are expensive, this should be avoided unless obviously necessary . 2. Preparation . The next step for each inspection con ISts of preparation. Here, in pectors review the work in compl ete detail al their ow n workstallons (e .g., c he king that the code under inspccl.on correctly implements the detailed design ), pos ibly using checklisl provided for guidance Whal makes the .nspection process valuable, but also expenSIve , is the fact that this lime' co nsuming process is performed by several people in complele detail. The process .s not a "review," because inspectors work at the same level of derail as the author In pectors frequenlly enter the defects they And intO a database (e g., Web· accessible) together with descriptions and c1assiAcations. ThIS help to prevent duplo ca tio n, and it minimizes unnecessary meeting time . Some prefer to u e paper to record their defects. and orne conSIder the number of inspec(Qrs who recognize a given defe t to be a useful metric. 3. Inspection meeting. When every participant is prepared , the inspection meetin g takes place . Durong th.s meeting , the participants honor their deSignated roles. Of I>articular importance is (Q not cry and solo, problems that arc raised, but instead to ensure that they are recogn.zed as defects, to record lhem as action items on ly, and to move o n. 4. Rework. Normally , the author is able to repair all defeclS, working alo ne. This.s the rework phase. If the inspection meeting deCides, however, that the defects are so pervasive that a reinspecti o n ' 5 required, then the item is recycled through the process. 4A. Causal analysis . If the defects are due to a mi su nderstandi ng or Widespread mISco nception , It may be necessary to ca ll a separate mecling at which these causes are analyzed and discussed Again , since meetings are expensive, these should not be scheduled casually, 5. Follow-up. Aher the author repairs the defects identified during the inspectio n meet.ng, a brief follow· up meeting is conducted at which the moderatOr and the author con Arm that the defects have Indeed been repaired. This is not intended to bea detailed review by the moderator. Theonus forrepairison the author, who is responsible for the work. If the number of defects repaired is high , a follo\~-up inspection may be required 6. Improve process. Organizations shou ld always analyze the efAcacy of their pro e ses and strive to improve them . For Inspection , the group meets from lime to time to review the inspection process itself, and decides how it can be improved . They exa mine the metric collected, including the Ii t of defec ts , and decide how the development process can be improved to reduce and/or prevent the same types of defectS in the future . Fi8ure 5. 1 I shows the average relative times for each inspection process step, u cd as reference data b one of the .uthor's c1.ents The Inspec ti o n meeting t.me in Figure 5. 1 I is shown as o ne hour for the sake of reference Ind ividual compan.es or developme nt 8roups record .n'pection times and quanti lies in pected, and lhey e tllnatt' future inspections based o n these historical data . The IIme< ,hown in Figure 5. 1 I may d.sturb the uninitlaled , wh may wonder whether it rea lly does take that Io n!! to check code. Producong profe Slonal.qualoty produ t ~s .ndeed lake a substantial 'mounl of time, and a~y fa. lure 10 recog n.ze lhe true co t end. lip o n,um.ng f.r more t.me in the end , Inspect. on, have bee n esti mated by .chan. and Mc e un k [4 J to o n'Ulne a, onu h is 10· 15 percent of the development budgel.
91
92
CHAPT£R 5 QUALITY IN THE SOFTWARE PROCESS
Rewor\( Analysis
One company's estimates 1 hr x (1 person) 1 hr x (3- 5 people) 1 hr x (2-4 people) 1 hr x (3-5 people) 1 hr x (1 person) 1 Ilr x (3-5 people)
Total:
7-21 person-hours
Planning Overview Preparation Inspection meeting
Figure 5.11 Inspection time/costs per 100 non-commented lines of code Inspecti on are expensive because they co n urn e the time of everal e nginee rs. Nevertheless, various s tudle (fo r example, [ I ]) have h own that they payoff handsomely. This is due to the astronomical cost of detecllng and repairing defects undiscovered untd cia e to delivery time. Quantified benefits of ,"spcctlOns from sour es uch as IB M , ICL, and Standard Bank , for example, are summarized in [5 ]. Appc ndi x D of the case stud y sh ows an example of a form for reporting t he results of an inspection .
5.5 QA REVIEWS AND AUDITS The QA organizallon works wi th th e project leadership to defi ne the manner in w h ich external quality assessment will be perfonned , specifies this in th e SQAP, and execute it during the course of the proj~.ct . External QA activities are either rrol(WS (sometimes called walk-throughs ), which are scheduled in advanc~ , or a"dllS, which are not so scheduled_ A project can expect both types of activities. Figures 5 . 12 and 5 . 13 show th~ range of options for QA involvement in reviews and audits, starting fro m the most invasive to the least.
• Participate In a ll meet ings Including fonna ll ve sessions and inspections. • Review all documents Participate in a ll inspec tio ns (but d o not attend all meetings ). • Attend final reviews and revie,,, all completed documents • Review sci en completed documents But do not participate ot herwise. Figure 5.12 Options for QA reviews
• Audit at unrestricted random times Includes visiting with e ngineers . Includes inspecting any document at any time. • Audit random meetings • Aud it ra nd om ly from a speCified list of meetings • Audit wit h notice • No audi ting Figure 5.13 Options for QA audits
DEFECT MANAGEMENT
Benofits of Frequent Intervention
Costs 01 Frequent Intervention
© Helps in aSSessing prOject
®Time needed to get
status
documents ready
© May help to improve process
® Engineer time taken to explain
or project
® OAtime
Figure 5.14 Comparing frequent VS. occasional QA intervention Frequ~nt intervention by QA has the advantage of provIdin g QA personnel with greatly improved
understanding of the health of the project. but it may disrupt the project by frequently calling for documents or for engineers' time. This trade·off is summarized in Figure 5. 14.
5.6 DEFECT MANAGEMENT Projects encourage the submission of defect repOrlS by all team members. Usually, a screening process that ~nsures def~ct reports are valid and accurate is put in place . To manage defects, QA standardizes on the manner in which defects are defi ned and tracked . These data can then be compared between different projects so that estimates can be made rega rding new projects . We explain this standardization next.
5.6.1 Classifying Defects Teams classify each defect by its stv"ily (how serious it is), priority (i ndicati ng when it will be handled), It s type ( th~ kmd of problem ) and its soure< (the phase during which it was injected). These classification arc illustrated in Figure 5. 15.
• Severity
How serious is the defect? • Priority
?•
In which order will defects be repaired?
? "
~
- - --
• Type What kind of problem is involved?
L" '"
• Source
During which phase
1
was it injected?
1""'- 1 fl&ure 5.15 Defect classification
93
9.
CHAP I ER S QUAUTY IN THE SOFlWARE PROCESS
No more than two decl,tona ar. required.
Defec, Hverlty 10 m%r
el.
"I v
Defeel severity Is 'rlv'.'
else 2
V Classify as "medium"
Clasally a. "major"
Clasally a. "1r/vl.,"
Figure S.16 The triage decision metl10d applied to defect severity classification
A Si ngle severity classlncation scheme can be used for all artifacts. It is possible 10 be very discriminating among levels of severity, but this consumes time. The results should be worth the time. One of the authors has frequently e ncountered teams using diSCriminating classincation schemes that consume significant decision · making time and yet the data that they produce are not utilized by the organization . Deciding the severity level of a defect fa lls into can sometimes be difficult. Triage is a useful and simple decision -making technique when confronted with a large number of possibilities, a situation occurri ng often in software engineeri ng. Utdl zi ng triage for defect classincation has the advantage of being fast to perform because eaeh classification requires answering just one or two questions as shown in Figure 5. 16. Once a list of defects develops, the team approaches the major ones first (they can be placed in order with the ' major' category if necessary). Once they have becn attended to, the medium severity defects can be handled. The team gelS to the trivial o nes o nly after this, if time allows. A simple way to classify the severity of defects when using triage is shown in Figure 5. 17. Although triage is fast, the three·category classincation lumps together all defects that fail requirements, whether serious o r not. Thus, "name neld is not purple, as required" and "system crashes every minute' Ca "shows lopper" si nce its effects are catastrophic for the applicatio n) are given the sa me severity, which is rather extreme. Shows toppers usually need to be separa ted . To address this, the IEEE has deAned a more refined classification of defect severity as shown in Figure 5. 18. The "None" category is added to collect unprioritized defects.
• Major
Causes a requirement to be unsatisfied. • Medium Neither major nor Irioial. • Trivial Defect doesn't affect opera tion or maintenance. Figure 5.17 Classifying defect severity by triage
DEFECT MANAGEMENT
• Urgent Failure causes system crash , unrecoverable data loss, or jeopardizes personnel. • High Causes impairment of critical system functions, and no workaround solution exists. • Medium Causes impairment of critical system functions, though a workaround solution docs ex.ist.
• Low Causes inconvenience or annoyance.
• None None of the above.
Figure 5.18 IEEE 1044.1 Severity classification A defect's Priority is the order in which the team plans to address .t. This is somewhat aligned with the defect's severity but is not identical. For example, a defect can be classified as "urge nt" but it may not be necessary to repair it immediately. For the sake of project effiCiency, fo r example , its repair may be batched with a set of repairs to the same part of the product. Different phases use different defect type classificatioll' . For example. a defect in the requirements may concern ambiguity but "ambiguity" docs not apply very well to code. On the other hand, code may have a logic defect but "logic" does no t apply to requirements in the same way. Some types of defects an common to all artifacts, as listed in Figure 5. 19. The 'OUret of a defect is the phase in which it was introduced (or '''jecred ). For example, you ma y d iscover while testing a video store application that it does not-but should-accept the video /(, A Mad. Mad. Mad, Mad World because the requirements document stated that no word rn a title should be repeated more than once (supposedly to prevent bad data entry). Even though the defect may have been discovered during the testing phase, its ,ourer phase was requirements analysis.
5.6.2 Tracking Defects Table 5. 1 shows a typical way to track known defect.s . The information is u.s ed to manage ongoing work and to record defect history for postmortem and estimation purpos~s . • Omission Something is missi ng.
• Unnecessary The part in questio n can be omitted . • Nonconformance with standards • Inconsistency
The pan in question contradicts other part(s). • UnciassiRed None 01 the above. figure 5.19
Common defect types across all artifacts
95
96
CHAPTER 5 QUAUTY IN THE SOFlWARE PROCESS
Man bug. tracking program, a.,<: indispensable 111 tra king "nd managing defects. Bugzil/a i< an cxample of an o pen , o uree defect·tracking sy
5.7 PROCESS IMPROVEMENT AND PROCESS METRICS Even a very good process has to adapt to changes such as new technology and new kinds of requirements. For these reasons, very effective software development organizations include a mtla·proass with every software process: a process for improving the process itself. This usually takes the form of meetings at the end of phases to review the effectiveness of the process used with a view to improving it for furure projects. A meta·process is outlined in Figure 5.20. To measure the dfectiveness of a process, an organization has to use it for several projects and then compare the project metrics. Table 5.2 gives an example. These results suggest that process U is the most effective, since it produces the best results in every category. Process V is the worst for the opposite reasons. Matters are not often so simple, however. For example, suppose that we had to choose between Waterfall and "Waterfall + Incremental." The latter process is superior in defect count, developer cost, and customer satisfaction, but it scores worse in the other categories. Making the call depends on the relative importance of the factors to the organization . Figure 5.21 lists a sequence of actions that can be taken throughout the life of a project in order to continually improve the process. Figure 5.22 is an example of the kind of data that can be collected about the process. It is applied to the process of collecting detailed requirements, which is covered in Part IV , but the table is applicable to most phases. The numbers are illustrative only, and should not be regarded as industry standards. A comparison with the organization's normative (typical ) data reveals deAciencies in the team's meeting process and in their individual execution (i .e., the actual writing process). This exposes problems in meetmgs . for example, which were subjectivc:1y evaluated 2 out of 10 by the team . It was determined (though not visible in the data) that the meeting process would improve if the straw man proposal brought to the meeting was more complete i.e. an explicit proposal that can be used as a basis for discussion . The other problem observed in the example shown In Figure 5.22 seems to occur during the execution step, where the actual work of writing the requirements is performed . The defect rate is higher than normal (5 versus 3) and the self·assessed quality is a little below average (4). Comp.red with company norms, there appears to be room to spend more time executing the work (i.e ., as individuals ), thereby redUcing the defect count and improving the subjective self·assessment. You can observe from this process that a tandard for counting the parts of the phase is fundamental to our ability to measure it. In this case, we are counl1ng "detailed reqUirements," a concept that will be explained in Chapter 4. Even in the absence of historical data , the team predicts what the values of the metrics should and will be. With these advance predictions, teams tend to work better, and they tend to remember results. ll>e dat.. collected become the basis for furure historical darn. Man.ging all of this is not technically d.ffkult, but it Ns
Table 5.1 A typical way to track known defects Defect Tracking NO. 1
Name
Description
Checkout flicker
Checkout screen 4 nickers when old DVDs are checked out by hitting the Checkout button.
Discovering engineer
Responsible engineer
Date opened
Kent Bain
Fannie Croft
1/4/04
April Breen
1/4/06
Source
Severity
Type
Integration
Med
GUI
Being worked; begun V1 0/04
Requirements
High
Math
Not worked yet
Status
-t Bad fine
2
• •
• •
•
•
•
• •
•
•
• •
• •
• • •
Fine not correct for first·nun DVDs checked out for 2 weeks, as displayed on screen 7. • •
•
•
• •
• •
•
Fannie Croft
•
•
•
• •
•
• •
• • •
•
• • •
• • •
•
•
• •
•
•
• • •
•
•
•
• • •
• •
•
• •
•
• • •
• • •
•
•
• • •
•
•
• •
Tested with suite 9023
m
l:l
-
•
Resolved •
~ •
• •
•
•
•
• •
•
•
:s
91
CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS
QVlpul
Inpul
Prac1lces to discard
Metrlc data on multiple projects using the process
Pract ices to retain Practices to Introduce
Figure 5.20 The process improvement meta-process to be d o ne at th e sam e ti m e as many oth er urge nt ac t ivities. For t h is reaso n, t h e assignment of cl ear respo nsib i lities and th e regular revie w o f th e m etric data are wor ked o ut at th is ea rl y sl age i n th e process. As you wi ll see in the ne xt sectio n , process impro vemen t fee dback se parates g rea t dev el o pm ent o rg ani zations fro m m erel y good o nes.
Table 5.2 Data from multiple projects used to compare processes
Waterfall
Waterfall + Incremental
Process U
Process V
1.3
0.9
0.7
2.1
Development cost per detailed requ irement
51 20
5100
58S
S135
Developer salisfaC1ion index (1 to 10 ; best)
4
3
4
3
Customer satisfaction index (1 to 10 ; best)
4
6
6
2
Cost per maintenance request
S130
5140
59S
5165
Variance in schedule on each phase :
+20%
+70%
- 10%
+80%
+20%
+65%
- 5%
. 66%
23%
51 %
66%
Process -" Average over 10 projects: Major defects identified w ithin first 3 months per 1000SLOC in delivered product
•
00 aC1ual duration - projected duration projected duration 1 x Variance in cost : 100 x aC1ual cost - projected cost projected cost
Design fraction : lolal dtSig . limt lotal progralflm i.g timt Humphrey: Should be at least 50%.
PROCESS IMPROVEMENT AND PROCESS MEI RICS
I . Identify and define metrics tcam will use by phase
Includt- . . tim~ spent o n research, execution, and review · . size (e.g ., lines of code) · .. number o f defects detected per un it (e .g., lines of code) include Source · .. quali ty self-assessment of each o n scale of 1- 10 main lOi n bell -shaped di stribution 2. Document t hese In the SQAP.
3. Accumulate hi to rica I data by phase. 4. Decide whe re (he metTic data will be placed . As the project progTesses SQAP) SPMP) AppendIX? 5. Desig nate engineers (0 manage collectio n by phase . QA leader or phase leaders (e.g., design leader) 6. Schedule reviews of data for lesso ns learned . Specify whe n and how to feed back improvement. Figure 5.21 A process for gathering process metrics
Requirements Document 200 detailed requirements
Meeting
Research
Execution
Personal Review
0.5 x 4
4
5
3
6
% of total time
10%
20%
25%
15%
30%
% of total time: norm for the organization
15%
15%
30%
15%
25%
2
-
8
5
-
4
-
6
Defects per 100
N/A
N/A
N/A
5
per 100: organization norm
NIA
NlA
NlA
3
4
Hours spent per detailed requirement
0.01
0.02
0 .025
0.015
0.03
Hours spent per detailed requirement; organization norm
0.02
0.02
0.04
0.01
0.03
Hours spent
Self-assessed quality 1- 10
Process Improvement summary
Improve st. awman brought to meeting
Spend 10% more time executing
productivity: 200/22 = 9.9 detailed requirements per hour
Figure 5.22 COllecting project metrics for phases
Inspection
99
100
CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS
5.8 ORGANIZATION-LEVEL QUALITY AND THE CMMI · o/tWJ'" development orga ni za tio ns pcrlCldKally as,e S and upgrade their overa ll capabi llly . ln the 1980sthe nonproht o ftwa ..: Engineeri ng Institute ( EI) establl
5.8.1 Level 1 : Initial The "In itial" CMM I level is the mos t primitive status that a so ftware o rganization can have. Organizations at level I ca n be sai d o nl y to be capable o f pro dUCin g software (i .e ., "someth ing") . The o rga nization has no recognized process for software pro duction . and th e quality of products and projects depends entirely on the indi vidual s pe rfo rm ing th e design a nd implementation . T ea ms de pend o n metho ds prOVided by membe rs of the gro up w h o take initiative o n the process to be fo ll owed. Fro m project to project, these could be very good o r very poor. The success of o ne projec t has little relatio n to the success of another unless they are sim ilar and e mploy the sa me so ftware engineers. W h en a project is completed, noth ing is kno wn o r reco rded abo ut its cost, schedule, o r qua lity. Ne w projects are as uncertain of success as past o nes . For rn a t organi za ti ons, th is is unacceptable.
IncreaSing maturity
•
LevelS OPTlMIZfNQ
'r
Level 4 QU4NTTTAnvUY MAHAOEO
Level 3 DEfINED
,
Level 2 MANAGED
Level 1 INITIAL
Figure 5.23 CMMI model for organization with staged processes
ORGANIZATlON·lfVEl QUAlITY AND THE CMMI
Table 5.3 SEI specifications of capabilities required for each level (see [7J for a full description) level. Title. and Summary
Expected Outcome
Characteristics
Undefined; ad hoc
Unpredictable; depends entirely on team individuals
Organizations often produce products, but they are freQuently over budget and miss their schedules.
2. MANAGED
Preceding level plus:
Measurement and control
Project outcomes are qualitatively predictable
3. DEANED
Preceding level plus:
Processes standardized
Projects consistent across the organization; qualitatively predictable
4.QUANTITATIVElY MANAGED
Preceding level plus:
Processes measured
Metrics available on process; quantitatively predictable
5. OPTIMIZING
Preceding level plus:
Improvement meta·process
Processes improved and adapted using process metrics
1.INITIAl.
Respect organizational policies Follow established plans Provide adeQuate resources EStablish responsibility and authority Provide training Establish configuration management Monitor and control: Take corrective action • • Evaluate process and product relatIVe to plans: address deviations
EStablish process objectives Ensure process Objectives met Establish orderly tailoring Describe processes rigorously Be proactive
set quantitative goals for key subprocesses Control key subprocesses with statistical techniques Identify and remedy variants
Establish quantitative process improvement objectives Identify and implement innovative process Improvements Identify and implement Incremental process improvements Evaluate process improvements against quantitative objectives
101
102
CHAPTER 5 QUALITY IN THE SOFlWARE PROCESS
5.8 .2 level 2: Managed 11,c "Managed" MM I level applies to o rga ni zatio n, apab le of trackin g projec ts as they unfold Such organizations make plans, manage co nfiguratio ns, and maintain records of project costs and schedules They al 0 descnbe the functionality of ea h produ t in writing. It i. therefore pOSS ible to predict the cost and sch edule of very si mil ar projects pcrfonllcd by a very Similar team . Although level 2 orga ni za tions track projec ts, no tandard development process for the o rga nizat ion is 8ll arantced.
5.8.3 level 3: Defined The "Defined" CMM I level applies to o rga ni zations that do ument and enforce a standard process. Suc h a process I typica lly o ne of those described in the previous c hap te rs (waterfall, spiral , etc.). Some o rganiza · tio ns adopt existi ng sta ndards suc h as IEEE's, while o thers de fi ne their own . Ro ug hl y speakin g, as long as manageme nt enforces coordi nated , professional standards, and e ngi neers imple me nt them unifOnll!y, the orga nization is at level 3. Training is typically required for an o rganization to reach level 3. Teams are allowed Aexibility to tai lo r the o rga nizatio n's sta ndards fo r speCia l c ircumstances. Level 3 includes o rga niza tion-wide standards for project manageme nt, complete configuratio n ma nageme nt, inspections, design notation, and testing. Level 3 o rga nizatio ns lack ge neral predictive capabi lity. They arc able to make predictions only for projects that arc very si milar to o nes perf'Onlled in the past.
5.8.4 level 4: Quantitatively Managed The "Qua ntitatively Managed" CMM Ilevei applies to o rga nizati o ns that can predict the cost and schedule of jobs. A commo n way to do this is to usc statistical techniques and hi storical data. Such an organization c1assilles jobs and their compo ne nts; it measures and reco rds the cost and time to design and implement these; the n it uses these me tric data to predict the cost and schedule of subseque nt jobs. As Humphrey has pninted out, this is no t "rocket science," but it does require a significa nt amou nt of orga ni zation , as well as an ability to analyze the data . Level 4 requires a complete, metric·oriente d quality plan . Even though level 4 is a hi gh level o f capability, it is no t the highest. Software engineering c hanges rapidly. Forexample, the object-oriented paradigm made rapid inroads in the 1990s, reuse and new component concepts are having a growi ng impact. Future improvements and paradigms are unp",dictable. Thus, the ca pabilities of. level 4 orga ni zatio n that does not adapt and Improve may actuall y decline over time.
5,8.5 levelS: Optimizing Rather than trying to predict future c hanges, it is preferable to institute pem1ane nt proe,JurtS fo r ""king and exploiting new and improved meth ods and tools. Level 5 organizations, at the · Opti mizing" CMMI level build in prace 5 improveme nt. In other words, their process (actually a meta -process) includes a systematic way of evaluatin g the o rb'
5.8.6 Relationship of the CMMI to the PSP, TSP As we have seen, the C MMI is a measure of ca pability at the orga nizationa Vcorporatc level Wall~ Humphn: and the Software Engtnceri ng Institute have also deA ned coord inated proce<s models a t the learn levcl.nd at
CASE STUDY: SOFTWARE QUAlITY ASSURANCE PlAN FOR
the indiv.dual engineer level. These are called the Tea .. Softwa,. Process (TSP) and the PtrSO,,,t/ SoftlDa" Procn, (PSP), respectivciy. The PSP, TSP, and CMMI frameworks fonn a relatively coordinated set of capabilities and procedures at the indiVidual, team, and organizational levels, respectively. We will describe the TSP in the project management chapters and the PSP in the implementation chapters.
5.8.7 Relationship of the CMMI to Agile Methods CMMI appears to be almost contradictory to agility because it is process heavy . However, CMMI and agility are at different levels. CMMI is used to assess the capability of organizations as a whole to produce good applications. Those that use agi le methods are just as interested in such an assessment as those that are not, and it is reasonable to assume that CMMI will evolve to assess devc10pment organizations of all kinds.
5.9 CASE StUDY: SOFTWARE QUALITY ASSURANCE PLAN FOR ENCOUNTER The Software Quality Assurance Plan (SQAP ) for Encounter is based on IEEE Sid 730-2002 Slandard for Soflware Qua[ilyAs,uran« Plan,. The table of contents was outlined in Figures 5.8 and 5.9.
ENCOUNTER SOFTWARE QUALITY ASSURANCE PLAN
Th aulbor i, indebled
bi, ,'udenls for inspeclion, of Ibi, do"" ..enl and for Iheir improv""o.,, 10 Ih, original. 10
Note to the Student, Organizations usually have a standard quality assurance procedure. The SQAP for each project relics on this and provides projectspecific QA plans. We will effectively combine two such documents here.
The table o f contents of this SQAP follows that of IEEE standard 730·2002 in most esse ntial s.
Revision History
This assumes the existence of a method whereby revision numbers of documents are assigned.
Version I 1.0.0 E. Braude, created 1/ 17/99 1. 1.0 R. Bostwick, reviewed 5/ 30/99, added substance to Sections 7 through cnd I . I . I E. Braude, integra ted and revised contents
5/ 31 /99 Approvals,
Title
Engineering Manager
Version 2
~ :1.1-0
2.0.0 E. Braude, significant edits of Section 5.2 1/ 18/04
6115104
20. 1 E. Braude, edits 1/23/04 2. 1.0 E. Braude, edits in many sections rc pond ing to reviews by student 6/ 17/04
QAManager
£WiWv..
6111104
Project Manager
a. !J'Cuil1
617104
Author
£"1KauiU
611104
Table of Co ntents I . Purpose 2. Rcferen cd Do lIments
103
10.
CHAPTER 5
3
QUAUTY IN THE SOFTWARE PROCfSS
M~l1 all~ m e nt
1
fRanl 2oltion
2 Ta
3. Re,ponsibiliticS 3.4 QA Estimated Rc,ources
Typically, mD't of the conten t of a SQAP are common to all of the o rganization's proJCClt. EngOlleers would need SImply to taIlor pans 10 the projec t in question.
4. Documenlation 4 . I Purpose
4.2 Minimum documentation requirements 4.3 O ther 5 . Standards 5. 1 Purpo e 5.2 Conte nt
6 . Reviews
1. purpose This docu me nt des ribes the means by wh,ch the Encounter project will produce and maintain a h,gh. quality product. It is also tnte nded to describe mech · anisms for improving the quality assurance process itse lf. "Q uality" is d~fi n ed as the degree to which the applicatio n satisfies its requ ireme nts.
6 . 1 Purpose 6 .2 Minimum req uirem e nts
6.3 O ther reviews and audits 7 . Test 7. 1 7 .2 7 .3 7.4
Unit Test Integration T est System Test User Acceptance Test
There is no separate "scope" s~tion in the IEEE standard, so we have insened it bere. "Scope" contains vital information sucb as whether this document appli~ to the first rdease only or to maintenance as well.
8. Pro blem Re porting and Corrective Adion
The scope of this document compnses the artifacts of all releases.
9 . T ools, Tec hniques, and Methodo logy
2. Referenced Documents
10. Media Control
See Section 4.2.
I I . Supplier Control
12. Reco rds Collection, Maintenance, and Retention
3. Management
13. Training
3.1 Organization
14. Risk Management
15. Glossary
16. Sqap C hange Procedure and History Appendix A - Metric History for this Project Appendix B - Problem Reporting Form Appendix C - Change Reporting Form Appendix D - Inspection Meeting Report Form Appendix E - Document Baselining Checklist
State the rol~ that are involved in ensurina quality. Actual nam~ are provided in Section 3.3. The process described in tbis case is a ..... of internal and exte"",1 quality as,unnce.
This section assumes the description of the organizational Slructur<: of the Encounter project in 4.2 of th~ SPMP. This document will r<:fer to the quality work of d~velopers as "internal : In addition, for the Arst three iterations of Encounter, a quality assurance enaine"r
CASE STUDY; SOFTWARE QUAUTY ASSURANCE PLAN FOR ENCOUNTER
will be designated who will be responsible to the manager of QA. The QA leader will take the lead for project-wide quality Issues QA tasks will be referred to 3S "" temal :
• Carryi ng out the reviews and inspections spcciAed rn Section 6 of this document
3.2 Tasks
3.3 Responsibilities
Summarize what needs to be done.
External QA tasks shall include, for all iterations: " Maintaining this document • Documenting the quality of the evolving product and associated artifacts • Managing external review meetings
• Ensunng that veriAcation takes place and logging verification • Preparing for and attending all inspections • Post·unit testing Documentation
as
per the Software T cst
• Engaging in activities designed to improve the quality assurance process itself • Keeping the project leader apprised of QA prog· ress through weekJy written reports " Carrying o ut the audits speciAed in Section 6 of this document • Providing the development team with feedback from QA's activities • Assign defect repair to softwa re engineers • Identifying methods and tools for collecting and maintaining melrics
Internal QA tasks sha ll include, for all iterations: • Each team member responsrble for the quality of hr~ or her work , as deRned rn this document • Marntaining an issue datahase • Collec trng the metrics desill natc by thr~ and other project documents
• Unit lesting as per eCI manual 023 .2
State what roles will fulfill what job functions .
It is the quality assurance leader's responsibility to see to it that the tasks in Section 3.2 are performed and to ensure that the prescri ptron s in this document are followed , including scheduling the reviews spec· ified. For the first three iteratio ns, the QA leader will perfo rm all of the quality control (QC) functions . For subsequent iteratio ns , the QC team , appointed by the QA department manager, will take over this function . The quality leade r and the QC team are responsible for all non ·unit testing. (See Part VII of the book for background informatron on these types of tests). A description of the QC team will be supplied. The project leader will be respo nsible fo r ensuring that inspections and unit tests are per-
formed . The schedules are to be placed in the SPMP.
No names are assigned to these roles here because they are in the Software Project Management Plan, which is their proper place. Duplicating a name here would require us to update more than one document when there are changes. The leaders de ignated in the SPMP are re o spo nsible for the quality of th eir respective areas (requirements, design, etc .). They shall e nsure that the designated metrics are collec ted and that the quality self·asse sments as outlined in cction 5.2 of thi document Me onducted. Each member of the Encounter development team is responsrble for quality as spc iAed In ce tr o n 4.5 of the company document ' ual it resp n~ibrlr · tres of engi neers at I." Thrs in ludes teSlIng rndividual method, and ornbrnatr o ns of methods in a las. ("unrt testinR') .
105
106
CHAPTER 5
QUAUTY IN THE SOFTWARE PROCESS
• oftwa rc Vc ri flcallon and Val idallon Plan (SVVP)
3.4 QA Estimated Resources 11,,, e,nmated n ',our es reqUired fo r ter are as fo llows, •
A un Encoun ·
ne engineer working halftime for the Arst tI",d of the proje t
• One engi neer work inS fu ll time for the ccond th ird of the project • One engi nter work ing full time for the last third of the project • An additional engi neer working half tllne for the last third of the prOJec t
VenAc.tlo n and Validation Report ( VVR) (No/t Th " book does nOt cover the VVR )
• oftwarc
• Maintenance Plan In addit io n to the<e documents, the Java
4.3 Other - i ntenti onally left blank
4. Documentation 4.1 Purpose The purpose of this sectio n is to ident ify the docu · mentallon that wi ll be used to ensure quality.
4.2 Minimum Documentation Requirements
This ection lists all of the project documen· tation , since the documentation is a major
factor ensuring the quality of the product. Note that the User's Manual is excluded, it is a deliverable rather than a project document . The following documents wi ll be produced , • Software Quality Assurance Plan (SQAP; this document) • Software Configuration Management Plan (SCMP) • Software Project Managcment Plan (SPMP) • Sof·tware Requirement Specifications (SRS) • Sohware Design Document (SDD ) • Software T est Documentation and the tcst doeu· ment that It refers to (STD )
It is customary to make a comment like this SO that no one wastes time looking for what may be missi ng.
5. Standards, Practices, Conventions, and Metrics 5.1 Purpose Th is sec tion describes the standards, practices , con· ventio ns, and metrics to be used for the Encounter project. These are intendcd not only to ensure qua lity of the Encounter product but also to obtalll qua ntitative metric data on the SQA process itself. These data arc to be used to help el evate the CM 11 level of Caming Consolidated Industries (CC I) fr.om level 2 to level 3.
5.2 Content Describe the standards, practices, con~n tions, and metrics to be used. Organintionwide quality goals can be supplied here or in a separate appendix . Thc contents of this S(Ction should be a speCific as possible, For example , sta tcments such as ' quality should be a< hlllh as po<slblc· should be avoided.
CII.SE STUDY: SOFTWARE QUAUTY ASSURANCE PLAN FOR ENCOUN IEft
Standards:
An oj EjjrcliJ}f Comm"HlcalioHby Justin Zobel (Springer
The IEEE documentation standards as of July I , 2004, w,th appropnate modiAcations. are to be u ed for all documentation . The standards for Jav. ndoc commentlOg will be fol!owed as found at http]/ j."• .sun.com!j2 e!javadoclwriti ngdoccommentsl mdex.hmll and http}/java.sun .comlj2se!javadod writingapi pecslindex .hrm L Documentation stan. dards or templates developed by the company may supersede these at the discretion of management. Uni fled Modeling Language standards, as spec. iAed in ... shall be used in th is project . Refer to the Co nve nt ions section below for additional standards.
Practices: I . Because delaying qualiry is expensive, GCI Inc .
strong ly precepts thought. "internal
encourages engineers to apply quality while working, rather than as an after· This is referred to in the company as qualiry." It includes all unit testing.
2. GCI lnc.'s policy is that the QA department provides independent, external testing. The QA department at GCI also has a role in educat ing engineers in the practice of internal quality and working with project mangers to ensure that it takes place . 3. All project artifacts are inspected and are made easily avail.ble to the tea m o nce released by the developer. 4. All project artifacts are placed under conflgura .
tion management, where the co ntents can be ~en by anyone in the team at any time ( ee the Software ConAguration Management Plan for details). 5. The development process i< to be reviewed at least once for improvement, and the written results forwarded to the software engineering laboratory (see Section 6.2. 10).
Verlag. TI,e codi ng conventions as lound at http}/java. sU I1 .comldocslcodeconvlhtmVCodeConvenlions.doc .html will be followed .
Metrics: This section is liable 10 be extensive. The numbers used here would be based on histori· cal data obtained from the group that is devel· oping Encounter. GCI's li st of standard metrics, found at http:// xxx, sho uld be gathered as speCified there. The following includes some of them . For every process and document, metrics shall include the following , I . Time spe nt by individual s on preparation and .
revIew .
2. Number of defects per unit (e .g .. lines of code), classified per Section 8 of this document. 3. Quality se lf·assess me nt 01 the QA process and performance on a sca le of 1 through 10, ap· proximately in a bell·shaped distribution; se ll· assessment scores wi II not be used fo r the evaluation of personnel by manage ment; failure to produce them, however. may negativel y af· fect the evaluatio n of an engi neer by manage· ment, however.
We would specify all metrics to be collected on this project. Possible metrics are described in Chapter 6.
The standard for defect classification is given '" cctio n 8 of this document.
Quality Goals: Conventions: Where fellSiblc , wrlt,ng wnve nt Jon& hauld conform to the suggestions In Wri'IH9 for (omp""r cin,a Tb,
G I quality goa ls for delivered products nre as follows, measured in tenn of defc ts detected within two month< of delivery .
107
108
CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS
•
known " rili al" or \ enous" defects rcmalll III ,lI\
delivered artifa t
In additIon . • Reql1lT1:mcnts. No morc than one "medium ," and
no more than three "trivIal " defectIve detailed requirements per 100 • Design : No mo re than o ne "mcdlllm" defect pcr nve diagrams. A "dtagram" is any Agure that uses about a page of easily legible parts
one responSIble Lu,tom 'r representative. They w,1I be led by the requtrement, leader, who WIll deter. mine their frequency and scope
6.2.1A software Requirements Inspections After they have been revIewed, all requ irement, will be inspe ted in ac o rdance with GCI , Inc 's document G I 345678 "Inspections and Review procedures at GCI." Requtrements sections must be completed and sig ned within a week of beginning the desig n
• P eudocodo No more than two "medium" defects per 1000 lines pseudocode is described
In
C hapter 19.
6.2.2 Architecture Design Reviews
The data from thIS project are to be reported as Appendix 1 to this document.
Th,s I a review of alternative architectures with the entire team . The review will be led by the design leader in accordance with GCI 345678 on a freque ncy to be determined . The team will provide feedback , which will be reAected in the final design.
6. Reviews and Audits
6.2.2A Architecture Design Inspections
• Code: No more than two "medium" defects per KLoC ( 1000 lines of non ·commented code)
6.1 Purpose The purpose of reviews and audits is to continua lly focus engineers' attention on the quality of the applicatton as it develops. Rroi,ws effect this in a scheduled and thorough manner. Audits do so on the basis of random sampling with short notice.
6.2 Minimum Requirements Large projects require the full set of reviews and audit listed here . Student teams should tty to conduct reviews and inspections of requirements and design , as well as postmortem reviews. "Reviews· are discussions of proposed artifacts. "Inspections· are conducted on completed artifacts presented to the team . The SQAP d~s not call out inspections as a heading, so the author has inserted section "A~s for this purpose.
After they have been reviewed, architectures will be inspected in accordance with GCI, Inc.'s inspectIon process manual , document GCI 345678. Architec· ture sections must be completed and signed off within a week of beginning detailed design.
6.2.3 Detailed Design Reviews These are reviews of all proposed detailed designs In the prese nce of the entire development team . They will be led by the design leader, who will determine their frequency and scope, but at least one design review will be conducted per iteration . If possible, the architecture will be decomposed into detailed designs of its parts, and these will undergo separate detailed deSIgn reviews.
6.2.3A Detailed Design Inspections After they have been reviewed, detailed desIgns will be inspected in accordance with GCI, Inc.'s inspection process manual , document GCI 345678. DetaIled design sections musl be completed and _igned off within a week of beginning implementation.
6.2.1 Software Requirements Reviews
6.2.3 Test Plan Reviews
These are walk -throughs of all proposed require ments in the presence of the entire team and at least
The e are reviews of all proposed test plans in the presence of the entire team . They will be led b Ihe
CASE STUDY: SOFTWARE QUALITY ASSURANCE PlAN FOR ENCOUNTER
QA l..ader, who WIll detemlin~ their f~quency and scope. The t t plan will be de o mpo cd into pans, and these will undergo separate reviews.
exceptions arc at the discretion of the VP for Engi . neering . It is the project leader's re ponsibility to schedule this review and provide the appropriate documentatio n and software demonstrations.
6.2.3A Test Plan Inspections Aft~r the>' have been reviewed, test plans will be in peeted in accordance with CO , Inc.'s inspection process ma nual , document CCI 345678. Test pl.n sections must be completed and sig ned off within a week of beginning testing .
6.2.4 Verification and validation Plan Review V&V is to be conducted by an independent team (i.e., not associated with QA), fo llowing the process d~tailed in CO 345678. The QA e ngineer will review the SVV plan prior to its execution .
6.2.5 Functional Audits The QA leader shall be responsible fo r auditing the product relative to the SRS. The audit will follow company guideli nes in ' CO 8902: Rel ease Proc~dur~s. "
6.2.9 SCMP Review The QA leader shall review the status of configura. tion management o n a monthly basis in a manner indepe ndent of the procedures speCified in the SCMP.
6.2.10 post-Implementation Review As with all GCI projects, the Encou nter team shall co nduct post· implementation reviews to provide data for future projects. These will include reviews of the project phase just completed and reviews of the QA process itself. The QA team o r QA leader shall fi le a process improveme nt report fo r every phase , and for the QA process itself. with the manager of the software engi neering laboratory.
6.3 Other Reviews and Audits -intentionally left blank
6.2.6 Physical Audits Prior to each delivery , the QA leader is responsible for checking that the physical software and its documentation designated for delivery are complete and the corr~ct versio n.
6.2.7 In-Process Audits
7. Test This section describes how testing is to be managed. The text here should refer to, but not duplicate. the software test documentation.
Proj~ct personnel should expect rando m audits of
their work. These will consi st of visits to the work si~ by individuals or teams designated by division managem~nt . A day's no tice shall usually be given for all visits, but audits without notice shall Ulke place as well. The subject of these audits will be the curre nt work of teams and individuals that has been alloca ted to the project All project artifacts wi ll be made freely available to all leam members and auditors at all times. It w111 be organized in a clear, standard fash Ion, so that audits will be po<siblc wilhout any nOltCe.
6.2,8 Managerial Review The Encoun~r prOJe t shall he rcvlewed by the VP for Enl!IOeenng during the first week of every month .
The responsibi lities for testing were described in cction 3.3. Refer to the Software Test Docume n · tation for detail s o n testing Encounter.
8. Problem Reporting and Corrective Action This section explains how defects come to be recognized, described, and repaired. They do not follow the details of IEEE standards. The reader is refelled to the IEEE standards, as wdl as 10 Humphrey [H) for additional defect $c:verity and IYpe lassl/lcalions.
109
110
CHAPTER 5
QUAUTY IN THE SOFtWARE PROCESS
The team will us,," the lJugzilla defect manage . mcnt system .
The code nnd ps,udocod, defects tyP"S arc a~ [oilows, • Syntax
Instead of describing 8ugzllla, we will de· scribe a hypothetical manual ddect system for the sake of clarity, even though a soft· ware-based system is common practice and far preferable. Such sysu,ms also allow for a dialog thread involving, typically, testers and devciopers.
• Logic • Data (I e ., allows a wrong variable value) • Insecure (allows unacceptable security breach) The workflow of a defect status is: I . Open: defect found by tester
The Problem Reporting Form to be usrd by the Encounter development team in response to a software problem report generated by QA is shown in Appendix B. To use this form , engineers should retrieve the form from www .a.b .c .d . The defect number will appear automatically , and the site will ensure that the appropriate fie lds are fi lled in. The values for s"miry arc as follows ,
• Crilieal, Causes the application to crash with sig· nincant frequency
• S,rious, Causes at least o ne documented require· ment to be unmet
• T rioial , Could be allowed to stand ad infin itum without impeding the user from exercising a required feature • Mtdium : Is neither serious nor trivial
The documentation defect types are as follows : • Incorrect
• Missing material
• Unclear • Ambiguous • Incomplete • Redundant (within or between documents) • Contradictory • Obsolete
2. Assigned: defect assigned to an engineer 3. Corrected: defect nxed by engi neer 4 . Closed : defect closed by tester
If the defect is reopened, the defect will move from the Corrected state to an Open state. The QA leader will create and the QA team will maintain a database of problem reports that describe the defiCiencies, discrepancies, and anomalies for Encounter. They will ensure that defects are conSiste ntly recorded on this form and that they are routed and repaired in a consistent manner. Problem reports shall be routed in accordance with the SCMP. Full traceability as to their effects and status shall be maintained, including after they are repaired. After iteration three, when a problem is encountered, the QA manager will distribute the problem report to the members of the Change Control Board (CCB). For the first three releases, the configuration specialist will carry out the functions of the QA team, and the projcct leader will perform all of the CCB functions in accordance with the SPMP. The CCB evaluates the problem report and then assigns a priority to the report of either j",,,,,dinl,, 10 b, do"" or oplio"nl. The problem report is then assigned by the CCB to the Encounter devdopment team , QA, or CM for resolution. The CCB determines the schedule for problem report .(solu· tion based on problem report priority and analysis report results . After the problem in the report is corrccted, the QA team review thc results .nd the QA manager reports on the review to the cca If nccessary, the process i repeated .
CASE STUDY. SOFTWARE QUAlITY ASSURANCE PLAN FOR ENCOUPlTER
9. Tools, Techniques, and Methodologies QA re hnlquc~ Include the aud,ting of standards, rt:qu iremen~ rra ing, de" gn venncatlon . software In'l'«l1ons, and the verin atl on 01 1 mlal methods. The QA tool, o n.i t of software verincation progTams. checklIsts, med,a labels, and ac eptance stamp . Checklo ts ",ill be obtai ned fTO m the compan 's software engoneering laboratory, and tailo red for En ounter. These arc augmented by NASA checklists at [9). C heckl ists include the following : • Review checklist are used at formal meetings, for document reviews, and for inspectio ns. • Checklists will be used for verifying the qualIty of the following activitie and documents· PrelimI nary Design Review , Critical Design Review , Test Readiness ReView, Functional ConAgurati on Audit, Physical ConRguration Audit , SRS, SDD , SPMP, and Software Development Folders. • Separate checkli sts and form arc used for software audit purposes.
This book contains checklists throughout. These checklists involve meeting and inspec t10n procedures, for example. T cams often begin with published checkli ts, and augment thelil according to additional spcciAc needs of thelf projects. Additional SQA tools, techn iq ues. and meth odologies for config uratio n manage ment arc described on the SPMP.
10. Media Control Describe the meaM by which d,sks, tapes, and so on will be managed TI,e SQA team verifies that the ,,,ftware mcdi a are bwlt and co nfigured per the CM P and th3t authorized chanRes have hee n ," ~ ra ll ed and te,tcd In
addillon, the QA team verofles that the so ftware media arc duplocated using only the procedures identified in the CMP. SQA acceptance Is indicated by an SQA stamp on the media label. The SQA audIt report for media co ntrol are intended as fllrther evi dence that QA procedures have been foll owed All backup medIa WIll be stored olfsite as described in the SCMP.
11. Supplier Control
This section concerns re lationships with suppliers 01 software and hardware. h describes how and by whom these relationships are to be handled. The SQA team verifies all commerCIal thirdparty products provided by the suppliers during incoming inspection by reviewing the packing slip that identify the products and theor version numbers. The QA manager is responsible for en uring that all thord party software and hardware meets the expected reqllirements. TI,e products WIll be va lida ted by the QA manager through installarion and accepta nce tests. A QA representative will be responsible for te tlng all new versions_ He will also be responsible for the relationship wit h the external vendor.
12. Records Collection, Maintenance, and Retention
This section describes how phy ~ical records will be handled and who will be responsible for them . Include disk ,Ies that arc not under conAguration control. Th e SQA record< colle ted and ar hIved ,hall on lude the fo ll ow on g, • T •• k reports • AnOll1aly report, not handl ed 1» l t he rCB"lar problem. rcrortinli oncehan l 111
111
CASE STUDY: SOFlWARE QUALITY ASSURANCE PLAN FOR ENCOUNTER
Appendix A: Metric History for This Project preparation Time
Defects Product
SCMP
Defect Unit
Section
Expected Rate
Actual Rate
Expected Time
Review Time Expected Time
Actual Time
Actual Time
-t-
1 minor defect per section
SPMP
Section
1 minor defect per section
SQAP
Section
1 minor defect per section
SRS
Section
1 minor defect per section
SOD
Section
1 minor defect per section
SIP
Section
1 minor defect
+
per section SWP
Section
1 minor defect per section
SWR
Section
1 minor defect per section
Requirements
D-Requirement
1 medium and
3 trivial defects per 100
Pseudocode
Diagram
1 minor defect per 5
KLOC
2 medium
defects COde
KLOC
2 medium
defects
Code Defects A frcc online tool ca lled "Refa to rl t" fTom hup j/www re f. tont. om estimate LOC. N 1..0 • and LO .
s hallll~cd
b , the Projc t 1"nol:cl to
113
112
CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS
•
lem a",. including rc:conlmcndl1tion" 10 rl"SpOnSI ·
ble partlc, o
Logbook of QA" tivl tics
o
Audit report
o
igl1ed-off checklist< from reviews Jnd audits
o
Mlllutes of inspections
o
Metrics for the QA process itself
Besides verifying the archive procedure speciRed in the S MP, QA shall separately archive its OW" records at least once a week . These records arc retained throughout the operation and maintenance phase.
13. Training
record,n/! mctfl es QA Will also conduct monthly three-hour cla>'es for development team members 10 keep them Informed of qua lity goa ls, lools, and tec hl1lque< T tJm members ca n waive atlendance at the,c meellnt;( by sco flng perfectly on a muiliple. hOlce qUIz available al GCllmomhly/SQAlquiz. Ea h team member is reqUIred to attend a three -hour course on wntll18 slyies and conventions conducted by QA .
14. Risk Management QA tea," members are encouraged to Identify risks as early as pOSSible and direct them to the project leader The procedures for risk management are speCified in Sectio n 5.4 of the SPMP.
15. Glossary • •
•
•
Includes SQA training speciRc to this project.
16. SQAP Change Procedure and History The SQA o rganization will conduct an initial four-hour orientation on quality for the development team This will include a pre entation o n the metrics to be used and a workshop on how to use tools for
•
•
•
(The material in the following appendices was supplied by Jane Dyson .)
114
CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS
Appendix B: Problem Reporting Form lOde lllumhcr:_ _ _ _ _ _ _ _ __ 2 Pro po«d by · _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ 3. Documcnts I scctions affcc ted : _ _ _ _ _ _ _ _ _ _ _ _ __ 4 . Documcnt dcfc t ty pe. 3.
Mis ing matcrial
b.
L1nclear
c
Ambiguous
d.
Incompl etc
e
Redundant (within or between documents)
f.
Contradicto ry
g.
O bsolete Source code affec ted (fo r source code defec ts):
5. Packa ge(s) _ _ _ _ _ __ 6 . 0.ss(es)'_ _ __ _ _ __ _ 7 . Met hod(s)_ __ _ _ _ __
8. Severi ty :
a.
High
b.
Med ium
c.
Low
9 . Code defect type : a.
Syntax
b.
Logic
c.
Data (i.e., allows a wrong variable value)
d.
Insecure (allows unacceptable security breach)
CASE STUDY: SOFlWARE QUALITY ASSURANCE PLAN FOR ENCOUmER
10. Phase mjected (earl,est phase with the defect). a.
Requirements
b.
Architecture
c.
DetaIled design
d
Code
e.
Implementatio n
II . Detailed descriptio n: _ _ _ _ _ _ _ _ _ _ __
12. Priori ty:
a.
___ Immediate
b.
___ Intermediate
c
___ Deferred
13. Reso lut ion : _ __ 14. Status:
a.
___ Closcd
b.
___ Opc n
Sign -off: 15. Description and plan inspected: _ _ __ 16_ Resolution code and rest plan inspected: _ _ __ 17. Change approved for incorporation , _ _ _ _ __
Appendix C: Change Reporting Form I . Change number: _ __
2. Proposed by: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ 3. Documenlslsections affected: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ __ 4. Reaso n for change or addition : •
•
•
5. Enhancenlent:_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __
•
•
•
6. Decails: •
•
•
Signatures: Descroption and plan inspected (QA tcam leader) _ _ __ Resolution code and test plan inspected (QA team leader) _ __ _ hang" approved for incorpor.Jtlo n (Team leader) _ __
115
116
CHAPTER 5 QUAUTY IN THE SOFlWARE PROCESS
Appendix 0 : Inspection Meeting Report Form A ompl cl cd I", pc li on " kC lin g Report must be ,.,el uded at the end of each document. Only the latest report i rcqlllrcd . Inspection Meeting Report PROJECT: DATE:
STARTING TIME :
ENDING TIME:
PRODUCED BY: TYPE OF INSPECTION:
0
INITIAL INSPECTION
0
REWORK INSPECTION
DOCUMENT NUMBER AND REVISION : BRIEF DESCRIPTION: APPRAISAL OF THE WORK UNIT:
0
InspectIon not completed (co ntinuatio n sc heduled for
0
No further inspection required
0
Minor revisions required
0
Major revisions req uired
)
MATERIALS PRODUCED
0
Issucs list (Not Au thor's Responsibility)
0
Issues list for Au thor
0
Traceabi lity Issues)
participant
Role(s) Author Moderator Recorder Inspector Inspector Inspector Inspector Inspector
Org.fDept.
CASE STUDY: SOFTWARE QUAUTY ASSURANCE PLAN FOR ENCOUNTER
Inspection Meeting Report Issues Ust ISSUES, NOT FOR AUTHOR Issue
Issue must be resolved prior to Document Baseline? YIN
Response
Assigned To
1.
2. etc.
ISSUES FOR AUTHOR Issue
Re~onse
1.
2. etc.
Appendix E: Document Baselining Checklist Document Baselining Checklist Item
0
Inspection Meeting Report completed and all issues resolved .
0
Revised document sent out for consensus after Inspection.
0
All comments accepted via Word's Track Changes. Track changes feature then turned off.
0
Check for clean requ irements traceability completed. (SRS only)
0
All high-level requirements have been allocated to detailed requirements. (SRS only)
0
Final traceability report generated and stored. (SRS only)
Comment I Initials
117
118
CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS
5.10 SUMMARY Quaht practi es arc IIllcgrJ ted throughout Ihe devciopment process Thcy 'tart wIth planning, when , pc If, documents u h a the Sohware Quality A\Surance PI.n (SQAP) and the Software VenAcalion and ValIdatIon Plan (SVVP ) are produced , describing the qua lity policie" procedures. and practIces to be Implemented. The QAP is the m.,t er qu. hty plan and specifies the people and o rganizati o n, rcspon,ible for quality. the proJe t documentallon to be produ cd , the metric, to be co llec ted , the procedures to be practIced. and the techniques to be IInplement ed . It IS an impo rtant document as it sets the expectatIons regarding quality early in a project and helps guide its implementation . In pections are an important qllality technique that involve peer reVlcw of all project artIfacts including documents, test plans, and code . Their goa l is to identi fy defects as close to their mtroduction as possible so that they can be repaired quickly. Co nsiderable research has shown that the cost to repair a defect increase dramatically the longer It i all owed to per;ist in the software. Quality reviews and audits by a quality assurance (QA) orga nization are benencial. An external QA group IS mdependent of the people developing the softwa re and o ther artifacts and can objectIvely assess quality. Again , a sess ing quality and addressing it throughout the devel o pm ent process helps identify problems as earl y as possible. Problems arc identi fied by team members throug hout the development process and are submitted as d4rcls. A scrcelll ng process is implemented to ensure that the defects are accurate and va ltd. A classilkation system is employed to understand the severi ty of each defect and priority fo r its repair. In addi1ion, maintaining metrics such as number of defects, time to repair, and so o n is useful for comparison with other projects and in making estimates for future projects. Improvi ng the effective ness 01 the overall software process is accomplished throug h implementation 01 a meta · process. Th is inc ludes the co ll ection of pl ocess merrics, and meetings at the end of projects phases to analyze the metrics. In additIon , lesso ns· learned meetings are co nducted at the end of a project to analyze project successes and identify areas of improve ment. The Software Engi neeri ng Institute has deve loped a comprehensive meta·process for assessi ng an o rganization's overa ll capabi lity . The process is ca lled the Capabil ity MatUrity Model IntegratIon (CMMI), and it de Rnes several leve ls of ca pabil ity and maturity an organization can measure itself against. The levds range from the lowest, Levell Initial , to the hi ghest, Levell Optimizing . At the Initial level an organization can produce so.ftware but has no recognized process. At the Optimizing leve l, an organization implements a meta · process for process improvement
5.11 EXERCISES 1. In a paragraph , explain why it is important to document quality procedures at the beginning of a
projec t rather than later on. 2. The number of people attending an inspection can have a direct impact o n the effectiveness of the review. list the di advantages of having either too few or too many people attend an mspect ion. 3. Give two advantages and two disadvantages to using standards for documentatio n of the various software phases. 4. Why is it generally a good idea to. have a cross· functional group be parI of an inspection team What type of review (that is, during what development phase) might It not be a good ide.
BIBUOGRAPHY
5. Your instructor will pair up student project teams. Conduct an inspection of an ani fact produced by the other team, such as a SCMP or SPMP. Use an inspection checklist, such as one found in [3]. to guide your in pection. 6. Give an example of a delecr that might be clossiAed with a hi gh severity but a low priority. Be spcciAc with your answer. 7. (a) In your Own words, describe each of the CMMI levels.
(b) How does applying the CMMI levels promote organizationaJ quality7 Explain this paragraph or two, using your own words .
•
In
a
BIBLIOGRAPHY t. Figan, M. "Design and Cod~ Inspections 10 Reduce Erro~ 10 Progr.sm Devdopmrnt " flL\.1 SYJ/.nII) J01Inwi. Vol IS, 0 3, 1976, pp. 182-21 1. 2. Wiegers, Kilrl. "-Improvlng QUJ hty lluough Soft ..... a~ Inspections: Procm 1.. ~C1, 1995. http llww\Ol' procc5SImP3ct c.omlanlclesl inspects hIm! [accessed November 15. 2009}. 3. Wiegers. Karl, "Goodies for Peer Revie.....s... PrOC'rf$ Impacl, 1utp 11W\tt"'W prOCCSSUT\polCl com/pr....,good,,:, [olccosed ()'.'cmw 15 2009) .. Gchani , Naronn, and A. McUunck, "SojtWtJr, SptCIji. af/(7PI Ttd""qulS. " InternatIonal Computer Science ~nes, Addlwn -Wesley. 1985 5 Cllb, T., and D Cr.aham. " Softuu~rt 'nJPtrIlO"." Addl~n · Wes ley, 1993 6. Bugzil1~ . hnp:llbugzi lla orglaOOu t html [accessed December 10, 2009 ] 7. upability Maturity Model )!': lotegr.nion (a 'MIS:-" J, Version I I, hup Jlwww !!oC' emu cdulpubldocumenl oz·reportv pdfl 02 ln0I2 .pdf [,cc..sed December 8. 2009 J. 8, Humphrey. Watts 5., -A D'SClpli"( for 5
119
Software Configuration Management
•
What is the purpose of software configuration management?
•
What activities does it consist of?
•
How do you plan for configuration
The Solrware
management?
Development
Ufecycle
•
What tools are available to support it?
•
How is configuration management handled in large projects. in praclice?
Figure 6.1 The context and learning goals for this chapter
Many artifacts are produced in the course of developing a software product, uch as specIfications (e.g., requirements, design), source and executable code, test plans ond test data, user documentation, and supporting software (e.g., compilers, editors) Each undergoes numerous reVISions, and keepIng tTack of the vanous versions needs to be managed in a reliable and con istent manner. Soffware Configuralion 1\ InnagC!lloll (SCM) IS the process of identifying, tTacking, and storing all the artIfacts on a project. In the context of SCM, each 01 these artifacts is referred to as a ConAguration item (0 ).
SCM ACIIVmES
1 conrnbut to overall software quality in that it supportS a reliable way to control a project's arti~ ts For c ample, the (]vI proces ensure that the proper source mes are included when building the softw,re, tern and that the orrcct project documentatIon IS retrieved when required . 1any , tlvitie contribute to configura tIo n management . including identiAcalton of artifacts as configuration items, storage of artifucts In a repository, managing changes to artifacts, tracking and reporting these changes, auditing the CM proces to ensure it's being implemented correctly , and managing software builds and relea cs. Many of these activitIes arc labor intensive, and SCM systems help automate the process.
6.1 SOFTWARE CONFIGURATION MANAGEMENT GOALS We first define the overall goal of software configuratIon management: b.,,/i"t .-Itly, outrwrilr .-Irfy. 'tumio", Q.d disasltr rtCoorry. Baseli n" safety is a process of accepting new or changed Cis fo r Ihe current version of the developing product (the baseline), and safely storing them in a common repository so that they ca n be retrieved when needed later in a proJect. Overwrite salety means that team members can safely work on Cis simu llancously , and changes can be applied so they do not overwrite each other. Overwrite safery is needed when the follOWing kInd of sequence occurs.
1. A. Engineer Alan works on a copy of
CI X from the common reposi tory.
B. Brenda simultaneously works on an identica l copy of X.
2. Alan make changes to X and puts the moddled X back in the repository.
3. Brenda also makes changes to X and wants to replace the version of X in the com mo n repository WIth the •
new versIOn .
Overwrite safery assures that Brenda's changes don't si mpl y replace Alan's, bUI Instead are added correctly to Alan's. Reversion occurs when a team needs to revert to an earlier version of a CI. This IS typically reqUired when mistakes transition a project to a bad state-for exa mple, when it is found that a new version of a CI turns ou( to cau.se so many problems that it is preferable to revert to a prevlou verSIon . ReversIon requIres knowing wh,ch version of each C1 makes up a previous version of the project Disaster recovery is a stronger form of rcversion-it is thc process of retainIng oldcr versions of an applicatIon for f\Jture use in case a disaster wipes out a newer version . These four goals, fundamental for configuratio n manage me nt , arc summari zed in F,gure .2.
6.2 SCM ACTIVITIES There are several SCM acttvitie and best pracltce th at arc Impl emented to successfully meet the gal. JUSt descnbed They are maInly the following . I . ConfIguration Idenltficalton .
2. Saseltne control 3 Chan!!e control 4. Version contm/
121
' 22
CHAPTER 6
SOFTWARE CONFtGURA liON MANAGEMENT
• B.seline S.fety n
Is arc .fely storcd In a repository and can he retrieved when neussary
• Overwrite Safcty En ure that engineer, hanges to the 'arne
I arc applied corre tiy
• Reversion Ensure ability to revert
10
earlier version .
• Disaster Recovery Retain backup copy In case of disaster Figure 6.2 Major goals of configuration management
5 Configuration auditing. 6 . ConRguralion tatus reporting. 7 . Rele.se management and delivery. Each of thcse IS desCribed in the folloWing ections.
6.2.1 Configuration Identification The first step in configuration mana gement is to ident ify a project's artifacts , o r configuration items (CIl, that are to be controll ed for the proJect. As deSCribed in the introduction , candi date C is include source and object code, project speCifications, user documentation, te t plans and data, and supporting softwarc such as compilers , editors, and so on . Any artifact that wi ll undergo modification or need to be rerrieved at some time aher its creat ion is a candidate for becoming a CI. Individual fi les and documents arc usually C is and so are classes. Individual method may also be C is, but thIS not usually the case . A CI may consist of other Cis. C is are too large when we can't keep track of individua l Items that we need to and we are forced to continually lump them wit h other items. Cis are too small when the size forces us to keep track of ite ms whose history is not relevant enough to record separately . Once selected, a C I is attached with identifying information that stays with it for its lifetime. A unique identifier, name , date, author, revision history , and st.tus are typical pieces of information associated wit h a CI.
6.2.2 Baselines While an artifact uch a source code or a document is under development , it undergoes frequent and ", formal changes. Once It has been formally reviewed and approved, it forms the basis for further development, and subsequent changes come under con tro l of configuration management poli ies. uch an approved artifact is called a bas"i", . IEEE Std 1042 defines a baseline as a " pecificatlon or produ t that ha been formally rcviewrd and agreed to by re ponsi blc management, th.tthereafter serves as the basis for further development , and can be changed on ly through fo rmal change control pro cdure " Baseline, not only rerer to individual C I< but also to collection of Cis .t kc proje t milestones. The are created by recording the ver>lo n nllmber of all the Is at that time and .ppl ins a Version I.belto uniqud identify .t. Milc>lones can occur when ,oft ware is internally rdca<ed to a testing organization, or when a
SCM ACTIVITIES
A baseline is an individual or group of Cis labeled at a key projec1 milestone.
Each version below is a baseline .
.. 0.3.4.2
v 0.4.1
.. 0.3.4.3
/ - CI 's
Update
Removal
Addition
A1 E3
05
figure 6.3 Transitioning from one baseline to the next
version of software IS packaged for release to a customer. For example, a new software version is created and a set of source files and documentation that constitute software release 1.0 are grouped together, given a unIque label such as "version 1.0," and are recorded as belonging to the same baseline. This allows all the fi les constituting software release 1.0 , and their correct versions, to always be correctl y idenllfied and g rouped together. If files belonging to a baseline are added . deleted , or modiAcd , an updated baseline is crea ted with a new version number. Figure 6.3 illustrates ,his concept. Once baseline are created and labeled, they are utilized in a proJect for three primary reasons ( I], I. Reproducibility
2. Traceability 3. Reporti ng These are explained next. I . Reproducibility means that you can reproduce a panicular software version o r set of do umentatio n
when necessary . This i required during product development as well as during ma intenance . For example, software is shipped to customers, and different cu tomer ma y usc different vcr ions In thc meantime, the project tcam is developing a new software release, and as a result is updating many of the Cis u.s ed in previous software releases If a problem is reported by a customer nonn ing an o lder software verSion, because It was saved as a baseline the o lder versio n can by resurrected by the projc t team and used to identify and repaor the source of th e problem . 2. Traceability means that relations hips between various project artifacts can be e tabllShcd and re og · nized. For exa mple, test cases can be ti ed to requirements, and requ irement> to deSIg n. 3 Reporting mea ns that aJ) lhe cleme nt o f ~ ba c line an DC dctennlned and the o ntenlS of various ba e1,ne~ can be com pared Th,s apab,loty ca n be ulllozcd when trying to Identify problem I l l ' n,'''' relea<e of software. Instead of performong a length y debuBgi ng effort , diffcrcn e< In , ource file, bet\ ee n the previous and current o ftware verSIons ca n be analyzed Th,s may be enotlgh to Ide ntl! the wlIrce 01 the problem If no t, knowing exactly what c hange< occurred ca n pOInt to rOlential rOOl callSC', 'reed,ng up the debuggIng effort a nd leading to faslcr and ca
123
124
CHAPTER 6 SOFTWARE CONFIGURATION MANAGEMENT
6.2.3 Change Control onfiS\lratio n items undergo han!!" throughout the course of development and ma intenance:, as a result of error con'cctio n and enhancemenl. Defects d iscovered by rest lnll o rgan Izations and customers ne~esSltatc repair Rel ease of software in lude e nhancements to eXIsting fu nctio nailty or the addition of new hlnctionality . 1'"119' cOl1 lrol, . 1 0 known a co nAguration control , includes a tivltl e. to request. evaluate , approve o r disapprove, and implement these changes to baselined I [2]. The formality of these activitIes varies g reatl y from prOject to project For example, requesting a change ca n ran ge fro m the most informal no d irect oversight for changi ng a C I- to a fo rmal process filling out a (om, or request lI,dic"ung th e I and reason for change, and ha vi ng the request approved by an independent group of people before it ca n be released . Regardl ess of the formality of the process, c hange contro l involves Identification, documentation , analysis , evaluation , approval , verificatio n, impl eme ntatioIl , and release as described next (2).
Identification and documentation The CI in need of change is identiRed, and d ocumentatio n is produced that includes ," fo rmat ion SLtch as the fo ll owi ng: • Name of requester • Description and extent of the change • Reason fo r the chan ge (e .g., defects fixe d ) • Urgency • Amount of time required to complete change • Impac t o n o ther Cis or impact on the system
Analysis and evaluation Once a C I is baselined , pro posed changes arc analyzed and evaluated fo r correctness, as well as the potential ,mpact o n the rest of the system. The leve l of anal ysis depends o r the stage of a project. During ea.rlier stages of development, it is custo mary for a small group of peer develo pers andlor the project manager to review changes. The closer a project gets to a rel ease milesto ne , the more closely proposed changes are scrutiniud, as there is less time to recover if it is incorrect or causes unintended side effects. At this latter stage, the eva luation is often conducted by a change contro l board (CCS), which consists of experlS who are qualined to make these ty pes of decisions. The CCB is rypically compri sed of a cross- fun ctional group that can assess the impact of the proposed change. G roups represe nted include project manage me nt , marketing, QA, and development. Issues to consider during the evaluation are as follows , • Reason for the change (e.g., bug flx , performance improvement , cosmetic) • Number of lines of code chan ged • Complexity • Other sou rce flies affected • Amou nt of independent testing req uired to validate the c hange C hanges are ei ther accepted Into the current release. rejec ted o utrI ght, or deferred to a ubsequent release .
SCM ACTIVITIES
Approval or disapproval Once a change request is evaluated , a decisIon is made to eIther approve or djsa pprove the requesl- Changes that arc technically sound may still be disapproved or deferred. For example, if software IS very close to being rele~sed to a customer, and a proposed change to a source file reqUIres many complex modificatIons, a deC! Ion to defer repair may be in order so as to not destabilize the software base. The change may be scheduled for a h'Nre relea,e .
verification, implementation, and release Once a change is approved and implemented , it must be verified for correctness and released .
6.2.4 Version Control Version control supports the management and storage of Cis as they arc created and modI fied throughou t the software development life cycle. It SllPPOrtS the ability to reproduce the precise sta te of a CI at any point in time. A configuration management SYSlem (al 0 known as a version control system) automates much of this process and provides a repository for SlOIing versioned Cis. It also allows team membe rs to work on artifacts concurrently, Aagging potential conflicts and applying updates correctly. A good version con trol system supports the following capabilities, 1. Repository
2. Checkout/Checkin 3. Branching and mergi ng 4. Builds 5. Version labeling These arc explained in the fo llowi ng sections.
6.2 .4.1 Repository At the heart of a version contro l system is the repository, which is a centralized database that sto res all the artifacts of a project and keeps track of their various versions. Repositories must support the ability to locate any version of any artifact quickly and reliably .
6.2.4.2 Checkout and Checkin Whenever a user needs to work o n an artifact , they request access (also known 35 ch,cko"l ) from the repository, perfonm their work , and store the new version (also known as ch,ckill ) back in the repository. The repositOry is responSIble for automatically assigning a new version number to the artIfact. Files can usually be checked out either lock,d or ""'ock,d. When checking out locked, the file IS held exclUSIvely by the requester and only that perso n can make modin atlon to the file and check in tho e changes. Others may check OUt the fi le unlocked, which mean s it is read ·only and they only receIve a copy Concurrent wnte pnvileges ca n be achieved by branching, which IS explainod in the next section. When checkIng 111 a Ale , versIon control systems record the user making the change and ask the person to includ.e an explanation o( why the Ale was changed and the nature o( the changes ThIS makes it ea>ler to see how a Ale ha~ evolved over tIme , who has made the changes, and why they were made
125
126
CHAPTER 6
SOFlWARE CONFIGURATION MANAGEMENT
File A (a) John branches. _---.... v1 .2 01 fila A
/
(c) Sally branches v 1.2 otfile A
1.2
o
o
' -__~ (d) Sally mod~ies her copy 01 v 1 .2 of
(b) John modifies his copy 01 vl.2 of ~__-....
file A
~---.... tileA
1
1
1.3
(e) John merges his ..........__~ changes to me A
(f) Sally merge. her changes to file A
1.4 (g) v1.4 contains both sets of changes Figure 6.4 Branching and merging changes
6.2.4.3 Branching and Merging Projects are Illos t ofte n developed by teams of people . Version co ntro l syste ms provide mechanisms to allow team members to work on the same se t of files concurre ntl y (branching ) and correctl y apply changes to common files 0 that no ne are lost or overwritten (mtrging ). This is also known as overwri te safery Figure 6.4 depicts an example, in which Jo hn creates a branel, by checking out versio n 1.2 of file A. A branch is a private work area in a version control system that allows you to make changes to baselined files without conflicting with other team members. John maintains a private copy of the fi le o n his branch and makes his changes. Concurrently , Sall y also needs to work on file A. so she creates he r own branch and checks out versio n 1.2 H er copy starts out the sa me as John's si nce he has not yet checked in his updates. O nce)ohn finishes his changes, he c hecks in his mes to the reposi tory, and the file is given a new version number 1.3. Later, Sally finishes her modifications to A and wants to check in the file . If the version contro l system allowed her to just replace the current copy of file A (versio n 1.3, which now includes John's changes) with her copy, John's changes would be lost. Instead , the versio n control system supports mrrgl"g , which intell igently applies Sally's changes to version 1.3 and creates a new version 1.4 with both of their cha nges applied cor reetly. If the set of c hanges are made to various parts of the same fi le , the system ca n usually perform the merge operation automa tica ll y. If the ::hanges conflict wi th each other, as when the same lines of code are c hanged, the system Wi ll ask the u or to merge the c hanges manuall y. In this case the system will sh ow the user which lines overlap so that person can apply the changes correctl y.
6.2.4.4 Builds Version contro l systems provide support so as to reliably and reproducibly compile and build the latest version of software fi les into an executable , usable file . A user ca n specify which branch of code to build from , all OWing concurrent development. In addition to the executable Ric, builds produce logs containing lhe Rle versions comprising the build .
SCM ACTIVITIES
6.2.4.5 Version Labeling
6.2.5 Configuration Audits As defined by IEEE 1028 · 2008 (3]. a software audit is "an independent exami nation of a software product , software proce , o r Set of software processes performed by a th ird party to a sess compliance with specifications, sta ndards. contractual agreements, or other cri teria." In the contex t of co nfi guratio n manage · ment, the goals of a configuration audit are to accompl,sh the following : • Verify that proper procedure arc being followed , such as formal technica l reviews. • Verify that SCM policies, uch as those defined by change control , are followed . • Deterrnine whether a oftware baseline is comprised of the correct configuratio n item . For example, arc there extra items includcd 7 Are there items missing7 Are the versions of ind,vidual ,tems correct( Configuration audits are typically conducted by the quality assurance group.
6.2.6 Configuration Status Reporting Configuration sta tus reporting supports the development process by providing the necessary ,nformation concerning the softwa re configuration . Ot her parts of the configuration process, such as change and version control, provi de the raw data . Configuration statu reportin g includes the extraction , arrangement, and formation of reports according to the requests of users (4 J. Configuration repo rts include such infomlat'On as the following· •
ame and vcr ion of Cis
• Approval h,story of changed Cis • Software release conte nts and compamon between releases • Number of changes per CI • Average time taken
to
change a
I
6.2.7 Release Management and Delivery Release management and del,very define how
127
128
CHAPTER 6 SOFTWARE CONFIGURATION MANAG MENT
I
3 . 3 .2
Inlrodu tlo n
.2 3 2. I 3 .2 .2
•
rgJ nl ZJtlo n
1\·1 respo nslbtlltl c,
.2.3 App ll able policies, directl vcs. end pro cdu re~
3 .2.4 3. 3
Ma nagcllIe nt of the
M proce>'
M activi ties 3. 3. I
o n~g u ra tl o n identi fica ti o n
3 .3. 1. 1
Idc nti fy lllg co nfigurat io n Na mIng co nfig urati o n items
3. 3. 1.3
Acq uinn g config uratio n •
Items
3. 3 2 . I
Requ estIng changes
3.3 .2 .2
-valuattng c hanges
3 .3 .2 . 3
ApprovIng or dt<.pprovtng changes
3. 3.2 4
Im plem enti ng changes
3 . 3.3
o nfiKuration status accounting
3. 3 .4
onfigu ration evaluation and rCVlews
3 3.5
Interface co ntrol
3 .3 .6
Subcontractor / vendo r control
3.3.7 Re lease manaKement and delivery
Ite ms
3. 3. 1.2
o nflK"rati o n contro l
3 .4
SCM schedules
3.5
C M reso urces
3 .6
SCM plan mai nte na nce
Figure 6.5 IEEE 828·2005 Software configuration Management Plan table of contents SOUrce IEEE Std 828-2005
6.3 CONFIGURATION MANAGEMENT PLANS T o speci fy how the softwa re co nfiguratio n is to be managed o n a project, it is not suffici ent me rel y to poi nt to the co nfi gura tt o n manageme nt tool that will be used. There is mo re to the process, suc h as what activities are to be do ne, how they arc to be im plemented, who is respo nsible fo r implem enting them, when they will be completed. and what resource are req uired- both human and mac hine [2]. The IEEE has developed a standard for oftwa re config uratio n managemer,t plans. IEEE 82 8· 2005. Th is ca n be very useful in maki ng sure that all bases have bee n covered In the process of C M. Figure 6.5 shows the re leva nt conte nts of th is standard, whI ch arc Included in C hapter 3 of the plan. The topics to be pecificd in Sectio n 3.3 of the SCMP arc largely covered in Section 6.2 of th is chapter. Sectio n 3.3.3 of the SCM P doc-uments the mea ns by whi ch the st"tus of SCM i to be communicated (e.g., in writing. o nce a week). Sectio n 3.3.6 applies if a C M tool is used o r if configuratio n management is handled by a ubcontractor The IEEE sta ndard describes the purpose of each section of the above outline in detail. IEEE 828 · 2005 ,s used in the Encoun te r case stud y later in th is chapter.
6.4 CONFIGURATION MANAGEMENT SYSTEMS Fo r all but the most tri vial applicatio n. a co nfig uration management system (also known as a version control system) is indispensable fo r mana8m8 all the artifacts o n a project. Microsoft's SourceSafe™ i in commo n use. VS is a commo n enviro nment. as well as Subversio n and others.
6.4.1 Concurrent Version System (CVS) The Concurrent Version System (CVS) is a commonly used, frec, o pen ource configura tio n management system. C VS Implements a client-server architecture, With users running client V softw3l'e o n their
CASE STUDY: ENCOUNTER VIDEO GAME
• Up-Lo·dare Is id~ntlCal to the latcst revision in the repo ItOry. • Locally Modified File has been edited but has not replaced latest revision . • N""ds a Patch om~one else has committed a newer revision to the repository .
• Needs Merge You have modified the nle but someo ne else has committed a newer revision to the reposi tory. • Unknown Is a temporary fi le or never added . Figure 6.6 File status possibilities in CVS
machines, and a CVS seTVer storing a repository of project fi les. Users check out projects (using the chtekoul command); make changes; check in (usi ng the com mil command); and merge with the changes of others who checked out at the sa me time (using th e updQI' command ). C VS automatically increments the version number of fi les or directories (e.g., fro m 2.3.6 to 2.3.7). The status possibilit ies for a fi le are shown in Figure 6.6. 6.5 CASE STUDY: ENCOUNTER VIDEO GAME
What follows is a configuratio n management plan for Encounter. The Softwa re Configuration Manage· ment Plan (SCMP) for Encoun ter is based on IEEE Std 828·2005 Standard for Software Configuratio n Management Plans. The tabl e of contents of the relevant sections is outl ined in Figure 6.8, which is Chapter 3 of the IEEE specificanon.
Signature
Date
Engineering Manager
".:;.....,
6/ 15/ 04
QA Manager
£. 'Wiluv.
6/ 11 /04
project Manager
a. !I~"itJ.
6f7/ 04
ENCOUNTER SOFTWARE CONFIGURATION MANAGEMENT PLAN
Author
l.. $ 'QU4c
6/1/ 04
APPROVALS
Revision History
Note: to the Student, It ii a good idea to have cach team member Sign off on the phYSIcal document. This pro· ces, focuses their attention on the fact that they Ire accountable for Its contents, and they will be more likely to ensure that It Is the dowment they intend
Title
This assume<; the existence of a method whereby revision numbers of documents are assigned. Versio n I I 0.0 E. Br""dc '
re.ted first d",ft 11/9
1.1.0 R. Ilosrwick · Rr viewed 1/ 10/99
129
130
CHAPTER 6 SOFTWARE CONFIGURATION MANAGEMENT
I 1.1 E. Braude. Expanded 3.2 1/ 18199 1.20 E Braude· Reviewed for re lcasc5/ 18199
A , pc ifl ~ engine r, prOVided by the A or~a . nlz.llon, woll be d e"~ n ate d "s the "conAguratlon !eadcr" fo r Ihe durati o n of the pro) ·ct
1.2. 1 E. Braude, r-inal edltong4/ 30/99
3.2.2 SCM ReSponsibilities Version 2 2.0 .0 E. Braude: Significant edit of section xx S/2/99 2.0 I E. Braude: edits S/ 13/04 The table of conte nts of this SCMi' follows that of IEEE standard 828·200S .
3.1. Introduction
3.2.2.1 Configuration Leader
This Software Co nfiguration Management Plan (SCMP) describes how the artifacts for the Encoun · ter video game project arc to be managed .
3. 1. 1 Definitions Approved Cis: Cis signed off by project management Artifact: A Anal or interim product of the project (e.g., a document , source code, object code, test result) Master Ale: A particular designated Ale for this project, defined in Section 3.3. 1.2
3.1.2 Acronyms
CI: configuration item-an item tracked by the configuration system CM: configuration manageme nt-the process of maintaining the relevant versions of the project SCMP: the Software Configuration Management Plan (this document)
3.2. SCM Management 3.2.1 Organization
5..... ho .. this is
tatc the tasks that each role must carry out If thi is not tated, essential actiVitieS will not be done, and ome activities will be done by more than one team member Include backup reo sponSlbilitie~ In case the main individual is incapacitated .
be manaRed. Supply role (.), but lID names or R:lponsibillties. Names In: supplied In a liter section. 10
"Responsible" does not necessarily imply that the individual does all of the work merely that he or she organizes the work and sees to it that the work is done.
The configuration leader shall be responsible for organizing and managing configuration manage· ment (CM ). Whenever possible, the configuration leader shall discuss CM plans with th~ devdopment team prior to implem entation. He or she will main · tain this document (the SCMP). The configuration Ieadcr is responsible for the installation and main · tenance of the conRguration management tool(s) speciRed in Section 3.2.3. Archiving is to be per· formed in accordance with department policies 1234S . The SCM leader shall be responsible for ac· quiring, maintaining, and backing up the configura· tion tools used He or she shall also develop a plan of action if tools become unsupported (e.g., by dis· continuance of the vendor). Additional respon Ibili · ties of the configuration leader are stated in Section 3. 1-3 .6.
3.2.2.2 Project Leader The project INder and his or her manager will take over the config\lration leader's function only under exceptional circumstances. They are respon
CAse STUDY: ENCOUNTER VIDEO G6~E
rd""ant means of access [0 documents throughout the life:: of the project. The project leacler shall ensure that arch iving is performed in accordance with the policies In Section 3.2.3 below. Additio nal responsibilities of the managers are stated in Sections 3.3. 3 and 3.3.4 .
5. CM passwords should ~ changed in accordance with corporate security practices, with the fol· lowi ng addition, No password shall ~ changed until the project leader, h is manager, and the manager of QA have all been notified and have acknowledged the notiRcati o n.
3.2.2.3 Engineers It is the responsib ility of eac h
6. The prOject leader and department manager are to have complete access to all documents under co nfiguration at all times. Access verificatio n form www.ultracorp .division3 .accessVeriRcati on is to be subm'tled evety two weeks by the project leader to his or he.r manager.
engineer to abide by the CM rules that the configu. ration leader publi shes. Engineers are also referred to ' Standard Engi neering Respo nsibilities," docu ment 56789. Additional responsibilities of the engineers arc stated in Section 3.3 below .
3.2.3 Applicable Policies, Directives, and Procedures
7 . The Encounter project will u e SuperCMTool
release 3 4, a configuration management product b), SuperCMT001.
These are fictitious names. Activities such as CM are generally conducted in accordance with group or corporate guidelines. Student teams should identofy and li st their policies in this sectioa . Policy 3 should be included .
8. Arch iving is to be perfonned in accordance with de partment policies 12 3456.
3.3. SCM Activities I . Configuration management for th is project shall
be carried o ut in accordance with the corporate guidelines for configuration management , cor· po rate document 7890 versio n 6 (8/ 15/98 ). 2. In accordance with division software improvement policies, midstream and pOS1· project review ses· sions are required, where improvements to these guidelines are to be doalmented for the benefit of the o rganization. These sessions are required to help prepare the d ivision for level 5 CMM certl fi · cation. The sdf·a sessment rt.'SUlts are to be sent to the manager of Software Self-Assessment wi thtn three weeks of the assessment session. All "room for improvement" section are to contai n sub tan·
tive matenal , with speCific example . 3. All curre nt and previo usly released versio ns of Cis will be rctalned.
3.3.1 configuration Identification Th is section states how conAguration items (Cis) come into being and how they get their names. Witho ut such procedure being 5tated and followed , chaos results.
3.3.1.1 Identifying Configuration Items The project leader shall be rcspon ible fo r identifying all Cis. Engtnecrs wishing to pro pose Cis shall secure hiS or her agreement, via c·mail or otherwise. If the project leader is unavailable for one busi ness day fo llowi ng the engi neer's c·mai led proposal for inciuslO n, the config · uration leader shall have the authonty to a cept the proposed item.
4. The master Ale (defined in ection 3 3. 1.2) can be
accessed o nl y by the conngu rallon leader and , In his Or her absen e, the department manager
3.3.1.2 Naming Configuration Items The on figuratio n leader shall have the rt"Spons,blhry fo r
131
132
CHAPTER 6
SOFTWARE CONFIGURATION MANAGEMENT
labellOg all fo ll ow,
Is T he file
co n vc nll O Il~
shall be a,
Root directory , Encount er ubd, rcc tory
R or DD or ..
o ntrol th rough upcr MTool A read·only version of th e I IS ava .l ablc to all englnce r~ Under no cirwm
3.3.2 Configuration Control
File N· N· N xxx correspond",!; to ve""on N.N.N For example, vc r Io n 2 'I 8 of the SR will be o n me Encounle r/S RS/2_ 4_8.0<1. The texl m~ Master 10 Ihe root directory states Ihe versions of the Is that compri e Ihe current and prior tates of th e prOjeCt For exa mple, Master could melude mfo rmati on such as: The current versio n of Encounter is 3.7. 1. It compn everSio n 2.4.8 of the SRS, verSion 1 4 of the SOD. The previous version of Encounter was 3.6. 11 . It comprised version 2.4.8 of the SRS, version 1.3 of the SOD. Thi s Informatio n shall be maintained in a table of the followi ng form . Encounter SRS verSio n SDD version.... Release
3.3.1 .3 Acquiring Configuration Items In specifying this section , imagine the most stressful part of the project, which is the implementation phase, involving several people in parallel. The process has to be very orderly, but it also has to allow engineers reasonable access to the parts of the project so that they can start work Quickly. Engineers requiring Cis for modification shall check them out using SuperCMTool's checkout procedure. Note that SupcrCMTool prompts the user with a form requesting an estimate of how long the checkout is anticipated , and store this mformation for all requesters of the CI. Anyone requiring a CI that is currently checked out should nellOtiate with the current owner of the CI to transfer
This section spells out the procen whereby configurallon Items are changed. This prDCeH should be Aexible enough to allow Quick changes, but controlled enough to keep changes very orderly so that they improve the application, not damage it.
3.3.2.1 Requesting Changes As specified in the Software Project Management Plan (see Part III ). the team will designate an "inspector engineer who is allocated to each team member. Before requesting a change, engineers must obtain an inspection of the proposed change from an inspection team or, if this is not pos ible. from their inspector engineer. To request the incorporation of a changed Cf into the baseline, form www.ultracorp.division3 .Encounter .submitCi must be submitted to the configuration leader and the project leader, along with the changed CI and the original CI.
3.3.2.2 Evaluating Changes For larger proj~ts , a group of people, often called the Change Control Board, evaluatrs and approves changes. SlUdent teams must make this process reasonably simple. The project leader or designee will evaluate all proposed changes. The project leader must also specify the required Quality standards for incorporation .
3.3.2.3 Approving or Disapproving Changes The project leader must approve proposed changes. If the project leader is unavailable for thn:e business days follOWing the submission of a proposed change, the configuration leader shall have the authority to approve chan!!es.
CASE STUDY: ENCOUNTER VIDEO GAME
3.3.2.4 Implementing Changes To avoId chaos, it is natural to give to the eM leader the responsib,l,ty for incorporating changes; this can create a bottleneck at imple. mentation time, however. Before this "c runch" occurs, the CM leader should find ways to remove this bottleneck by distributing as much work as feasible to the engineers making the changes.
Once a CI is approved for incorporation into the baseline, the co nfi guration leader shall be reo sponsible for coordinating the testing and integra· tion of the changed CI. Thi s should be performed in accordance with the regression test documentation described in the Software Test Documentation . In particular, the configuration leader shall coordinate the building of a version for testing . Version releases must be cleared with the project leader, or with the manager if the project leader is absent.
3.3.3 Configuration Status Accounting The configuration leader shall update the configu· ration summary at least once a week on the project configuration Web si te www.ultracorp .divi sion3/ EncounteriCo nfiguration . SuperCMTool's sta.(Us report will be a sufficient format for the summary .
3.3.4 Configuration Audits and Reviews In industry, random audits are often employed. They are not commonly conducted by student teams due to a lack of resources, although rome teams have carried them out successfully. PeriodiC reviews, as part of the regular team meetings, do not take much time , and they arc recommended .
Configuration efforts will be subjoct to random audits throughout the project's hfe cycle by the IV&V team .
3.3.S Interface Control The CM system interfaces with the project Web site. This interface shall be managed by the configuration leader.
3.3.6 SubcontractorNendor Control The con~guration leader shall track upgrades and bug reports of SuperCMT001. He or she should be prepared with a backup plan in case the maintenance o f Super. CMTool is discontinued. This plan is to be sent to the project leader within a month of the project's ,"ception .
3.4 SCM Schedules TI,e SCM schedule can be prOVIded here, or combined with the project chedule in the SPMP. In the latter case, this section would not repeat the schedule, but would merely point to the SPMP.
The schedule for configuration management reporting , archiving, and upgrad ing is shown In
Figure' 6.7.
3.5 SCM Resources The configuration leader will require an estimated average of six hours a week to maintain the system config urati on for the fir t half of the project, and t,_elve hours a week for the seco nd half We have cho ' en no t to call o ut separately the time spent by the ot her team members o n configuration management.
3.6 SCM Plan Maintenance The project manager shall schedule a review by the CM leader of the cnnfiguration at least once every two weeks, preferably a. an agenda Item for a regularly scheduled weekly project mee tIng The CM lead~r shall review CM status, and report on the proposed detailed pro edures to be fo ll owed at code and ontegratlo n time
All project documents undergo change throughout the duration of the project. The SCMP is especiDlly sensitive to change, ho",· ever, because It controls change Itself.
133
134
CHAPTER 6
SOFlWARE CONFIGURATION MANAGEMENT
Month 1 Month 2 Month 3 Month 4 Month 5 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
Stable eM
eM reviews
---4 --'. ' • Ve ndor backup plan due - -- tttH Ufftff --
eM process Im provement session
---
I
I Random IV and V audits
Figure 6.7 Configuration management schedule Due to the Importa n c~ of a stable SCM plan , all changes to this document mllst be ap proved by the entire Ctvl team In vic w of the soft\\fare de velopment o rganiza · tlon' goal to anain CMM level 5. the conR ll urati o n leader will do the following for the CM process improvem ent se sions:
• Review the effective ness of this plan • Qua ntify 10 se due to defects In this plan • Re view the effectiveness of Super CMT 001 • In vestigate the literature fo r new CM meth ods; q uanti fy the costs and beneRts of improveme nts • Investigate new CM tools • Sugges t speciRc improvements to this CM process • list the beneRts of improvements • Provide cost cstimates on effecting the improvements • Prioritize the costibeneRt ratios of all the slIg · gested chan ges
6.6 CASE STUDY: ECLIPSE CONFIGURATION MANAGEMENT IN ECLlPSE 1 Open o urce projects such as Eclipse arc developed by geographical ly dispersed e ngineers who have I
This section is bilsed on information rrom (6).
difrerent so urce code access requirements. Most are de velopi ng their own plug " ns, which are exten · sions to existing Eclipse code and fu nctio nal ity, and o nl y require access to Ecl ipse source code for debu gg in g their work. Others may want to change existi ng Eclipse sou rce code if they are Rxing a bu g, o r add code if the y are develop ing a feature . Th ese develo pe rs require write·access to Eci ipse code . Source code is managed in Eclipse using CVS (Concurrent Versioning System ), which is the de facto version co ntrol system fo r open source proj· ects. Eclipse integrates a built ·i n CVS CUI, making version control very easy to use . CVS implements a c lient· server architec ture, with the Eclipse repository housed o n a ce ntral server at dev.eclipse.org that stores all the Eclipse source code. In ge neral there arc two classes of Eclipse users as follows , I. Those that want to read andlor modify Eclipse
code but don't have write access to the reposi tory
CV
2. Those that do have write pemlissio n for the Eclipse source code and can modify and update the CVS repository . These people are call (o mmllttrs
The fo llOWing IS quoted from [7) and d~cri~ these t'Wo classes of lI<ers .
CASE STUDY: ECUPSE
Anonymous CVS For pc::opl~ who actually want to change Ecllp e code but who do not have the required commit rights In that area, all clements of the Ecl,pse proje t arc available via anonymous access to the development repo itory. U 108 anonymous acce> you can checkout code, modify it locally, but cannot write it bad. to the repository. Th,s is handy if you would like to fix a bug or add a feature . eet the code via anonymous access, do your work. and then pass the work on to a commilter for inclusion in the reposi tory. .. All committers mu t use SH (Secure SHeil ) to acce the CVS repOsitory if they wish to use their u er id and password (o.e. , If they want to write to the repository). Full CVS Developc::rs WIth commit right have individual user ids and password, in the Ecl,pse prOject development reposItory. As a committer you can use SSH (Secure SHeil ) to connect to the CVS rcpository as follows . .... Once your information is authenticated , you can browse the repository and add projects to your workspace. If you do some changes that you'd like to contribute, after testing and enswing that you have followed the contribution guideline~ , you are free to release your changes to the rcpository . Of course, you can only release changes to projects for which you have commit rights. Note that you can use the SSH protocol and your Eclipse user id to access projects for which you arc not a committer, but you will not be able to release changes.
• Major- thi s numb('r i incrcmcnlcd each time there is a breakage in the API
These points arc summarized in Figure 6.8.
VERSION NUMBERING Eclipse plug·ins use a versio n·numb""ng scheme that captures the nature of the c hanges implemented by the plug.in . Versi on numbers are co mposed of four parts as follows : Major. minor. service , and qualifer. Major. mitior. and suvir! are Integers, and qualifltr IS a stn ng.
• Minor-this number i increme nted for "extemally visible" changes • Service-this indicate a bug Ax or ot her change not visible through the API • QualiAer-thls indicates a partIcular build
OHiclal
Eclipse Code Base (CVS)
Write access with password
General User
Com miller
Figure 6.8 Eclipse configuratIon management
135
136
CHAPTER 6 SOFTWARE CONFIGURATION MANAGEMENT
Firs t develop me n t s trea m I 0.0
Second development s trea m I 0. 100 (ind ica tes a bug flx ) I I 0 (, ne w AP I hJ bccn Introduced) Thc plug -IO ship a, I 1.0 Third dev~ l op m ~ n t s tream 1.1. 100 (IOd,ca tes a bug flx )
2.0.0 (indi ates a brca kln g c hange) The plug-in . hips as 2.0.0 Mai nte na nce stream afte r I . I .0 I. I. I
Th e plug" n ship as 1. 1.1 Figure 6.9 Eclipse plug-I n version num bering ' of 2 Source, EclIpse Wilt!. I'lttPl tw1ki eclIpse OrgIVersion_Numbenng.
The exa mple shown In Figure 6.9 and 6 10, take n fro m hnp j/wiki .ec ilpse .o rg, s ho ws ho w the versio n numbe r c h anges as a result of plug· in devel o pment. The descripti o n sh o ws that bug fixcs , new
applicatio n programming Interfaces, and shipping to the community are rcAected in the numbering in partic ular ways.
6.7 STUDENT TEAM GUIDANCE: CONFIGURATION MANAGEMENT Student tea ms sho uld create a Software Configuratio n Management Plan (SG\1 P) for their projcct using IEEE Std 828· 2005 as a template and the Encou nter SCMP in Section 6.5 guidance . The rest of this section descnbes how to o rga nize fo r this task. co
'"'CI>" -
"
II:
First dey stream
Malntenonco 51'~m ef'tef
Second dev stream
Third dey stream
Figure 6 .10 Eclipse plug-In version numbering 2 of 2 Sour" EdIpse WIkI, hUP:JIWlIeJ.ecllps8.cwgNOfsAon_Numbtf1ng
SUMMARY
1. Roughl
ske tc h out your SCMP
a
Detemlme procedures for making changes.
a a
Omit tool references unless already identified o nc . See the case study fo r an example .
2. Specify what you need from a CM tool a
For class usc, maybe o nly locking and backup.
3. Evaluate affordable tool agai n t needs and budget a Commercial tools arc in wide use. a
For class use, try f,.ee docum ent sto rage Web si tes[ simple method of checking out, e.g .. re naming, can be too si mple .
4 . Finalize your SCMP Figure 6.11 Planning configuration management
Figure 6. 1 1 shows how teams can go about deci ding their configuration manage me nt met hods. When there is insufficient time to learn a CM environment, teams have succeeded reasonably well with simple Web sites, such as www.yahoogroup •.com . thatalio wdocument sto rage. Asimple checkout system is needed, one of which is to change the document type. Fo r example, when the SQAP is checked out to Joe, the file is changed from sqap.txl to sqap.jor . Alth ough configuration management applies to both documents and source code, the file-naming convention usually has to be planned separately For example, we canno t change ",yClass.java to myClass.jor without disrupting compilation . Some groups maintai n twO directo ri es. O ne contains the current baseline, wh ich cannot be changed witho ut a formal process. The other directory contains versions that arc currently being worked on . Trial CM tools or free ones such as CVS and Subversion are available. Coogle supports frce docum ent hosting with Coogle Docs and has support fo r versio n control. Be sure that your process does not rely on excessive manual intervention , and that it does not result in a bottleneck where o nc person is overl oaded. If you are co nsidering usin g a tool, be sure that the le ngth of th e learnin g curve ju tifies its use. There are many other software e ngineering aspects to learn besi des usi ng a particular CM too l. Whatever system yo u select , try it out first o n an imagined implementation . Makc sure that the process is smooth. You do not wallt to worry about your CM process durin g the impleme ntati o n phase , when time is limited. In the work world , however, professional CM tools arc a neces ity .
6,8 SUMMARY Software configuration manage ment (SCM ) is a process fo r managi ng all th e artifacts produced o n a oft'ware project, including source code, specifications, and suppo rt ing software. Planning for SCt", stans earl y in a project, starting with the Softwa re o nfiguratio n Management Pl an. It specifics the SCM activitie to be implemented throughout development and so ftware ma inte nance, such as Iden tification, change conn'ol, v."ion co ntrol , audits, status reporting, and rel ease management. Ea rl y in a projec t, artil-acts arc ide nti fied a5 config uratio n items ( I) to be stO red in a repo Itory and managed . After a C I IS reVIewed and approved It become part of a basehne and i< offiCIally managed by M pohcies. ArtdaclS go throug h ineV Itable change, being newly crea ted or modified due to ei ther error correc tion or enhancement. S M denne, actIv Ities to request, eva luate, approve o r disapprove, and implement changc, \0 basdi ncd Cis.
137
138
CHAPTER 6
SOFTWARE CONFIGURATION MANAGEMENT
A ~c l'equIJ-cmCIll of ,1, the abdllY to reproclu e Ihe precIse "alc of all I, 01 any POlf11 In lIme A VCI';lon Iltra l , '>tem (al,o kn own ", a cOllfigurallo n manaK me nl sy,tcm) au to mal ,mu h c,r th IS proce,s and provide< a rcP<"' t )ry for to nng ver
6.9 EXERCISES I. In your own wo rds , deA ne the term cOHfigliralion il,," and desc ribe Its purpose .
2. \'(Ihy is it necessary fo r compilers to be idcntiRcd as configuratio n items? Describe a scenario that illustrates whe n th,s is l1l'cessary . 3 Describe the four goal of configuratio n l11anageme" t in your own wo rds. and explain why each is important.
4 . If you are devel o ping a software app lication usi ng an incremental process, at what points would you minima ll y c rea te baselines) 5. Explain the difference bel'ween change co ntro l and version control. 6 . Agile processes pro mote conti nuo us integration. which results in branching and merging at very frequent in tcrval (as ofte n as every few hours). Describe one advantage and disadvantage of branching and mergi ng so freq uentl y. Describe one advantage and disadvantage of branching and merging less frequentl y. 7 . As mentioned in the T eam Guidance sectio n (Sectio n 6.6), forsmaliteams it may not be necessary to utilize a n aut omated conRguration management syste m. Describe the process you would follow to perfo rm branch ing and merging wit h out such a sy tem . 8. Research a configuration m"nagement system such as Subve~ion or CVS. Describe how it implements the seven SCM activities listed in Section 6 .2.
TEAM EXERCISE For the team exercise. consi der as a group how you wil l perform it, check the hints below, and then carry out the assignment.
eM Plan Produce a software configuration manaBeme nt plan for your team project using IEEE tandard 828· 1990. The case >tudy should guide your team. but your document will be mo~ SPCCIOC, I't'Rectlng t~
BIBUOGRAPHY
panicular resources avaIlable to you. Do not include material unless it contributes to the document's goals. Avoid bottlenecks and unnecessary procedures. Include procedures for what to do if people cannot be reached and deadlines loom. Bdore you begin . estimate the number of defects per page the team thinks it will discover during the fi nal review. Keep track of and report the time spent on this eHort by individual members and by total team effort . State the actual defect denSity (average number of defects per page). Assess your team's effectiveness in each stage on a scale of 0 to 10. Summarize the results using the numerical results, and state how the tcam's process could have been improved. Criteria, I . Practica lity , H ow well does the plan ensure that docum ents and their versions will be secure,
coordinated, and available7 (A = plan very likely to ensure coordination and availability) 2. Specifics, H ow specific is the plan in terms of suitably naming places and participants7 (A = no doubt as to what engi neers must do) 3. Process as essment and improvement, To what degree did the team understand the strengths and weaknesses of its process, and how speCific are its plans for improvement7 (A = full , quantitative understandin g, with plans for improvement very speCific and realistic )
Hints forTeam Exercise Do not fi ll in sections that arc as yet unknow n; add only parts that you are confi de nt of being able to implement within the semester. Make your plan realistic. For example, don't state that "all other team members will review each contributor's work" unless you are reaso nably sure that this ca n be done within the probable constraints oi your project. It is too earl y to make any assu mptions about the architecture and des ign of the application .
BIBLIOGRAPHY 1 8cllagio, David, and T
Mliligon. "Softwa re Co nRguratlon Management Strategies Jond IBM Rational C lea rnsC' A Practical
Introductio n,· IBM Prcss/PcMson pic, 2005, p 7 2 "IEEE Standard for Sortware Conflguralio n Manogcmcnt Plans: fill Srd 8 28 - 2005 . August 2005 . 3 "IEEE StJndard for Software RcvlC' ....·s and Audits," JEEE Std lo n - l OOS, August 1008 4 Ha~~, Anne M J, "ConMJlt'tJ llon Mand91'n1(r1' Prr"cipl,I and PractICc," Addlso n.Wesley, 2003, p. 25 S "Systems and so hwau: cn8tnt't'nn~-So ft''A'art' Ide cycle procc'ic;;cc;;,· IEEE Sid 1220 7·1008 Second edItion. January 2008 , p 69
6 Eclt psc, http}I""",,'W ecl Ipse 018 (acC('sscd AuA'U'i' 13, 2009 ] 7 Echpsc-. hup Jlwww eclipse org/eci lpsc/ [Jccc ..scd Augllst 13, 2009 )
139
principles of Software project Management I: Organization, Tools, and Risk Management
The Software Development Ufacycle
•
How are software development prOjects organized?
•
What is an appropnate team size?
•
What happens when teams are geographically distributed?
•
What tools and techniques are available to support projects?
•
How do you handle risks?
•
How are projects managed In practice? In student teams?
Figure 7.1 The context and learning goals for this chapter
SoltlDa" project ""'H"9c""Ht is the process of planni ng . organIzing. and monlto nng the development of a oftware prOject from its Inception to its completion . It incorporates a set of tool s and technique practIced b the person or people responsible for a project during every phase of develo pment. The person respon ible I the proJcct ",aHa9" (a tenn usually u cd for larger projects) or tca", lcad" (a tcnn typically u cd for smalkr
PRINCIPLES OF PROJECT MANAGEMENT I: ORGANIZAnON, TOOLS, AND RISK MANAGEMENT
• Customers are sddom sure 01 what they want. •
ustomers change their requirements and plans may not be updated.
• It i hard to estimate up front Ihe magnitude of the effort required . • It.s hard to coordinate the many requirements , the design elements corresponding to each requirement , and the correspondi ng code. • There may be unforeseen technical difficulties to overcome .
• It is not easy to maintain constructive interpersonal team dynamics . Time pressures cause stress, and [earn members have differing opi nions.
Bur rbm ohslaclts co .. all br oV(rcomr/ Figure 7.2 SOme challenges of software project management
projects or teams). Sometimes the perso n responsible is called the project manager and has o ne or more subordinate team leaders. In all cases, these people practice project management. C ritical to the success of a project is the organization of the project team . Many different organizational structures are possible . each with a set of strengths and weaknesses. It is very difficult to deliver a quality, full y accepted softwa re application o n time and within budget. Figure 7.2 gives some of the main reasons . Software project management addresses these issues by incorporating a range of activities and structure into a project , including project orga nizati on, {ools, and
support, management of project risks, project estimation and scheduling, project docume ntatio n and tracking. These are summarized in Figure 7.3 and explained in this chapter.
• Organization o
How is the project team structured?
• Project Management Tools o
What tools are available to support project mana gement?
• RJsk Management o H ow arc risks to the project's success identified and mitigated ? • Estimation
o
How long will the projec t take to o mplete and how many resources are reqUIred ?
• Scheduling o What are the different parts of the project , in what order will the y be completed , ,nd who will work on each part] • Documentation and Monitoring o How j~ a project plan c rea lcd , a nd how i, the plan monito red to c n
Fleur. 7.3 What does software proJeCI management add ress?
141
'42
CHAPTER 7
PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT
T he rest ot Ih" ch"p ter foeu,,,s o n the o rga nizatio nal stru ture" too ls, and rISk management that support proJ Ct managc ment T he next hapt er, whl~h ompletes our d,scuS
7 ,1 SOFTWARE PROJECT ORGANIZATION The way," whic h a compan y is o rga nized has a direct bearing on how proJeu, are executed, Some ompanlcs
rganlze around th c lf proJec ts. In these companu.:s pro)cl.l managers have t(rcat autonomy, with
team member di rec tl y reporti ng to tht'm. O ther o mpanie orga",ze arou nd functional areas such as devci o pment, marke ting, fi nance , and so on , givi ng projec t manage rs respo n ibility for monitoring and reporting o n proje t progress. O ther compan ies empl oy an organization that mixes both of these In ge neral, there are three type of orga niza ti o nal Slnl c turc : projtCf-orjwttd, j 'Hlcliotl -oriw ttd , and m(lfrtx . W e examine each of
these," the ect lo n that (ollow.
7.1. 1 project-Oriented organization In projecl-orien ted organiza tions , personne l arc o rga nized around the projects of t he compa ny. When a new projec t is initia ted, a project manager is assigned to head up the projecl. O ne o( their first tasks is (orm ing the team , whi ch is made up of new hires or people who are finishing o ther prOJects. The project team comprises people from multiple functional area such as marketing, fi nance, development, and so o n. Team members report to the project manager, who is thei r ult imate boss. They are attached in all ways to a parti cular project, and have no o rganizational affilia tion with peo ple o n other projects . This type o( o rganization is illustrated in Figu re 7.4. The principal rca on to o rganize around projects is to develo p loyalty to the project rather than to the functiona l manager [ I]. Since employees are dedica ted to a si nglc project, they can focus their ti me and energy o n that project. Th is increases the predi ctability o( sc hedul es as there IS less chance of team membe rs spending unschedul ed time o n other projects. H owever, th is type of o rganization has the potential disadvantage of isolat ing engi neers professio nally and redUCi ng the amount o( reu e and profeSSional stimulatio n between projects as a resu lt o f this isolat io n.
Senior Manager
Prolect Manager
Project Manager
Project Manager
Project Team (Mar1<etlng, Finance, Sohware, OA)
Project Team (Mar1<eting, Finance , Software, OA)
Project Team (Mar1<eting, Finance. Software , OA)
Figure 7,4 project-orlented organization
SOFTWARE PROJECT ORGANIZATION
President
I
Finance
Marketing
Oevetopment
OA
Finance
Managers
Marketing Managers
Sohware Managers
OA
Finance
Marketing
Personnel
Personnel
Sohware Engineers
Managers
OA
Engineers
Figure 7.5 Function-oriented organization
7 _1.2 Function-Oriented Organization F","ction-orirnttd organizntiolls arc a very common type of structure. A compa ny is organ ized IntO groups based on their fu nctions , such as marketing, Anance, development , QA , and so o n. Th is type of structure is dlus trated in Figure 7.5 . In this form , functional orga nizations have projects, but the scope of their prOjects IS lim ited to the boundaries of ,heir group responsibilities. As an example, if a software functional group is working o n the user interface (UJ ) software of a larger software product , only the UI software being developed is considered the current project fo r that group. Functional managers in this kind of organization act a project managers. re pon ible for the" projects as well as the hiring, Aring, a nd salaty of their team members. Managers may be responsIble for multiple projects. TI,is structure has the advantage of clear and responsible decision· makin g c hannels However, because managers arc responsible for multiple projects , their knowledge of proje ts is nece sari ly limited by their available time. In addition , they must wei gh carefully the needs of each and e nsure that they don't favor one over the other. If one of their projects is falling behind schedule, for example , they may shift personnel from another project to the lagging project . ThIs may cause a delay," the other project.
7 _1 ,3 Matrix Organization A-latrix organization, are a c ro s between project - and function -oriented organizations. They try to gain the advantages of both project-onented and function -oriented organizatIOns. In a matrix orga nizatio n, employ ees belong to a functional g roup (e.g ., marketing, engineering ) but arc loa ned to projects based o n the" expertise_Thus, a software eng,"eer's supervisor- who" responsible for evaluating that person-would be a member of the softwa re engIneering fun tlonal unit . Within ea h project o n which the person is ,,'orking, howl>ve r, he or she would be supervI sed by a project leader Eng,"cers arc u uall y In vo lve d o n a regular baSIS with one project, sometimes two, but ~e ld om mo re. FIgure 7_6 illustrall><; the reponing srru lure of a matfl x organlzatron In lh" .tm lUre, a prOject manager" aSSIgned to each project For example, Oscar Man IS' mcmber of the marke ting depanment alld a<signed to the airline r=rvati on proJec t, headed by Al PruItt For all proJe t-related aCtiVItieS, Oo;car repom directly 10 I
1U
144
CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS. AND RISK MANAGEMENT
Project
Malrix
rgani zll tlon
.-'"oc:
-v c:
Airline reservation project
Bank accounting proiect
Molecular analysis project
Fluid mechanics project
AI Pruitt Full lime
Quinn Parker Full time
Ruth Pella Full tIme
Fred Parson< Full tIme
Marketing dept Oulia Pitt, mgr)
Oscar Mart Full time
Pete Merrill Full time
ue More Half tIme
Elton
Engineering dept Ooe Roth, mgr)
Hal Egberts
Proiect manage me nt dept
Mar~ton
Full time
::>
Ll-.
•
•
•
•••
Mary Ericson
Ben Ehrlich
.
, .
." •
• •
Len Engels •
••
•••
•••
Figure 7 .6 Matrix organization
However, Oscar's boss is Julia Pill , a manager in the marketi ng department. Julia would consult with AI when doing performance apprai sals. An advantage to this approac h is that project managers maintain focus and have responsibility for the success of the .. projects . Functional managers are focused o n the content of their functional area and can more easi ly coo rdinate the efforts of their g roup members, some of whom may work on multiple projects For example . the software manager of a database group might recogn ize that multiple projects have similar requirements for accessi ng a database . The manager can coordi nate a software design that is ge neral enough to be used by multiple projects. We will consider team size next.
7.1.4 Agile Organization Agile teams consist of technacal people. The .. principal no ntechnical contact is with the customer. Stili, function s of the kind mentioned above conti nue to be required. An example is Anance . Every o rganization needs to understand the costs and benents of projects. Agile teams become adept at estimation , and so nnance people-who are not part of the agile team itself-have good shon ·term data and forecasts but are required to be agi le as well. This is because agi le teams are not plan -driven . n,e upshot is that the nontechnical people must base their work on good but relatively short-term data.. They perform their work by interacting with the customer and WIth the development team .
7.2 TEAM SIZE To be precise, a "team" is a group of people who work closely together on a daily basis. One mIght imagin~ that the appropriate size of a team depends strongly o~ the size of the application (large team for large applications, etc.) but th IS is not so . Large teams (not necessarily groups-keep the deRnitoon of "team' in mind) have the advantage of div iding the work Into many pans but the disadvantage of communication lhat i
TEAM SIZE
I Effectiveness per developer
Developer communicales regularly with 11 people.
Developer .r~-
O~--
communicates regularly with no one.
I
3
7
I Number of people with whom developer must interact frequently
Key:
0; engineer
f"tgUre 7.7 Options for team size showing extremes
time-consuming and error-prone. A significant aspect of such communication is the need for tea m members to explain what they are doing. Having to keep forty people up-to -date on a daily basis , for example, requires a lot of meeting time. In his ciassic work , Th, Mylhical MnH -MoHth [2]. Fred Brooks pomted out that adding !><,ople to a failing project invariably makes mailers worst . In other words, for many projects the disadva ntage of increased communication channels, which are panicularly heavy during the learning process of new team members, may often outweigh the advantage of divisio n-of- Iabor. What is the optimal size of a team ? This is a mattcr of trading off the benefit of haVing many helping hands against the cost of communication among them . The optimal size depends on the nature of the projec t, Routine projects can usually benent from larger team sizes because a lot is understood about what each person should do. Let's consider extremes for a typical project, shown In Figure 7.7. The vertical axi reAccts the effectiveness per developer. Experience of the authors and others shows that the number of develop,:rs with whom each developer needs to interaa on a regular basis should normally be between three and seven. (Humphrey (3) suggt'Sts four to elght.). Formal studies on the effect of team size on performance are rare. At one extreme shown in Figure 7.7, the developer works without interactmg regularly with anyone on an individual basis. Although no time i spent on communication, such isolation typically results In misunderstandin!." of what is required of that developer, leading to a relatively low level of effectiveness. At the other extreme, the developer has to intern t regularly with so many tndiv,duals that there is not enough time left to perform development itself, again resultinG in relative ineffectiveness. In panicular, true "regular communication" could entail speaking with someone for an average of approximately two hours a week_ If an engincer were In regular communtcation with ten others, then fully one half of his time would be spent communicating, leavmg only half of the week for hIS tndivldual contnblItion. Project organizers, whether planning twenty -person or hundred-person projects, have to a count for thiS. Figure 7.8 Illustrates these potnts as follows. If you pick a team size such as three and draw a venicalline, it into,..;e ts the blue area between two values of 'effectiveness per developer ' TI,e inexactn""s of this measure leads us to talk in telms of ranges rather than absolutes. We arC interested in picking a team ,izc that yields the most effiCIent work on a per-developer basis. Figure 7.8 shows this occumnlj between team siz"" of about three and seVen As the number of participants in a prole t grow>, an orilanlzation where everyone is a peer b<:comc ImposSible to usc because thft number of commu nica tio n llilk (between all of the pairs) grow . With the square of the number of panicipants Three people entail three Itne, of o",munl 3tion, four pt'oplc cntatl ix, nyC people ten, six pee. pic fifteen . " people rcqlttre (II - I) + (II - 2) + ... + I = II (/I - 1)12 hnes of Olnrllun lcat lon . This grows With the square of H ne hundred people would have til participate rCHttlorly In 4,950 lines 11 communlcationl One alternative for laflje pro, e~t' 1< the orga nizotilln ,huwn til l' lgttrc 7 _, In whic h peN
1U
146
CHAPTER 7
PRI NCIPLES OF SOFTWARE PROJECT MANAGEMENT I' ORGANIZATION, TOOLS. AND RISK MANAGEMENT
r Ellectiveness per developer
Dovoloper communlcalos regularly with 11 people. Communlca llon lime outweighs /)Onefils 01
Approxlmat" optimal ra ng"
Interaction.
"
Developer communlcales regularly wllh no one. No communlcallonllme is lost. bul developer is too Isolated and has no help.
,• 7
Number ot people with whom developer must interact frequently
Key:
0
= engineer
Figure 7.8 Range of optimal size for beneficial interaction
Team of leaders
Figure 7.9 A peer organization arrangement for larger projects groups remain small , and one member of each group is deSignated the communicator with the other peer groups . This type of organization tries to preserve the benefits of small teams. but it harnesses the large number of people to bui ld a large application . Note that team leaders have double the amount of communication rime than non · team leaders.
7 .3 GEOGRAPHICALLY DISTRIBUTED DEVELOPMENT Independent of whether a team IS project-oriented , fun ction -oriented, or m.trixed, team members maY be either collocated or geographically distributed . The latter prese nt a unique et of challenge Managers naturally try to make usc of worldwide programming talent to optimize costs and improve quality , a process sometimes called oifsbonn9 . The Internet and collaboratIon tool have mad .. offshonng increasingly practical. per-hour costS of remOle progra mmers are traded off against the ommunlcation
n,e
GEOGRAPHICAllY DISTRIBUTED DEVELOPMEHT
•
me ofR e arca
+ -
ideal for group commun Ica tIon labor rates suboptl1nal
• Same city , different offices communIcatIon fair reasonabl y good communication
+
+
-
common culture
labor rates suboptimal
• Same country, diflerent cities
+
common culture
-
communication difficult
• Mul ti -cou ntry
+
labor rates optimal
-
communication most difficult
-
culture issue problematical
,• Figure 7.10 Possible locations of distributed team SOc.rce. GraphICS reprodUCed wtth penTlfssion from COrel
problems incurred by physica l remoteness . TIlls trade ·ofl depends large ly o n the degree of need for continual interaction wIth the customer. Options lor remote tcams are illustrated in Figure 7 10. Bob Schudy , a colleague 01 the authors who has extcn ive experien e wIth offshon,,!:, lists its advantages, • Work can be done around the clock • Good ·quality work is available • There is potcntial for cost savi ng He lists the lollowing a, dIsadvantages . • Incre'hed ddfi ulry lor the offsho re per<;onnel to understand reqU1remenlS • The lack
01 IOIomlal " hallcr" thaI an smooth progre"
• Tim d,fference< lor (VIrtua l) meellngs
1. 7
148
CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I' OflGANIZATION, TOOLS, AND RISK MANAGEMENT
Costs 01 OHahorlng
® Communications hampered ® Cultural dilteronces ® Increased projecl
Benefits 01 OflshQriog @ Lower oltshore labor rales
© Work continues during
U,S.
management coslS
night time
Figure 7 ,11 TO offsilQre or not to offshore •
urprises in ski ll CIs
• Travelmg ills, e pec lall y for westerner; in the East Schud y includes Ihe following in his remedies for these disadvantages, • Meet face -to -fuce initially and periodical ly , • U se various media (c ha t, VO IP, conference calls, etc.) . • tv'ake sure there is strong on ite management'.
o rne of the trade -o ffs that arc accounted for in deciding whether and how muc h to offshore are shown in Figure 7 I t _ Figure 7 , IllS an e xample of how a project can be distributed among "ncar-shore" (same country; remote locatio n ) a nd offs ho re , Fi gu re 7 . 13 shows how tasks coul d be allocated in a distributed development project _ The particular allocations are shown as exa mples o nl y, and were quoted by a group at IB M _ IBM lis ts the methods in Figures 7 14, 7, t5. and 7, 16 for dealing with distributed development The word · reqUlrements" in the Rgure refer; to what is needed about the process, not the reqUirements of anyone application_ CDD stands for geographically distributed development. UML is a deSign notatio n covered in this book.
--., !{l
---!:!.'" '" ~
-'"
'0
u
w- e.
.-5 <:
--!{l'" 0
'-' =>
<: 0
'-' ~ <:
c
E '-' 0 c 't:: => .,
--
,0 -
-.,'" --., <: <:
8. E 0
U
-., <:
E >.
-.,c0
0
-g
--
0
a..
Figure 7 .12 Example of how tasks can be allocated In a distributed development project . Souru 18M, c.opyr18t't (j ;l lntcmallonal BuSiness MacJllnos COrporation, rtPrInted WIth pOfmlSSlOr\, httDJlwww3 software ibm comlibn'd,./'plltl,~~'¥'" weblgvkleslGC34 2500 00 IXl'
GEOGRAPHICALLY DISTRIBUTED DEVELOPMENT
In -house team
Remo te subcontracto r
• Business analysis
• Testing on pre· release builds
• New feature development and related testing
• Testing maintenance rc1ea es of current version
• Requirements: capturing, doCUmenting, and
• Build and deployment
managing
• Selected project management
• System architecture, modeling
• Mainta ining current version
• Project management
• Unit testing components modiAed during maintenance
• Creating and modifying requirements for maintenance
Figure 7.13 An allocation of tasks SOUrce IBM, COP'Il'IgTlt
,~
Intemaoooal Business Machines COrporation. reprlnle
aprOSIcammaranollndex.html.
- -
---~~-~
REQUIREMENTS United leams despite diverse languages and cultures
-IBM RESPONSE
• Enable brow<er-based access to Ihe same knowledge base for all teams • Provide easy access 10 guidelines, template and tool mentors based on underl yi ng best practices • Visually communica te discipline workAow and interactions wilh the Unined Modeling Language (U ML)
Reduc tio n in work transfer issues
• Imple me nt a fTamework based on core process workflows fro m business modeling through deployment • Use a phased approach to software development that detads execution for each disci pline
Easy-to-navlgate pro · cess that is not over· whelming for users
• Jump-slart planning and gel new team members up to speed fast with knowledge assets and guidance
Demonstrated progress toward expected return on investment for CDD projects
• Track metrics th roug h out the project life cycle
AbIlity to assess and manage distributed resources efAc lcntly
• Maintain a broad and deep understanding of an organization's capacity, skills inventory, total workload and resource de mand
• All ow users to create personal process views that are central to individual needs • Provide intuitive naVIgation wi th a browser- based interface
• Report on variance measurements and adjust process to ach,eve desired results • Track project progress and quality through quantitative analysis
• Optimize ski ll usage with resource planning to align mission-cntical resources with h,gh-priority projec3
Figure 7.14 Tools and methods for distributed development, IBM. 1 of 3 SOlI"
I:BIA., copyngtlt (' internatiOnal ~5 MaChines Corpotillon, reprinted wltn pet'mlsslOn. nnp JI'WItWl softwatO iOOl C
\': eblpArx:lGC34'25CO<X:I pdf
1_9
150
CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT
I cmo nstrated proBreSs tow."d expeLl<'d return o n II, ,,'lInerll for ,I D prOjects
o
Abrlity to assess and manage dr stributed resources efAcrently
Scalable projec t
o
Track metncs throughout the projecl life Lycle Report on vorian e measurements and adjust proc~s to achieve: dcsl~d ,eoul~
o
Track project progres and quality through quantitative .oalysls
o
Maintain a broad and deep understanding of an organiUltion's capaCity, skills rnventory, tOl.1 workload and resource demand
o
Optimize ski ll usage with resource plannrng to alrgn mission-critical resources with high-priority projects
o
Centra lize sensitive schedu le, budget and resource data while allowing secure, high -performance access anywhere in the world
management so lution o
Consistentl y executed processe
Implement native scheduling, resource loading and ·what-if" scenarios that avoid performance issues by integrating with third·party scheduling products
• Capture and reuse successfu l GOD engagement models, work breakdown structures and workAows to ensure execution against IT governance requirements and best practices • Enable reusable project templates and task guidance based on a proven process, so teams never have to start planning from scratch
Accurately tracked labor costs for in ·house
• Accurately track labor expenses and budget for time and materials or fixedbid resources
or external re ourers
Figure 7.15 Tools and methods for distributed development, IBM, 2 of 3 SOUrce; IBM, copynght ~ InternatIOnal BuSiness MaChines corporation, reprinted with permisSIon. htU>:t/WwW3.soltwure.it>m convlbmdVpub/softwaretrabOflall weofgl"udeslGC34-2500-00 pdf
-
-
REQUIREMENTS Quick and easy Implementati on to start col-
laboratin g in days, not mo nths
Consolidated work arca where team s can more effectively com muni ·
care and co ll aborate on project issues
IBM RESPONSE • Facilitate discussions, set up chat rooms and combine team calendars with ready-to-use templates • Leverage out-of-the box functionality that users can customize themselv~ • Centralize installation on one server • Create a centralized location to post and share project documents that can be viewed and modified by other team members • Share team member project calendars • Track feedback from other team members • Enable the creation of forums and partiCipation in threaded discussions • Allow team members to share files in real time via Web conferencing
Figure 7.16 Tools and meU,ods for distributed development, IBM, 3 of 3 sou('~ 10M. eopyngnt
Intem800n81 Business MachInes coworatJon. repr1otl!(l with pmml$:Sloo. nttoJMww3.50ttwate Ibm.
webigWoeslGC3H5OO
THE TEAM SOFTWARE PROCESS
IBM RESPONSE n demand
omnlunl .
carion optIons for di . tributcd team mcmbe"
• Let users know which team members are available for collahoratlon through IOregrated presence awareness • PrOvide lOstant messaglOg fo r real . time, ~~on · to·person communication • Leverage browser·based confcre nci ng to share presentations and meeting materials
b.!,ty for all di para!e project membc~ to e· curdy conneCt to the team workplace through the intranet, Interner o r mob.!e devi es
• Enable full-featured browser-based a nd mobile access to presence , instant m saging and team spaces
Figure 7.16 (Contmued )
7.4 THE TEAM SOFTWARE PROCESS Te.am s avoid reinventing procedures thar arc common to everal sohwan: devci opment proJects- O rgan iza .
tions create procedures or gUi delines in adva nce for tea ms to apply . \'(fans Humphrey's Tm., Soj,","" Proem '" CTSP) [3] does this in a detailed manner. The TSP proVIdes gllidance to gTOUpS o n each of the prole t development phases aftcr requirements analysis. Humphrey has reponed encollraglng re lilt in estabhshlng matunty goa ls and procedures for software teamwork. The objective of [he T P are sho wn In Figures 7. 17 and 7. 18. Whether or not a team uses the TSP, much can be learned from It. TSP share, ,everal charactenstlcs with agile teams, sllch as the autonomy of teams . TSP is heaVIl y metric·oriented , and alt houg h ag .!e me th ods are not, they do take seri ousl y the velocIty measure. The TSP's emphaSIS on team inillative and bottom -up interacllo n encourages an In r<'ased degree of profe sionalism among so ftware eng inee r For exa mpl e, H umphrey Slates that it is unprofcs<1 o nal fo r enginee~ to prOVIde management with sc hedules that ca nno t be accomplished , cvt'n ,,,he n requested to do so. He counsels negotiation In such a sitllatl o n The phdosophy here IS sllll1lar to that for agdc project'
• Build self·dlrec ted tea m ~ • 3-20 c ngln ce~ • establtsh 0'''' goa l\ • es tabltsh ow. process a nd plans • track work •
how manager\ how 10 rn anagt: (came;
• <-oaeh • motrvaLe
• sustain peak perforllla" e
figure 7,17 Objectives of the Team SOftware Process, 1 of 2 SotHt;B GfIlPh'Cl r8Qfodu'~ 'HIm r~ f,om COt
I
151
152
CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT
•
cierate • make
MM Improveme nt
/\'IM 5 "normal"
• · Provlde Improvement 8U1de llnes to hi gh-maturity organizations"
• "Facilitate university teachin g of industrlal .grade teams" Figure 7.18 Objectives of the Team Software Process, 2 of 2
Professlo nalt sm, Humphrey reminds us, involves an oblt ga tio n to Serve society responsib ly, In addition to serving employers Also nOleworthy is the TSP's emphaSIS o n " oaching" by managemen t external to the team. Managemcrrl I expected not simply to give orders and specify deadl ines, but to provide guidance, tools, and ot her required resources In this respect, TSP is beller able to handle teams with varyi ng degre'!s of experience and kills. T Pi orga ni zed around Iterations of the waterfall sequence; It requires that the team "launch" each iteration at a mee ting where a number of predeAncd Issues are addressed. Humphrey provid(~ numerous detailed scripts and checkl ists to support the TSP. Figure 7. 19 su mmarizes these points regarding TSP The phases can be iterated severa l limes, requiring several launches. Launch is lies to be settled are shown in Figure 7.20. Humphrey recommends that the items listed in Figure 7.21 be produced by each phase launch. Much of thi is covered by procedures and IEEE documents discu"ed in this book .
7 .4 .1 Introductory Team Software Process (TSPi) Formal training for TSP is beyond the scope of a stude nt team working together during a softwa,e engineering course . For exa mple, it requires t he already extensive Personal Software Process. The TSPi is a sca led·dow n versio n of the TSP designed to At in an academic semester. The TSPi roles arc /tam ltadt!', drutlopmt>llmaHagtr. pla""",g maHagtr, quality/proem ",."ag" , and support "'all.g". In the TSPi the "support manager is responsib le for obtailling and 'upplying all the tools and environments, such as compiler., fo r ~xample. Humphrey describes a spcciRc emester.long schedule for the TSPi , consisting of three it~rations ( h~ ca ll s them "cycles") as hown in Figure 7.22 . The Idea of this schedule template is that data obtained from each cycle is used to estimate the metncs for the next cycle. Cycle 1 is comparatively long because it includes the team's first progression through th~ stages. It is intended to be a "minimal function workin!: subset of the final product." Cycle 3 is long enough to
• Team initiative • Bottom -up interaction
• Professionalism among software engineers • Negotiate schedules • Emphasis on "coaching" by management Provide guidance, tools . and other reqUired re ources • PartiCipants required to be PSP trained • Organized around iterations Each requires a "launc h" • Numerous detailed scripts Figure 7.19 TSP praC1ices
SOFTWARE PROJECT TOOLS AND TECHNIQUES
o o o
Process to be u cd QuaillY goal Manner 01 tracking quahty goa l
DHow tca m WIll make decision s
o
What to do if qua lity goals no t aHai ned o
o
What to do if plan no t approved o
o o
Fallback posHio ns
fallback positio ns
Define team ro les As isn tcam roles
Figure 7.20 ISSUes to senle at TSP launch Source. Humphrey. Watts S . "InUOCIuction to tfle Te.lm Software Prorv ss (The SEJ serk!:s reprodUCed WIth ptlllll ssaon from
iO
SOftware EngJneenng)." Ac1C!rSOO W """ey. 2000, P 496 GraphICS
wei
wrap up the job completely n, is Icaves a reiallvel y sho rt m,ddle cycle "Strategy" (phase t 01 an Ileralion ,n Figure 7.22 ) rerers to the overa ll way in wh"ICh th e team wdl go about budding Ihe cycle ,n ques ti on Th" requires a hi gh.levei discussio n 01 the requirements, a conceptual design, and an overall assembly plan For the components. The results are then made into the concre te plan (phase 2), the wnllen reqUirements (phase 3 ), and so on .
7.5 SOFTWARE PROJECT TOOLS AND TECHNIQUES Projec t manage rs and teams use a variety of 100is and techlll Q.ue to manage a soFtware proJect, such as A E tools, budd vs. buy decisions, language selectio n, deC ISion making w,th t"age , and the u e of project variables . Each is described In the sections that loll ow.
I. Writte n tea m goa ls
2. Defi ned team roles 3. Process development plan 4 Quality plan 5 Project' suppo rt plan co mputers, sofrware, per o onei , etc 6. Overall development plan and schedul e 7 Detailed plan lor each cng,neer 8. Projec t risk assessment 9 Project StalUS report Figure 7.21 Artifacts to be produced at launch .Sour", ~. Watts S. "",t/OOUCUOn to tJ1e- Tetam SOftware Proc: c ss CTh9 5£1serIeS N'1 Software EngJneenng)," AdOII5OI'j \~. 1tXIO. p. 496
1S3
154
HAPTER 7
PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT
Week
--
-
1 1 1 1 1 1
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 Delivery
Cycle 1 launch
• Cycle 2 launch
Milestones
<dele 3 launch
• I
1. Stralegy
2. Plan
Iteration 1
3. Requiremenls 4. Design 5. Implemenlalien 6. Tesl 7. PeSlmenem
Iteration 2
, I
Iteration 3
•
I
,
1. Stralegy ....
11. Slralegy.... I •
Figure 7.22 TSPI cycle structure (Humphrey) SOurce Humphrey, Watts S. "Introduction to the Team SOftware Process O'he Sfl Senes In Software Englneering>," Addison·WE '!"/. 2000. P 496
7.5.1 Tool Selection A numbe r of vendors e ll lools and e nviro nm e nts for he lping e ngi neers to devel op software applications These arc so me lim es referred to as computer·aided software engineering (CASE) loo ls, and o metlmcs as "integrated loo ls " to.·lany are packaged with o r connected wi th de velo pmenl environments such as Microsoft's VI ual Stud io Th ey ma y also be a coll ec li o n of tools obta ine d fro m unre lated ou rce Figure 7 23 lists some pos ible lools. They Include scheduli ng loo ls sllc h as M icrosoft Project . co nfigurat io n manage ment tools such as Sou rce Forge or C VS, requiremenl< manage ment lools uch as Rat io nal' Re qlllsitePro. design representation . t)' plca ll y With U ML too ls such a Borland' T ogether, code- budding tools like Am , and tesling Sllpport lOols sllch as Ralio nal's T estMa nager. Large projecls Si mpl y ca nnot be managed with out at leasl some of these co mpone nt ; In particular, configura tion manage ment too ls arc indispensable
chedulin g
•
•
•
•
•
•
•
•
•
Managing requirements
•
•
•
Drawing deSi gn especially UML
onfigll ralion management
• • •
Code build
• • •
Testing te st case manage ment automation
Figure 7.23 Potential CASE 1001 components .soc.vu. Graphics reprOd!JC8CJ wu:n p; e:mission 'rom cent
TOOlS AND TECHNIQUES
BUi1dcosl ! Bwcosl
Comments multi-year costs nol accounted for
- : : : : thousands)
Supplies
$ 0
•••••••••••••••••••••••••••••••••••••
• ••••••••
FirSI-jlerson perspeclive $ 5
$40
••••••••••••••••• ••• •••••••••••• •••••• • ••• • • •••••••••••• • •••••••
$ 0
•••••••••••••• •• •••••• • ••••• ••• • ••••• ••••••••• •••••••••••••••••
3-D
$10
Putchase Ajax engine
$ 1
Ajax
has Ihis fealure
. ............................................ "
Cuslomlze Ajax applicalion
•••••••• • •••• ••• ••••• •••••••••••••••• • ••••••• • • ••• ••••••• • ••••• • ••••••••• ••• ••••••••••••• •••••••• • •••• ••••••••
Lighl refleclion
$15
$10
TOTALS
$30
$51
"""
Cuslomize Ajax applicallon
•
BuI Id, do not buy
Figure 7.24 Example of build vs. buy decision making for a video game graphics engine
7.5.2 Build or Buy Decisions Tools and applications Ihal promise to help or form Ihe basi. for new applicalion are often available For example, in planning for a Web ·based auclion app lication , we would compare the purchase of ready ·made auction software with developing our own app licalion fTOm scralch Typicall y, we delay thcse deci ions untd the requirements are known, bUI they arc discussed here si nce Ihey are a part of proje I management A rational manner for approaching Ihis kind of decision is 10 make a IIsl of expenses and to eSllnlale the magnitude of each alternative. An example is shown in Figure 7.24 , ",hich iiiustraies the decislon ·making process concerning the purchase of Ihe (hypothetical ) Ajax graphics sofrware thai would help us enhance Ihe graphics of our video game. Figure 7.24 reduce'S [he decision to a comparison of numbers, which is a common way of deciding among altemarives. In other words, II computes the bottom line wllh and withoul purchasing Apx' sofrware. It breaks oul the relevant desired graphics features and estimates Ihe co I of cacho Ajax Implement> Feanlre I. firsl.person perspective, completely (i .e , conlinually d, plays Ihe view of Ihe scenc fTOm Ihe player's perspectIve). On Ihe Ofher hand, Ajax does nOI do a complele Job of handling 3·D (Feature 2), so we WIll have to pro&""m 10 compensate for Ihis. Finally, we need light rcnrclion (Feature 3), where the scene gives Ihe impression of a lIght sOllrce shinIng onlo ilfrom a si ngle direction. Ajax helps here, but we will have 10 perfoml considerable programming to make II work The ",ble in Figure 7.24 could be an appendix to Ihe projcci plan or Ihe Software Design Document. A more realistic version of the lable would com l>are Ihe com on a muillycar ba IS, and wou ld In lude mainltnan e expenses. The more features we are reqUired to implemenl ourselves, the less attracllve Ihe purchase Many deciSIon ca n be framed in a cost compamon form like tillS Mamlalning a wnllen re ord of deciSIons such as quanlilative budd -or· buy trade·offs helps In commlllll aling Ihesc decI> lons to Ihe learn and oth~rs . The form can be refined and updaled as more mforma lio n becomes known , and II aIds postmortem and pfocess Improvemenl.
7.5.3 Language selection Allhough Ihe Identlficallon of an Impl ememallon language or language IS freque ntly a de I~n de I"on , lanljuagcs arc of len Idcnllf,ed ncar the belllnnlnK of Ihe prole I OI1lCl lmeS Ih,s dec ",on ",trJI!{hdo"".rd a< when Ihe organlZ3110n mandale, a I.nguag· , or whell a language" Ihe on ly one apoble of IInpit:menllllj.: Ih~
155
, S6
CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMEm
Factor
Bencftt of
Weight (t - / 0)
Iknefl! of Language 1 1 10 10 = besl
I to 10 = bHt
una....'
1
Internet -friendly
)
-
8
2
Familiarity to deve! ormcnt tea m
8
-
3
9
Compilatio n speed
s-
2
8
7
3
-3 .. 8 + -8 .. 3 + -5 • 2+
-3 * 2 + -8 .. 9 + -5 * 8+
,-
Runtime speed o n processo r p
Score
-1 * 7 =
65
1*3 = 121
-
--
Figure 7.25 Example of method for deciding language choice requirement . Sometimes, however, the implementation must be chosen from several alternallves. A common wa y to deCide among alternative is to first list the factors involved , and then to give factor each a weight (measure of 'Illponance). After that , each alternative I scored relative to each factor Calculations are then made that produce a total score for each alternative. Figur~ 7.25 shows examples of factors and weights that could enter onto suc h a de termination . The weig hts are faclOrs in arriving at the botlOm line . For example, the score fo r language I is 1. * 8 + J! .. 3 + .2. • 2 + ! .. 7 (weights underlined ). Dec' sion -making tab les such as this arc no t subs titutes for mabn g judg me nts, they merely decompose large deCISions (e g., wh at langua ge 10 c hoose) into smalle r o nes (e .g ., Java is mo re Web-friendly than C + +). Suc h decompositio ns provide mo rc s tabili ty , but th e conclusions that they provide are se nsitive to the weighting c hose n, the factors selec ted, and th e judgments made . Their results should be compared wi th commo n se n e co nclusio ns.
7.5.4 Decision Making with Triage Execu ting projects is frequently an overwhelmin g experience . For example , a "to do" list of wants and needs accumulates qUickly, g rows during the project more tha n it shrinks, a nd can easi ly induce a feeling of futility. The natural way to deal wi th this is to prioritize. A complete prioritization is frequently overwhelmed by events, h owever. For exa mple, if we have a list of 100 things to do , a nd time for probably only 20 of them, then It is a wa te of time to meticulously order all 100. Triag, can be useful for situations like this. Instead of a le ngth y decision process, triage requires o ne to make no more tha n two decisions about each item , as shown on Figure 7.26. O nce this has been performed, items from the "do at once" category a~
• Among top items in importance') If so, place it in
I
categoty
• Otherwise, could we ignore without substantially aHecrlng project} If so, place it in • Otherwise (do not spend decision time on this) Pia e in
category
Figure 7.26 using triage In project management
SOFTWARE PROJECT TOOLS AND TECHNIQUES
Number of ....eks before del/very
Schedule Quality
Number of
requirements
Cost Functionality
Defect count
Number of engineers
o
Figure 7.27 Variables available to the project manager
carried out unt il they are e xhauste d (if eve r). and the n we move o n to the middle list, and so o n. When necessary , items can be prioritized with in their category. The benefit of this is that little time is wasted In splitting hairs o r wonderi ng about the exact o rder of ac tio ns that wi ll never be performed . As reported in Bu,i"ts' W"k (4), for example, triage teams were used by Microsoft in combing through bug reports durin g the debugging of Windows™ 2000. Next , we consider what rools the project manager has at h and to steer his o r her prOject to success.
7.S.S project Variables To achieve project objectives, the project leader has fo ur va riables that conceivably can be manipulated.: co,t, schdul" q"ality. andju"ctio"ality. As Figure 7 .27 suggests, this is something of a balanCing act, because there are man y trade·offs among these four attributes . For example, if the project leade r is asked to spend less time producing the application (affecting sch,dul, ), he or she has to negotiate for reduced requirements (affecting j,,"cllo"ality ), Increased defect expectations (affecting quality ), or inc reased labor (affecting co,t; assum ing that mo re people ca n be used effectively) in order to offset the reduced time. Project management deals constantly with trade ·offs among these va riables. T o make the best decisions, we quantify these trade·offs whenever we ca n. One wa y to VISualize them is by means of a "bulls ·eye" di agra m, suggested for this purpose by Humphrey. In a bulls·eye dia gra m, each of the va riables IS plotted by means of an axis originating at the cente r. This is s hown for the cost parameter in Fi gure 7 .28 . The axes are drawn symm e tric all y re lative to each o ther. In the bull s·eye d,a gram shown in Figure 7.29, there are four variables , so that they form 90· deg ree angles.
Parameter: Projected cost (S) Unfavorable
Iaroet : $70K ... __ .............. "_.. Favorable
MOIl teyprabl, : $OK ...... -.. ~
f1cure 7.28 IntrOductJon to bull·eye figure for project variables
157
158
CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I. ORGANI ZATION, TOOLS, AND RISK MANAGEMENT
, ProJocted cost ($)
... ' ...... - Tarael: $70K
Taraet: 100%
\ ...,\ Pro1ected , Projected I > '-00% (unct/onallty - - - ~S=8'itl;::'SIif.led5-+---~,..-- schedule ( % requirements (fatal weeks to saUsfied) ,.,.. _.., comp/ele) '.'.
\• Targel: 30 wl<s
Taraet: 4 defectsIKloc ... .................... . Projected quality (de/eel densllyj
I Figure 7.29 Bulls·eye framework example for project variables The va ria bles h ave to be arran ged so that o n eac h of th ese axes, th e origill is th e most favorablt va lue, and th e ta rget va lue , m ark ed o n eac h axis th e same di sta nce fro m the o rigi n, fo rm ing a quad ri latera l. (If there we re five va ria bles, they wo uld fo rm a regular pe ntago n, etc. ) Fo r example, o n the "projec te d functio nality' ax is, th e o rigi n de notes "man y mo re than the deSignated requirem e nts sa t,sfied ," while the unit mark represents " I 00% of the re qu ire ments sati sfied ." TI,e actual values co uld lie o utsid e the po lygon if they exceed goa ls, as shown in Figure 7.30 . The status o f a project can be visualized using the solid po lygon o bta ined by joining the values on the axes and fi lling ,n the res ulting polygo n. The m o re the resulting po lygo n li es within the Origi nal regular polygo n , the he alth,e r th e projec t . The example project sh o wn in Fi gu re 7 .30 f
• Projected cost
--- -----
Taraet100%
,
Acblfl:
•
.' ................... Target; $701<
90%
, •, ,
Projected' , (unctlonallty' - - - -
Aaa/: 1.5
ProJ«ted schedule
,,
---
•
,
•,
qu.llty
Figure 7.30 Bulls·eye figure for project variables on a particular project
---
Tal!!8\: 30 wI<s AIifwI: 20 . .
RISK MANAGEMENT
Organizational I . The team may not have the reqUired Java skills to exccute the job on time because several of them have no t used Java in a bus: ness environment. 2 . We ma y lose a team me mbe r. Technical 3.
An off-the-shelf database mana ge ment system may not be versatil e e nough to cover the types of operations required of a vIdeo store.
4.
We Intend to u e Web services, but no o ne in the team has used these before.
Figure 7.31 Example risks in video store a pplication
7.6 RISK MANAGEMENT All projects invo lve a degree of risk. These arc issues that ca n potentially cause problems such as a delay of the schedule o r increased project costs. Figure 7.3\ shows some risks from the video store example. We try to confront risks as soo n as possible rather than waiting fo r them to confront us in the proces of build ing the application . Th is is ca lled risk maun9"",,, I. and it consists of the activities in Figure 7 32 . Perhaps the hardest part of risk manageme nt is iden ti Rcatio n , because it requires imagining parts of the process that may not seem at first to harbor a ny risks. Once a risk is identified, it is important and vety useful to express the risk with as much precision as possible . For examp le, "a team member may get sick" is too vague a descriptio n. Much bette r would be "sick ti me will exceed the company norm by 50% due to an unu ual number of youn g parents in the team ." Figure 7 .33 illustrates a way to thinking about ri sks, It shows two obstacles to a project . We ge nera l.ly dea l with risks wi th o ne of two di fferen t stra tegies. They arc cOllq.usl (such a building a traffic ligh t at the roa d ) or nuoida"" (e.g ., routing the path around the h ouse). These two strategies arc Illustrated in Figure 7 .34 . Teams develop a plan to address eac h risk and assig n an individual who sees 10 it that the plan is carried out. The c halle nge here is to develop a concrete plan and avoid ge neral statem e nts such as "we will alil ea m Java: For exa mple , we ca n address the "inadequate Java ski lls" risk mentio ned in Figure 7.3 \ by conquest : 'Tom , Sue, a nd Jack wi ll pass level 2 Java cert inca tion by Dece mber 4 by attending a Super Education Serv.ces
I. Identify risks by imagini ng all worst -c ase sce narios: lasts for approxi matciy
Am thtrd of project.
2. Analyze each risk to understand it potential impact on the project. 3. Typically too man y risks give n time . H e nce , prioritize .dentiAed risks
lO
e nable foc u on most enou .
4. In dealing with each risk, c hoos< to conquer or avoid it. Co nquering 0 risk mea n In vesti ga ting it and takIng action so thac the eve nt docs not mate rialize Avo ldin\;\ mea ns c h angi ng plans so that the I sue never occurs.
5 F,nally , develop a pla n to retire each ri k
Figure 7.32 The main risk management activities
159
160
CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I' ORGANIZATION. TOOLS, AND RISK MANAGEMENT
Risk 2: House blocks path
Risk t: Road blocks path •
••
•
• • • •
Project start Figure 7.33 Retirement by conquest or avoidance risk examples SOurce CraPhlcs reproduced wrtn J)efmlsslon rrom Corel
Intermed iate Java cour ·e." Alterna ti vely, the risk can be retired by avo idance: "Use C ++ instead of Java" (assuming that the team is skilled In C+ +). A reti rement strategy for the "Web services know ledge immature' risk IS to set up a couple of sa mple Web services and write access code for key Video store functions that use them . If the resu lts are satisfactory, we will have empl oyed risk reti rement by conquest. Table 7. 1 illustrate o ne way to perrOm) risk prioritization . First , the risks the mselves shou ld be deSCribed fully . The priority de pends o n fac to rs such as the likelih ood of the risk and the seriousness of its impact on the project. A h,gh,prlorit y task has a low.pri ority ",,,.lur because people usually rerer to their "highest priOrity" a priority number I The more expe nsive it is to deal with a risk. the lower its priority. In particular, when managing a risk becomes a very large amou nt of work, we may be better off not working on it
2. Retirement by avoidance
Risk 1
1. Retirement by conquest
Figure 7.34 Retirement by conquest or avoidance SOcxee GraohJC:S reorOCluced wltn pc:.j.lkslon from COf~
Table 7.1 A way to perform risk prioritization ~
No. Title
Estimated likelihood of occurring (L : l · l0 with 1 low est IIke-lihood)
Estimated impact (1:1· 10 with 1 lowest Impact)
Estimated cost of managing (M: l-l0 with 1 lowest cost)
priority number (lowest number handled first) Retirement Responsible (11 - L) . (1, - n . M plan person
1
Insufficient Java skills: See note 1
8
9
9
3 . 2 . 9 = 54
See note 3
Jared
2
WebSeMces immature: See note 2
3
7
2
8 , 4·2 = 64
See note 4
Jen
•
•
Target
completlon date 10/ 15
8/3
•
'"-
V>
"
3:
i
m
3: m
!i
...... ...
162
CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I; ORGANIZATION. TOOLS, AND RISK MANAGEMENT
In ad an ~ at all, but simpl y dealing wllh the ,,'ue In volved when It aCluaJl y arlS", I or exa mple. If the o nly wa to anticipate a mk "to Om li1J t an expen Ive Imulatlo n, thell we may simply have to acce pt the risk Note I 11,c n
7.7 STUDENT TEAM GUIDANCE: ORGANIZING THE SOFTWARE PROJECT'S MANAGEMENT This section describes how the student team o rganizes for the development task, prOVide a hypot het ical account of interactions among students, and gUides students in producing a Software Project Management Plan.
7.7 .1 Team Guidance
Student Team Organization
Student teams are usually organized as peers. T o make pecr teams effective. the team leader encourages consensus but keeps the chedule firmly in mind, making clear and timely deCisions when requi red. In ruden! teams, team leaders tend to mtervene too "ttle. Meeting drag 00 unreaso nabl y in the quest for consensus or agreement , and the team leader is not experienced enough to make a resoluti o n. Being Arm Without alienating team members is a valuable skill. A ke y to this IS en uring that team members' opi nions are respectedwhether adopted o r not. Fi gure 7.35 lists the steps for orga nizing a team . particularly a student team . One effective management arrangement for a team is to pair up developers by haVIng them work together some-or even all-of the time. The lalter is called pair programmi"g . Another way is to deSignate team members as leads for the project phases with a backup for cach oT ypi ca ll y, the lead and the backup work together, o r the backup serves as a continual in pector. ready to take over the lead role If necessary The project arrangement shown in Figure 7.36 is deSigned to make each perso n the backup fo r the actiVity on which his or her primary activity is dependent. Once a projec t leader has settled the procedural aspect< of team organization . it IS time to consider what really counts with team members: how they feel about what they are doing. If a person belongs to a motivated and well -organized team . he will probably enJoy his work and the team wtll probably produ e a good product. People are motivated when they are respected and arc engaged in an activity that the feel ennch them . Part of each member's Job is to create those conditions for himself and others The project leader creates a well -organized project by settmg schedules and limits, with the team' as=ment. In partl ular. when it comes to meetings the issues In Figure 7.37 can be u
STUDENT TEAM GUIDANCE: ORGANIZING THE SOFlWARE PROJECT'S MANAGEMENT
I.
Sdect team leader. Responsibi lllies: o o
e n ure that all project aspects are a tive All all gaps
2. Designate leader roles and document responsibilities. team leader: proposes and maintains . SPMP configuration manageme nt leader: ... S MP qualoty assurance leader: . .. SOAP. STP requirement manage ment leader: ... SR.S design leader: .. SDD implementation leader: . " cod, bas, 3. Specify leaders' responsibilities . o
propose a straw-man artifact (e .g., SRS, design)
o
seek team enhancement and acceptance
o
ensure that deSignated artifact is maintained and o bserved
o
maintain corresponding metrics if applicable
4. Designate a backup for each Icadcr Figure 7.35 One way to organize a team
individual. If no significant change is observed in that person's behavior after about a week, the proJect leader should confirm th ~ team's concern and th en di scuss th e issue with the instructor. Instruc tors will either remove the individual from the team or discuss wa ys to app o rti on credit accordingl y.
7.7.2 Team Guidance Team Meetings One activity regularly requircd of project managers is to hold meetings. Figure 7 38 lists som e good mee tin g practices from which all team members can benefit. The ite m s marked with a si ng le asrensk sho uld be perfo rmed before the meetIn g . Since gro ups are not particularly good at c reatin g artifacts from sc ratch (especially designs ). it is far better for someo ne to bring to the meetin g a tentative ("straw · man") ve rsio n of the artifact to form the ba sis fo r di scussi on . For example , the design leader brings a t
backs
up ...
Team leader Configuration management leader Ouality assurance leader Requirements management leader Design leader ImplementaJlon leader
Figure 7.36 A wwy to back up leaders within a learn
163
162
CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I; ORGANIZATION, TOOLS, AND RISK MANAGEMENT
In ad an e at all , but '1"'1 Iy deallnll wIth the IS~ue involv d when It a tuall y aro \e, I' or example, 01 the only wa to antIcipate a ri>k i, to co n,lO~1 tan expemive ,imu lation , lhen we ma y ~ Impl y ha ve to aLeepl the r"k. Note I The rosk 0< that the leam duc, nOt have enough ,k oll, n java 10 handle the programmIng requored by tillS proJe t wIthin the lime requIred N o te 2. TI,e ri k I that a lthoullh Web erv lce lechno lollY "a good ChOILl', tec hnIcally spcak,ng, It IS new to the Industry at the tIme of thIS prolect , and ItS Immaturoty ma y reatc dolf'c ult,e, N o te 3. jen, Os ar, an d Alf ho uld pa,s level twO java c
7.7 STUDENT TEAM GUIDANCE: ORGANIZING THE SOFTWARE PROJECT'S MANAGEMENT This section describes how the student team o rganizes for the development task, prOVIdes a hypothetic
7.7.1 Team Guidance
StudentTeam Organization
Student teams are u uall y o rga nized as peers. T o make peer teams effective, the team leader encourages consensus but keeps the sc hedule Rrmly in mind, making clear and timciy deciSIons when required . In tudent teams, team leaders tend to intervene too little . Meetings drag o n unreaso nably in the quest fo r con ensus or agreement, and the team leader i not expe rienced e noug h to make a resolutio n. BeIng Rrm without al,enating team me mbers is a valuable skill. A key to thi s is e nsurong that team members' opi ni o n ane respectedwhether adopted or not. Figure 7.35 lists the steps for o rga niZ Ing a team , partIcularly a student team . One effective manageme nt arrangement for a tea011 IS to paor up developers by haVI ng them work together some or even all of the time. The latter is ailed pnir progmml.i"9 . Anot her way is to designate team me mbers as leads for the projec t phases with a backup for each . TypIcally, the lead and the ba kup work togethe r, o r the backup se rves as a continual inspector, ready to take over the lead role If necessary. The project arrangement shown in Figure 7.36 is desig ned to make each person the backup for the actIvity on which hi s o r her primary activity is de pe ndent. Once a project leader has settled the procedural aspects of team orga nization , it is time 10 con Ider what really counts with team members, how they feci about what they arc doing If a person belong to a motivated and well·organized team , he will probably enjoy his work and the team will probably produce a good product. People arc motIvated when they arc respected and arc e ngaged In an activit that the ' feel enriches them. Part of each member's Job is to create those conditions fo r hIm elf and others. The proJe t lead« crcates a well ·orga nized project by sellIng schedules and limits, with thc Icam's agreement In partIcular, when it o ones to mee tings the issues in Figure 737 ca n be usefu l In the case of student leams, ""tv'" (o"'/lb""o" i, often . majOr problem · som~ team member> m3\' fc-el that a member IS not contributing enough . A team member who feds th" wav ,hould dISCU<, the I su~ WIth the project leader If there is ge ne ral agreement about tl"', the proje t leader ,hould spea ~ provatcl ' to the
STUDENT TEAM GUIDANCE: ORGANIZING THE SOFlWARE PROJEcrS MANAGEMENT
I. Sd«t [cam leader.
Rcspons,b,l i tics: o o
en . ure that all prOject a pects arc active fill all gaps
2. Designate leade r roles and document responsi bilities. team leader. proposrs and 'MI"la;., .. . SPMP configur
3. Spedfy leaders' responsibilities . o
pro pose a str
o
seck team e nhan eme nt and acceptance
o
ensure that designated artifact is mai ntai ned and ob erved
o
maiorain correspond ing me trics if app licable
4. Desi gnate a backup fo r each leader Figure 7.35 One way to organize a team
individual. If no significant change is o bserved in th at person's be hav,o r aft r about a week , the prOject leader should confiml the team's co ncern a nd the n d,scuss the issue with the Instructo r Instructors will either remove the Ind ivi dual fro m the team o r di cus ways to apportion cred it accordingl y
7.7.2 Team Guidance Team Meetings One activity re gularl y req uired of project mana gers is to hold meetings. Figure 7.38 list some good meeting prac tices fro m which all tea m members ca n benefit. The items marke d with a si ng le asteri sk sh ould be performed before the meeting. Ince groups are not partic ul a rl y good at creating artifacts from sc ratch (e peCiafly designs ), it is far better for omeone to bring to the meeting a tentative {"st raw . man"} versio n of the artifact to form th e basis for d iSCUSS io n. For exa mple , th e d e ign leader brings a tentallve design , o r the team leader brin gs a tentative work breakdown. The ve r ion s h ou ld no t be overly speCific , because there must be plenty of room for input b y the me mbers.
Team leader Configuration management leader Quality assurance teader backs
up .. ,
Requirements management leader Design leader ImplemenlaUon leader
Figure 7.36 A way to back up leaders within a team
'63
,~
CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT
• Develop an . genda In ~dva n ce of mec lIn g, with everyo n 's 'I!rccmenl. • SCt lime limits (or meeting a a whole and for each a!le nda item . Allow exIra lc n or Aft.en mInutes for unanll clpated Items. • Designate SO meone to tak e minutes, ilt Icas t for a l ion i tems.
• At mcetll' g, begin by brieOy reviewing the age nda a nd tIme limits. • De,ill na le o meonc
10
walch lime and warn of time lim ils.
• Insist o n o ne person speaking at a time . Listen to people, even if their idea seem ourrageous. (Probably aren't ) • Move unproductive d i cu sions offline. Figure 7.37 Planning and conducting meetings
Man meeting participants, but especially students, compla in that meetings last too long WIthout acco mphshing e nough. \'(rhe n the approximate time fo r discussio ns is ag reed to in advance, however, members tend to focus o n th e issues te be resolved, and meetings ca n be quite effective. Decid ing when to all ow (urt he r discussion and whe n to break il o ff is a duly of Ihe learn leader. The keys to doing this are whether the discu sion is productive, and whether lhe discussion of the present topic is preventing the di scussio n of more impo rta nr o nes, g iven the time remaining. II is al so the leader's task to ensure that the discu sion remallls focused and that a conclusion is reac hed. At times, the leader must step in and make a decisio n, because co nsc n us is nOI always possible. The member recordin g ac tion items also records decisions take n. Th,s should generall y be do ne 111 a crisp form-minutes are meant primarily to remind everyone of the decisio ns made. I. "DistrIbute Start time, e nd time, and agenda with approxi mate times. o
li st impo rtant items fi rst .
2. ·Ensure that "straw ·man" Ite ms arc pre pared . 3. Slart o n time 4 . H ave somco ne record action items.t 5. Have someo ne track time and prompt membe rs. 6. eet agreement o n the age nda and timing . 7. Watc h timin g throughout, and end on time. o
Allow exceptio ns for important d iscussio n.
o
StOP excessive discussio n; take ofAine.
8. Keep d iscussio n o n the subject. 9. ··E ·mail ac tion items and decision summary.
·in advance o f mCelln!!
lactions membe" must perform
Figure 7.38 Team guidance team meetings
··aflcr meetlO l!
SUMMARY • I . (;(,t agreement on agenda and time allo atlon
2. (;(,t volunteers to: ... record dcci ions laken and actIon items . .. watch time and prompt members 3. Repon progres on project schedule _ 4. Discus strawman artifact( ) 5. Discuss risk retirement -
•
10 tnUl
x mill
fO min
6 . , 7., ... < more agenda items> (I nclude metrics and ['rocess improvement]) n Review acrion items
5 mUl
F'lgUre 7.39 Specifying agendas
One good management practIce is to create and follow agendas for meetings. Some items, such as concise status reviews, arc almost always appropriate. Risk retirement (cove red in Section 10.4 ) sho uld be a mandatory agenda item at most meetings during the first third of the project. Metrics and process improvement are sometimes appropriate topics. These are discussed after a phase has been completed, not necessarily at every meeting. An examp le of a generic age nda is shown in Figure 7.39.
7,8 SUMMARY Software project management is the process of planning, o rganizing , and mo nitonng the deve lopme nt of a software project from inception to completion . A project is typically headed by a project manager, who IS responsible for the daily project activities. Companies can be organized in severa l different ways, each havin g an effect o n how a project team is organized and run . In a projtct-arir>lttd organization , people arc organized around the projects of the compan y. Every employee is assigned to a proJect, which is their primary focus. In aJ"ncilon-aritlltrd organizati o n, people ~long to a functional group such a.s marketing or sohwar-e development. Each functional gro up has its own projects centered around their area of responsibility. Managers assume the ro le of project managers A mnlnx organization is a cross between project· a nd function ·orien ted organizations. Employees belong to a functional group (e .g ., marketing , engineering) and are loaned to projects based o n their cxpertise They directly repon to their functional manager, who is responsible for directl y supervisi ng the m Thcy also indirectly repon to the project manager, who IS respo nsible for the daily actiVIties of the project. The size of a project team has a direct effect on the success of a project. Team that arc large ca n d ivide tht work into manageable pans, However, large teams have the dIsadvantage of requiring communication that IS time -consuming and error· prone_ Expenence shows that the optimal number of people WIth whom a person needs to interact with o n a regular basis hould norma ll y be between three and eight. Not all prOject tcams arc colloca ted W,th the advent of lIs'"g rem ote developers , project teams ma y be split across conti nents Th, s is known as off hOrlng . There arc many advantages to u ing remote tcams, IIc h as COSt savi ngs and the benefh of qu.),ty work . H owever, the re a rc di sadvanta ges to be over o me, slic h as time zone differences, cu ltural differences, and potential communIcatio n ddn lIltles. Se tting lip reglliar fa <' · W· lace m«tmgs and having strong o n 'Slte manageme nt arc key elements to mak,n g offshOring work . SM Watts Humphrey's Ttam oJllQart Procm (TSP ) deAnes a
165
166
CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT!. ORGANIZATION, TOOLS, AND RISK MANAGEMENT
in n:" , ed dcl!'"cc of rrofe",onall<11l among 'oftW"I'C enHineers . A.. an c~am pl , Humphrey stale. that It IS lInprofes 'ional forengin ccrs 10 provi d~ managemenl wil h ,e hedul e.that ca nnot be accompl,shed , even when ,..,que,ted to do so. ProJe t m""ager and team< carry Out many lask< a, part of Ihelr job, 'ncludlng project scheduling, onhguration management , reqUirement< man.gement, drawIIlH de"gns, building code, and testing As mu,h as po
7.9 EXERCISES I. a. De cribe in your own wo rds the st.ructure of a project.based organization , and explain how it promote the successfu l delivery of software. b. Name twO lo ng· term disadvantages of a project-based o rga nization. 2. a. Describe in you r own words the structure of a function·based o rganization , and explain how it promotes the successhtl ddivery of softwa re. b. Name two lo ng. te rm disadvantages of a hillctlo n·based orga ni zation. 3. a. Describe in yo", own words the structu re of a matrix organization , and explain how it promotes the successfu l delivery of software b. Name two lo ng·tem, disadvantages of a matrix organization . 4. Write a paragraph explaining why adding people to a project docs not ne essaril schedule and may worsen it .
Imp ro~
•
It
5. Co nsider a project team you have been a m ~ mber of, either as part of a student leam Or in industry De'cribe the o rga nization of Ihe tcam, and des ribe in sufAc ient detail two a peets th~t worked well and two that did no t work well 6. Consider a softwa re prOjec t under devel op m ~ nt , with half of the e n 8 lnc~rs In one \lOle zone and the o th er half in another time zone twelve hou rs away H ow would 011 recomm .. nd the pro)CCt
BIBUOGRAPHY
t~am be organized) Describe two challeng~ that need to be overcome due to the time.zone
difference.
7. a. Explain how a bulls·eye diagram can help visualize the progress of a software project. b. Suppose you are managing a project that has the following goals, ·Cost: lOOK · Schedule, 12 months · Quality , 12 defeetslKloc . Fun·e tionality, 90% requirements implemented Draw a bull -· eye diagram that shows on ly one of these goals being met or exceeded. 8. Why plan for risk identiAcation and retirem ent when developing a project plan) In a paragraph or two, answer thi s in your own words.
9. Describe a kind of project under which risk identiAeation and retircment would pro bably off. Explain.
"01
pay
10. Suppose that your team IS tasked to implement a system that provides Web· based books. l1,e application is intended to execute on desktops, be downioadable, and be automallcally upgraded over time via the Internet. You arc to assume the following · i. The team includes employees who are based at a new offshore Site. ii . The application is to be rcady in a month . iii . Preliminary plans call for a Java implementation on a PC model that is due 10 amve in two weeks. No one in the team is ,.ell versed in Java . They all know C. + we ll. You arc concerned about the risks associated with items (i) and (II i) above. Explain the kinds of risks these are , your speCific responses, and the kind of soluti on YOll arc propo ing. II. You have been tasked to build a ystem for managi ng online DVD rentals. Descri be four plausib le
risks and indicate how you would retire them. Be as concrete as possi ble in describi ng the ri sks
BIBUOGRAPHY I Heldman, Kim. "PMP P'O)'C1 !vt4M#Cfflml Pro/mlo",,' Exam Sillily CIl/dr," SybexlWll t'y Publ lshlO~ Inc .. 2007 p. 17. 2 8rooh. Frederick P., '7bt My/b,eDI A-tan·M01'Irh Essays on SojlWilte Ett9,"cmn9. Altnll'crsary EJ,hon Addl;;on.\X!c<;ley . 1995 3 Humphrey , Walts S .. "1,.,,011111, 110" 10 ,bt Tcom Soilll'llft Proem (1lH Sfl Smd '" ojllN " E"9t"(m"'9'~" Addl ..on · \'(I~lcy, 1000, p 496 .. Iht' MOlht'r of All So hwilrc Pro,ec ls,· BIA.5i"lH \Vuk, Fc:bnlJry 22 . 1999
167
principles of Software project Management II: Estimation, Scheduling, and Planning
....nnlng
The Software Development LIfe Cycle
•
How do you estimate the cost of a sohware Job?
•
What are good ways to go about creating a project schedule?
•
What does a Sohware Project Management Plan look fike?
•
How are prOjects planned in practice?
•
What are good ways for student teams to plan their proJects?
Figure 8.1 The context and learning goals for this chapter
This chapter explaIns the methods that prOject managers use to e timate the ost. of a prOject and way to
COST ESTIMATION
1.1 COST ESTIMATION The proc:<:sS of esrimating project co
(i.e., for Axed ca pabilitle , quality level , and schedule) often starts at the inception of a projcct and continues even after coding has begun . There are severa l speciAc techniques used to estimare cost that are described in the following sections. Before doing so, however, let's examine how plecise we can expect such estimates to be. fS
8.1.1 Estimate Precision When a project is ini riated , the team ca n typicall y have o nl y a vague idea o f its cost. TI,e more we learn about the requirements for the product and the more desig n we perforn1 , the more precise we ca n be about its cost. This is illustrated in Figure 8.2. Since complete precision is a practical Impossibility in most cases, a range is a good way to express projected cost. There is always a need to estimate a 'ball park range" from a summary requiremenfs statement , hence the cost estimation following conceptualization shown in Figure 8.2. Our assumption here is that the goa l consists of auaining a set of capabi lilles rather than starti ng With a fixed amount and asking what capabilities ca n be implemented for that amo unt (a related but different process). The fourfold <sri mation error shown in Figure 8.2 is from a study reported by Boehm [ 11. For an application that will eventuall y cost $ 100,000, for example, estimates made after the application's concept has been developed can be as low as $25,000 and as high as $400,0001We use various techniques to sharpen our esti mate of a project's cost as earl y as possible , which amounts to reducing the height of the vertical lines In Figure 8.2. O nly at the latter e nd of implementation can we have complete confidence in our estimates. (The estimates are far less useful at that time, h oweve r, si nce most of the fu nds will a lready ha ve been spen!!) It puzzles some people that we ca n eve n begin to think about the costs of a project without detailed requirement.s , but this is a common practice in o the r Acids. For exampl e, one can gain a ro ugh estimate of the cost of building a h ouse without any desig n or detailed requirements. One can use rules of thumb such as
$4
Rough range of cost estimates after _ - - - <'(lOceptualization phase. Assumes evenlual, actual cost of $1 ConceptualIzation phase
$1
$3
$.25
_ _ Requirements analysis
I
$1
Design
I
Rough range 01 cost estimates a ller requirements analysis $2
I
$1
Implementation I lntegrationITeat
Fleure • .2 Range of error in estlmatlng costs narrows as the project progresses
I•
169
170
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING
"" u,e, In th IS area O,t about $ 100 per "ll'are foo t to budd: dnd so J I ,C)OO. ,(]uare. foot house w.II c.ost about $ 100,000 A good way to appro. " proje t cost estima ti o n at the very early sta~e' of a project IS to develop c,t ima te in severa l independe nt way, a nd the n combin e th e re
8.1.2 Estimation Methods Cost esti mation methods fo r agile projec ts, described in ectio n 8. 1.6, focu o n esti mating rhe upcoming itera tio n ("sprin t" in scnlm te rn,s), based o n its requ ired user story o r stories, as well as experience from past itera tio ns. These arc small ·sca le estimates but it is part and parcel of the agil e philosophy that large projects arc composed of sma ll deliveries. Now let's turn 10 estimatio n of projects in the la rge that are not necessarily agi le in whole or in part. Whether o r not o ne actually uses the methods described, they do contain many hard ·won ideas that ca n be con figured for various situations, including variations in ag de estimation . Figure 8.3 sho ws a typical road map for the earl y estimatio n of project co t a nd duratio n. The next section shows an example of the usc of lines of code and past projects. The function point methodo logy and COCOMO (Construc tive Cost Model) are explained below.
8.1.3 Estimating Lines of Code without Function Points This section discusses ways to estimate lines o f code at a very earl y stage, well before any design has been performed. O nce desig n work is performed , the me thods are based o n the parts of the design and become far more precise, as ind icated in Figu re 8.2. Several estimation methods , no tabl y the COCOMO and COCOMO II model , de pe nd o n the number of lines of code. "COCO MO " stands for Boeh m's "Constnlc tive Cost Mo del" [ 1]. At the very earl y stages of a project . COCOMO may not sou nd very useful because coding is a long way off when o ne is in the project planning stage . By compari ng the product with other products, however, esti mating hnes of code may well be feasible . For example, we could estimate that our current sate li ite co ntTOI job is comparable to our last satellite job, which requi red 3 millio n hnes o f FORTRAN . H owever, our currenr job has the add itio nal requirement of being able to mo nito r hurricanes. It may be possi ble to roughly e timate the ize of th is additional piece based on other hurrica ne trackers (700,000 lines of FORTRAN , for example). When impicmentation languages change, mdustry ·standard language conversio n factors arc used.
I. Usc comparisons with past Jobs to e timate cost and duration d irectly or to estimate line of code and / or Use function point metho d to estimate lines of code.
i.
Compute unadjusted function points.
ii.
Apply adjustment process.
2. Use lines of code estimates to compute labor and duratio n usmS
Figure •. 3 A roadmap for estimating the cost of a software project
(II) fo nmula .
COST ESTIMATION
Orglniutions wonting above Cap;lbillty Maturity Models level I must be able to record the person hours Ind duntion of the pans of jobs. In the ab ence 01 such data, we would have to compare our Encounter "dec Illme, for "xample, with other game . It is difficult, impossible even, to obtain data directly from comp;lnles other than one's own, although trade publications and general industry studIes sometimes provide pI~1 data. For example, we may know from industry announcements that "BugEye Inc." has worked on its rw: iI same for two years, The announcement may even mention a number of programmers. Such data is suspect, however, sin e companies regard their development knowledge as a corporate asset, and commonly or underrepon numbers as the case may be. In the absence of historical data , it may be necessary to compare the project with related projects, (simulations, lor example, in the ca e of our video game). Let's say that we have very little experience programming gam~, and some experience programming simulations and Java. Our lines-aI-code estimation may have to be something like the follOWing : lance wrote a nongraphical simularoon of a simple queue in C. + , which required about 4-8 pages of code_ At about 30-50 non -comment lines pcr page, this totals 120 400 lines. We will assume that Java requires the same number of lines. The first commercial release of Encounter has 4-15 such queu~ and 30-90 additional components of comparable size to make It interesting, so that yields between [( 120 lines) x ( 34 components)] minimum and [(400 lines) x ( 105 components)] maximum as our range, or approximately 5,000 to 42 ,000 lines of code. The use of graphics multiplies the effon by 1.5 to 4, depending on the degree of sophistication , so this gives us a range 01 1.5 x 5, 000 to 4 x 42 , 000 = 7 .5 to 170 K-lines (thousands of lines) of code. (NoI" The case study in this book encompasses a prototype. which is far less ambitious than Ihe version o n which this estimate is based.) By documenting such data o n a spreadsheet, we establish a baseline, and we ca n then sharpen our estimates as the project goes forward . Note that the range 7 .5 to 170 K-lines is consistent With Figure 8.2, in which a 16-fold range in es timate is expected at the conceptualization stage. The preceding calculation is a bottom -up approximation , sillce it estimates the cost of the whole from the cost of the pans. An example of a top -down approximation follows , lIsi ng indu try data (or, preferabl y, historica l data from the organization performing the work). Suppose we know that a very good video game required the servIces 01 5-20 expert programmers for 1- 2 years. Since we can invest only 1/ 10 of the amount that was invested on that ga me , we WIll assu me that ours will ha ve about 1/ 10 of its ca rability. A suming 5-25 lines of (fully testedl) Java code per day, this yields ( 1/ 10 capability of th,,(amous game) x (5 - 25 lines per day ) x (5 - 20 programmers) X ( I - 2 years) X( 48 - 50 weeks pcr year) x ( 35 - 60 hOllrs per week ) ~ 4_2 - 300 K - lines of code This range is different from the bottom -up «timate obta illed previously , but it helps to grollnd our ideas about the job'~ magnitude, Since the method" ed this lime is quite different . Free estimation tools, 'u h a, those at www.con
8_1,4 Function Points SUrtlllg In 1 ~79 WIth All recht (2 ), th e mo re (undame nt,,1 nOli on OfJ""Cllo" pO;III. wa> developed to assess the size of a prOject Without ha Ving to kno w II, de
171
'72
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II; ESTIMATION, SCHEDUUNG, AND PlANNING
durat.on by cOl1l parison with th e fun t.on pOint values 0 1 ot her proJects . Functton POtllts arc a\tra<.t.ve .n oncept , s",ec they try to /let to the hcan 0 1 a future produc l" ca pability H owever, It take. a grcat deal of rra ti e to appl y them in an accura te and o", .Stcnt manner
8.1.4.1 Calculating Function Points Funerion pOint calculat. o n compri ses th ~ following teps '
Function Point Step 1 Ide nttfy th e luncltons (e .g ., "retrieve ," "dISplay") th at the app lica t.o n must have. The Inte rn a ti o nal Function Point U ers Croup (lFP U C ; ee [3)) has published c riteria as to what constitutes a "fu nct .on" of an applicat.on in th is e n e . TI, ey consider user-le vel functiona lity, rather than programming -level functions as in C Typically , a function is the equivalent of processing a scr ee n o r form on the mo nito r. For o ur role-playing vi deo ga me prototype , for example, we ca n .dentify the followi ng fun ctions. I
e t up the c harac ter representing the playe r.
2 . Encounter a rorelgn character.
Function Point Step 2 For each such function , compute its funct io n point co ntribution from the sources shown in Figure 8.4 The followi ng summarizes the sensc o f each contributing factor. The g uidelines have to be carefully fo ll owed , otherwise it is hard to o btain consistent estimates . • Exlmlal j"puls, O nl y inputs th at affect the function in a differe nt way fro m each othe r are counted as sepa rate . Thus, a funct.on of an application th at subtrac ts two numbers would have EI = I , no t EI = 2. On the o ther hand , if the character A ca n be input to req uest an addition and S for subtraction, these would contribu te 2 to EI. • Exl,,,,"1 ou lpuls, Only o utputs that account to r true eparate algo rithm .c o r no ntrivial funct io na lities should be counted . For exampl e , a process that o utputs a charac ter in several font would be counted as I ; ellor
External Inquiries (EIN)
~ ~
Function •
Internal Log;",,' Fifes (ILF)'
•
LagIcII
cf
External OUlpuls (EO)
External Inpuls
File
Figure 8.4 Function point computation for a single function SOtJrC.t' IluemaUof\ll Ful'lCtlol'l PoInt Usen Group. nUp'JMww.lfpug 0fJ
, Internal logical grouping of user data into files
COST ESTIMATION
PARAMETER
imple
Ext. inputs El Ext. outputs EO
• • •
)(
Ext. inquiries ElN
)(
Complex
J
or
•
•
•
or
• •
•
J
or
•
•
7
or
· .. 5
or
•
• • •
6 :
5 or
• • •
7 :
6 :
4 or
•
•
•
•
4 or
•
•
•
10 or
•
•
Int. logical files lLF
)(
Ext. logical Ales ELF ) (
•
•
"
7 or
15 : .. 10 = _
Count Total
I I I I I I
I I I I I I
Figure 8.5 Function point computations (IFPUG)
messages are not counted . Chart representatio ns of data are counted as 2 ( I fo r the data and I for the formatting ). and data sent to separate nontrivial destinati o ns (e.g ., printer) (3).
• Ext""al inquiry: Each independent inquiry is counted as I. • Inttmal logical files : This counts each unique logica l group of user data crea ted by or mainta ined by the application . Combi nati o ns of suc h logica l g roupings arc not counted; each functional area of the application dealing with a unique logical grouping increases the count by o ne.
• Extmsallogical files: This counts each unique gro uping of data o n fi les external to the app hca lio n.
Function Point Step 3 As shown in Figure 8.5, each o f these parameter values IS the n fac to red by a numbe r, depend ing o n the degree of complexity of the parameter in the applica ti o n . IFPUG [3) has publi sh ed derailed description of the mean ing of · simple" and "complex" in this context. Applying this process to the two selec ted functions of the Encounter video game me nti o ned above, we obtain the s preadsheet tables shown in Figures 8.6 and 8.7 . These fig ure arc hi ghl y pre liminary , but the y do beglO to provide estimate parameters for the job . The lo tal unadj usted func tio n point e limat e for th ese twO Encounter fun c tio ns is 25
+
16 = 41 .
Function Point Step 4 Next , one computes weights for the fOllrteen ge nera l hara tcristlcs of th e project. ea h bct"'een 0 and This is shown for the twO selected Encounter funclions in Figures 8.8 and 8 9 . \Vlc have actually u cd a range for tach o( these to reAe t our cu rre nt uncertainty abou t the ap pl ica tio n. O ncc again , It takes on iste nt expenence 10 assc~s the appropria le values for th e e variab le . For example, fa to r 6 a
173
174
CHAPTER & PRINCIPLES OF SOFTWARE PROIECT MANAGEMENT II : ESTIMATION, SCHEDUUNG, AND PLANNING
Ext. Inputs
olm'
Factor
COInI'
I
3
I
Nmn,
comm.,nts:
Co mp/eK
S"b-
(ormt
Faclor
lolal,
1
6
13
MedlulII
Imp/"
Foclor
Qualities
Ready/ move
Ext. outputs
o
4
o
Ext. inquirks
o
3
Int . logical Ales
I
7
o o
5
10
Total
o
7
o
o
6
o
o
15
7
o
10
5
25
Data about the user's c haracter
comments:
Ext. inl.,rface Rles
o
5
I
7
Data about the user's character
comments :
Figure 8.6 Unadjusted function point computation for first Encounter functions: "Set up player character."
Medium
Simp/It
Complex
S"b-
(D util
factor
CO lmt
Factor
counl
Factor
lolal,
Ext. inputs
o
3
o
.
o
6
o
Ext. outputs
1
.
o
5
o
7
,
o
6
o
o
15
7
o
10
5
R,porf
co," mtHts;
Oil
",,,/I,
Ext. inquiri.,s
o
3
o
Inl. logical Ales
f
7
o
Ext. inr.,rface RI"$ COIII""" I, 011
10
Data about flu user's charnelcr
commel1ts:
-
Total
f
s
o
7
aba., /'" .,"', cbaracttr
Figure 8.7 Unadjusted function point computation for Orst Encounter functions: " Encounter foreign character."
16
COST EST1MATION
Incldenlal
Average
EssenliBi
0----- 1----- 2 ----- 3 --___ 4 _____ 5 None
Moderale
Significant
Ca" Study
1. Req uires backup/ recovery7 2_ Data communicattons required, 3. Distributed processi ng functIOns ' 4. Performance critical , 5. Run on existing heaVil y utihzed environmenO 6. Requi res online dara entry' 7. Multiple screens for input'
0-2 0- .
o ]-4
0- .
5
' -5
(co""",ud) Figure B.B General characteristics for function point adjustment. numbers 1-7
Function Point Step 5 Fi nally , th e (adjusted) function point total is ca!culated by the formula shown in Figure 8 10 This equation tates that if there are no special demands at all on the apphcatlon ( tora l ge neral characteristics = 0 ), then the fu nction poinr mea ure should be sca led down from the unadjusted (raw ) score by 35 % (whIch explains the ' 0 .65") . Otherwise the measure should be caled up from the unadjusted amount by o ne percentage po int for each general characteristic unit. For the case study, a reasonable allocation of ge neral cha rac tenstics is shown In Figures S.8 and 8 9 . The total value of these is between 24 and 43 , so the Rnal (i.e ., adjusted) funct Io n poi nt computati o n IS 41
X
[0.65 +0.0 1
X
(24 to 41 )] = 41
X
[0.89 to 1.06] ", 36 t0 43
8.1.4.2 Converting Function Points to Lines of Code Once accurately obtained. function poi nts arc very useful. For example, they can be used a ompariso n met rics. allowing organizations to estimate jobs based o n function point mernes of previou Jobs. They can be converted to lines of code using tandard tables. lines of code can then be used to estimate total effort In person- months as well as duration (see the next section o n COCOMO ). For example, [4] estimates 5 3 hncs of Java source per function poi nt. Using th is factor for the Encounter example, we anticipate Average
Incidental
0----- 1 None
Essenlial
2 ----- 3----- 4 ----- 5 Moderale
Signlficanl
8. Master fields updated online, 9. Inputs, outputs , inquiries of Rle complex' 10. Internal processing complex II Code designed for reuse? 12. ConversIon and installation included? 13 Multiple installatIon in d.rfcrent organizatIons? 14. Must facliitate c hange and ease of usc by use r?
Case Study ]-.
,- 2 .-]
2- ' 0-2
1-3
'-5
figure B.9 General characteristics for function point adjustment numbers 8- 14
17 5
176
CHAPTER S PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING
(Adjustcd) Fun tio n Points = (UnJdju,tcd fun ction pOints] X [0.65 + 0.0 I X ( lolal gcnera l charac teri stics)] Figure 8.10 computation o( adjusted (unction points
(361044 ) 53"" 1. 9 - 2.3 K-Hne of Java source As expecled , thi s is much lower than the previous estimates of -\.2 -300 and 7.5· 170 K-lines of Java source. This is true because " applies to o nl y two "function s' for Encounler, whereas the larger e limale were for a full game.
8.1.4.3 A Further Function Point Example Let's consider a system that tracks Video rentals. We will conRne the appJ.cali o n to a cus tomer-oriented appl icatio n, in which customers rent videos and need informalion about availability. \VIe assume that the application requires two Poles only, o ne for custo mers and a second for videos. The unadjusted functi o n po int computation is as shown in Figure 8. 1 I . Now we estimate the adjus tment faclors , as shown in Figure 8 . 12 , yielding a "General Characteristics' total of 35 .
Medium
Simple
Ext. inputs
Sub·
cotmt
factor
COUIII
factor
COllttl
factor
lolal,
2
3
f
4
o
6
/0
Na ..t , pi,. , Ext. outputs
Complex
o
4
Tolal
Vidto dala 5
I
o
7
5
Amosml dut
Ext. inquiries
o
3
o
Int. logica l files
2
-
Customers, Videos
Ext. interface Ales
6
10
o
15
..
7
o
10
o
Jl
Availability
- ncpla""'io",
ncplaoallO"
o
f
o
7
s
o
Figure 8.11 Unadjusted (unctlon point scores (or vide store example
COST ESTIMATION
None
tncidental
0---1
Moderats
A vs"'ge
Significant
Essential
2---3---4
1. Requires backup/recovery' ... ... ............ .. ...... .. . 2. Data communications required' .......... ....... ... . 3. Distributed processing functions' .... ..... ...... .. . 4 . Performance critical, •• • •• • •••• •• • • • • • • • • • • • • • • • • • • • • • • • • • 5. Run on existing heavily utilized environment7 6. Requires online data entry' . .... ... .. ................. . 7. Multiple screens for inpun ..... ..... .. ... ... ... ...... . 8 . Master fidds updated online' ... .... .. .. ............ . . 9. Inputs, outputs, inquiries of files complex, .... . 10. Internal processi ng complexL ... ............. ... '" I I. Code designed for reuse' .......... ... .... .... ... .. . . 12. Conversion and installation included' .... .... . . 13. Multiple installation in different o'lls ., .... .. .. . 14. Must facilitate change case of usc h y user' .. .
5
•
0
0 )
, 5 )
5
2
,
3 3 3 2
Tolal 35
Figure 8.12 FP adjustment fa ctors for video store example
The Function Point formu la gives Function points = [unadjusted fu nction points] x [0.65 = 33 x [0.65 + 0.0 1 x 35 ] - 33
+ 0.01
x (total general characterIStics )]
This yie lds 33 x 53 = 1, 749 lines of no n-comm ented source lines of Java code . The function point method is summed up by Capers Jones in [5], a practiced advocate of function pOInt applicatio n. See also [6 ].
8.1.5 Estimating Effort and Duration from Lines of Code O nce lines of code have been estima ted , either throug h use of historical data, by companson to related projects, or via function points, they can be used to estimate labor reqUIrements and prOject duratIon uSIng Barry Boehm's COCOMO model [ I) COCOMO is based o~ the idea that project outcomes, plo tted as graphs, have a consistent basic shape A para meterized formula is found for the shape, so that to obtain the graph for a particular project, he si mpl y has to detemline the parameters fo r it.
8.1.5.1 COCOMO I Boehm observed that the labor required to develop applicatIons tends to in rea e faster than the applicalto n's SIZC. He found In his init Ial rc earch that the exponentIal fun Iton, WIth exponent close to 1.12. expresses thIS rtlationship quite well Boehm's model also says that the duratIon tncreases exponentia lly \ IIh the erfon , but WIth an exponent less than 1 (the exponent used III th , case is clo e to 0 35 ). Th,s rell t, the observalto n that .fter. c;.,n.atn sIze (the "knec' In curvc (2)), additional reqUIred effort ha on ly a gradual lengthenIng effect on th~ time It takes to complete the project TI,CSC are illustrated In F,gure 8 13, wher~ L ",ho n for "Iine< of ode '
1n
178
CHAPTER 8 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT II: esnMATloN, SCHEOUUNG, AND PLANNING
(1 ) ellort' lor Increasing LDC , '2 (y _ 3.. . ) ~
(2) Duration lor Increasi ng ellort' (y _ 2.5 .. 0.35)
,
Exponent < 1 > 1
Applies to design through Integrlll/on lind testing ' Ellort = total person-months required Figure 8.13 Meaning of the COCOMO formulas Source Boehm., Barry. " Sol tware EngIneerIng EconomIcs," Prentice Hall, 1981
U lng data fro m num erous projects, Roehm estimated the parameters fo r these re latio nsh ips, assuming an e xponential re lations hip. H is fo rmulas arc illustrated in Figure 8. I 4 . In this system, organic applications an: stand-alone applicatio ns suc h as classica l (i.e ., no n -Web-enabled ) word processors or our Encounter case study . Embrddrd applicati o ns are integral to h ardware -softwa re sys tems (e .g ., an anti lock braking system). S""idew hed apphcatio n arc in between . A Web-enabled Encou nter, for example , is semi -detac hed: it is not o rganic , but neither is it as heavi ly e mbedded as the code in an antilock braking system, for example. En counter would commU ni cate with the Inte rnet via signals that are o nly occasiona l when compared with the frequency o f C PU Instruc tion execu tio n. Boehm's mo del says r,rst that the required effort and durat ion ha ve separa te models (fo rmulas) fo r each ty pe o f appli cat ion (differing in factors a and b). For examp le, a sta nd-alone job with 20,000 lines of code would take 2.4 x 20 1.05 '" -I person -mo nths duratio n if organic (stand -alone) but about 3.6 x 20 1.2'" 76 person-mo nth if e mbedded _ The duration formu la ca n be expressed directly 111 te rms of line of code (KLOC) as follows: l
Duration = c x Effon = c x (a
X
KLOCb)J = c x
i
X
KLOCIJ
At nrst glance, Boehm's duration fo rmu la may appear strange because the relations h ip between effort and duration seems to be simpler than his form ula indicates. For example, If we kn ow that a job ,..,quills 120
Effo rt in Person-months = a Duration = c x Effort'
Software Project
a
-
b -
c-
Organic Sem i ·detached Embedded
2.4 3.0 3.6
1.05 I. I 2 1.20
2.5 2.5 2.5
FIgure 8.14 Original COCOMO I formulas SolKco Bco'1m, BatTy. "SOftware Englneetlng Economics," P,oouat Hall.. 1981 ,
X
KLOC
d0 .38 0.35 0.32
COST ESTlMAnON
pc:r.;on .months, and we put ten people onto it, won't it get done in 12 months? This would indeed be the Ca3e if we could usefully and con istently employ all 10 people on the project from day 1 through day 365 , but this is not usually possible Consider, for example , day 1 Since all the engineer.; can't know much about the project (it has just begun ), what u dill activities could all ten engineers do that day; It follows that if we allocate 10 engineer.; (Tom the first day , the 120 per.;on .mo nth job w,1I actually take longer than 12 month . Boehm's duration fonnula has the strange property of being Independent of the number of people put on the jobllt depends only On the size of the job. Actually, the formula assumes that the prOject Will have roughly an appropriate number of people available to it at any given time (for example, one on day I , th irty on day 100, assuming that is what's needed). Boehm's model , whi h has been tested extensively and is widely respected , has been refined over time, and has been largely updated with the more complex CO OMO II , described next. A great deal of practice is required to use even COCOMO I effectively. It i< best used along With an independent method and a healthy dose of common sense (sometime called a "saOity c heck") . U"ng Boehm's basic formula on the prototype ver.;ion of Encounter (conSISting of two basic hIOction ), With 4· 300 K·hne. of code, we obtain 10 to 1,000 pcr.;on.months of effort , and 6 to 35 months in duration, as shown in Figure 8 15.
8.1.5.2 COCOMO II COCOMO (I ) is somewhat identified with the Watcrfall process because it does not speCifically account for iterative development. It mu t be used anew for each iteration , and docs not account for factors such a whether the iteration is early or late in the process. For this rca on and others, Boehm updated it to COCOMO II. (See, for example, httpi/sunset.usc edulresearch/ COCOMO IIl) The n of COCMO I can be interpreted as a scaling factor. COCOMO II replaces it with a product of various scaling factors F F" SF" " SF <, and SF, . This al lows for a more refined set of parameters. The b parameter In COCOMO I expressed the number of times KLOC is multipl ied . CO COMO II replaces thIS with a product of seventcen quantillc EM ,
-a
K -
b
-
approx. nK" b
Effort LO
2.4
4.2
1.05
10
HI
2.4
300
1.05
1000
c
P
d -
approx.
-
-
cP" d
Du~lion
LO
2.5
10
0 .38
HI
2.5
1000
0 .38
Flaure ' ,15 using COCOMO I to estimate the magnitude of the Encounter effort
6
179
180
CHAPTER 8
PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT II: ESTIMAnON, SCHEDULING, AND PLANNING
Effort In Person ,mo nth s
=
{I
X
n,
,'?EM,
L,
w here n = 1.0 I + I' SF, EM, ore multiplica ti ve cost dnvers SF, a rc sca ling cost dri ver Figure 8,16 Basic COCOMO II Formula SOUrce Boehm, Barry. " SO/tw;lfC ErlS'lncerlng Economics," Prentice Hall, 1981 . httP l/sunset uscec!U/researchlCOCOMOIV
(so eoch replace KLO in CO O M O I) These arc called l11ulliplica l,", co,1 d,,",,,, and they allow for m o r~ re~ nem c nt in dc>cribmg the produc t and project. The CO OMO II Effort fom1U l. is shown in Figure 8. 16. 11,e sym bol ] (cap ital p) is the product symbol For ex,mpl e, ,k' means I ' X 2' X 3' X 4' . Fi gure 8. 17 lists the ty pes of the quantities SF, and EM}' The SF, parame ter, for examp le, allows for fac tonng in the maturity o f the develo pment o rgani za ti o n. The SF, parameter allows for the degree of risk re maining in the projec t. The va lue o f SF. is hi gh for initial iterations a nd low for later ones The EM .. parameter account for the modern practice of developi ng in several physical locations. Each of th~ porametcrs has a de fi ned scale.
n:
8.1.6 Assessments for Agile projects: Story Points and velocity This eetion di scusses esti mation techniques for agi le projects . In o rder to commit to delivering capabil ity at the e nd o f a cycle , a team must assess th e effor! req uire d . As with fun c tion points, ,lory pOlnls are a means by which to measure the size of a story as it relates to implementation . Unlike function po ints, however, which attempt abso lute measure me nt, Sto ry points are a relative measure . In other words, they compare sto nes w ithin a project o nl y. Th e size ra ngc is typically betwee n I and 10, and the size of a Story is based on the team's hi story o f implementing stories in past cycles of the project. One way to establish story poi nts is to take a n executed story that the team considers to be average, assign it 5 story points , and use it as a yardstick (or fu ture stories . Another is to select a vcry small implemented story, count it as 1 point, and thcn calculate all o ther stories as multiples o( it . A mo re sophisticated way is to create a plot as shown in Figure 8. 18 . A big ad va ntage of agile meth od s is that they involve man y entire creation cycles. In a pure waterfall, team member find it difficult to estimate the size and completion time of a job because they will not usuall y have performed o ne just like thi s in the past, with the same participants. Agile methods, on the other hand , facilitate th e assessment of how much completed work a team is capable of producing by relying o n observed past performance within the same project. Recall that in physics, velOCity is defined as di,'a"ct co"md p" lime 'IIIil. Similarl y , agile project velocity is defined as the amolln l of fun "o"alily lilO' unil. This translates into story points per cycle. Assuming the constancy of cycle (e.g ., alway two weeks), the reliability of a ve locity calculatio n depe nds only o n the ability to accurately as ess story points With the ex perie nce o f repeatedly making thi s estimate, te om mcrease their estimation accuracy as the proJeCt prog resses. Sec Figure 8 . 19. As effective as this kind o( agi le estimation is, it requires augmentation when larger scale estimation i required. The reader is referred to ohn, Agilt Eslimaling and Planlling , Prent.ce Hall, for example, for further reading.
,."lta ""
COST ESTIMATION
Sym.
Abr.
SF,
PREC
Precendentedness
FLEX
Development Flex,bility
-
,...
,
SF, SF,
Name
-
, RESL
-
Architecture and Risk Resoluti on
SF.
TEAM
Team cohesion
SF,
PMAT
Process Maturity
-
EM ,
-
-
-
-
RELY
Required Software
DATA
Data Base Size
EM,
CPLX
Product Complexity
EM,
RUSE
Required Reusabili ty
EM,
DOCU
Documentation Match to life-cycle Needs
EM.
T IME
Time Constraint
EM,
STOR
Storage Constraint
EM .
PVOL
Pladonn Volat ility
EMg
ACAP
Analyst Capability
EM IO
PCAP
Programmer Capability
EM"
AEXP
Applications Experience
EM"
PEXP
Platfonn Experience
EM "
LTEX
Language and Tool Experience
EM
PCON
Pe ~o nncl
-
"
Cont inu ity
0>
T OOL
Use O f Software Tools
EM , 6
SITE
Multi ·Si te Development
EM 17
SCED
Required Development Schedule
EM
Fl&ure '
-
"
.17 Basic COCOMO II cost drfvers
~" 8OllYrl. Barry. ·'SQftwate Engineering ECOOOiTiJCS," Prentice HaJJ, 1981 , htlP IIS1Jnsetusc edlJ/reSoeNd'VCOCOM08I.
111
182
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II' ESTIMATION, SCHEDULING, AND PlANNING
10
Upper bound , Estimated size In story points • Actual size In person·hours
•
~
0
• 0
•
• 01
I
• • t , Com pule past e rror % 2. Estimale using compaMson , 3. factored by Irend in past errors % 0
1/
•
1
2
3
4
5
6
7
e
Cyclo number
Figure 8.18 Estimating story points
• DeAnitlOn , Number of story points the team ca n execute per cycle • Relies on history of perfonnance and consistcncy of story points a
\'qit hln this project and past ones
• Depe nds on accurate story poi nts Figure 8.19 Velocity in agile development
8.2 SCHEDULING Project estimates are used as input for co nstruc ting project sc/"d" I". Teams develop schedules so that everyone knows what to expect, ,. hat to do, and when to do it. Figures 8.20, 8.2 I , and 8 22 step through a tYPical schedule construction using a spread; heet . Substa ntial projects arc best' perfo nmed with specialized tools such as Microsoft Project . Softwa re project sched ul ing confro nts a fundamental c h icken .and·egg problem , as fo llows. Part of a software e ngi neering project is to ga ther the requi re ments but until we know the requirements fo r the application , we ca n't say h ow lo ng it will rake to do the job and so, strictly speaking , we can't schedule it. There are severa l approaches to breaking out of this loo p. One is t'o develop a sche dul e o nly afte, the req uireme nts ha ve been speciRed . Although thi is logical, it is no t often used. The main reasons fo r thi arc a follows , I. As me nti o ned befo re, it is usuall y imprac tical to specify all req uireme nts up fro nt.
2. Management uSllally needs to know llP front how much time the project will consume and how muc h it will cost. A common way to approach these issues is to begin With deadl ines and to ae am pi ish as mJn of the important requi reme nts as possible with the speClAcd time and Ananei.1 resources , and the n to i~rate this process. For the purposes of dIScussion, this is the approach used herc. The AT'i t step is to show the deadline for ddiverables to the cus to mer. In Ollr ca e , we wtll
I
I
T
I
I
Schedule for VideoStore Application
4-
January
1
t
t Milestones
2
February
3
4
1
2
1"
I I I
I I Ap ~1
March
3
Prototype X
4
1
2
3
X Freeze requirements
4
t
May
1
2
3
1
4
Final product X
I .
-- -
-
Figure 8.20 Building a schedule part I-setting milestones
1
l'i
~' -
2
3
4
- '" -
1
2
3
1
~
:r: m
Figure 8.21 Building a schedule Part II-shOWing phases
o C c z
Cl ~
e:
~
\:
2 ~
~
CD
4
4
1
2
"0
3
-z
;0
-
n
"0
f;;
V>
o."
~
~
;0 ITt
"0
e'" ITt
~
~
~ m
;::
ITt
1
1
11111
1
1
1
1 1
1 1
11111
I
1 1 1
1
1 1 1
~
1
4
--
"
1 -•
~ I ' I
I
~;:: -o~ z
•
~
I
ITt
g C Z
Figure 8.22 Building a schedule part III- showing work breakdown structure
'"
• ~
Z
o "0
~Z
-Z
'"
THE SOFTWARE PROJECT MANAGEMENT PlAN Oependendes: subset of schedule
Critical paths: sequences of dependencies
---., ---i-,
-
phise I dBHllled
'
- -
-
-
I
•
phue I delilled
--I --r-- -
-
,
phase II detailed
-
-
Figure 8.23 Dependerrcies shown in schedules
technique used in setti ng a sc hedule is to build in buffers to compensate for factors that we don't or can't know about. For example, our schedu le assumes four weeks per month , whICh provides at least o ne unscheduled week. This is shown in Figure 8.20. Some project managers frown on approaches like thi s because they hide things. Now we work backward from the mil estones to show the times for the various phases, as shown in Figure 8.21 . Finally , the team needs to ensure that people are availab le to do the work . This requires a work b".ktiown (WBS) showing who will do what work. Figure 8.22, for example, Includes a WBS In the example of Figure 8.22 , the last week of design requires Just o ne person and the first week of implementation requires twO eng,neers . Schedules show the intended o rder of tasks. 11 task A is schedu led to be performed prior to task 13, this docs not necessari ly imply that 13 depends o n A. For example, we may have selected the order because it i more convenie nt to perform task A befo re /J. However, if task X depends on ta k Y, then task Y should be scheduled to complete before task X begins, and the dependency should be made clear on th~ s hedu1c. We can denote dependencies o n a schedule, as show n In Figure 8.23 These become ,mportant whenever we want to aller the schedule. They are al so necessary in detennining the proJect's rillcnl pnl" : the sequence of activities that ",usl be performed, and the order in which they must be performed To ummarize: The dependencies form a subset of the schedul e, and the crit,ca l paths are seque nce of depend ... n ies
"ruc'u"
8,3 THE SOFTWARE PROJECT MANAGEMENT PLAN The prOject plan is docume nted <0 that everyone knows what to do and when to do ,t . There are many formats forsu h a plan. We will use IEEE Soltware Project Management Plan ( PMI') standard 105 · 1 98 for this purpose. TI,e table of contents for 1058 · 1998 I< show n in Figure 8 24 , and is used 111 the ca e ,tudy 111
115
186
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING
I Overview
/)
Tech nica l process plans
1. 1
Project ~ul1lrnary
6. I
Prote , model
I .2
Evo lution o f the S PMP
6 .2
Mellwds, lOols, and te hn lqucs
2 Refe re nces
3 Den nilions 4. Project organ iution
4. I 4 .2 4 .3
Exte rnal interfoces Internal struc ture Roles and responsib il ities
5 Ma nage rial p rocess p la ns 5 . I Projec t start·up plan 5 .2
W o rk plan
5.3
C ontrol plan
5 .4
Risk management p lan
5 .5
Project closeout plan
6.3 Inlras lruc lU'C plan 6.4
Produc t acceptance plan
7. Su ppor ti ng p rocess p lans 7 . I Configuration manage ment plan
7 .2
Verification and validation plan
7 .3
D ocumentation plan
7.4
Quali ty assuranc e plan
7.5
Reviews and audits plan
7 .6
Problem resolution p lan
7 .7
SubCOnl"raClOr man.gement plans
7 .8
Process improvement plan
8. Additio na l pla ns
Figure 8.24 IEEE 1058-1998 software Project Management Plan table of contents
Section 8.4 . The IEEE standard is someti mes viewed as belonging only to "document-heavy" projects. In fact , its parts should be used when and o nl y whe n they provide value . Agile project leaders can gain by perusing the topics and dec iding how a nd when the issue me ntioned is to be hand led . Non-agile projects are not bound to usc a ection unless the effort IS worth it. Prob lems arise w hen needed issues arc igno red and when docume ntation is used for no productive purpose. Section 1. 1 in the SPMP-the overview-sh ou ld ide ntify the project but should not cover its requireme nts (i.e ., descriptions of its behavio r). These arc cove red in the Software Requireme nts Specifica· tion , described in Part " of this book. Repeating th at materia l in the SP{\'IP would violate the principle of single· source documentation (to say each thing in one place only). Section 1.2 dcscrib", t he ways in which the SPMP itself is expected to grow a nd c hange. The Software Co nAguration Management Plan (SCMP) hould have been developed by th is ti me (see C hapter 6), so that versions of the SPMP can be properly controlled . A reference to the SCMP is provided here. Section 4. 1 describes the ways in which orga nl ZJtions wi ll co mmunicate with the development team This depends o n t he project's stakeho lders (the people w ho have an intere t in it). For example, how will engineering interface with marketing (regu lar meeti ngs, E-mail, etc .) Section 4.3 speeiAes the responsibili. tics of project personnel. Section 5.2, the Work Plan , caR co ntain the project's schedule. Section 5.3, the Control Plan, peciAes who will manage , con trol , andlor review the project, together with how and when this IS to be done. For example, sen io r management needs to know how projects arc progressing, so we would de. cnbe the process for keepi ng them informed here. Risk ma nagement (Section 5.4) was described in hapter 7. Constraints on the languages and tools used are provided in the "technical proce s plans: L"CtlOn 6 for exa mple, 'This project shalilisdava from Su n, versio n 1.2. 1, and Rational Rose versi,o n I: Section 6. 1 refers to the software development process to be u
CASE STUDY: ENCOUNTER PROJECT MANAGEMENT PLAN
In Section 7, the • upponing Process Plans references or dc:scnlxs activill'" that suppon the development process, such as configuration management and quality assurance. If the suppon function is descrilxd in separate documents (e .g ., the configuratIon manage ment plan or the quality plan ), we reference those document ·. Otherwise, We describe the upport hlnction In full. These and other aspects of the SPMP are explained fun her In the ca e study at the end of this pan of the book. The reader will find a ample SPMP for the Encounter cases study in SectIOn 8.4 of thIS chavter, wh,ch conforms to IEEE standard 1058· 1998 Excerpts from management documentatIon for the Eclipse and OpenOffice open source projects can be found in ections 8.5 and 8 6 res pectively. In compari ng them , the reader will notice the benefits of using a standard but also some of the limitallons in ncxlbility.
8.4 CASE STUDY: ENCOUNTER PROJECT MANAGEMENT PLAN The Software Project Management Plan for Encounter sh own in thIS section i based on IEEE
1. Overview
SId
1.1 project Summary
IOS8-199B
Slandard for Soflware Pro)tCI M"'''9''"''''
PI.ns. Figure 8 .24 is lhe table of content for the doc ume n t. Approvals
TItle
Signature
Date
Engineering Manager
!I. '}onI.>
7/ 15/ 04
QA Manager
£WiUn.
7/ 11104
Project Manager
a. ~.u jU
7/7/ 04
Author
£. !1J.tl uA~
7/ 1/ 04
Revision History Version I 1.0.0 E. Braun: Created first draft 6/ 1/98
Note to the Student: This should be at a hI g h enough level that 11 does not need to change milch over time. Derads should appear in sub equent sections, not this one. This summary should not substi· tute for any pan of the requirements document.
Thi s projecl is organized to produce a role· p laying video ga me called Encounter ThIS ga me will be developed in several stages Ince the customer intends to specify the requirements in
1.2 Evolution of the SPMP
1.1 .0 R. Chadwick: Revlewcd 1/ 1 1/99 I 1.1 E Braun: Expanded 3.2 1/ 19/99 1.2.0
R.
Chadwick: RevIewed for release 5/ 19/99
1.2 . 1 V Brahms: Final editing 4/ 30199
Versio n 2 2.00 E. Braun : Updated to 5/18/2004
1998 standard
Explai ns how and by whom this document will be maintained. It will have 10 be mo(hfied In severa l ways (e .g., with a more detailed schedule as more is known about the reqUlremc.-nts ). If a concrete plan is not Pllt In place to maintain this docum"nt, It will be worked on sporadically or not at all.
187
188
CHAPTER8 PRINCIPL 5 OF $OFlWAREPROJECTMANAGEMENT II: ESTIMATION. SCHEDULING. AND PlANNING SPMP = Softwa re Project M anagement Pla n (th is document ) SRS = o frwa re Requ irements pcci fi ca tio n SDD = o ftware De ign Document STP = Softw are T est Pla n tbd = ro be decided
h" docum ent wdl be m a '"t a ll, ~ d o n a wC('k ly h.
2. References 4 . project organization [IEEE) Th e appl. able IEEE standards are pub lished on "IEEE Standards Collecti on," 1997 edition. [MPA L5) Th.s document is to co nform to the company's "MaSler Pl an for the Attainment of CMM Level 5 " [Braude) l1,e princi pal source of textbook ref· erence matenal is 50fl.,ort E"gi""",'g , A" Objtcl-Onmltd PmptClovt by E. Braude (Wiley, 2000).
3 . Definitions
CI = Configuration Item CMM = Capa bility Ma turity Model, the SE I's model fo r o rganizationa l imp rovement IEEE = Institute of Electrica l and Electronics Engineers QA = Qua lity Assurance SEI = Software Engineering Institute, Pittsburgh , PA SCMP = Software Cor-figuration M anagement Plan
4.1 Externa l Interfaces Name the people and organizations with whom the team shou ld communicote. The projecttcam will interface with the fo llow. ing individuals and organizat ions, VP, Engi neering (for tech nical and standards direction), Marketing (for requi rements), Came Laboratory (for advanced game features). and the quality assurance engineer.
4.2 Internal structure Figure 8.25 shows the organ izati o n of the Encounter project within Camin g Industries Consolidated. The project will be organized as a team of peers with designated roles. The role are team leader, conRguratio n management leader, qual ity assurance leader. requirements management leader. design
President
I
VP Marketing
•"
VP Engineering
j"' I IV&V I I Soltware I Englneerlng
-
"
."
.
Labs
Game Lab
Game 123
Figure 8.25 Organization of Gaming Industries Consolidated
Encount. r
SOA
CASE STUDY: ENCOUNTER PROJECT MANAGEMENT PlAN
Team leader
Ualson
CM
QA
Leader
leader
VP Engineering
SPMP
Requiremcnts Manaaement Leader
Marketing
SCMI'
Responsibility
SQAP STP
Leader
Leader
Software • • engmecnng lab
SDD
SRS
Code base
Figure 8.26 Encounter project responsibilities
leader, and implementation leader. In addition . there are liaison roles to marketing and to the software engineering labora tory .
4.3 Roles and Responsibilities The responsibilities of the participants in the project are shown in Figure 8 .26. Being responsible for a doc ument Includes the following , • Making sure that the document is created on time • Having the team leader identify the writers of the document • Keeping the document up· to-date throughout the project life cycle
s. Managerial Process Plans
5.1 Project Startup Plan This seclion spc:cifles the planning activities thaI will be conducted once: the project is under way It IS i plan 10 conduct planning- . meta·plan, if you like.
5. 1. 1 Estimation Plan As a project progresses, our ability to estimate its cost and duration improve (but also become progressively less useful). This section explains when and how we intend to perform these •
•
estimations.
Estimations of prOject cost and duration Will be made following the specification of hi gh -level re o quirements (using funcroon poonts), detailed require · ments (uSing a method to be determined), and aftcr high- level design The latter estimates will be made by com pari o n with past projects Before beginnrng requirement analYSIS, we have estimated the size of this effort in three differ· ent ways: 1. Usin g an informal top·down e tim.te based on the expenence of team members With somewhat sim ilar p,oJects. 2. Usi ng a to p·down approximation with industry game development data. 3. USing fun tion pOint on two known function s, extrapolating to the cnllre application . The results are shown on Figure 8 27
,,,
'90
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDULING, AND PLANNING
Mini
( I)
Comment
Max 170
(2)
4.2
00
(3)
1 1.4
46
1.9 · 2.3 for two identified func ti ons, 6 ·20 times as many in comple te a pplication
Most conservative
1 1.4
300
Maximum o( minimums and maximum of maximums
Least conservative
4.2
46
Mini mum o f min im ums and minimum of maxi mums
Widest range
4.2
300
Minimum of min imums and maxi mum of maximums
-
Narrowest range
1 1.4
46
-
tvtaxi mum of min imum s and m inimum of maximums
Figure 8.27 Very rough estimate of application size prior to requirements analysis
There arc many ways of presenting this data, dependi ng on the needs of manageme nt and the development staff. So me of these are shown in Figure 8.27. In the absence of wrinen requirements, estimates are necessarily very rough. The estimates themselves can be an appendix to this document instead of he re within the body, and updated as the project progresses.
The reaso n fo r the very wide ran ge is tha t the figu res have been obta ined with negli gi ble interac· tio n wi th the customer.
5.1.2 Staffing Plan
Th e impleme ntation leader wil l e nsure that all team members arc supplied with the selected devel· opment environment within two weeks of project starr .
5.1.4 Project Staff Training Plan All staff me mbers whose Java profiCiency level is less than "advanced," as defi ned by the Ajax certification, will be trained by Uni versal Training Inc. courses wit hin the (irst mo nth of the project. The objective will be to attain advanced· level profiCiency.
5.2 Work Plan 5.2. 1 Work Activities
The ro les will be fi lle d as fo ll ows.
5.1.3 Resource Acquisition Plan This section indicates how resources will be obtained other than staff (computers, soft· ware, etc .)
ThIS sectio n specifies how the work will be subdivided . Th~ work o n th iS project w ill be diVide d inlO con Aguratio n manage me nt, qunlity a<surance (i n· eluding testi ng), reqUirements annl is, d", lgn, and
CASe STUDY: ENCOUNTER PROJECT MANAGEMENT PlAN
Leader
Fadlitator
Rc:sponslbilty
Report at wc:c:kly meeting
x
Marketing
QA
Game lab
Risk
liaison
liaison
liaison
retirement
x
x
x
Orculate wc:c:kly report Orculate biweekly report Orculatc: monthly report
I.
·Report forma ts 1
see CI 34 : "monthly project status fo rm"
2
sec CI 87: "mo nthly marketing status form "
3
see CI 344 : "weekly QA status form "
4
see CI 48 : "biweekl y game lab result form"
Figure 8.28 Program monitOring and control
Name Ed Braun
Team uader
CM uader
QA Leader
Requ . Mngmnt Leader
Implementation Leader
X
X X
AI Pruitt
X
Fern T ryfill
X
Hal Furnass
X
Karen Pders i.JailOn with
Design uader
VP Eng.
Rgure 8.29 StaHlng plan for Encounter
Marketing
Soft. Eng. Lab
'9'
192
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING
Monlh ,
, SCMP complete ,
-Mon,h 3
Monlh 2
2 3 4
,
2 3 4
,
,2 3 4
2 3 4 t 2 3 4
Begin system testIng ' , SOAP complete
Milestones
Month 5
Month 4
Delivery ,
, SPMP rei. , complete Freeze requirements ' Iteration'
, Iteration 2
Risk Identification and retirement
I
I Preg:. for maintenance
I
I
Figure 8.30 High·level chart of tasks with fixed delivery date, ordered by completion imp lementati on. The prOject roles and responslbili . ties are shown in Figure 8.26 .
5.2.2 Schedule Allocation 11 we are given a Axed completio n date and have identiAed the process that we will use, we may have enough Information to provide a high.level schedule. We increase the amount of detail in the schedule as more becomes known about the design. The schedule is shown in Figure 8.30. Refer to the SQAP for the schedule of quality activitIes.
5.2.3 Resource Allocation The work breakdown structure is shown in rlgure 8.31 . The bottom line shows t~e person · month available for each month . We have not yet pcrfonned any design, so it is too early to name the engineers who will work on speCific pam. These names will be added he~ after the designs for the various configu· rations have been detennined.
I
Ie , Including bc:ncAts
5.2.4 Budget Allocation The budget allocation, shown in Table S. I, matches the work breakdown structure shown in Figure 8.32, and includes an additional 10 percent to cover unantIcipated cOSts. Loaded I labor rates arc $4,000 per week.
5.3 Control Plan The IEEE describes this section as ' ",etria, reporting mechanisms, and contlol plocedlUcs necessary to measure, ~port, and conllol the product requirements, the project scheduk!, budget, resources, and the quality of worlt processes and work products.' It is usually advisable to schedule regular team meetings (typically weekly; sometimC!S short daily stand·up meetings). When there is no business to conduct, such meetings can easily be canceled. On the other hand, sched, uling a meeting on short notice m~y be when team members have other commitllknlS. Even teams that work to~ther every ~y need to schedule negular review meetings to avoid drifting. The meeting convener should __ mally cancel a meeting if there ~rc no qcncIa it~~lmIiS.
CASE STUDY: ENCOUNTER PROJECT MANAGEMENT PlAN
Month 1
- r-,--.--!1
2
3
4
1
Month 2
Month 3
Month 4
Month 5
- - ---.----.-+---.-....,..-,--+-.---.--.--1
234
1
234
1
234
1
234
SCMP Milestones
6
6
Complete testing
SQAP
6 Freeze requirements
SPMP rei. 1
6
Delivery
6
Iteration 1
Tasks
..... Risk I&R
Iteration 2 ....!.;;;"""""..............""'"
E. Braude
11111111111111111111
J . Pruitt
111111111111111111
F. Try1111
1111111111111
H. Fumass
111111111111
1111111
K. Peters
11111111
1111111
F. Smith (tech support)
.5 .5 .5 .5 .5 .5
TOTAL
~
.5 .5
.5 .5 .5 .5
~
.5 .5 .5 .5 .5 .5
5 . 55 . 55 . 55.55.55.55 . 54.54.54.54 . 54 . 54 . 54 . 54 . 54 . 54~3 . 5
F'1gUre 8.31 Work breakdown structure. excluding clerical work
The ~ ntire team w, lI meet at the begi nn,ng of ~ach phase (reqUire me nt s, d esig n, and imple me nta · tio n) within each it~rati o n . There w,lI be wee kl y project m~e t ing< on Tuesdays from 10:00 a.m. to noon. T ~am members are requested to keep Friday mornings from 9:00 a.m to I I :00 a.m. o pe n fo r an additio nal meet ing, in case suc h a meeting becomes
nece sary. The team leader wli l inform the team by Thursday at 4:30 p.m. if the lotter meeting is to take place .
5.3.1 Requirements Control Plan The req uirements leader will report to the project leader o n the status of the SRS in wnting each Tucsday.
5.3.2 Schedule Control Plan
Table 8 • 1 Budget allocation
T he project leade r wi ll report to the tea m o n the status of th e
Month Number
Allocation
1
596,800
2
S96,8oo
5.3.3 Budget Control Plan
3
S87,120
The rrojectlcader wi ll rcpurtto management on the
4
S87,120
5
S77,440
5.3.4 Quality Control Plan
Total
$445,280
T he A representallve wi ll I" v,de wnlten re f' rtto the manaR ' r QA , w llh copie. to th e proJ
nr
193
...• ~
'" ;!1 ""z
n -
•
RIsk Tide (details alven above)
likelihood 1-10 , . /east likely
Superi mpose
1
Impact 1- 10 , =/east
impact
3
""m Retirement Cost 1- 10
Priority (lowest
, =/owest cost
handled first)
1
8
10
numb~r
Retirement / Mitigation Plan
Responsible Engineer
Ta'llet Completion Date
a."
V>
a
~
'"
IT' -0
Expe rim e nt wi th Java images
P R-
1/99
images
'"-ma
<:l
:;::
Deficient Java skills
2
Alan Gray maybe pulled off th is project
3
6
9
7
3
80
8
288
9
H .T .. K.M .,V.I.,and L.D to Jttc nd trai ning course begin . ninS 1/5/99 at Ultra T rai ning Corp. obtai n Java level 2 certl nca tio" by 3/ 1/99 and leve l 3 ce rt ifica tI o n by 4/ 15/99
Susa n Ferns to
In Sp t::Cl
all of
H. L
4/ 15/99
> z
~
IT'
:;:: m
~
-m-
"
~ -
SF.
Continual
Ala,,'s work
:;:: -~
a z •
~ :r IT'
o C
•
• •
•
•
•
•
•
•
•
•
FIgure 8_32 sample risk analysis for Encounter case study
• • •
,
..
C
-
Z C>
-> Z
o
~z
-
a
CASE STUDY; ENCOUi'ITER PROJECT MANAGEMENT PlAN
kader, on a chcdule to be determined by the manager o f QA .
5.3.5 Reporting Plan The written repo rts referred to in this section (5.3) will be via e · mai l. Issue affecting human safe ty will be reported to all project personnel and managc . ment , regardless o f the plan in th is document.
and eve n if they are, we do no t know ho w lo ng it Will take to come up to speed. ThiS co uld dama ge the project irreparabl y. •
••
5.5 Project Closeout Plan Encou nte r will no t be ma intained and released be · yo nd 2006 A phase·out plan for the second half of 2006 wi ll be develo ped.
5.3.6 Metrics Collection Plan Sec the Software Quality Assurance Plan.
6. Technical Process Plans 5.4 Risk Management Elaborate on the risks a specific ''bad happen· ings·, do not leave as generic titles. For exam · pie, "deficient Java skills· by itself does not specify the issue. Perhaps the project can be performed adequately by a team whose Java skills have deficiencies.
Figure 8.32 shows a format for risk reporting and retirement. Each project meeting i to have an agenda item for risk identification brainsto rming and reporting o n risks that have been identified. Risk # I : "Superimpos in g images" co nce rns image manipulall o n In Java. Thi s is a reqUired capability, becau se characters have to move abo ut, superimposed on backg ro und image . No o ne in the team has experien ce with placing th e im age o f a character against a backg ro und witho ut carrying a rectan gle alon g with th e c harac ter. We do no t know whether th i is easy , difficult , o r impossi bl e to do. Ri sk N2: "De fic ie nt Java skill s" indicates the fact that 40 percent o f the team is no t suffi ci entl y skilled in Java to implem ent the movement and interactio n o f c haracte r ima ge . We anti ci pate th at it will also be necessary to sca le th e ga me e nvi ro n· ment , but no o ne o n th e team has any experience With th is. W e do no t know whethe r th e ca pabil it ies that our cu, to me r ha in mind are doable wlthJ ava ,
Here is where we describe the process to be used (waterfa ll , iterative, etc.).
6.1 Process Model Th e first two versio ns of this project wi ll be executed using a spiral develo pment process wi th an Itera tio n correspo nding to each versio n. The first iterat ion will be a wo rking pro to type but wi ll be fu ll y documented The seco nd iterati o n will result in versio n I of Encounter. The number of subsequent iteratio n and the naruro of versio n 1 arc to be decided afte r the custome r has witnessed a dcmo nsrratlo n
6.2 Methods, Tools, and Techniques The Encounter projec t will usc Rational Rose™ for design and will be Implemented In Java O bject. O rientatio n is to be used thro ugho ut. Javadoc wlil be used fo r documentatio n as mu h as possible (sec the SR fo r this requireme nt) Refer to ectlo n 2. 1 (process model) fo r a de cripti o n o f the process.
6.3 Infrastructure Plan The En o unto< team Will reqUire model 9 1234 P s, Internet access, 100 G il torage o n FeliX. and the Ajax team co llabo ra tio n applicatio n upport.
195
196
CHAPTER 8
PRINCIPLES OF SOFTWARE PROJECT MANAG M ENT II. ESTIMATION, SCHEDUUNG, AND PLANNING
"n plclllc ntcd for Ec l, ps T he , haded material Con.
6.4 Product Acceptance Plan
ECLIPSE DOCUMENTATION
" Ianageme nl and "We, lo r re pro,c ntat lves will r,nalIze acccp tan e c ntena ' \fit hill three weeks or proJcc t start A cp t. " cc tests w il l take p lace a t the M e office with", a wcek of the proJect comple tio n date .
T he ho me page for "pse documentation IS at "docuht tp j/www.ecli psc.org/eclipseh ndex.php me ntati on .' T h iS ",eludes use r manuals Documen tation IS classified as a subprojec t in Itself
7. Supporting Process Plans
Note to the Student: Documentat ion is so substantial that it is designated as a (sub )project unto itself.
Thi s section references plans supporti ng pro cesses that span the duration of the software project such as the SCMP, SVVP, a nd SQAP.
ORGANIZATION OF THE ECLIPSE PROJECT
8. Additional Plans N o ne
8.5 CASE STUDY: PROJECT MANAGEMENT IN ECLIPSE The material In thi s section is quoted , edited , or adapted fro m the Ecl ipse Web sites as the y existed at various pOints In time. It is no t a formal SPMP but rather a descript io n of h ow projec t m..na gement is
The Eclipse project conSISts of several 'TopLevel Projects_" A management committee is respo nsible fo r each of these . Each top-l~eI project consists of several (non -top-Ievel) projects. Each project has a project lead, the project p la ns, a nd the developme nt team _The developmen t team consists of developers and "committers." Only the latter have the authority to comm it artifacts to the baseline_ These are explai ned later in th is section . This is largely special to open source projects.
Sec Figure 8.33 for the project tructure_
Proposed Eclipse Project Structure and Roles Top Lovel Project B
Top Level Project A
Project 1
ProJOC'Ilead
Prole~
2
Project 3
Development Toam
Subsystem(s)
Comm.nors
Top Level Project C
Project Management Committee (PMC)
Project Plan
T"" lask2
T.... 3
Figure 8.33 EcJJpse proJeC1-ploposed structure and roles SOtNce: Ed.pose Protect. hltp'J IWWW ecJ~ org.IOr'gIOOCuIllE ntslECllpseS2(C s 'llocltnentYa2OProceS$1It202OOJ~ t 1_OK2QF~pdf
CASE STUDY: PROJECT MANAGEMENT IN ECUPSE
CHARTER FOR THE ECLIPSE TECHNOLOGY (TOP·lEVEl) PROJECT The "Eclipse Technology Project" diflers ITOm the "Eclips.... Project." The following document includes a description of project management in Eclipse. It is fou nd .t http-Jlec1,psc .org! technology/ technology -ch.rter.html and h.s been reform.tted and .nnotat .... d by the author. As described below, • project can migrate from being an "Eclips.... Technology Project" to being an .. Eclips .... Project: This "ch.rter" docume nt mainly d .... cribes organization .nd manag.... ment. Without committing this kind of thing to paper, there would be little c hance of a successful outcom .....
overview This is a good overview. It includes the overall motivation lor the project and, as with.1I good overviews, does not attempt to provide comple!e descriptions. It starts by providing the motivation for Eclipse.
The Eclipse Tec hn o logy Top-Level Project (the ' Eclipse T echnology Project") is an o pen source sofrware researc h and development proJec t. whi ch encapsulates three related activity streams. each of which is based o n or uses the Eclipse Platfom, andlor Eclipse Tool s: I. Academic research projec ts and o ther exploratory investiga ti ons ("Research Stream'), 2_ Development of educational matenals , tNc hing aids • and courseware ("Education Stream"), 3 Incubati on of smail -sca le . innovative platform and tools projects ("Incubators Stream").
small , informally structured prOjects that add new capabl),ties to the Eclipse software b.se (l ncub.tors Stream). fos ter gre.ter communtty .w.reness and underst.ndlng of Eclipse (Education Stream). or explore researc h ISsues in Eclipse -re levant dom.ins uc h as program m"'g I.nguage , tools, .nd development envlfo nments (Rese.rch Stream). The Eclipse T echno logy Project IS Inte nded to : I . Provide the o pen source commun ity with a
lighter-weig ht .Itern.tlve to the I.rger scale, more strucrured development activities carried out by othe r PMCs, .nd 2. C rea te o pportu nitte for rese.rc hers, ac.de mlcs, and educators to playa Significant ro le Within the Eclipsc com munity
Scope A "Scope" seClion in • docume nt often refers to the scope of the document itself, th.t is, the exte ntth.tthe document is intended to cover. Th.t is not the case here _ This section describes the scope of the .ctu.1 Eclipse Techno logy Project .
The scope of the Eclipse T ech nology Project Will encomp. s a Wide v.nety of small prOjects rather than a few large o nes. Although .ntlClp.tln g e no rmous diversity In the coment of these aClIvitle , from a process·oriented viewpoin t the y will all share important common characteristiCS, which argues (or a commo n management envelo pe:
• Focus on pr
MiSSion
• Sma ll teams
The mISsion of the Ec),pse Te hno logy Projec t IS to pruvlde a ho me With", the Ec),p>c Foundat io n for
• Rcsour e comm itm e nts te ntalt ve, due to vol unte~r labo r o r la k of ponsor funding
197
198
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II ESTIMATION, SCHEOUUNG, AND PLANNING
• I cvclopmc nt ol tcn ross·cuts the ~CO I)C o f <evera l o ther E Ilpse Foundation Proje ts
n,e
Eclipse T ec hno logy Pmjt t serves as a inSIe pOint of fo us for such teams, and provides the m wit h a h o me wllhin the Echpsc commuI1Ity . In man y cases uccessful Researc h Projects wi ll evo! c into IOcuintor
I
and Incubator.-. in turn ma y
migrate to oth er Projc 1 ManJgcmcnt
project Management Committee This section speciAes the Eclipse project man· agement by specifying the responsibilities of the project manageme nt committees.
The projects under thi s c harte r are managed by a group known as the Project Management Com· mittee PMCs are expected to e nsure that, • Each projec t opera tes effec ti vcly by providing leaders hip to gUide the project's overall direc tio n and by removing obstacles , solVing prob lems, and resolVing conAlcts. • All project plan s, tec hni cal documents, and repo rts are publicly available. • All projects operate usi ng o pe n source rules of meritocracy .
• Ensunng that prOjeL t plans arc produced. • WorklnS WIth the Eclipse Management Organlza . tion (the EMO ) to c'tabhsh the development processes a nd infrastructure nceded for the devd. opment team to be errective
o mmittecs
(PM s), ei ther by me rgi ng into an existing project, or by fo mllng the basi for a new o ne . . .
engagement:
rCl110vtng ob,r" 1«, so lVIng problem" and resolv. ing conflIcts.
tran sparency ,
and
open panicipation . These principles work to · gether. Anyone ca n panici pate in a project. This ope n Interaction, (Tom answerin g questions to
repon ing bugs to makIng code co ntributions to c reating dcsig n~, enables everyone to recogni ze and utilize the Contribut ions.
Documents should explain abbreviations lhe Arst time they arc introduced, like lhis, but also include them in a glossary SO that the readrr knows where to look for an explanation. 1ne reader is expected to know the meaning of "the Eclipse Management Organization: This is normal , the project management for a softw~ developme nt effort typically reports to a higher. level person or body within the company.
• Reco mmendin g new projects
to
the EMO .
• Recomme ndin g the initial se t of project commit· ters for each new projec t overseen by the PMC, and e tabl ish ing the procedures consistent with thi s charter for votin g in new committers.
• H elping to ensure that the projects overseen by the PMC have e nough contributors, and working to fill vacancies in role .
• Produci " g "how to get involved' g uidelines to help new pote Atia l contributors get started . • Coordinating rel ationsh,ps with other Eclipse Foundation Projects. • FaCilitating code or other donations by individual or companies .
• Making reco mme ndat ions to the EcI ,p e Founda· tion Board
The PM C has the fo ll OWi ng responsi bilities, • Providing the leadersh Ip and viSIon to guide the projcctJs overall direction in a manner con~i s t e nt
(This IS the overall controlling Eclipse.)
body for
with the Eclipse FoundatIon Architectural Roadl11ap. • Providing assistance and
regarding contributio ns proposed under Ilcensrs other than the 'tandJrd .,., ,,,..d by EcI,p5C
CASE STUDY: PROJECT MANAGEMENT IN ECUPSE
• Working Wifh the EMO and committers to ensure that in-bound contributions arc made in accordance with the Eclipse Foundation IP. (Jntenectual Property)
Policy. • Acting as a focal point for the community in re:p=enting the projects it oversees.
Since Eclipse is open source, this documenta. tion has to include procedures that ensure the continued existence and health of the Project Management Committees (PMCs) themselves.
monitor the main roject mailing list and the devel opor mailing lists for all projects and components they are overseeillg.
Roles Many roles in an open source development are: typically different from commercial develop· ment roles. They depend on volunteers and not paychecks. For that re:ason, there: is Increased potential for participants to come and go. This document de;cribes policies to deal with this. The projects under this charter arc operated as meritocracies: the more you con tribute , and the
The PMC lead is appointed by the Board. The initial PMC is selected by the PMC lead. Thereaher, to become a member of the PMC, an individual must be nominated by another member of the PMC and unanimously approved by all PMC members. In the unlikely event that a member of the PMC becomes disruptive to the process or ceases to contribute for an extended period, the member may be removed by unanimous vote of remaiOlng PMC members. PMC members may resign at any time by delivering notice of their resignati o n to the PMC lead. The PMC is responsib le for produci ng and maintaining the project charter. Development must conform to any rulcs or processe outlined in the charter, so a change to the development process may necessitate a change to the charter. C hanges to the charter are approved by the board The work of the PMC is shared by the PM C members. All PMC member arc expectcd to contflbute actively In particular. PMC membt-rs arc expected to take responSlb"ity for overseeing crtain areas of work in the project, and reporting to the PMC on these arcas. Active participation in the user new
higher the quality of your contribution , the more you are all o,,'ed to do H owever, with this comes increased responsibi lity.
Users Users are the people who use the output from the project. Output will typicall y consis t of software and research . Software in this context means intellectual properlY in electronic form , including source and binary code , documentati on, courseware, reports ,
and
pape~ .
Developers Users who conrribute soft\vare or research become developers. Developers are encouraged to partici pate in the user newsgroup(s), and should monitor the developer mailing list associated with their area of co nrributi o n. \XIhen appropnate, dc velope~ may also contribute to development desig n discus io ns related to their area of conrnbution. Developer are expected to be proactive In reporting problems In the bug tracking system .
Committers Develope~
who gIve frequent and valuable ontnbu · tions to a project , or compo nent of a proJcct (Ill the
199
200
CHAPTER g PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II ESTIMATION, SCHEDULING, AND PLANNING
ca,c o( large proJcct,), an h,ve Ihelr 'talll' promoted to that o( J • (1II1mIIlC( for that project or omp!}nenl ~,p<'t.tivcly A comnllllcr h", wTite access to the sou~e de repo>l tory (or the .«ocIJted proJcct (or o mpo· nem), and gall" votlllS rights allowlnB them to affect the fu t\J~ of the proJcct (or compone nt).
The followlIlg par
In order for a developer to become a committer o n a particular project overseen by the PMC, another comminer for the some project (or component as appropriate) can nominate th,t developer, or the de· veloper can ask to be nominated. Once a developer is nominated , the committers fo r the project (or compo· nent) will vote. If there arc at least three positive votes and no nega tive votes, the developer is recommended to the PMC for commit privileges. If the PMC also approves, the developer IS converted into a comminer and given write access to the source code repository for that project (or component ). Becoming a commincr is a privilege that is earned by contributlllg and showing discipline and good judgment. It is a responsibiliry that should be neither given nor taken lightly.
A good management document anticipates negative circumstances like the following .
At times , comminers may go inactive for a variety of reasons. The decision.making process of the project relies on active commincrs who respond to di cussions and votes in a constnlctivc and timely
manner. The PMC is responsible for ensuring the smooth operation of the project. A committer that is disruptive , docs not participate actively, or has been inactive for an extended period may have his or her commit status removed by the PMC. Active participation in the user ncwsgroup and
the appropnate developer mailing Ii ts is a responsi· bi lity of all committers, and is critical to the success of the proJect. Committers Jre required to monitor and contribute to the use r newsgroup
omm llleT> arc reqUITed to monitor the devel· op r m.dmg Ii t .<soc,ated With all prOjects and compo ncnts for which they have commit pnvdeges ThiS 1<" ond ltJon of being granted <.Ommit righi, to the prOject or component. It IS mandatory bccau~ commltters must participate in votlllg (which In orne ca,es reqUIres a certam minimum number of votes) and must respond to the mailing list III a timely !-ashion in order to faCilitate the smooth oper
information from the submitter. Committers are responsible for updating problem report. when they have done work related to the problem .
projects The work under this Top · Levei Project is further organized into projects. New projects must be con· siste nt with the mission of the Top. Level Project, be recommended by the PMC, and conRrmed by the EMO. Projects can be discontinued by decision of the board. When a new project is created, the PMC nominates a project lead to act as the technical leader and nominatcs the initial set of commit~rs for the project , and these nommatlons arc approved by the EMO . Project leads arc accountable to the PMC for the success of their project .
Project Organization This section describes the o ....niDliun projcclS within Eclipse,
of
CASE STUDY: PROJECT MANAGEMENT IN ECUPSE
G"oen the fluid nanu'e of EcI ,p<e Te hno logy Projects, organozational c hanges arc possible , in par. t,cul • .., d,viding a Project into components; dividing a Project into two or more independent ProJect . and merging t"'o or more Projects into a song Ie Project. In ea h case the initiative for the c hange may come either fro m within the Project or from the PMC , but the PMC mu t approve any ch ange, and approval must be confirmed by the EMO. If a project wishes to di vide into compo nents, commit privileges arc no nnall y gra nted at the com . ponent level , and the committe rs fo r a given com . ponent vote o n issues specific to that component . Components are established and discontinued by the PMC When the PMC creates a component it ap· points a component lead to ac t as the techn ica l leader and names th e initial set of comm itteTS for the component. The compone nt lead is designated as a committer fo r the project and represents the component in discussions and votes pertaining to the project as a whole. Component committers do no t participate in votes at the level of the project as a whole, unless they are also the component lead . In cases where new projects are be ing created , either by splitting or by mergi ng , the usual proce· dures as set forth in this c harter are fo llowed . In particular, developers will not necessanly have the same rights after an o rganizatio nal c hange that they enjoyed in the previous strucn" e .
This section is a useful checklist for most softwao-e projects.
The PMC works with the EMO to e nsure the required infrastructure (or the project. The project tnfrastructure w,lI ,"elude, at monimum: o
o
o
Bug Database Bugz ilia database for trac kin g bug< and feature requests Source: Repository - One or more V reposi to · roe, COntalnin/! all the ~oftware for the projec ts Web Ile- A W eb \lte Will onta in in formati o n about the proJect, In 11Idlll~ docum e ntallOn,
report, and papers, coursewarr, downloads o( reo lease" and thIS c harte r. o
o
o
General Mailing List-Ma,ling list for develop· ment dl scu sions pertaining to the project as a whole or that cross projects Th is mailonB list IS open to the publoc. Project Mailing List-Development maili ng list for technica l di scussions rel ated to the project. This mailing lost is ope n to the public. Compone nt Mailing List-Development mailing list for techn ica l di scussions related to the compo · ne nt. This mading li st IS o pe n to the public.
The Development Process In this section, the phrase "release cyde" wi ll refer to a signiri'cant block of project activity , which corre · sponds to an ac tu a-l rel ease cyele in the case of incubators or Education Projects , o r to a majo r stage of a phased Research Project.
This assumes an interactive development pro· cess. However, each iteration is actually released, and so must be a usable version of the product.
Each project lead must produce a development plan for the release cycle, and the development plan must be approved by a majority of committees of the project. The plan must be submitted to the PMC for review. The PMC may proVide feedback and advice on the plan, but approval rests with the p,oject committees.
The document mandates he re that each project provide a requirements document. It would have been better to be more speCific about where such documents arc deployed : it is not easy to And Ectip e requirement docume nts in prac tice, and It Is questionable that they exist in many cases. Even for non ·open source project , It an be dlmcult to understand the extent of doc ume ntation . This IS sreatly larifled wilt'n an organization stondardi zes o n documt'nt a· t'on types (e.f( ., selected IEEE ta ndards).
201
202
CHAPTER 8 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT II" STlMA TlON, SCH DULING, AND PLANNING
EJLh proj 0 11 Its
t mll
cb .. he , th e rcqulrc mcnl C:; .1nd pnontl zall ul1l.i
it i \ orking al't' II'\! ,n the curre nt re i , e cy Ie, In addll,on , each proJe l n""t PO,l J release p lan sh o wll1 g the date and co nt e nt o f the nex t major rel ease , in ludlng any mJJo r mdc .. to ll c!t. and must
kee p this plan lip to date T h e o mm itters o f a prOjec t o r compo ne nt d eCIde whic h hanges ma y be o mmittcd to the m" tel' code hase o f a project o r compo nent , respec · ti vely Three + I ("yes" votes) \Vllh no - I (" no" votes or vetoes) a rc needed to approve a code hange, Vetoes must be fo ll owed by an exp lanati o n fo r the veto within 24 ho ur or the veto becomes invalid , All vo tes are co nduc ted v,a the devel oper mailing list assoCia ted wi th th e prOjec t o r compo nent.
Special rules ma y be eSlabli he d by the PMC for prOjec ts o r co mpone nts with fewer than three co mmitters. For effiCIe ncy , o me code c han ges fro m so me contribut ors (e ,g " feature addit io ns, bug Axes) ma y b e app roved in advance , o r ap · p roved ,n prinCip le based o n a n o utiine of the work , in w hi c h case th ey may be comm itted Arst a nd c h a nged as needed , wi th co nnic ts reso lved by majo rity vote o f the co mmitters of the project o r compo ne nt, as appli cable , The master copy of the co de base mllst res ,d e o n the projec t W eb site, where it is acce si bl e to all users , de vel opers , and c o mmitters, Committe rs must c h eck the ir c h anges and new work into the master code base as promptly as po sible (subject to any c heck · in vo tin g rules that ma y be in effec t) in order to fosler co llabo ratio n am o ng widel y di stri · buted gro ups and so that the late t work is always availabl e to everyo ne , The PM C , responsible for workin g with the Eclipse Foundatio n to establish a release e ngi neering and build process to ensure that builds can be reliably produce d on a regular and frequent basis from rhe ma ster code base and made available for download from the projec t Web si te . Builds in this context are intended to include not only code but also reports , documentation , and
Th" docume nl docs not eS labllsh quality goal As a resull, there ,s s'gn,hcant vanatlO!> in the qua li ty of Edpse prOjeCIS, A commer· c ial e fforl would be ",uc h more , pc(.,nc ,n this res pel. L
All development techn,cal diSCUSSIOns are con· ducted u Ing the development mailing lists, If d,scussio n< are held offl ine, the n a summary must be posted to the mailing list to keep the o ther comminers informed.
Licensing All co ntribut,o ns to projects unde r this c h arter must adhe re to Ihe Eclipse Foundation Intellectual Prop · e rty Po licy ," Eclipse i o rganized into the Platfo rm , JOT, and POE subprojects as fo llows [7].
In describing the management of • projcct, it may be necessary, as here, to refer to particular requirements or design issues. Otherwise, we try to separate project processes from require· ments , Requirements are not known during the Arst iteration of project management docu· ments but they do become known more during subsequent iterations,
Platform
'The platfo m, project provides the co", frameworks and services upon which all plug . in '"-xtensions are created . It al 0 provide the runtime in which plug · ins are loaded, integrated, and executed. The primary purpose of the platfom, subproject" to enable other tool developers to ea ily build and de liver integratro tools."
JOT
courseware.
Each project is responsible for establishing test plans and the level of testing appropriate for the project ,
"The JOT (lnlHl Droclopm(nl Tool ) proJcct provides the tool plug. ins that implement a Java IDE Sl'pportil18 lhe developme nt o f any Java applicatIOn, IOciUdlO8 E II~
CASE STUDY: PROJECT MANAGEMENT IN ECUPSE
"I
A method of prOViding some shon·t¢rm doc· ument history.
PI,as, smd com",mls aboul Ihis drafl p"'n ecl 'pse·dcv@eclipsc.org d",t/op
10 Ih,
POE 'T he PDE (Plug.I" Dwt/opmrool En voro"mnl l) project provides a number of views and editors that make is easier to build plug . ins for Eclipse Usi ng the POE, you can create your plug·in manifest file (plugon xmll, specify your plug· in runtime and other required plug·ins, define extension points, including the or specific markup, associate XML Schema files with
As an application, Eclipse has f,al1ms . As a platform, Eclipse has to have an API stl, a means for interfacing with il (or programmers extending It.
the extension point markup so extensions can be
Thos document lays out the feature and API set for the next feature release o( Eclipse aher 2. 1, designated rel ease 3.0 (Why Eclipse "3.0") .
validated, create extensions on other plug.in exten· sion points , etc. The POE makes integrating plug·ins easy and fun ." These subprojects are further decomposed . For example, the Platform subp roject is broken down into componen ts. Each component operate like a
A hyperlinked table of contents like the fol· lowing is useful. Notice the emphasis here on deliverables and schedule, expressed in the first item .
project unto its ow n, wi th its own se t of com m it·
ters, bug catcgorie5, and mailing lists. These are as follows [8],
Release deliverables Release milesto nes
Project Name
DeSCription
AnI
EclipsclAnt integration
Compare
Universal compare facility
•
•
•
Targct operating environments
Compatibility with previous releases Eclipse Platform subproject
•
Java development tools UDT) subproject
DRAFT PROJECT PLAN FOR ECLIPSE RELEA.SE 3,0 The following is excerpted and quoted from the projec t plan for release 3 of Eclipse [9]. It provides an example of a specific project plan when compared with the c harter LAsI rwistd Friday, J.nuary 30, 200< (' ",arb 1.lmsli09 chan9cs IInC( Ih, prtOIOU S drnfl of Oclob" 27, 2003 ) .
Plug·in development subproject
environment
(POE)
This part is a seop" statement. It also specifies the management of this document and pro· vides an overview.
Plans do no t materialize Ollt of nowhere, nor are they entirely stiltic To ensure that the plannong process
203
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDULING, AND PLANNING
I tran<po",nt and open to the en tire E itp
PM:: = Project Management Contmi[t",e .
The Irs t part of the plan deals with the impo r. tant matte rs of re lea c deliverables, release mil e· stones, target operatin g envi ronments. and release-
to·release compa ttbility. These are all things that need to be clear fo r any release, even if no featllre were to change.
The remainder of the plan consists of plan items for the various Ecli pse subprojec ts. Each plan item covers a feature o r AP I that is to be added to Ecli pse, or some aspect of Eclipse that i< to be improved. Each plan ite m h as its own e ntry in the Eclipse bugzilla database, with a title and a concise summary (usua lly a si ngle paragraph ) that exp lains the work item at a SUitably high e nough level so that everyone can readily understand what the work item is witho ut haVi ng to understa nd the nitty ·gritty detail.
Note that, in place of a detailed requirements document, the detailed requirements are effec· tively provid",d via the Bugzilla database, where there is no real distinction between required fearur"" and a bug in what's been implemented. Bugzilla is an open source defect tracking appli· cation. 5<-e httpJlwww.bugzilla.org/. A refer· ",nee on Eclipse's specinc use of Bugzilla is at httpsJ/bugs.eclip"".orglbogsldocslhtml
• • • •
A seri"" of dots, as her", (an "ellipsis), indicates that the .uthor omitted material from the original in the inrer",st of brevity. The activi · t;"'s listed in the next paragraph are consid",red Nmaint",nancc: the topic covered in the last p." of this book,
WIth the preVIOllS re lease as the starting pOInt, !his i< the p lan for how we wi ll enhance and Improve It h xinl! bUf(s, imprOVIn g te
This provides more on the sCOp'" of thIS docu· ment. The activities listed are cODsidered "mainte nance: covered in the last pan of this book . A three · part scheme for require· ments priority is used , with the added ore· jected" category. This merely k","'P' track of requirements that were proposed at some point .nd rejected.
The c urrent status o( each plan item is noteel Committed plan item A committed plan item is o ne that we have decided to addr""s for the release . Proposed plan item-A proposed plan item is o ne that we arc considering addr""sing for the release. Although we are actively inves:igating it, we are not ye t in a position to commit to it or to say that we won't be able to address it. After
due conSidera tio n, a proposal will either be committed, deferred, o r rejected. Deferred plan item A reaso nable proposal that will not make it in to this release for orne reason is marked as deferred with a brief no te as to why it was defellcd. Defellcd plan items may resurface as committed plan item at
a later point . Rejected plan item Plan items that were praposed but judged unworkable are marked as rejected plan items, with an accompan ing Slun' mary of why they were dlsml sed. Keeping tT3Ck of rejected Items avoid, repeatmg the di. ion.
CASE STUDY: PROJECT MANAGEMENT FOR OPENOFFICE
tria8~ classiRcOflon , except Ihill ilems considered and rej~c ted are milinlilin~ lor reference.
This is more or
I~ss
a
Release oeliverables The release deliverables have the sa me fo rm as previous releases, namely , o
o
8.6 CASE STUDY: PROJECT MANAGEMENT FOR OPENOFFICE The case tud y ,n thi S sectio n pro vides excerp ts fro m the O pe nOffice pro ject management plan Fo r the most pa rt. we will use the same headings as fo und in the offiCial O pe nOfnce docume ntatio n
OPEN OFFICE PROJECT GUIDELINES
Source cod~ release fo r EcI,p c ProJect, ava il able as versions tagged "R3 0" in the Ecl ipse Project CVS repository . •
•
•
Note to the Stude nt: n,e fo llo wing is take n fto m h ttp Jlwww.o pcn. o fRce o tg/ d ev d ocs/guidel ine s. html . with mino r editing. It is titled ' CUldelines fo r Partici· pating on OpcnOfficc.org' and constitutes a proj· ect manageme nt subject.
•
Release Milestones Release milestones occurrin g at ro ughl y six· week intervals exist to facilitate coarse ·grained plann ing and staging . The milestones are as fo llo ws.
There is an attempt here to pace milestones at regular intervals to facilitate regular communi· cation . Oth~rwise, long gaps wo uld occur in which no communication is guaranteed, which is undesirable .
o
o
o
Friday June 6, 2003-M ilesto ne I (3. 0 M I ), stable build reflecting progress Friday Jul y 18, 2003-Has been tested and vali · dated In the targe t o pe ratin g co nfig ura tio ns Ii ted below. •
•
OpenOfflCe.o rg IS an open source prOject th ro ug h which Sun Mic rosystems has relea ed the tec hno logy fo r the S t a rOffice!T~" prod uc ti Vity
commun i allOn
mcc harllsms,
such as mailing lISts and fo rum O pe nOffi e.org has cstabli hed the necessary fac dot ies to make thi S open ·sour e tech no logy ava" · abl e to all inte re
The remainder of the mat e rial at http ,llwww. ecl ipse .org/ec I i p se/deve I0 pmen tl ec Ii pse_ proj~c,-plan_ 3_0 . html c onsis ts o f require· ments, and are excerpt e d In C h a pter 18, th e ~quirements Analysl part of thl ~ boo k.
and
Es tabl IS hm e nt of open, XML· ba<ed standards fo r of Ace p rod uc ti Vity fi lc fo rm ats and la nguage ' lIldc · pe nde nt bind"' gs to compo ne nt AP I.
• Ope n a c'\!!o to the source.' code: Vl a
V ver-C; lon·
to e nanl e ",nova tio n for bUil ding the next ~c n cra ll o n ope n-network pro du [lVll seNI C: ' 111 8
or
205
206
CHAPTER 8 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT II. EST IMA nON, SCHEDULING, AND PLANNING
GOVERNANC E
OpenO/A e participant: members, ckvelol'Cn, and prOject leads . The e are explained next."
For a proprietary project, thIs would correspond to a management section. MEMBERS penOfRce org I governed b), the Communtty CounCIl , which is constituted by member> from the Open fA e .org community . They creJled the charter establishing the ouncll ll,e Council holds penodic meetings by IRC a well as conducting business via discu s@counCll.openoffice .org mail list. Both IRC records and mail · ltst archives are public Agenda items may be proposed by any member and should be sent to agcnda@council.openoffice .org . For more information, go to the Council Web ite. The following ections describe guidelines regarding technIcal roles and responsibilities at OpenOffi e org and handling of source code. Sub· stantia l enhancements or mod lAcations of these guidelines need approval of the Communiry Council. For guidelines on the protocols for proposing projects 10 OpenOfflce.o rg , please sec Protoco ls for Project Proposal.
ROLES AND RESPONSIBILITIES Everybody can help no matter what their ro le. The more a person gels involved in the project . the more h e or she develops a trusting relationship with others. Those who have been long ·term and valuable contributors to the project earn the right to commit directly to the source repository. OpenOfflce.org respects the rights of its com· munity to post messages and use the mading lists to further the aims of the project. In fact , we cncour· age people to usc Ihe mailing lists. To this end , we will do our best to I,mil "spam" and to ensure that communication among community members
I
car-
ried out politely and efficiently . We have posted some "Mai l·List Guidelines" that detaIl our
"Members" rders to those persons who have JOIned the project by regi tering WIth OpenOfficc.org and have a u ername A member may not have subscribed to a mailing list, and a subscriber to a mailing list who is uSing Ihe project may not have registered, only tho e who have regIStered arc members. It IS strongly encouraged that all members joi n the general and relevant specinc prOject lists as well as joining a particular project. Initially, one can only Join as an observer, a role that allows one to contribute to the project and otherwise participate in it. DEVELOPERS
Written rules like these are essential for getti ng the job done. Without them, there would be c h aos a nd no OpenOfnce.
Project members who give frequent and valu· ab le contributions to a project can have their status promoted to that of a "deve loper" for that project. A developer has write access to the ource code repos, itory . A "content developer" has write access to a project's documentatIon but not to the source code In order for a contributor to become a developer, another developer has to nominate that contributor The project lead may convert the contributor into a developer and give write acces to the source code repository for the project. Al times, deveiopers may go inactive for a variety of reasons. A developer who ha been Inactive for six months or more rna
lose his or her
status as a developer. In Ihis ase or if the value of a developer's contributions dimlllishe wTit~ access may be revoked by the responsible project lead. A commItted change mu1 I1t of a I
commitment.
We would sute here something like the follOWing: "There are several categories 0/
CASE STUDY: PROJECT MANAGEMENT FOR OPENOFFICE
'bug
fu, commit The situation must be rescinded
bcfoit the cha~ can be included in any public release. belongs on a location whe~ ipOLi8c ruI~ lI~ gIVen for committing code to
This
OpenOIficf:.
PROJECT LEADS There are three main categories of public projects in OpcnOfAce.org : • Accepted projects ("projec ts") • Incubator • Native-lang All accepted projec ts must have two leads. It is up to each project to determine the actual cor.te n. of the roles each lead will take o n . Nati ve- lang and incubator projects may have o ne lead . Size and complexity are the determining factors : a large proj ect requires two leads .
P,-esumably, the ~qui~ment lor two committed project leads minimizes the risk that a lead becomes unavailable, thereby threatening the health of the project_ This is a facet of risk management.
A project lead is res po nsibl e fo r givin g guid ance and directions fo r his o r he r project a nd it part in the OpenOffk e .o rg e ffo rt _ The lead es pecia ll y should make sure that q uestio ns abo ut his o r her project are answered a nd tha t a frie ndly and up portive enviro nm e nt is c reate d . Co ntributio ns. maillist diSCUSSions, and fo rum inte rc hanges. as we ll .s is>ucs and other adminis tra tive duties should be handled in a n e ncourag ing a nd pro du li ve fa hlo n. Los o f project lead ~ t a tus may occur no . o nl y due to contrtbullo n inac t iVIty (as descrtbed fo r de velo pers ) but a lso because o f m lSsrn g ful Alime nt of responsibilitIes fo r the projec t the project lead is 10
c harge o f. Any member o f the affected projec t may ask fo r the C ommun ity CounCIl to reconsIder a project lead , o r to interve ne in disputes o r questio ns co ncern ing project leadc",hlp _ A decision by the Commun ity C ouncil IS requ ired to revoke project lea d status. A ny me mber o f a project is el Igi ble fo r e lection to projec t lead of tha t project Electio ns arc arranged by th e project concerned . A list of our current project leads can be fo und in the Irs. of projects.
SCHEDULE See httpl/d,:velopme nLopcnoffice.orglre leaseslOOo_ 2_0_timetable.htrnL
SOURCES This section is effec tivel y a Software Configu ration Manageme nt Plan .
The codebase is mai nta ined in share d info rma tio n re posi .o n es usrn g C VS O nl y developers and project leads have write access to these reposi tOries Eve ry o ne has re ad access via a no nymous CVS or the Web fro nt end _ All sourc e cod e co mm itted to th e p roject' re posi to ries mus t be cove red by LC PL and S ISS L Fil es in the rcp o itory must conta in a h eade r acco rdin g to th e O pen OfRcc.o rg te mpl ates (avai lable fo r code and makefi lcs). Co ntrib uto rs of source code large r .h an s mall c ha nges must have sig ne d the JO Int copy rr g ht a sig nme nt fo rm before the ir co ntributi o n can be comm itt ed to the rep osi tory . Strai ghtlo rw ard patc hes and fea ture Impleme ntat ions can be committed wi tho ut prior no llce o r di scussio n. Doubt ful c hanges and large -sca le overhauls need \0 be d iscussed before comm itting them into the re pository . An y c hange th at affects the se mantics o f a n eXIstIn g API hrnc tion. co nfigura tI o n datal o r Alc fo rmalS o r other major arc3!t m us t re CIVC a pproval A proJe t lead may Info rma l! ap prove c ha nge< with in h,s or her project n,e re are .h ree dIffe re nt ty pes of c han ges·
207
208
CHAP IER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGE MENT II ESTIMATION, SCHEDULING, AND PLANNING
Info Recommended
Required
Informational notice about an API change; no developer action necessary, Use the new API as soon as possible. The old API is obsolete and might go away In the near future. New code should always use the new API. Not com plying with the new API will break the build or cause runtime failure. Developer acbon IS mandatory.
This gives a grea t deal of d iscreti o n to project leads. A more fo rmal process, involving more people , may be Impractical for an open source project like this. Proposal< for mterproject changes of type "rec· ommended" or "reqUired' must be published wi th the sugg"'ted change date to the interfucc d iscussion mailing hst After o ne week of review, a change announcement mus t be published to thc interface anno unce mailing list Dunng this announcement period, dependi ng projects have to prepare their projects fo r the changt-s so that t he fo llowi ng build Will not break They are n..-sponslblc for reflecting th e c han ge In th ei r proJect , no t the requester. W ithin the two weeks of diSCUSS ion/a nno uncem ent, project leads may ra ise a Aag, and project leads majority has to deCide about ca ncellation o f the c hange requt-st.
IOtO prac tice by a h ypothetical stude nt prOject team, using the Encounter case study as In example.
• Before beginning the Software Project Man · agement Plan (SPMP), t he team met at least o nce to diSCUSS the prOject in ge nera l te rms, a nd Ed Braun wa elected a team leader. The configura tio n man· age me nt plan (SCMI') and quality plan (SQAP) were written.
PREPARING FOR THE PROJECT PLANNING MEETING Well befo re the mee .ing , Ed looked through the IEEE SPMP headi ngs (refer to Figure 8.24 ) for the major issues, and drafted material for each of them . in t he cascoof the Encou nter vi deo ga me, he co nsidered th ese to be the project o rga nizatio n (primary and backup roles, and their responsibilities) (Section 4.3 in Figure 8. 1), risk manage ment (5.4), and the sched· ul e (5.2 ). Ed also drafted a brief parag raph for Sectio n 1.1 (project summaty ). He left the staffing plan blank (i.c., who nils what ro le) because he felt it best to have membe rs volunteer for roles at the meeting. He planned fo r th e remain ing issues to be ri lled in a fter the meeting. Via e · mail , Ed asked
fo r a volunteer to pcr(onn cost estimation, since this Th= documents provide a flavor for the man· agement of the OpenO fficc project. They arc not intended to be complete.
8.7 CASE STUDY: STUDENT TEAM GUIDANCE TI'l is section describes a hypothetical account of inter· actions among students as they prepare and conduct a project planning meeting, and guides students in producing a Software Project Management Plan .
8.7 ,1 Team Guidance: Steps to a Project Management Plan for Encounter Note to the Srudent: This section explains how the principles explalOcd in this part 01 the book arc translated
,
i a .ec hnical task that requires sig nifica nt lead time, and IS best done by o ne or at most two people. Ed wro te up opti ons fo r objectives and priorit · ies ra.her than selecting the top priority, since he did no t want the group to fee l rai lroaded int o a deCisio n. H e included "attaining quality goals," "developin g so met hing that the members ca n usc" (a favorite of his), and "complete project o n schedule" as opt;ons fo r thc top prio rity. He was pretty su re that the group would ag ree to a flat ro le · based o rgani za tion as d esCribed in ection 9 4, so he wrote this into the straw man document. V ia e· matl , Ed asked team members to think about the ns ks that they consider threatening to the project , and to send write -up to him 48 hours befo re ,he meeting, in the fom, of Table 8, 1 in Sect ion 10.4 . Karen was concerned about the g roup' Java cap.bili"es. he commullIcoted with the reS! of the te.m about their knowledge of Jav.,
,
CASE STUDY: STUDENT TEAM GUIDANCE
lind d~crib"d this risk a speclRcally as she could . She also ~searc:hed companies that provide o n-SIte training 3t short notice. Her step -by-step rIsk ~ti~ment plan was included in the malerial she sent to Ed. Hal Furnass had a concern about superimposing images in Java , and he sent h is n sk identification and retirement write · up to Ed . The latter collected these in the straw man SPMP, and listed them in priority. Ed then drafted the following agenda for the m~ting .
Meeting to be held in Engineering 397 at 10:00 a.m. to 11 :30 a.m. Friday, September I 1. Appoint record keeper and time keeper (5 min · utes, 10:05)
2. Approve agenda and times for this meeting (5 minutes, 10: 10) 3. Review SPMP sections supplied by Ed (25 m in· utes, 10:35 ) 4. Allocate remaining SPMP section to writers (20 minutes, 10:55) 5. Arrange review process (via e-mail andlor meet ing) (5 minutes, 1 1:00) • 6. Brainstorm for additional risks ( 10 mlOutes, 11:1 0)
7. Rev iew action items (5 minutes, I 1: 15) 8. Miscellaneous business ( 10 minutes, I 1:25 ) Ed e -mailed the agenda and his straw man SPMP to the team members two days before the meeting, and asked them to read it over before the m~ting . His version of the SPMP contained all of the IEEE headings .
THE INITIAL PROJECT PLANNING MEETING At the meetIng , Ed asked Fern to re cord action ILems and major deciSIons, and asked AI to watc h the time and remInd the team if It exceeded planned l,mits, It wa s unders tood th at the se two roles would rotate among the members In futllr., meetings Most of Ed's Id eas were accepted . Sev. eral c hanges to Ed's proposed schedul e we re
suggested . Hal pushed very hard for a buffer week in which no tasks are assigned . Karen pointed out that no work hould be aSS Igned during the week before the midterm . There was also a discussion of using a simple waterfall to avoid the compl, cat ,ons of revisiting document , but thI S was dismIssed as not reRecting the real world . Fern pushed for Incremental development because she wanted to begin coding as soon as possible , but there was little support for this because the team did not even have architecture yet . Members felt that "quality" was an area they needed the most practIce with Arter considerable debate about building an eXCIting computer game, the team decided that "the attai nment of the specified quality parameters" would be its top priority. It ,",'as recog nized that a quality ga me worth playi ng was ou t of the questoon in the time available, and that the actual capabi lities would be have to be minimal. When the tea m arrived at role allocation, Karen volu nteered Immediately for the "design leader" role . There were three volunteers for "imp lementation leader" and no ne for QA leader Ed compromised by suggestIng that two of the three people plit roles as QA and implementatio n leaders, switch ing halfwa y throu g h the semester. The other roles were filled , and Ed reminded them of their responsibilities , and of theIr addotional backu p ro les, as stated in the SPMP. The dis cussion of h ow to allocate the wflting of the SPMP went over its planned I,mot , but the discussion was productive and to the point , so Ed did not try to curtail it. It was de cided that on ly two team members besi des Ed would write the SPMP , and the rest would reVIew their writing , since ot would be too difficult in a
209
210
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDULING, AND PLANNING
110allzc the do lIment A tcn tatl c meeting was se t for l ondo at II · 0 a m . In Arts 283 in C" C It was
nece ory, and Ed was ta ske d wit h Informin!! th e team by unday ni g ht at 8.00 p .m. w he th er the meetinS wou ld be reqlllred or not. Fern reviewed the dcci ion made , who was to "'nrc what sect ions , and when the duc dales were , The meellng adjourned.
COMPLETING THE PROJECT MANAGEMENT PLAN In wrillng the document details, the team rea lized that vanou issues had not been disQJsscd at the meeting, Including th e deta ils of "mo nito rin g and contro lling" (Section 5 3 in Figure 8.24 ) Hal's Init"! write·up of this section spoke or man y meetings at which the project was to be reviewed , but most of the other member< fe lt that many of the meetings were un · necessary . After reading several propo als, Ed tned to resolve the c·mail discus ion by proposing that project monitonng be accomplished at weekly meeti ngs, supplemented by meeting at the inception of each phase (which he would try to fold into weekly meetings as well ). The team agreed. To allow for the possibility that more project meet ings would be needed, a second
weekly !Hne was selected which members would keep available, but would be used only If reqUired. /
The case srudy contains material concemmg liaison activtties. These are shown for illustratio n purposes, and would not normally be the res ponsibility of stude nt teams. Some teams mi ght want to designate a member as liaison to the instructor. Thi s is usua ll y best performed by the team leade r. If the project has a true customer (i.e., the project is not just an inven· tion of the team itsel f), then a liaison to the custome r would be required , the requirements leader wou ld normally ha ve this task. If the
•
projec t were an agile o ne, a customer repre·
<entative would be part of the team.
8.7.2 Team Guidance Management Plan
Software project
Stude nt teams shou ld c reate a Sofeware Project Ma nage me nt Plan (SPMP) fo r their project using IEEE Std 1058· 1998 as a template, the Team Guid· ance in the previous section, and the Encounter SPMP in Section 8.4 as guidance.
8.8 SUMMARY Projc:ct costS are estimated as early as prOject Ini tiation, well before the requirements arc defi ned. The earlier the estimate is made the greater the margin of erro r, and we therefore use ranges as a way to calculate estimates. For example, during c..onceptualizarion , co t estima tes ca n have a fou rfo ld estimatio n error,· afte r deSign , a ewofold error. Project eStimates are done by nrst fi nding something objective to measure , such as lines of code (LOC). Since this is done before any code IS ...'ritten , the applicati on IS compared to the LOC of si milar or related software produced in the same company, and the LOC of the new app lication is extrapolated fro m that. Ano th er way to produce LOC is to compute f.II Clioli POilil' , which objectively measure the intended fu nctionality of the new software. The function point calcu lation produces a si ngle number that is then converted to lines of code using a standard conversion . Once LOC arc calcu lated, the COCO 10 model can be used to compute an eHort estimate. Agile projects can be estimated by the use of story points, whic h are assigned based on a compa ri on of new stories to existi ng stories. For example, an average story 1S give n a score or 5, ilnd all new Slories art' compared to that story. Once an estimate is made, a detailed schedule is constructed that lists all the tasks, their duration, th.,r dependence on each other, and the resource assigned.
,
,
EXERCISES
A ... project . .m format.on . ..ncludml! . project . " plan is created that includ es aII prOject organization , roles and respons.b.Iot.es ' ks . It aIso mcludcs . . ' project estimate • sched U Ic, an d ns references to such doc'Ument5 as configurallon management , and verification and valodation plans.
8.9 EXERCISES 1. Describe in at least one paragraph at least two consequences of failing to develop a written project plan.
2. Suppose you are tasked with computing the numbcr of function poi nts for a small application . Assume the application implements the following functionality measures, all of which can be c haractcrized as having medium complexity: - number of external inputs: 4 - number of external outputs, 5 - number of external queries: 2 - number of internal logical files : 2 - number of external files : 3 - Suppose also that the application has the following ge nera l characteristics: - requirements backup, 0 - data communications: 0 - distributed processing: 1 - performance critical : 2 - hea vi ly utilized: 1 - online entry: 4 - multiple screens: 3 - master fidds: 3 - RIc inquiries: 2 - internal processing: 3 - reuse: 2 - conversion and installation : I - multiple installations: 0 - change and ease of use: 5 Compute the number of function points for this application . 3. Cost estimation is important , but can you cite. circumstance under which .t is probably not worthwhile performong at all? Explain yo ur answcr. 4. Give one major advantage and one major disadvantage to the use of function points on estimation 5. Ust a part of the SPMP that you r student tcam IS probably unable to supply at this stage of the project. Th.s refers to a part you will have to return to after mo re work has Ix.'en performed on the prOject 6 Explaon why project planning is considered one of the phase in the software Io fe cycle and al umbrdla act.vity that stretches acros several phases
0
an
211
212
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING
TEAM EXERCISE SPMP Develop a oftw.re Project Manageme nt Plan for YOllr project. Use (or tail o r, or improve upon) the IEEE sta ndard, as shown ," the cas. srud y bel ow, Include at least two ite ratio ns ," the sche dule, Obtain a roug h estimate of the size of the produc t, Befo re you begi n, es timate the number o f defects per page th e team th inks it will discover during its fIOa l revlc,,'. Keep track of, and report the time spent by individual members and by total team effort in the fo llowing stages: research , docume nt preparation , review (including inspections). Show the actual defect density (ave rage number of defects per page). Assess your team's effectiveness in each stage ," a scale of 0 to 10. Summarize in a narra tive, usi ng the numerica l results, and state how the team's progress could have been improved . The team is encouraged to usc additional metrics if they co ntribute to effec tiveness in this and future efforts. Criteria: I.
j
I
Degree of clarity o f the plan and addendum (A = very clea r writing; all specifics included, especially of risk retirement)
2. Degree of realism of the plan and addendum . (A = sets realistiC goals a nd procedures (neither too ambitious no r too modest» 3. Extent to whic h the plan and addendum include all relevant speCifics. (A = relevant specifics included) 4 . Exte nt to which the plan and adde ndum exclude irrelevant mate rial. (A =
> 95% of knowable,
< 5% if details supplied
Irrel eva nt) Usefulness of you r self·assessme nt.
BIBLIOGRAPHY iJ<x'hm, Barry -Sojhm1rc EltglPlccnrtg EC01l0FfllCS, ~ Prentice Hall , 198 1 2 Albrtthl , A J, "Mea surmg Applicauo n Development ProductiVity: ProadrflJ' of fix )oi,,' SHAREICUIDEflBM APPOCIlII01f DtlJtlopst7ll 1.
S1"'Posnlllt. Octo ber 1979, pp. 83-92 3. I nternatIonal function POlOt U sers Croup (D~cmbcr 1999) htlpj/~. ifpU8 org ( acccs~d November 15. 2009] 4 ·'Functton PO'"t Ungu.1ges Table VersIon 0 ," Quant ltiltlVe: Sohwilre: Management . Apri l 2005 hnpJIwv.'W q-s-m coml1q c rcsourccsl
5 6 7 8
9.
funcllo n.polnt -Ianl!:'uascs-tablellnde:x.html {JccC'Osc:d November 15. 2009 } jonc-s, Caper;, "Ap plied SojJIl,jj rf McalVfrI'Il"I1 Clobnl Alfo1 /y5IS oj P,o;/wCfl('nf)' a1fd Qwa/Jty,·' 3rd edLtLon, McGraw- Hill Osbome M~dl.l, lOOS Dorfman , M , and R A. Thayer (ed'\: and contnbu lon.). "Software: Enslntc:rtn8." IEEE COIII~rtT SOC-IrC)', No,,~mbc:r 1999_ Ecl ipse:. httpJI""",,-w.c:c1tpse:org/cclipscli ndex php [acccmd December 10, lOO9] Ec1tpsc. hnp,J/ww'W eclipse orglplatformlindex php Eclipse. http IIwww.«lipscorw.C.CI I.... c/de:vdopmc:n tl«Jlp<;c_pro.tc~_ploln_3_0 hlml ,
,
•
uality and Metrics in project Management
"
-
The Software Development Life Cycle
•
How do you cultivate a quality mind-set in a project?
•
What are examples of project matries?
•
How do you use metries 10 improve
proJects?
•
What Is a software verification and validation plan?
•
What is a good example of a planned verification and validation?
Figure 9.1 The context and learning goals for this chapter
• Soft'wa re qua hty docs nOI come about by a ci d e m Achieving II Slarts by cu ltivolm g a quality culture withm the prOject team . It also req uires careful plann ing and mo nlto nn g, with project manaKcrs continuously asking ques lio n suc h as the fo ll OWing Ihro ug h o ut the h f~ of a projecl. • Is the prOject on schedule ) Is it late) • Arc too many defec ls being d , covered ) Too few )
21.
CHAPTER 9
QUAUTY AND METRICS IN PROJECT MANAGEMENT
• Are dcle ts being Axed too slowly) • I testing progressing at the desired pa~e ) Agile teams become adept at answeri ng these questions for tcam · level work. Continua l interaction wlth the ustomer, short, mutually deAned spri nts, and con tinual testing mcan that questions like these arc being continually asked and answered In the co ntext 01 the team and customer rcpre entative. On the other hand, the scope of the project can exceed a single group, in which case various non .agile techniques a re applied a, well. As introduced in Chapter 2, the answers to these and si milar questions are provided by metrics, which arc data collected and analyzed throughout a project. Examp les of project metrics are dtftclS ptr KLOC (thousa nd lines of code), lilltS codtd ptr ",an-",onl/, (MM ), and Irst case f'Xtcuti01f rale. Each provides an objective measure of a project and its processes. Metrics are an
important tactical tool of Ihe project manage r. They allow tho manager to continuously assess project quality a nd c hedule, identify problem areas, and gai n Insights into the project that allow him o r her to make proactive decisions to head off problems. As an example, if during the testing of the software an unusually high number of defects are discovered in a particular soltware module, action ca n be taken to proactively remedy the root cause, such as conducti ng a co de inspection, redeSigning the module, or executing unit tests.
Without metrics, it is difficult to know how a project is executing and the quality level of the software. Metrics help not only current projects but also future o nes. This is because future projects base metric targets o n pa.st • ones.
Targets must be established to effectively utilize the metrics collected. For example, if 50 teSt cases are executed during the nrst week 01 system testing, is the testi ng team making good progress or poor progress) The answer depends o n the test case execution goa l deRned during project planning. If the plan called for executing 100 te t cases, then lhe answer is poor progress; if the plan was 20 teSt cases , then the answer is good progress. This also aS$Umes a Standard for "test case." The goa ls are establi shed by analyzing metries collec ted during prior projects and using them as baselines.
9.1 CULTIVATING AND PLANNING INTERNAL QUALITY T"'rmal quality rders to the quahty activities undertaken by the development team itse lf. Th is calls for cultivating a quality culture among the development tcam , an attribute of good leadership. The essential goal here is a sense of shared responsibi lity and pride amo ng the team members. Fundamental gai ns in a quality attitude accrue when the project ieader continuously ensures that the work is very o rde rl y, and that the team's effort 3_fC focused on appropriate: pri orities. We plan for the management of a projecl and its internal quali ty assurance procedures at the same time.
Internal qual Ity procedures, standards, and habIts arc active throughout the project management plan , the requ.irements, the design, and the code. Exltm,,1 provision for quality is specified in a eparate set of documents, the quality assura nce plan, the verification and validation plan, and the test documentation . The relationship of internal and externa l quality activities is illustrated in Figure 9 .2. The interna l management of quality is as much a mind-set as a document ct. It begin with a conRguration management plan that ensures con iSlc nl and 5.tlfe documentation. (For example, we were t'O
ir
implement the wrong versio n 01 the design document, the code would not match the requirements for the impie.mentation , and thus would hardly be a high-quality productl) Most project management plans de ignate team member; with specific responsibilities. Table 9. 1 shows an exampl e of respon ibility designation in which each member also has a backup responsibility. Each activity
•
PROJECT METRICS
/
Internal quality actIvItIes Plan pro/eci}
Introduce continuous quality
Perform reqUirements analysis
att~ude
Include tests lor each requirement
-
Create design
Include tesls lor each unit Implement
Perform unit tests
Perform Inspections -
"
---"r ------------- - ------------ -- ----- --- -- External gualirt activities
Plan QA , V&V Perform quality assurance
Perform system testing
-
Figure 9.2 Managing quality-internal and external activities to promote quality In projects leader promotes an atti.tude of quality for his activity. The backup members can act as palf Inspectors for each leader.
9.2 PROJECT METRICS Proj'c1 ",,'rics are those that apply across the board or ha ve broad implications during a project rather than being vety focused . The metrics process starts by identifying which mctries to collect . setting target goals for each . and regularl y monitoring and reviewing them th roughout the project. Th is is described in detail in the sectio ns that follow .
Table 9.1 Example of responsibilities for documentation, with backup Name
Primary Responsibility
Backup Responsibility
Alice Jarman
Team leader
configuration management
Bruce Stern
Configuration management
security
Bob Crowder
Internal quality
Team leader
sarah Fournier
Security
Internal Quality
Hans Ughtman
Requirements
Release
Vladimir Norsk
Design
Requirements
John Green
Implementation
Design
Susan Klein
Release
Implementation
215
216
CHAPTER 9 QUAUTY AND METRICS IN PROJECT MANAGEMENT
9.2.1 Identification DUri ng proje t planning, the metries to be collected are Identified . Some arc applicable to all phases (e.8., defect ) wh.le o the rs o nl y apply to a spec.fic phase (e.g, test case execution ). While there are many metric< to chose from . some of the most usefu l arc as follows [ I ].
•
• Project mile tones • Testing progress • Defect detection and defect injectio n per phase • Defect resolutio n
\Vle discuss each of these next.
Project Milestones A plan IS created early in a proje.c tthat contains a detailed schedule. including milesto nes, which are concrete objectives that must be achieved at speCific times. A project manager monito rs the progress of a pmject against these milestones to determ .ne whether it is on schedule. Project scheduling and the establishment of milesto nes were covered in Chapter 10. The obvious metric here is the number of days between a milestone's schedule and the day on which it was actually reached.
Testing Progress
•
A test plan is usually constructed before any formal testi ng commences . It includes information regarding the types of test cases to run and detailed information regarding each test case. The most common mctrics to collect during formal te ling arc the ralt oj ItSI cast t'Xtculioti and the )lumbrr oj passrd ttst cast'S , With these two metrics, project mana gers ca n determine whether testing is proceeding on schedule.
)
•
Defect Injection and Detection Defect metrics are probably the most common type of metric collected. Defects occur during each development pha e, but such defects may have been incurred (or "injected") during a previous pha... The drJecr dclrcl'ion ratt is measured for a given detection phase and a given injection phase. For example, a "defect detection rate of 0.2 per 100 requirements defects at the implementation phase· means that one defect in the requirements is detected, on average, when implementing a set of 500 requirements . Figure 9.3 shows an example project in which these data have been collected. It also shows the longevity of defects, phase of injection vs. phase of detection. For the sake of simplicity, we have omitted the test and post.dclivety pha.ses, which would complete the picture. Let's focus on the detailed requJrements part of Figure 9.3. It shows that two defects per 100 were detected during the requirements phase (assessed by means of inspections). This compares favorably with the organization's norm of 5 per I00. looking across the "detailed requirements" row, we observe that our process detected fewer than the normal rate of requirements ddects during subsequent phases. This seems to toll uS that our project, and possibly the process we are using, is comparatively effective when it comes to producing
quality requirements. However, it is also possible that our detection process is worse than usuali This bears investigation . To complete the table, we would include similar defect data collected during testing, and during a specific rime (e.g., three months) after product delivety. The results for d(Sign defects in Figure 9.3 are as follows . We detected more than the usual number of design defects during inspections at the time they were injected, but recognized fewer design defects at later
t
PROJECT MElldCS
Defects detected, Per 100 requirements/per . • in the design/per KLoC. etc. This project/llonn Phase in which defect was in jected
-
Phase in whic h defect was detec ted
Detailed requirements
Design
Implementation
Deployment
215
0 .5/ 15
O. I/O.l
3/ 1
3/ 1
IIJ
-
-
212
sh -
Detailed •
reqUirements
Design
-
-
Implementation Deployment
-
-
3/2
3/ 12
-
Figure 9.3 Examples of defect count-injection phase VS. detection phase
stages. Since it is more expe nsive to detect and repair a defect lalcr in the process, Ih, s indicates that ou r project seems to be superior to the o rganization norms. Figure 9 .3 also con",ins Information abo ut defects detected after deploymenl to customers , whic h is surely the most Im portant metnc In the end .
Defect Resolution Tracking defect detectio n tells us the rate at which we arc fi nding defects. giving an indication of the qualtty of the evolving product. Equally important is the met ric d,Jrcl rtSollllioll . wh ich measures the rate at which defects are being resolved. Defect detection and defect closure arc complimentary . Fo r example . even If defect detectio n is meeting o r beating the plan. if the defect resolution rate is bel ow plan . the backlog of ope n defects increases and the qualiry and schedule of the project suffer.
9.2.2 Planning Once the set of merrics to be collected is identified. a plan is t'Stablished with targets for each metTic. The be'St way to derive targets is to use the metrics collected during previous projects as a baseline. adjusted as neces<;ary Without projections based o n prc-vious projects, it is very difficult for project managers to kn ow whether a project is meeting expectations. An example of a plan used to track dcf,rt d,lrclloll and d,Jtrt mollifioll is shown in Figure 9 4. Figure 9.4 tracks the number of defects submirted and resolved weekl y versus the plan . Each week the actual number of defects discovered is fi lled in and compa red wi th the plan . In this example. note that the number of open defects for the first three weeks is g reater t han what had been anlicipated. At the e nd of week 3/ 10-3/ 16, 103 defects are open vs. a plan of 66 . Armed with thi s knowledge . th e prOject manager can take appropriate corrective action Similar plans are c reated for each of the other melnes collected .
9.2.3 Monitor and Review DUTlng the Ide of a proJecl it is a good Idea for key members of the project team to revlcw the metn cs On a regu lar basiS, usually week ly . One good way to do this is for the prOject mana ge r to c reate a pa ke t of IOformatlon co ntall"ng metfl cs c harts as shown In Figure 9.4 T h IS helps pre se nt th e info rmat IOn In a GonClse format for eaSie r review . H owever, JUSt presenting lhe se oVervIew e h art 111 a nOt be enollg h For example, in additIon to th e defec t pl a n ~hown In Figure 94 . ,ddillonal'llfo rm a ll o n ~lI h a detailed
217
218
CHAPTER 9
QUAUTY AND METRICS IN PROJECT MANAGEMENT
Build 44 45 46 47 48 49 50 51
20 10
TROUBLE!
5
o Figure 9.4 Example of tracKing defect resolution-recognizing problems with defects remaining open
defect re ports ma y be Incl uded to better uncie"tanci the ou ree of the probl e m bei ng d is ove red If thIS I ~ done fo r each of the mc-tn S Incl ud ed In the report , the amoun t of i nforrnalion Ciln become ovcrw hclnlln g Al lh ough it I S sti li a good Idea to Include It all , I t is common to crC
so me t,me s ,n the form o f a pro),rt dn ,I,/'onrJ . A dashboard pre Cllt a co ncise , g raphical summary of esse nti al InfOrmal lo n re ga rding the ge neral health of J project. Th is IS analogo l1 ~ t'o an automobile d ashboard . wh ich co ntains gauge.:; slic h as fue l leve l, odometer, and engine temperature , (0 quickl y a crta ln th e ge neral S1aru and hc alth of a cor F'g ure 9 .5 shows an examp le dashbca rd from the
J
PROGRESS PRODUCTIVITY
E... ,
1 ~ V~
(8CWP)
s 10
•
COMPLETION
Adual'-' T••' ' '....
tACWPI
Coo,Qlr"lJ uu" COh;:'.U ~ On T..,...
StD>*
I I I
---
, ,,,
SAp •• d T1me
'j
CHANGE
Figure 9.5 example of a project management dashboard Source- SOftware Program Mana,gen NetwOrt tsPMNJ, MltDIIW'ww5PI'M COlli ProviOtd DV AMERICAN SYStEMS With
pefrT\l'S:SlOn
USING METRICS FOR IMPROVEMENT
OJI. arr Progra .. AlII""g,'! N,'ulork l2J
Th e ty pe of 1I1formatlon cO llla in~d ,n a d .. hboard Includes the
following· • MilestOne ompl~tion • R~uirements changes •
onnguratloR changes
• tilff turnover • Staff overtime hours • Quality metries such as defe ts per phase • Risk analysis With this concise project rnformation , stakeholders can focus therr attent ion o nl y o n those metrics not conforming to plan. For "xample, it can be noted fTOrn Figure 9.5 that the plan ca lls fo r two requirements change per month, but in the period covered by the dashboard three requirements changed. Stakeholders can now look at more detailed informatio n regarding the requirements that changed to determine whether they pose a risk to the project. Other merncs that are meeting or beating the plan need no t be examined In great detail.
9.3 USING METRICS FOR IMPROVEMENT Companies strive to Improve their projec t ext:= ution in tw O ways:
• By improvement within a project, from one phase to the next
• By improvement across projects, from one project to the next But how do you Ide nti fy what needs improvement? There is a wise saying that ")'OU ca n't improve what you don't measure: Metrics provide the measures that allow projec t managers to identi ty how a prOje t IS performing, the areas requiring the most improvement , and the objective data needed to measure the ratc of improvement . The next two section desc ribe how this is accompli hed within and across project.
9.3.1 Improvement within a Project The first step to Improve qualrty fro m o ne deve lo pment phase to the next is to coll ect me trics dunng cach phase. Table 9.2 shows a summary chart that ca n be used, which include< prov i io ns for o mpariso n with P3>t projects The data ca n be used In twO ways· I. To assess the hea lth of ea h phase's artrfact .
Fo r example , If the defect ra te for o ur req uirement s IS 0.7 pel' page and the compan y's average " 0.3 per page, then we have Identified an i<sue with our requirement, (The o nccp t of a defect 111 a page I docume ntat ion has to be carefull y dcnncd to cn
219
220
CHAPTER 9
QUAUTY AND METRICS IN PROJECT MANAGEMENT
• Table 9.2 Data on actMties relating to document creation and error rates DraftlngTO RevlewlngT1 Finalizing" post·mortelll
TOTAL
Research
Meeting
Timet'
120
30
210
130
140
30
660
% Time
18%
5%
32%
15%
21%
10%
NlA
- 14%
- 7%
- 15%
- 30%
- 16%
- 18%
N/ A
N/ A
N/ A
22
N/ A
N/ A
N/ A
28
Productivity
TBO"
TBOll
6.3
TBO"
TBO"
N/A
2.512
(Average procuctMty)
TBO"
TaO
TBO"
TBO"
TBO"
TBO"
18.3"
Self·assessed Quality"
3
S
2
1
5
9
N/ A
Defect rate LS
N/ A
N/ A
1.513
N/ A
TBO"
N/ A
N/ A
(Average defect rate)
N/ A
N/ A
(1 .1)
N/A
TBO
N/ A
N/A
Process Improvement note #
(1)
(2)
(3)
(Average % tlme)l2 Quantity'"
I
'
(4)
•
,-, •
•
The informatio n in T able 9 2 is examined, co lumn by column, identifying data that are different from par. For cach datum below par, we de vise concrete actions that the team will perform differently for the next phase . For each datum above par, we look for beneficial techniques that may be applied in future phases. "Self-assessments" arc comparat ive, subjecti ve scores that the team assigns Various activities . One
"..
way to collect the m for four actiV iti es, le t us say, is to ask each team member to allocate 5 x 4 = 20 points among the fou r activities, each score being betwee n 0 and 10. The averages indicate how well the team as a whole th inks it performed o n each activity. Th is i a subjecti ve measure that can be profitably compared with other metrics .
Here
IS
an explanation of the superscripts in Table 9.2.
Left-Hand Column II Spent Ll
by
entire tcam , in person -hours
The average amount of time spent on these acti vi ties in one of the following (select one), entire organization o n all projects, e ntire orga nization on si milar projects (the ideal ), this department on all projects, this department o n similar projects, this team o n prior phases.
U
For documents, to tal number of pages produced in the case of documents. For code, X 1000 lines of no n-commented code. A line of non- commented code is de fi ned as < A precise definition is provided here. perhaps showi ng examples of how to count lines for common constructs such as for loops.>
L'
This is a judgment that the team makes about the quality of the activity's product It is subjective but ca n be very useful. A good way to obtain self-critiCism is to force the average of these numbers to be five on a scale of 0 to t O.
t
USING METRICS FOR IMPROVEMENT
This I a key metri . It i necessary to deAne the following : • What severity of defects will be counted (usually any besides trivial) • When in the proccs thesc are counted (so as to be consistent for the sake of comparison) Top Row 1'0 Spent
b>, team members preparing the an ifact to the best of their ability; before submitting anifac! to the rest of the team for review
TI
I nc Iudes inspectIOns ' .
T:l
After review; responding to comments from the rest of the team
In~rior
of Table
II Measuring productivity for these activities is a more advanced concept and is covered later. 12
Pages per hour = (total pages)*60/{ total time in minutes)
13
Found during the "finalizing" stage
1<
This metric is determined by the end of the project detected that were injected during th is phase.
or even during maintenance-when defects are
The following notes correspond to the last row in Table 9.2 and are examples of speCific process •
•
Improvement actions.
I. Our self·assessed quality measure on rmarch was 3. The team spent a percentage of time on this actlviry that is close to the norm, so the remed y is not to spend more time on research . If there were know n reasons why research was on the poor side (e.g., a new procedure or very unfamiliar type of application) then the data here may not be a cause for alarm . O therwise . the team would discuss how to improve the research process in the future . 2. The drajliHg of the artifact was poo r in several respects. It too k more than twice as lo ng to draft a page than is usual; the product of drafting was significantly poo rer than the self·assessed average of nve; and the defect rate was significant ly higher Ihan the norm. The table by itself proVIdes no explanations or trade · offs to deal with this, it merely indicates the problem . The tcam con iders the particular circumstances of the activity and deci des what went wrong and how to fix it. For example, perhaps the main reviewer wa Ed and his mother became ill during the actIvity The team may conclude that there was not enough backup for lead writers, for example . 3. The next problematical activity was ,rui,wing, where the score waS lowe
221
222
CHAPTER 9
QUAUlY AND MEIRICS IN PROJECT MANAGEMENT
Our self·evaluatio n gIve S o rcs of 3 to review and 8 to resea rch o ut of a forced average of 5. We spent 15% of our time o n revi ew and 25 % o n resea rch . We will spend 20% on each of these activIties for the next pha e
,,
O ur ddect rate decl ined steadily except fo r thi s phase , when it rose. This seemed to be due to a lack of commo n vi sion prio r to divid ing the writing. In past phases, we succeeded in establishi ng a common vision of what we wanted to do before beginning to write our parts. Before begi nning to write the next document we will conflnn a shared vision . The ratio of requirements time to design time was 1.2, which is lower than this ratio from past successful projects in the compan y. O ur design self·eva luatio n was 6, more than average . On our next project, we plan to spend 10% more time on requirements analysis at the expense of design time.
,
•
Figure 9.6 Using project metries to improve software development processes
•
Teams set aside time at the end of each phase to assess the conclusions drawn from me tries, and to write down how it will improve its process during the next phase. Figure 9.6 shows examples of improvement conclusions.
9.3.2 Improvement across projects Companies strive to improve their perfomlance from project to project. No matler how efficient they are, the be
l
orga nizations know th ey can always improve. Th ey iden tify area s for improvement and specify actions
that w"l lead to the desi red improvements in those areas o n subsequent projects. Ste ps that can be taken to achieve these improvements are as fo ll ows, 1. Ide nti fy several areas for Im provement that arc important to the company. Examples include ~uality,
,cb,dul, prrdiclahility. and ,fficorncy. 2. Identify and coll ect metnes ,hat measure perfo rmance in each of ,hese areas. These metrics arc used as baselines for setting goa ls in future projec ts. 3. As part of project planning fo r a future project, establi sh goals for improvement in each of the identified areas, usi ng melrics from prior proj ects as a base line.
4. Identify speCific actions to implement that will support achievement of the goals. As an example, Figure 9.7 Ii51 fo ur arcas ,hat have been identified for improvement, S<'brdul,. prrdiClahilily. cIficimcy, and timt-lo-mn,kcL A metnc is identiflcd fO accurately measure project performance i n each area. Note that the re may be severa l appropriate metrics to usc in each area, but fo r simp licity we are only identifying one. An improvement goal is identified for each category, and speCific ac tions arc defined to bc implemenl
,
I
SOFlWARE VERIFICATION AND VAUDAnON PLAN
Improvement
Metric
Description
Quality
Defect KLOC
New defects fo und dunng forma l QA testing , per c hurned KLOC
10 %
~diCtability
% schedu Ie accuracy
% improvement across releases
5%
.
Coal
Improvement
-
-
-
-
Efficiency
MMlKLOC
Pre -QA deve lopme nt effo rt per c hurned KLOC
10 %
Time to Market
Cale nda r rim elKLOC
Pre -QA ca le ndar time per c hurned KLOC
15%
Figure 9.7 Improvi ng projects across the organization
examples of Improvement goals
9.4 SOFTWARE VERIFICATION AND VALIDATION PLAN Recall that "(rificalio" respo nds mainl y to the question "Are we correctly building th ose artifacts in the present phase that were specified in t he previo us phases7" Validalion res po nds to the q uestion "Do rhe artifac ts JUSt completed in the prese nt phase sat isfy their speciRcations from previo us phasesi' IEEE 10 12-2004 Softwa re Ve rificatio n a nd Validati o n Pla n. whose hea din gs are reprodu ed in Figu re 9.9, provides a framework for expressing the manner in w h ich V&V is to be carried o ut. Th is specificatio n is writte n during in itia l p roject pla nn ing , a nd complime nts the Software Q uali ty Assurance Plan covered in Chapter 6 and the case study in C hapte r 8. The annexes to IEEE V &V S tandard 10 12- 1998 are as fo llows , Annex A. Mapping of ISO/ IEC 12207 V&V requirem e nts to IEEE Std 10 12 V&V activities a nd tasks B_ A software integrity level sc he me
C.
De~nition of independent verification a nd va lidatio n ( IV&V)
Improveme nt Category: Quality Actions, I. Identify compone nts o f so ftware that
o ntaine d most dekc ts.
2 Plan to conduc t de"lI n a nd Lode reviews in these areas. 3. Plan to re fac to r seve ra l o f these are as during slIhscqucnt projec t
FIgure 9.8 Example Improvement plan
223
22'
CHAPIER 9 QUALITY AND METRICS IN PROJECT MANAGEMENT
I Purpase 2 Referenced da cuments DcRni tlans
5.4 5.5
Opera tian V&V Maintenance V&V
6. V&V repartlng requirements
6. I Reparti ng
4. V&V 'Overview 4.1
OrganIzatIOn'
6 .2
Administrative
4 .2
Ma ter c hedule
6 .3
Documentatian
4 .3
Saftware integrity level scheme
4.4
Resaurce summary
7. 1
Anomaly reparti ng and resalution
4.5
R~ponsibi l i t ies
7 .2
Task iteratian palicy
4 .6
T 0'01 , techniques, and me thodologies
7 .3
Deviatian palocy
7 .4
Standards, practic~ , and canventions
5. V&. V pracesses 5.1
Management 'Of V&V
5 .2
Acq uISi tIo n V&V
5 .3
Development V&V
7. V&.V administrative requirements
8. V&V dacumentation requirements 'Subheadings arc typical examples (IEEE )
Figure 9.9 tEEE 1012·2004 Software Verification and Validation Plan-table of contents Source IEEE Std 1012·2004
C I Technical Independence C2 Managerial independence C3 Fi nanCIal independe nce C4 Farms of independence C4 . t Classical IV&V C 4.2 Modified IV&V C4.3 InternallV&V C4.4 Embedded V&V D. V&V 'Of rcusab le saftware E. V&. V metrics E. ! Metrics for evaluati ng saftwar< develapment processes and products E.2 Metrics for evaluating V&.V tasks and for Improvi ng the quality and coverage of V&.V tasks F. Example 'Of V&V organizatia nal re latianship to other praject res pa nsibilities G. Optional
V~.v
task descriptions
H. Other r
I. Definitians from existing standards (na rmative) Copyright
IEEE 2003
An ideal pracedure is for an outside group to perform V&V. This is ca lled '.d,Jontdtttt Vtnjk.rio. ""d V.lid.riml (IV&V).
CASE STUDY: SOFTWARE VERIFICATION AND VALIDATION PLAN FOR ENCOUNTER
TI,e next
s~ tion in the
hapter gives an example of a
VVP case stlldy .
9.5 CASE STUDY: SOFTWARE VERIFICATION AND VALIDATION PLAN FOR ENCOUNTER
4.3 Resource Summary Note to the SlUdent, This ~ction shows an example of Software Veritlcation and Validation Plan for the Encounter vicko game project, organized in accordance with IEEE 1012-2004. In the interests of space. various ~tions have been omitted.
1. purpose This document provides the verification and validation procedures that will be followed for the devel · opment of the Encounter video game .
2. Referenced Documents Software Project Management Plan Software Configuration Management Plan
3. Definitions
4. V&V Overview
4.1 Organization This section describes how the V&V effort will be organized (i n terms of roles) and how it relates to the development pha es.
The verification and validation of Encounter IS roordinated with eac h phase of every ite ration .
This section describes the person-hours required for V&V or the amount required to fund an external organization for IV&V.
Verification will be perfonmed Internally. Valida · tio n will be perfonmed partly by project e ngineers. The costs of this IOternal work are built into the SPMP. Validation will also be perfonmed by one 01ernal QA engineer. This person will consume four perso n.months.
4.4 Software Integrity Level Scheme The integrity level of software expresses how critical it is. Software components that potentially threaten safety have the highest integrity level. The IEEE standard describes four levels, high, major, moderate, and low. A tool supporting infonmal research, for example, would probably be required to have only a low integrity level.
The Encounter application is required to ha ve moderate integrity.
4.5 Responsibilities The development team members will • Perform verifica ti on ac tivities throughout the proj· ect, including Inspecti o ns within all pha ~cs • Perform and doc ument all unit testi ng uSing )Unit • Validate requirements d ocuments with the marketI• ng mCl nagcr
4.2 Master Schedule The QA e ngineer will Because of the orgamUllon of V&V "' de\ c rlbed "' Section 4. 1, the VI!< V schedul e loll ow< directly to the Ploject schedule as defined In th e SPMI'
• Verify that the teal11 h.\ lo llo wed lIs docume nted procedures, ln iudins tho. e cie< ribedil1thbd ume nt
225
226
CHAPTER 9
QUAUTY AND METRICS IN PROJECT MANAGEMENT
• Perform all post -unit te tin g
• Arc all cntlca l marketing factors identified?
• Report the =ults to the team and management
• Docs any conce pt Imply a SIi!nificant risk to pro~Ct completion) If so, should that concept be mitigated?
• Maintain this document
,
5.3.2 Requirements V&V
4.5 Tools, techniques, and methodologies To be supp hed
The Encounter SRS WIll be verified by answenng the follOWin g questions,
5. life Cycle V&V
• Are all critical requirements that were identified during the concept phase speCified)
5.1 Management of V&V
• Is the SRS organized traceability )
The V&V dforton Encounter (i ntemal and external) will be supervised by the manager of Quality Assurance.
• Does the SRS account for all required interf.ces with other systems?
In
a way that facilitates
• Does any requirement imply a significant risk to
Each of the following sections describes how V&.V of every process will be conducted. When this is to be performed internally, it can be included in the corresponding docu· ment (SPMP, SRS, etc.), and this V&V docu· ment can refer to those.
project completion) If so, sho uld that requirement be mitiga ted ) The Encounter SRS will be validated by expos· Ing it to the marketing department and to a sample of 30 game players.
5.3.3 Design V&V
5.2 Acquisition V&V ' Acquisition" is the process by which an organization obtains software. Using third·party software relieves the development organiza · tion of having to reinve nt the wheel. However, it places a burden on the organization to certify the Quality of such software. Many disasters have been expenenced because this step was avoided.
Each vendor·supplied tool used for the development of Encounter will be valIdated by the QA engineer.
The Encounter SOD WIll be verified by answering the fo ll owi ng question , • Arc all requirements accommodated by the design)
5.3.4 Implementation V&V The Implementation of Encounter will be verified by answering the follOWIng qu('Stions, • Are all requirements fully verified) • Is the code organized in a way that faCilitates traceability back to deSIgn and req uirements) • I all code documented according to standards • Is all code thoroughly documented )
5.3 Development V&V 5.3.2 Test V&V 5.3.1 concept V&V Conceptual work on the Encounter game concept will be verified by answering the following questions.
The test documentatIon of Encounter will be verified by answering the follOWing verifiCJIIOn Questions, and the .ahdation questions that follo,,'_
CASE STUDY: SOFTWARE VERIFICATION AND VAUDATION PlAN FOR ENCOUNTER
• Are ~II critical cequ",:mcnlS in tended to be fu ll y rested at every level of det~iI (e .g ., human safe IY) ~ • I
the
test
phdo ophy
adequate
for
the
requirements'
• Are the test plans complete a specined in the test philosophy • Are the test cas~s complele as specified in the test philosophy For the test plans and procedures, th e reader is referred to the Softwa re Test Documentation. These plans and procedu res are deSIgned to accommodate the following validatio n questions. • Do the defect cou nt . defeCl rate, outsta nding defects, and defec t seve rity anest 10 an acce ptable product? • If not, what success rate wi ll be required to allain acccptabi Iity7 • Do they account fo r all of the metri s peciRed in the SQAP ~
6.1 Reporting The QA person attached to the prOject reports the sta lus of V&V weekly to the manager of QA and copies the team leader.
6.2 Administrative This describes who is responsible for the V&V reporting effort. The project leader is respo nsib le for ensuring that all V&V reporting is performed.
6.3 Documentation A single repon that includc'S all version of the result of
the tasks described in this document is maintained.
7. V&V Administrative Requirements This describes who is respo nsible for the V&V effort.
5.8 Operation V&V This part verines that the application is appro· priately supported after deployment to users . To be supplied
5.9 Maintenance V&V TI,e maintenance plan hall be veri ned agai nst corn · pany mamtenanee crite ria , specified in the com· pany's mai ntena nce requirements and procedures, documenl 890.23.
7.1 Anomaly Reporting and Resolution The QA engIneer attached to the Encounter prOject wi ll mainta in th e current state and the history of each defect fo und . T he QA enginee r will rnai ntalll all metrics identi fie d in the SQAP o n a Web site and WIll e·mail a list of all anomalies (including defects) Ih at he or she deem to have excessive repa ir time· Iones. This includes defecls with no repair duration es timates and tho e that have exceeded their planned compictl on date . The Bugzil la fa cility will be used.
7.2 Task Iteration Policy 6. Reporting Requirements Th,s includes who reports the resu lts of the V.. V effort and to whom do they provi de
thcie report~,
Th ,s seclion explains the circumstance under whi h VsN tasks are repea led be au C 01 results obta Ined o r because of changes in the project.
227
228
CHAPTER 9
QUALITY AND METRICS IN PROJECT MANAGEMENT
v
Any pro posal to deVIate from this plan requires th e approval 0 1 the QA manager and the project
V tasks wlil be ropea ted at the discretIon of the QA repre e ntatl ve, but these wlil Include the f 1I 0"'lng c riteria .
manager
• A n inspectio n w hose defects count is more than 20
7.4 Standards, Practices, and Conventions
percent greater than the norm
• A test whose defects count grea ter than the norm
IS
more than 20 percent
• An entire phase ,f the previous phase c han ge by mo re than 20 percent.
7.3 Deviation policy Describes the procedures required to deviate from this plan .
These arc set down for all company prOjects at http:// •
•
8. V&V Documentation Requirements Section 6 de cribed what should be reponed. Section 8 covers the means for noting in writing the results of V&V. It specifics the form that all V&V documentation must take. For example, it could be organized as an appendix to this document.
9.6 SUMMARY Quality In project manage ment begins by cultivating a quality culture within the project team . Members develo p a shared r.spon Iblilty and pride . Many projects designate team members with speCific responsibili. tICS, and each actIvity leader promotes an attitude of qua lity for h is activity. En unng quality reqUIres carefu l planning and mo nIto rin g throughout. Metrics arc collec ted and analyzed, providing means of concretely assessing how well a project is executing . There are many useful metrics, some of the most ba IC arc projecl mtl,,'oHr plaIH"d '" fulfillrd , drJecl rOIlHI" and ",rruIIOH . After identifying the metries to be collected, a plan is created with goals for each . Targets are created by analyzing previous projec ts and using metrics fro m tho e a a baseline. If targets aren't established, project managers will not know whether a prOject IS o n track. During the course of a project, the team meets regu larl y to review the metrics. In addition to the detailed data , a grap h ical summary often known as a projrrl dasl,board is c reated. The dashboard presents the key metries in a clear, conCIse manner, allowing the team to quickly ascertain how each is aspect of the project is perfom"ng against the plan. Successful companies strive to improve the overa ll quality of their performance, both during the course of a project and between successive projects. Metrics are analyzed in each case to identify areas requiring the most improvement. SpeciRc actions arc then enacted, and metrics objectively measure whether the improvements arc providing {he anticipated results . The Sol-tware Verification and Validation Plan is an important part of project quality. It specifies a plan for generati ng artifacts based on specificatioAs of previous phases (otrifiralion), and for building software that meets customers wants and needs (validalloH) . IEEE to t2 · 2004 provides a framework for this document.
,,,1
9.7 EXERCISES I . In your own words, define · proJect metrics" and explain how they are used in managing a projcct. 2. The defect pl.n in Figure 9.3 shows the number of open defects falling behind plan st.ning in week I . Assuming you are the project m.nager, at what point would you start taking corrective aclton'
BIBUOGRAPHY
Would it be aftcr the Arst week, or would you wait a number of weeks to see whether the situation Impro v Arc there any other metrics you might collect to help you deci de? Write a paragraph to e):pl~ in
Ollr an wer.
3 D~cribc in your own words how a project manager could utilize a project dashboa rd in managing a project. 4. What metrics related to software testing mi ght you include in a weekly project metrics report to provide insIgh t into the status of the te ting process? Explain your choices. 5. For each of the remaining ca tegories in Figure 9.7 (predictability, efAciency, time to market), Clcate an acti on plan to reac h th e stated improvement goals. Use Figure 9 .8 as a template for your plans. Include a minimum of three actio ns to take for each ca tegory .
I EAM EXERCISE V&V Plan TI. Produce the relevant parts of a V&V plan usi ng IEEE standard 10 12 · 1986. Measure and report o n the metrics described in Team Exercise TI in C hapter 6. Criteria: 1 Practicality: H ow well does the plan ensure that the work will be adequately veriRed and validated?
(A = completely practicable in the environment of the project) 2 SpeciRcs: H ow speciRc is the plan in terms o( sui tably naming places and participants? (A = spell s out exactly how V& V will be performed in the e nvi ronment o( the development) 3 Team participa·nt pe rce pt io n: T o what degree are partici pants likel y to perceive your plan as a help to them ? (A = written in a way that respects the time and efforts of engi neers)
SQAP T2 . Produce a rea list IC softwa re qua lity assu rance plan for your project. Measure the time spen l o n thi s dlort by indivi dual mcmbers and by the complete team . Provide the corresponding metric data and self-assessment for this assign me nt , as described in Team Exercise in Chap ter S. Critcna: as (or Team Exerci se in C hapter 8.
BIBUOGRAPHY I la ird, unda M . Ind M
rol Srerman,
hware Mea suremen t and E~ um;ulon A Practica l Appro') h/'
P9 181- 192 1 SohwJr~ P,oKram ManDQl'!l1 Nl"two r'k (S PM N) hup Ilwww ~ nl1ln com.
W"ry- I'IIUlC"IOKt,
1006,
229
I
,
principles of Requirements Analysis
Planning Maintenance
The Software Development LIfe Cycle
•
Why the term requirements "analysis?-
•
What is the value 0' written requIrements?
•
Where do requirements come from?
•
What is the difference between high·level and detailed requirements?
•
What is the difference between functional and nonfunctional requirements?
•
How do you document requirements?
•
What does traceability mean?
•
How do agile teams handle requirements?
•
How can student teams gather reQuirements?
Figure 10.1 The context and learning goals for this chapter
Bdore a software system is deSIgned and implemented, one needs to understand what that system .s intended to do. This intended functionality is referred to as the rc4""",,,,,t5, and the process of gai ning the necessary understanding of this is col lled rrqulrrmrnts ,malYSIS. An application for Video store management , for
example, could mean different things to different people, each a somewhat differing set of require ments. One intop",r3tion could be an application that track. employee t.me and outputS paychecks; another, an e·m.,J
SOURCES OF REQUIREMENTS
• The proce of underst4ndinl! wh4t's wanted and needed in an apph ation For exa mpl e, yo u may know that you a colo nia l hou e in New England, bUI you may no t know that you will pro babl y ""d a baseme nt for it .
U'.,.'
• W e exp re require me nts in writing to comp le te our understand ing a nd to create a contract betwee n develo per and custo me r. FIgure 10.2 The meaning of requirements analysis
appl ication that processes Customer ren ta l req uests; a third , an a pplicatio n th at records rented vi deos and computes charges; and so o n. As in mOst busi ness endeavors, the reliable and professio nal way to specify what IS agreed upo n i to ex press it in writi ng. Therefore the o utput of requirements analysis is a software requirements speciReatio n (SRS). T hese po ints are ummarized in Figure 10.2. A requirement specioes wha l the customer wants. Th is no rmall y docs no t include any th ing about how the applicatio n is d esig ned o r programmed . Specifyin g a req uireme nt is like tell ing a cont racto r lhat you wa nt a 12 foot by 15 foot roo m added to yo ur house . You gene rally do no t specify how yo u wa nt the contracto r to build the additio n thai is a desig n a nd const ructio n issue.
10.1 THE VALUE OF REQUIREMENTS ANALYSIS A dd ective requirement (i.e., o ne not re paired before the requirements document is fina lI zed ) turns o ut to be very expensive. It i·s an estimated 20 to 100 times mo re ex pensive to re pair if allowed to slip thro ug h the develo pment process compared with re pairing it soo n afte r it is incurred, In Anancia l term s, if the cost of Rnding and repairing a defec t at requ irements time is $1 , then the cost of Rnding and fixing that same defect at the end of the deve lo pme nt process is $20 to $1 00. The damage that re ults fro m the custo mer's poo r experience with the appl icatio n is a fa cto r addit io nal to the expense involved. G iven the trem endous be neRt of detecting and re pairing defec ts at requirements time, "' hy are so many projects damaged by poor o r no nexiste nt requ irements anal ysis) A princ ipal reason is tha t custo mers usually do no t know at the beg inning o f a projec t all that they want o r need . Instead , they learn to understand what they themselves want o nl y while th e project progresses. Th e Encounter case stud y is an example of th is uncertainty; it has a purpose, but o ne whose de ta ils are still in fo rma tio n. Thi s book emphasizes ite rative develo pm ent and the close alig nm ent be tween the requirements, deSig n, and implem entation Agi le method s are a prime exampl e. Engi neers usi ng a well ·orga nized ite ra tive process gathe r requirement , desig n for those requi reme nts, and impl eme nt for them in coordinated ite rati o n ~ .
10.2 SOURCES OF REQUIREMENTS We usually th ink of cu,'omm as the source of requirements since a ppli at,o n. are bUIlt fo r them. In p ractice, matters are ra rely sim ple here because t he people paying for an applica tio n, the peo pl e who will be u ing the appllcallon, and the people de
231
232
CHAPTER 10 PRINCIPLES OF REQUIREMENTS ANALYSIS
t
Doclslon support system lor mlillary IBeIICS
•
Unconstra/n«J
Encountor video game
• •
Type 01
•
Corpora Ie payroll system
Factory control system
application
• • Highly
•
Enhancemenllo corporate payroll system
Flight CDntrol system for airliner
Missile guidance system
constrained
I Relatively low
ApproxImate % of requirements
•
gstheled from people
Figure 10.3 Source of reQuirements people and other sources Source" AMpted Irom ..Software Reqwem€I1ts-SEI Cumculum MOdule SEI·CM· 19-1 2 ,. by JOhn W Brackett copyright ," 2009 call1Egie Mt'Oon ~ WI!!, spec'al pel I i iksJon from Its SOftware Engineering InsUtute.
Requirement arise fro m mult iple sources, mostly from stakeholders, but also from documents and even from books As shown in Figure to.3, Brackett [ I ) has plotted severa l types of applications to illustrate the degree to which requirements are gathered from people, as opposed to other sources such as written material Figure 10.3 classifIes applications by the degree to which they are constrained by nature restrictions on the application that cannot be altered. For example, an appl ication that describes the trajectory of a ball is constrained by graVity; chemICal reactions arc constrained by physical laws. Generally speaking, the less constrained a problem , the morc its requirements must be obtained fTom people. At one constraint extreme, for example, is our Video game case study. Being the product of pure imagination, it relies on people for most of its requirement.<.
10.3 HIGH-LEVEL VS . DETAILED REQUIREMENTS A typical reqUirements document is large A detailed description of every requirement, although nccessary in some fonn or other, can be mlnd · numbing to read. Imagine, for example, a document that spells out evety detail of every property of MICrosoft Word™ . It would certainly no t read like a novell For thIS reason, we often divide requ iremen ts documents into two parts, "igl>-fro" and d,tai/,d , The first part of a requITements documen, is an overview, which is relatively readable and is wdl suited to customers Its contents are referred to as the
high-ltvd or hSlSI:1t'Ss requirements . Anyone wanting to get an idea of
what the application IS all about read the high-level requirements. In many organizations, the mark
fonnally necessary, the hi gh -level requirements often Include a de cri ption of why the application is being built, and they state the benents to both the developing organization and the customer [2). In some organization s the: hlgh .level requirements fonn a separate document such as a -market requirements-
document In thiS book we will include the high-level requirements In the SRS. As an example, the video tore application high-level reqUirements might contain sentences like the following ,
NONFUNCTIONAL REQUIREMENTS
The V,deo
tore .ppl. at,on sh.1I enable clerks to che k DVDs in and out
The followIOg hows a ketch
f the maIO u er ,nterface. . . .
The second part of a o mpl ete requirements do um ent con is ts of the complete particulars. They are espeCially u for developers, who need to know precisely what they have to build . These arc the d.l.i/.d rrquiJtm(IJts. Although de ta iled requirements are used frequently by developers, the y should be understandable 10 the u IOmer, and hou ld not conta in developer Jargon wh ere possi ble . Here are o rne examples from the ",deo slOre applicatio n.
,,"11
The dail y late charge o n a DVD shall be computed at half the regular two·day rental rate, up to the value of the DVD listed in the "Interga lactic Video Ca talog." '\>Vhen the amo unt owed reaches this value, the to tal late charge is computed as this amount plus $5 . When the "comm it" butto n is pressed o n CU I 37, the CUI shall diS3PP('ar and CUI 15 shall appear with a superimposed g ree n bo rder (RC B = 6, 32 , 8) and the name and address 6elds Riled with the data for the custo mer. One challenge of writing the hig h·l cvel and detail ed requirements is to ensure that they remam consistent over time. Thi s is facili tated by kee ping the hi g h. level requirement at a hi g h enough level-for example , "Clerk can enter customer particulars." Thi klOd of statement te nds no t to change very much O n the other hand, the details are provided in full in the detailed requirements and are much more liable to evolve. A corresponding examp le is, "Clerks ca n enter th e customer's Rrst name of I to 10 alphabe tical characters in the text neld shown in ngure 34 , a second name of I to 15 alphabetical characte rs . .."
10.4 TYPES OF REQUIREMENTS Requir-ements are commonly cla.ssiRed as either i""" ioll.' o r "o"i"""io,,.1. Thi s classiRcari o n applies to both high. level and detailed requ irements. Each type IS described in the sectio ns that fo ll ow.
10.4.1 Functional Requirements
Fu.d,o•• ' rtquirrmtnls, also known as beh.viora' reqUirements, spec,fy serv, ces that the application mus t provide (e.g., 'The appltcation shall compute the va lue of the lIse r's stock po rt fo liO ."). An appltcation all ows entities Interacting with it (ty pica ll y users) 10 accomplish tasks. Such an enti ty IS fTequent1 y a perso n, but it ca n also be a machine o r eve n ano the r program . Ai""elio,,,,1 "q"i,,",",' speCifies something specinc thatlhe applica tion allows such an entity to accomplish . In o ur video store application , fo r example, the fo ll OWing are fun ctio nal requin:ments .
The appli ca tion allows clerks to check o ut DVDs The applicatio n allows clerks to di splay the cu\to me r's ac ount tatus
10.5 NONFUNCTIONAL REQUIREMENTS
Any requirement that docs no t ~pcc ify fu nct,ona llty prOVided by tht· app lt atlo n I< "0..j"",,,0,,,,1 For cxarnri~ , • requJrement such ., "the ap plica tio n shall dl
233
23<1
CHAPTER 10 PRINCIPLES OF REQUIREMENTS ANALYSIS
somcthlnfl abou t th m). No nfun tio na I req uirements need to be , pc iAc, quantit.able, and testable. Consider a nonfun tlo nal requirement that read, The systcm shall ret neve user informatio n qui kly. This reqUirement is vague (e.g., what docs reln"It mcan l), no t quantifiable (e .g , how fast i quicidy7), and therefore no t able to be tested. An imp roved versIOn of the requirement would be as follows Once the OK butlon is pressed o n the "Retrieve Account In formation " sc reen, the user's account info rmati o n shall be displayed in less than 3 seco nds. This requirement IS specific (because it identi fies a specific button o n a specific screen), '1uantiAable (because of the specific response time), and testable . The documentatio n shou ld make it clear exactly what "the O K bUlton" refers to. Major no nfunct ional categories are· qua/il'" (e.g., reliability, availability, maintainability, etc.), Co", I'
10.5.1 Quality Attributes Rdlabllity "4u""",,,I, specify "the ability of the software to behave consistently in a user· acceptable manner when subjected to an environment in which It was intended to be used." [ 3]. In other words, it is the extent to which defects wi ll be detected by users dUring no rmal operation . This kind of requirement recogn izes that applications are unli ke ly to bc perfect , but limits the extent of imperfection in quantified terms. The following is an example , and assumes that a definition of 'kve l o ne faults" has been provided. The Airport Radar Application (ARA) shall experience no more than two level-one fau lts per mo nth . • Quality attributes • • • • •
Reliability and availability (observed fau lts, ave rage uptime) Performance (speed, throughput, storage) Security (maliciOUS and non malicious compromi se of data o r functionality ) Maintainability (cost to maint.,n) Portability (move to a different operating environment)
• Constraints on the applicatio n or it developm ent
• Extemal interfaces th.t the application "talks to" • Hardware
• Other software • Communication with external agents
• User interfaces
• Error handling Figure 10.4 NOnfunctJonal requirement categories
NONFUNCTIONAl REQUIREMENTS
to
A"",labi/ity losdy rdated 10 re"abllity. quantifie< Ihe degree to which the application is to be ava lable lIS u el'5 The followlllg i an example . ARA shall be avaIlable at level one on eIther the primary or the backup computer 100% of the l1mc.
ARA hall be unavailable on one of thcse computers at level o ne or two for no more than 2% of the time in any 30-day period. Often . high-availability requiremcnts are specified in terms of "the nincs." For example , Ave-nines, or 99999% availability, means that a sy tern ca n o nl y have a yea rl y downtime of 5.256 minutes. This type of requirement might be documented as fo llows. The system shall support "nve-nines" availability.
Ptr/o"",,",, rrqui,,,,,,,,', specIfy timing constrai nts that the application must observe. These include elapsed time for computat ions (speed), throughput, and storage (e.g., RAM usage, secondary storage usage, etc)_ The follOWing i an example . The Stress Analyzer shall produce a stress report of type five in less than a minute of elapsed time . Performance requirements are a critica l part of ,wl-,im, applications , where actions must complete within specified time lim its. Examples include collision avoidance software. Aight control applications, and antilock brake controls. The follOWing is an example . The computation of brake Auid pressure shall complete within o ne millisecond .
Stcurity "qui",,,,,,,, co ncem mal icious Intent toward a system. Th is makes security different from other requirements, which specify application behavior when used by well-intentioned people. One can specify requi rements that contribute towa rds security. These call for concrete measures, such as login procedures, password lengths, and so on, that contribute to making the product more secure. On the o ther hand, imp"cit security requirements are far more di fficu lt to deal with . Implicitly, no o ne wants an application that is vulnerable to attack. so the requirement exists in the abstract. H owever, the nature of many future attacks is not predictable, and so there is no way to specify a requi rement for their defense exccpt In genera l tcrms that are of little value. Mainlainability rrqu"""",', specify how easy or difncult it i to modify the softwa re. as a result of fixing a defect or implementing an en hancement. For exa mple , the easier it i to understand the software, the easier it is to maintain . Maintainability can be measured by th e time it takes to repair defects. The f-ollowing is an e.ample of a maintainability requirement. The average time fo r a maintenance engineer 10 repair a sevcrity ·2 defect shall be no greate r than 8 person -hou rs .
Portabil,IY rrqu",mtnl' Identify those parts o f the sohwarc that may need to run in dilferent operating environments, as well a ~ ho w ea
235
236
CHAPTel 10 PRINCIPLES OF REQUIREMENTS ANALYSIS
• Platform • E.xample: The application must execute on any I CH Linux computer . • Development Media • Example: Tl,e applicatIon must be implemented in Java. • Example. Rational Rose must be used for the design . Figure 10.5 Examples of constraints Tl,e maximum amount of effort to port the graphics subsystem from Windows to Linux shall not exceed 2 person · months.
10.5.2 Constraints A COll s/ralll/ o n an applicatIOn is a requirement that limits the available options for developing it. Recall that requirements are genera lly "what" statements. '"How" is usually left to the design . Constraints can be thought of as exceptions to this. Figure I 0.5 shows some examples. Design or implementation constraints describe limits or conditions on how the application is to be designed or implemented. These (nonfunctional ) requirements arc not intended to replace the design process they merely specify conditions imposed upon the project by the customer, the environment, or other CIrcumstances. They Include accuracy , as in the following example. The damage computations of the Automobile Impact Facility (AEF) shall be accurate to within one centimeter.
Tool alld lallguag< cOlls lra ;II /S are often imposed. These include historical practices within the organization, compat ibility , and programmer expenence. Here is an example.
The AEF is to be Implemented in Java and developed on the Eclipse platform .
D",gll cOlls/ra ;II/' arc imposed on the project because stakeholders require them . They can be speciAed in the requirements document or the design document. Such constraints restrict the design freedom of developers. The fo llowing requirement IS an example . 1he AEF shall utilize the Universal Crunch Fom, to dIsplay impact results. The constraint of having to follow certain , /alldards is often determined by company or customer policies. Here are examples. Documentation for AEF shall confom, to Federal Cuideline 1234.56. The AEF code is to be documented using company code documentation guidelines version 5.2. Projects arc frequently constnined by the hardware platforms they must use The following is an example. AEF shall run on Ajax 999 model 12345 computers with at least 128 megabytes of RAM and 12 Gigabytes of disk space.
NONFUNCTIONAl REQUIREMENTS
• Hardwa~ • Example: "The application must Inte rface with a mode l 1234 bar code reader." • Software • Example: "The application sha ll usc the compan y's payro ll system to retrieve sa lary Inlormatio n." • Example: 'The application shall use version 1. 1 of the Apache server." • Communications
• Example : 'The application shall communica te with human resources application via the company
.
Ifltranel. "
• Example: "The fonnat u cd to transmit "article expected" messages to cooperating shipping companie shall usc XML standard 18 3.34 publ is hed at http :// .... .. Figure 10.6 '!)'pes of external interface requirement for an application. with examples
10.5.3 Extemallnterface Requirements Applications are frequently required to interface with other systems . The Internet is a commo n example of such an external system. Interface requirements describe the format with whic h the application commu· nicates with its environme nt. Figure 10 .6 shows the common types. with examp les 01 each .
10.5.4 User Interface Requirements: prinCiples User interlace design is sometimes included with the "design" phase of software develo pment , but it ca n more properly be considered part of the requirements phase . This book takes the latter perspec tive . including o nl y sofllDare design in the "design" phase, and not grap hi c desig n. Customers commonly conceive of an application by visualizing its graphical user interface (C UI ), so a good way to help thelll describe the application is to develop draft CU ls. Our goal here is to provide some of the essentials of userinterlace design. This is quire different fro m the I,elm lra! design of the application, w hi ch is covered in Part IV. The latter includes considerations of what C UI c lasses to se lect and how to relate the m to other classes. In developing user interfaces for app lications, it is ideal to work with a professional de ig ner, who is trained In user behavio r. co lo r usa ge , and tec hniques of la yout desig n. Fo r many proje ts, however, especially smaller ones, software engineers must design use r interfaces with no such aSSIsta n e . Thus, we lis t some guidelines for user interface design . Calitz [4] provides eleven s teps fo r develo ping user Interfaces. We have adapted these. as s how n in Figure 10.7. Each o f these steps is applicable to the high · level req uire ments process andlor the detailed reqUirements processes. Steps I and 2 are described in C hapter II. Steps 3- 11 arc explored in C hapter 12.
10.5.5 Error-Handling Requirements Rtquiremcnt\ a nalySiS dea ls with two kinds of erro r~ . The first arc th ose that actors make (e ntit ks '"terac tillg with the application suc h as a user or ot he r syste m ), the Sc o nd consi,ts of errors that developers make Errorhandling rcqu"cment~ 'pecify how the applic ation responds to diffe rent· type< of errors. Figure 10.81i ts some of the ways of dealing With errors ~garding the flrs t kind of e rror. error-handling requirements explain h o w the application mli't re'pond to anoma lies In I[S enviro nm e nt For e xam ple. whal ,liould the application do if It rc e lves a m,-,,,asc fro lll
237
238
CHAPTel 10 PRINCIPLES OF REQUIREMENTS ANALYSIS
'rp 'rp
Know your user 1 : Under.tand the bUSlne<s funct.on in que t.on J Apply prinCIples of good creen design S"P' Scl«:t the appropriate kind of window< Itp s: Develop system me nus Sirp 6 Sclect the appropriate device-based contro ls SI,P 7: Choose the appropriate screen-ba cd contro l SI,P 8' Organize and layout windows S'rp 9 : Choose app rop riate color. SI'P 10: Create meaningful .cons S" P f f : Provide effective me sage, feedback , and gu.dance f:
',p
(Hl ) (H ) (H , 0 ') (H, O) (H ,O) (H) (H ) (H , D)
(0 ) (H , O)
(0 )
Figure 10.7 Steps for constructing user interfaces Sourte" "'rlatll!!d from Gafttz.
w~
'!he Bsentlal Guide to user mter13Ct' Deslgl'l Arl lntroductoo to GUI Prind oleS and Techniques," .JOhn WIJef So Sons, 1996.
• Ignore
• Warn user • Allow unlimited retries
• Log and proceed anyway • Substitute default values • Shut down Figure 10.8 Options for error-handling requirements another applicatio n that is not in an agreed-upon format l lt is preferable to specify th is in the requirements document r.uhcr than leave the cou~e of action to programmers alo ne.
The second bnd of error refer. to actions that the application sh ould take if it nnds il,d! having comm.tted an error-that is, becau e of a defect in its constructio n. This kind of error requirement is applied very selectively, because our aim is to produce defect-free applications in the fir.t place rather than cover our mistakes with a large set of error- handlmg requirements. In particular, when a functio n is ca lled with improper parameters, we program a continuation of the application onl y if such an erroneous continuation is prdcrablc to the actual cessat.on of the application. As an example, suppose that we have to specify the requireme nts for a device that automatically applies doses of intravenous drugs. U ser. arc entitled to assume that the application .s thoroughly specified, designed, implemented, and inspected, so that the drug composition and dosage computations arc correct. Nevertheless, it would be wise in a case like this to specify a n independent check of the composition and do age of the drugs before administering them , and to specIfy error handli ng accordingly_Error-processing requlTemenlS in this case may consist of a comple te stop of the application, or. temporary halt and a notincation to the operator of the device indic.ting the problem.
10_6 DOCUMENTING REQUIREMENTS The output of requirements analysis is what the IEEE calls the software requirements specification (SRS)There are several ways In which an SRS can be organized. As we will sec in C hapter I I and beyond, the Ecl,pse open source prOject is organized around three "subprojects." Within each, requiI'Cment are orgamud
AGILE METHOOS AND REQUIREMENTS
I. InlOoduction
1.1. Purpo>c 1.2. op
1.3 Definition , acronyms, and abbreviations IA . References 1.5 Overvi~w 2. Overall description 2. 1. Produ t perspectiv~ 2 . 1.1. System in terface 2. 1.2. U ser interfaces 2. 1.3. H ardware interface 2. 1.4 . Software interfaces 2. 1.5. Communications interface
2 I 6. Memory constraint. 2 I 7. Operations 2 1.8. Site adap tation requirement' 2.2 . Product functions 2.3. User characteristics 2.4. onstraints 2.5. Assumptions and dependencies 2.6 . Apportioning of requirements 3. Specific req uireme nts (sec Figure 9) Appendixes
Figure 10.9 IEEE 830-1998 Software Requirement Specifications table of contents. 1 of 2 SA ' ~~
IEEE Std 830-1998
around several "themes ." The OpenOfflce open source project organizes its requirements III four main pans, a word processor, a sp readshee t, a presentation faCility , and an illustration 100i. In this book we will ofte" use and modify IEEE tandard 830 · 1998 [6 ], ,hown In Figures 10 .9 and 10. 10. The IEEE sta ndard was developed and maintai ne d by a committee of very experienced software engineers . It is very helpful , but it requires mo difi ca li o n and tailoring 10 respond to changes In tools, languages, and p ractices . The Arst two sections of the landard , "In troduction" and "Overa ll desc ription ," correspond to the high. leve l requirement s and arc cove red in C hapter 11 . Section 3 of the standard, the "SpeCific requirements," corresponds to the detailed requirements . It is expanded and applied in Chapter 12 . ext we turn our attention to the essential links of the SRS to the resl of the projecl.
10.7 TRACEABILITY
Tractability is the abilrty to readily understand how the parts of eparate project artifacts relate to ea h other. In particular, it links indiVidual requirements With other project artifacts. (Sec, fo r examp le, [7 ]). A detailed requirement is traceable if there arc clear links between it, the design c lement that accommodates II , the ode that implements it , the inspection that verifies it, and the test that validates It. Figure 10 . 1 I shows relationships between the artifacts, based on a si ng le requirement. Table 10. 1 is an example of how a c hange in a requirement for DVDs in the video stOft application causes c hanges in the remaining artifacts. Hyperlrnking is a c onven ie nt way to transitIOn easrl y between art ifac ts. In particular, the requirements document can be placed on the Internet or an intranet, Jnd dependent artifac t can be connected v •• hyperlinks
10.8 AGilE METHODS AND REQUIREMENTS Agile prOCesses specify requirements analys" by " t e\labli
239
240
CHAPTER 10 PRINCIPLES OF REQUIREMENTS ANALYSIS •
3. I
External interlaces
3.2 Functional requireme nts -organized by feature , o bject, user class, etc . 3 .3
Performance requirements
3.4
Logical database requirements
3.5
Design constraints 3.5 . I
3.6
Software sys tem attributes
3.6 . I 3.6 .2 3.6 .3 3.6.4 3.6 .5 3.7
Rehability Availability Secunty Maln tai nabil ity Portability
Organizing the specific requirements
3.7. I 3.7.2 3.7 .3 3.7 .4 3.7 .5 3.7 .6 3.7 .7 3.8
Standards compl ia nce
System mode - or U ser class - o r Objects (see right ) - or Feature - or
Stimulus - or Response - o r Functional h ierarchy - or
Additiona l comments
Figure 10 .10 IEEE 830-1998 Software Requirement Specifications table of contents, 2 of 2-detailed requirements SOtIrre IEEE SUi 8JO.1998
and clear enough for all stakeholders to understand and relate to. This vision is kept as concise as possible without compro miSing the shared vision itself. Examples arc as follows, An appl ication that allows VIdeo store personnel to manage DVD re ntals A Web-based calendar program fo r individuals and depalllllents A system that analyzes individual. suscep ,ibility to d isease based o n the ir gene tic infonnation The vision stage is followed by multiple iterations that are typically 2-4 weeks in duration. Such an iterative style ha the advantage of kee ping misunderstandings to a minimum and allowing all concerned to grapple with the requiroments being considered. The requirements for each cycle are gat herod by means of lISt' ,writs narratives, always told from the us"-s perspective, of how the application is to be used. This process is summarized in Figure 10. 12 and described in more detail in the sections ,hat follow.
UPOAnNG THE PROJECT TO REflECT REQUIREMENTS ANALYSIS
Requirement 1---- accommodates-- Design Element
implements
relales 10
relales 10
implements
'<- validales ---:
Test verifies
verifies
---
verities
Code
verifies
Inspection
FIgure 10.11 Traceability among project artifacts Table 10.1 How a change in a requirement for OVOs in a video store application causes changes in other artifacts
Onginal version Requirement
The title of a OVO shall consist of between 1 and 15 English characters.
Revised version The title of a OVO shall consist of between 1 and 15 characters, available in English, French, and Russian.
Design element OVO title: String
Code
class OVO
class OVO
(
(
String title
•
•
•
Title title
•
)
~ing
..QYQ.
•
• •
•
)
class TItle ... Inspection report
Test report
InspeC1ion # 672:
Inspection # 935:
4 defects; follow-up Inspection #684.
1 defect; no follow-up Inspection required.
Test N 8920 . . .
Test # 15084 ...
10,9 UPDATING THE PROJECT TO REFLECT REQUIREMENTS ANALYSIS A project's document sct is a liVing e ntity It has to be "fed and cared for" at regu lar intervals thrOullhOlIl the life o( the project TYPically, when a pha e IS executed, severa l documenl must be updated For very large projects, the proce" of analYZlnR the customer's requirements IS (ormal and or~anl zl'd , Forexampie, the U.S_Department of Defense (000) ohe n publ"hcs a requesl for propo
241
2~2
CHAPTER 10
PRINCIPLES OF REQUIREMENTS ANALYSIS
Develop common vision
Specify user slories and lests
Each cycle: beginning
Write tests lor Each cycle: end
Each
Code
Figure 10.12 Agile requirements analysis
an SRS alone. Such an RFP contains a very hi g h level descripti o n of th e project. The RFP can be thought of as specifying the hig h . level requi re me nts. Contrac to rs res pond to the RFP, and a winner is chosen who creates dctailed require ments. To en ure that th e requirements are sa ti sfac tory, numerous meetiF'lgs are held. These
involve contracto r perso nn el , civi l serva nt specialists and managers, unifo rm ed ofRcers of the Navy or Air Force, and o th ers. The rcsu ltlrlg RS ca n be th ousands of pa ges lo ng. The winning contractor mayor may not be c hose n to perform the actual design and development of the application . Once h' gh · level requirements have been ga thered, the SPMP CJn be updated as shown in Figure 10. 13. Such upd a ting occ urs through ou t the' li fe cycle of an application. The result ing schedule wou ld rypica ll y be like that show n in Figure 10 . 14, containing more detail than th e schedule show n when th e SPMP was o n gi nall y drafted (C hapter 8) but still not ve ry detailed. In
Status after Initial Draft
Status after Obtaining High-Level Requirements
,WI"lo""
Initial
More milesto nes; more specific
Risks
Ide nti fy initia l risks
Reti re risks ide nti Red previously, identify more risks now th at more is known about the project
Sc/xdwl,
Very rough
Preliminary project schedul e
.Desig nate h ig h -level
Cosl EsI;""'lio"
requ irement' engineers
Designated e ngi neers fo r derailed requirements analysis
Very rough
First estimates based o n job conte nt
Figure 10.13 updating project plans after obtaining high-level requirements
I
.3 ...... '.1& 1' [ . ...1 (~a"t'b ~~4S.S
L
AlcHed\le
~
0eI7' 7 ~de,.."
1 '" '.EYote ,...
'! ICC
e ........ rele.u .....2 -0et0 - 0,
-
- 00.1 -
--
C~rec:,.MemerlS
tS$b ISO
-
! - _._------
I I
Figure 10.14 Typical schedule after obtaining high-level requirements
particular, we may know that release 0.0 .2 shou ld be made on November 13, but It may be too early to deCide other parts of the schedule . Cost estimation ca n be improved once hi gh -level requirement have been analyzed. Th e main Improvement stems from the increased understandlOS that developers gain concerning the scope and nature of the application _ Func tion pOLn! estimates (described in C h apter 8) can be made more comp lete , and 0 ca n the estimates derived from them for schedule and labor. Direct bOllom -up e timates can be improved as well. Another factor limiting rhe number of Iterations of the requirements IS the hi g h degree of coord lOatio n required to keep the project documents and th e ource code coordinated . 1111 is o ne reason that hi ghly iterative development techniques such a agile meth ods do not rea ll y atrempt to wnte detailed requirements documents.
10,10 SUMMARY Requirement analysis IS the process of unde rstanding whal ', ,"anted a nd needed 10 an application . The output of requirements analysis IS a software req uireme nts spe Ihcation ( R ), whi h serves as IOput IOtO the design process. The R document used in thi s book is IEEE standard 830 - 1998 ReqUirements arc divided into hig h -leve l a nd detailed rcqlliremen ... Hi gh -level reqUlrement< arc al 0 called business requlfcments These deSCribe why the app li ation IS belOS built and
2«
CHAPTER 10 PRINCIPLES OF REQUIREMENTS ANALYSIS
Iter.ttlon Each requirement IS u.ually ba cd on a """lory along with an explicit acceptance test. A uscrStory IS a hig h . level piC e of req uired runctional iry a seen by the antiCipated user. Detailed reqUirements arc usually expressed in terms of unit te ts r.tther than being wrinen explic itly . After requ irements analysis IS completed (or after each iteration," an Iterative process), the project plan I updated to reflect the new details known about the application . The more requirements that are known, the closer the schedule omes to being fina lized .
10.11 EXERCISES I
Explain wh y a defective requirement could be 100 times more expensive to fix after software is deployed ve rsus being fixed during requirements analysis .
2. Give an examrle or a so rtware application in which the customer is the sa me as the end user. Give an example in which they are different. In each case . identify the customer and end user. 3. In your own words, explain the difference between hi gh.level and detailed requirements. Give an example of a h igh -level and detailed rcq'Jirement for a typical word rrocessi ng application. 4. In your own words , describe the difference between functional and nonfunctional requirements. 5. Explain wh y the foll owing requirement is not sufficient. How would you amend it( " The o rder e ntry system shall not crash more than 5 times per year. The system shall recover from each crash as quickly as possible to avoid down time." 6. Bracken makes the po int that the more constrained an arrlication , the less reliance we have on people as the source of requ irement . (Refer to his graph in Figure 10.3 comparing "approximate percent o f requirements gathered from people" with "type of application.") Can you think of any applications that do not rail on the graph's diago nal ) 7. Agile requirement; ga theri ng calls for a customer representative to work continually with the development team generating requirements . Describe a scenario in which this type of arrangement may produce poor requirementS .
8. What are three major advantages and disadvantages of describing detailed requirements with unit testsi
BIBLIOGRAPHY 1. Brackett , ] "Softw3R' Rcqulrt~mC'nls SEI CU rriculum Module SE I· CM · 19- 1.2: January 1990. hupJlwww sc: ,.cmu.~dul1lbr.uy1 absrracw rcpof'tsl9OcmO19 dm 3cc~srd N ov('m~r 1S, 2009 J.
r
2. W iegers, Kl.rl E., W Mort Abcwr SO/llNrr RC4I1'ttM",fJ. Mic lO
3. Davis. AIVl M ., NSoJlll'IJrt RtqvlrtWlm lj Ob"trlt F"",ho"). a"J Staid", Prentice: Hall, 1993 , p 310 4 Callt'Z, W .• "11.1( EJsmlldl ~wJ( to Uw Irs'tr/act 00'9" k ,,,troJlI( llI1II !D CUI Pmlclp~ amJ Trcbrsrqllt)," John Wilcy & Son .., 1996 S. Alexander, lan , ;tnd Ncoll Malden (Ed itors), ~Sc",,"nos, Siono. US( Cam.. nr~h IIx Systmls Drotloplfln" Llt-Cyru" (pJ.pc'm;u:k), John WIley & Sons. 200 .. 6. ~I EEE Rccomme:ndC'd Pri)c~icc: (or $o(IWolr'C Rc:quJre:me:nts pc:-cl t\ca tions,· IEEE SrJ !JG- I90S, June: 1998 7 Wle:gert, K;ul E. ~Sof'1l)Q rr Rcqllll'CMnfb," Microsoft Prc:ss. 2003.
Analyzing High-Level Requirements
Planning
•
What are examples of customer wants?
•
What does stakeholder
•
How do you mtervlew for and document requirements?
•
How does one write an "overview" requ irements section?
•
How do you write -mcun functions" and use cases?
•
What agile methods are there lor dealing with high-revel requirements?
•
How do you SpeClty user Interfaces at a high level?
•
How does one frame secunty requirements?
•
How do you use dIagrams for h,gh·levet requ Irements?
•
What are examples 01 high· level requirements In practice?
VISion
mean?
Maintenance
The Software Development .-___ '___ Lifeeyele Require,i.e"t•
• ".iysls lion
Design
FIgure 11 .1 The context and learning goals for this chapter
2.6
CHAPTER 11
ANAL YlING HIGH· LEVEL REQUIREMENTS
Hi g h . level reqUire men ts descnbe the purpo e o( an appl.cation and ilS Intended functiona lity. They can al a descnbe the app lication's beneRts to both th e cu>tomer and the dcveloplng organization. This chapter de cnbe th e process w hereby we collect, ana lyze, and specify the requirements at a hi g h level . It is help(ul to express hi gh . level requ irements usi ng both text and dia grams, in o rder to convey a complete understanding of the intended application . Hig h . leve l requirements arc of great interest to all stakeholders, particularly eu to mers, who purchase and ult imately usc the applicati o n based on it require ments .
11.1 EXAMPLES OF CUSTOMER WANTS T y pically , at the time that requirements analysis com me nces, the customer is still (orming concepts of what he o r she wants and needs. ThIS is an.logou< to the requirements·ga thering ph.se between an architect and a client . Fo r ex. mpl"" a client may want a house with (our bedroom s and a large li vi ng room , but nevertheless rel ic o n th e architect to help clarify what he wants .nd needs (e .g ., a ranch house with a living roo m with ealing (or ten ). As an example , consider the Encounter case study. The (allowing is a fragment of customer thinking obta ined by a myt h ica l marketing depal tlllcnt. Encounter is to be a role -playing ga me that simulates all or pan o( the player's lifetime. It should be of interest to bo th male and (emale ga me players. Figur<'S I 1.2 and I 1.3 summarize the hi gh.level requirements (or the Encounter case srudy. The complete descnptlon of Enco unt er hi g h -level reqUirements is contained in Section 2 of the SRS, Overall Description. The requ irements sta tements In Figures 11 .2 and 11 .3 arc at a very high level with detail purposely omitted. For exa mple, th e requ irement "Each quality has a value" does not specify what those values are. SpeCific values are documented in the deta iled req uirements o( Section 3 of the SRS.
• • • •
Ro le·pla yi ng ga me that si mulates all or part of the lifetime of the player's character. Ca me chacac ters no t und er the player's control called "fo reig n" c haracters. Ca me cha rac ters ha ve a number of
• C haracters ""ncounter" each other when in th e same area, and may then "engage" each other.
Figure 11.2 High·level requirements for Encounter, 1 of 2
• The result of the engagement depe nds on the va lues o( their qualities and o n the arca in which the engagement takes place_ • Player characters may reallocate their qualities, except while a foreign character
IS
present.
• Realloca tion takes dfect aftcr a dela y, during which the player may be forced to engage . • Success is measured ... o by the "life points" maximum attained by the player - o r o by living as long as possibl e. Figure 11.3 High·level requirements for Encounter, 2 of 2
STAKEHOLDER VISION
At thiS rag~
requlI"cmcnrs analysis, there are usually unrcsolved bsues such as whether there is to be onc or several h.ra ters under the control of the player, what should occur when two character; Interact, and w~fher thc same an be played over the Internet. It IS the task of the development team to work With customers to clarify their wants and needs_ A common pro ess is to interview the customer, which is d~bed III Section 11 .3. In
Customer nccds can be Subt ler to las ify than their lV.n'" since customers arc typically less conscious of them . For example, a cu tomer may W.II' a musi application that allows computer novices to write music but may "ltd a periodic auto-save function to avoid lOSing work. Whether such a feature i a requirement or part of thc design dcpends on what is agreed between the developer and the customer. If the customer. having underilood auto-saving, wants this feature , thcn it becomes a requirement_ The customer may be content , however, to Icave it to the designer as to how to accommodate the computing needs of novice users. In that case, auto -saving would not be a requirement, but a desig n element.
11_2 STAKEHOLDER VISION The people who have some interest III the Outcome of the product are ca ll ed its ".ktl,old"s. As an example, consider the creation of an c-commerce W'cb SIte. One set of stakeholders consists of the site's Visi tors . Typically, their primary requirement is the ease with which they can And and purchase needed items . Thc company's owners are stakeholders, too. Their primary requirement may be proflt, sho rt - or long-term . For this reason, they may want the si te to emphasize high -margin items. Marketing, another gTOUp of stake holders, may rcquire the Web site to track visitors . The application's developers are stakeholders, 100. For example they may want 10 use new development tec hnology to keep up to date. In the case of packaged (shrink-wrapped) applications such as word processors, spreadsheets, and development environments, as well as their equivalents (such a do,vnloaded applications ), the deve lopment team pays a gTeat deal of attention to the acceptability of the application by as many users as possible. Although this can be a difncult marketing problem , it is clear that the users arc the most signincant stakeholders_ For many large projects, identifying the most imponant stakeho lders is complex. n,e ·customer" is often the pany paying to have the application developed, but even this is not clear-cut For example, the Navy may be paying for an application , but the developers' day -to- day customer may be a civil servant rather than a naval ofncer. Then again , arc not the taxpayers the "customers," since they arc actually paying for the application] The customer of a subco ntractor is the prime contractor. The Ctl tomer for shrink -wrapped applications is a composite of potential customers established by the marketi ng depaltlllenl. WRen an application is intended for Internal company usc, such as claims processing within an insurance company, the customer i~ an IIlternal organization . ConAicting takcholder interests ca n ea
247
248
CHAPT€R 11
ANALYlING HIGH-LEVEL REQUIREMENTS
may hold differing co ncep ts of what a software application enta,ls_ For exa mple, th e poss ible concept of operations for ' a weather syste m" could be • a facility for {"urning raw weather service information ,nto graphica l form or
• a real -tim e system fo r forecasting the weather or • af.\ application for alerting users to weather anomalies These diffe rin g co ncepts of operations lead to very d iffe rent applicationSi The project manager o r requirements engineer helps the stakeholders to clarify their concept of operatio ns , ince custo mers usua ll y lack the means with which to express such concepts, engineers can propose appropriate techn,que uc h a usc cases, data flow d iag rams, or Slate transit io ns, w h ich are described below These tec hni ques are also used for desi g n , as sh own in Part IV.
11.3 THE INTERVIEW AND DOCUMENTATION PROCESS Much of the analysis of requirements IS a person -to-person activity , organized to produce an application satisfyi ng the customer_ Figure 11.4 summarizes the process of preparing for and interviewi ng the customer to
ehcit their require ments. ince there are ryp lcally several stakeholders who want to provide th eir input, the Hrst issue is deciding whom to interview. Recall that requirements co m ing from different stakeholders may be contradictory. It is often effective to Interview a small number of primary stakeholders, and then solicit co mments from other key stake ho lders. Two interviewers at each session arc preferable to one, since a typica l interviewer tends to miss POIn[ . Bringing a recorder can help. with permission requested in advance. The most sig nifica nt person to Interview IS ofte n the most difficult to chcdule time with , so perseverance is called for. Interviewi ng the wrong
Befo're interview: 1. list and prioritize "customer" Interviewees • most likely to delenninc project's success. 2. Schedule interview with fixed sta rt and end times.
• at least twO from development team should attend . • prepare to recordi At interview : 3 _ Concentrate o n listening . Don't be passive, probe and encourage. • persi t in undt'rstandlng wants and exploring "tcds. • walk through use cases, also data flow ) state diagram s) Take 'horough nOles. 4 . Schedule follow -up mee' lng for validation .
After interview : 5 . Draft SRS hi g h -level requirements using a tandard.
6 . Contact customer for commen t'S. Figure 11_4 One way to handle Interviews with the customer
DESCRIBING MAIN FUNCTIONS AND USE CASES
ptOI'le can I.. sult III wa>ted o me and dfort. The e",,,, ' 8 ,1e process in particular tn, ist' that the customer communlt. supply ju
After the meeting , the hig h . level requirements are draft ed on a fo rm at such as the IEEE tandard. The draft should be provided to the customer communi ty fo r co",ments, and successive interviews arc conducled unt" there is sati sfactio n \vith the high · lcvel requirements. The great challe nge we fa ce is expressin g clearly wh at custo mers wa nt and need. W o rd alone ca n be appropriate, but for many applicati o ns, narrative text needs to be supplement ed by Rgllrcs of van ous k,nds. The following sectio ns describe how to express hig h· level requ irements.
11 .4 WRITING AN OVERVIEW An overview is inte nded to all ow readers to quickly understand the mai n purpose o ( the ,ntended applocation. O therwise, it sho uld be as sho rt as possible and should seldo m need alteration whe n projec t deta" s change The ch allenge o f writing a good ove rview is usuall y underesum ated. pro bably becau e it is often thoug ht that ,f one knows what a subject is about then summariz ing it sho uld no t be d ifficult The follOWi ng is an example for the video sto re appltcation, in th is ase, a songle se nte nce suffices V to re is inte nded to help video sto res manage DVD inve ntory and rentals. II IS tempt ing to add mo re details to thi s, but good requirements document< arc organtzed to provide detaI ls 111 o rderl y sta ges, so add ing mo re detai ls hcre wo uld result on dup lica ti o n and could reduce readabil, ty . "Manage D VD onvc ntory and re ntals" prOVIdes substantive info rmat io n but 's genera l enouglt so that changes on requirements detai l< are unl ikely to fo rce ,t to change .
11.5 DESCRIBING MAIN FUNCTIONS AND USE CASES FollOWi ng an overview sectio n, h, gh · level req uorement s u
249
250
CHAPTER l'
ANAL ¥ZING HIGH-LEVEL REQUIREMENTS
narrative of how Ihe application is used [3) . They have become a very effcclive way to express many fun tional high-Icvel reqUIrements. As an exa mple , when using J word processor, we usually ( 1) relrieve a fllc, (2 ) cha nge and add teX! , and Ihe n ( 3) store the resull. Functional hi g h -level requirement. are often naturally cxpre sed as an inleraCli o n belween th e applicalion and agencies eXlernal 10 it, suc h as the user. Agile projects rend 10 employ Ihe idea of IISer slo';t!. TI,esc are si mdar to usc cases but arc broader in scope and have dis llnc t c rileria . U scr stories are de cribed in Sect Ion I J .6. A use case IS ide ntified by its name and by Ihe Iype of u erof the applIcation, called theaclor. The main part of a usc case documcn a typical inleraction bctween an actor and the application , often called a scmario. A scenario consists of a numbered list of steps. Each step should be simply described and include who is carrying out the SlCp. A good way 10 start wriling a usc case is to list the tnai" sllcem sct"nrio, which is the sequence of steps that lead 10 a succt'Ssful o ul come. A single use case should nOI attemprto accouni for a significant number of branches. Other scenarios of Ihe usc case , such as error conditions, are ty pically documented as ext""j""s . For example, Rrlnroc
n File would be a typical use case for a \\lord processor, with the user as actor. The main success scenario
contains Ihe following seq ue nce of seven steps. NOle Ihal each step stans with Ihe entity Ihal execules Ihe slep. ln Ihe case of an error in ope ning the selected file . an alternalive is doc umenled in the Extensions secllon , RetTieve a File Main Success Scenano I. User clicks File menu 2_ Syslem displays op lions new and open 3. U ser clicks open 4. Sy lem displays Ale WIndow
5_ User enters directory and file name 6. User hits open button 7. System retrieves referenced file into word processor window Extensions
7a5ystem dISplays error ind icati ng file could no t be opened It is possible for a single person to use a system in several differenl ways, adopling Ihe roles of differenl actors. In UML, a usc case diagram shows Ihe actors, the use cases, and Ihe relalionship between Ihem. A use case diagram is a useful 1001 for d iagrammatically summarizing Ihe sel of aCIOrs and usc cases without having to show allihe delails of Ihe usc cases. Figure J 1.5 is an example of a use case dia gra m, wilh Ihe names of Ihe use cases shown in Ihe ovals, and the actors drawn outside the rectangle with lines connecting Ih<'TTl 10 the use cases Ihey inleract with. As furlher examples of use cases, Figures 11 .6 and 11 .7 contain examples of lise case scenarios for the I"ilialit< and E"ga9' Forcigll ChMaclcr use cases for lhe Encounler case ludy. The aclor in each of Ihese usc cases is the player of Encounter. Each use case is a sequence of aClions laken by the player and Ihe Encounter game, as shown for Ihe IniJializt lise ease. The Engag, Forrigll Charnelrr use case is a typical sequence of actions by Encountcr and Ihe player, whenever Ihe player's main characler and a fo",ign charaCier arc in the same area .1 the same lime. The aClor in the 5" Rub usc case is a game designer. The actor describes Ihe ability of Encounler 10 support the ediling of rule forcharacler interaction. The Trawl 10 Adjomol Arta usc case is explained in the case srudy accompanying this book. The Stl Rules use case is nOI included in t~ case ludy ",quiremcnts.
DeSCRIBING MAIN FUNCTIONS AND USE CASES
ActOG
Initialize
/ Player
Travel 10 adjacent area
/
Engage foreign character
"'-
""-
Designe r
)
Set rules
figure 11.5 Use cases for Encounter-a UML use case diagram
Initializ~
I. Systtm displays player's main character in the dressing room .
2. 3. 4. 5.
Sysltm P/Qytr P/Qy" Systtm
displays a window for semng his character's qualities. allocates the qualities of his main character. chooses an exit from the dressing room . moves player's main character into the area on the other si de of the exi t.
Figure 11.6 Initialize Use case
Engag~
Foreign Character
I. Sysrtm displays the foreign character in the same arca as the player's.
2 Sys/tm exc hanges quality values between the two characters. 3. Systtm displays the re ults of the cngagement. 4. Sysltm displays player's character In a random area . Agure 11.7 Engage Foreign Character use case
The actor need not be a human role- It ca n he another syste m th at lIses the application. For example, if the application under development I a robot con trol y.tent, then the actor cou ld be a fa tory au tomation system that uses the robot contro l sy~tcm Use cases can handle limi ted branching, but .r there is more than one leve l of bran h,ng, the exte n"on Idea. dc~cnDcd above, ca n be tned Ot herw l e the ",. ca," should probably he decomposed Into other lise cases Even a slOgle branch in a lise cas lead to an awkward description . Forcxample, the follOWing ould be a usc case for a personal budgeting aprl,cation f User selects "add checks' or ' reconcl lr a count"
2 If ' add che<.k. selected ,
251
252
CHAPrER 11
3
ANAl YZl NG HIGH-LEVEL REQUIREMENTS
ne .et lo n happen> not her a lio n happe ns
5
. (one o r more stcps)
•
6 . If ' reconclle account" selected: 7 One action happens S. Another actIon happens
9
• •
Th is would be better decomposed '"to "select o ptio ns," "add c hecks: ' and "reco nci le accoun t" use cases. Use case are like tones and so they provide excellent insight into applications. They can be expressed at d.ffe nng level of generality. The Uni Red Software Development Process [4] reco mmends using detailed use cases to specIfy a large fractIo n of the requirements. A usc C35e that is si milar to an existing o ne yields li((le addit io nal value . Usc cases sho uld be stq"mlial, or el e orlhogollal to eac h other. T wo usc cases are sequentia l if o ne can follow the o ther. Orrhogo"al is not a preCISely deli ned term , but o rthogonal use cases take completely different views o r options. For example, in a warehouse appl,catio n, usc cases based o n a fo reman actor and a Rnancial anal ys t actor would typIcally be o rth ogonal. In the Encounter case study, Sri Rul" is o rth ogo nal to £"gag, Forrig" Cbaraeltr. Chapter 14 shows how use cases are combined to produce new usc cases; it also introduces inheritance among usC' ca cs. Jacobson's [2 ] inspiration fo r the idea of use cases was that, despite the huge number of potential executIon . mos t applIca ti o ns are conceive d of in term s of a relat ively small number of typical interactions.
He suggests starting application desig n by writing usc cases, then usi ng them to drive class selection. This technique is demo nstrated in C hapte r 12. Use cases are also the basis for system·level test plans. Many established documentation standards, including the IEEE's, predate use cases and they must be augmented to accom modate them. The Encounter case study describes them in Section 2.2 ' Product Functions' of the SRS, as th IS IS the sect Io n that describes the functi o nal high -level requirements. Although use cases arc often identified with object-o riented methods, they can be used with any development methodology.
11,6 AGilE METHODS FOR HIGH-lEVEL REQUIREMENTS HIgh -level reqUIrements fo r ag de projects arc collected and understood in a manner si milar to that for non-agile methods except that the requirements process operates ," pieces and continues continuously through most of the li fe of the project. Non-agi le processes requi re a time when requirements are frozen (,.e , beyond which the customer has no right to change them). Agile processes, o n the other hand, accept frequent chang~ in require ment as a necessity How can one of these be a valid approach without the other being invalid] Th .. difference lies in the level of truSt e ngendered by very close customer contact. If the customer's trusted represe ntative works continuall y as part of the development team , it is unlikely that he will suddenly ask fOf un reaso nable requirements In agile processes, selected h igh-level requirements arc elaborated upon within each iteration. Each is usuall y based on a ",,,slory or slori", each accompanied by an explici t acceptance teSt A uscr story is a high-level piece of required functionality as seen by the antlcipaled user. According to B~k and West [5] a use r story must be discrete, estImable, teStable, and prioritized, as described in Figure 11.8. Compared with use ca es, us"r stories are described less by their form than by these qualities. Having to be estImable is o ne d ifference, and this is ill ustrated in the example below. User stories can al a be more utens;ve than usc' cases.
AGILE METHOOS FOR HIGH·LEVEL REQUIREMENTS
I. From US.,'S P"l"$pcctive
2. Dlscret., • Single functionality, feature , o r expectation . • Not neees anly precise. 3. Estimable • Developers can estimate required effort. 4. Testable 5. Priori tized • By customer, in consultation . 6. Can be Ilt in a Single cycle.
Figure 11.8 Required qualities of a user story
Beck and West [5J give an example of how to ga ther user stories. Thc custo mer starts wi th the fo ll owi ng story.
0.0 Will outpeifom1 all other u",dill9 machilles This is fine cxcept that it's no t estimable-there is no way to esti mate th e effoft reqll1red to carry out th is job. Consequently , the developer probes fo r more speCific stories to o btain estimable ones, a process known as splitfing. 1.0 Payment. Will accept all killds oj paym"'t' 2.0 Freshness. Will sell
110
stale or ou tdaled mcrchalldise
3.0 Restocking. Will auton,atically request rcstockill9 oj iteltls selli1l9 best ill tl" arm 4.0 Communication . Will (omm lm icntt with tht cus lonur
10
prtvw l tran sactio" (rrars
This is an improvement, but these are still not estimable, so further splitting is required. Recall that prioritization is also ca lled for . The agilc programmcr the n requests more speCtfics concernin g the highest priority story. If this were ' .0 Pay",,,,t , the uscr mi ght provide the following : I. t Accept coins
1.2 Accept
('''''"ey
1.3 Accept debit card 1.4 Accept mdit card
1.5 Acapt debIt or mdit card
1.6 Accept Jortlg'rl coilts {HId 1.7
OHVCrl
Uta
W,b Irallsaclioll
( UfralC)',
at least
C'IH 0 5 Jar snits III
Europt
("ur(tHeirs
1.8 Ellsu" Ihal pay",,,,t m"IS or t')(",ds tb, cosl oj th, "ltCled /Jrod" I
1. 9 Makr chall9'
253
254
CHAPTER 1 1
ANALVZING HIGH·LEVEL REQUIREMENTS
0 .0 WI/I
outperform all
o/h8r wmding machines
NOI eSlim able
Spill P8ymen~
Accspt all kinds 01 psyments
Spill
2.0 Freshness. Sell no stale or outdated
1. t Accept coins
1.0
merchandise
3.0 Restocking. Automatically request restocking 01 Items sell/ng best In tha
area 4 .0 . ...
t 2 Accept currency
t .3 Accept debit card 1.4 Accept credit card 1.5 Accept debit or credit
card via Web transaction 1.6 Accept loreign coins
NOl eSlim2ble
Needs prioritlzalion
••••
Figure 11 .9 SplItting user stones
The plrlling process is Illustrated in Fi gu re 11.9.
11.7 SPECIFYING USER INTERFACES: HIGH lEVEL Th e speCIficat Io n of a user iNerface at a hi gh leve l is often included rn the high . level requirements. Recall fro m SectIo n 106.4 rhe fo ll OWi ng steps in specifyi ng user interfaces. Step I . Know your user Step 2 . U nderstand the busrness function rn questio n Step 3. Apply pnnClples of good screen desig n Step 4 .
•
W e wrll discu s Steps 1 and 2 in thi c hapte r as the y app ly o nl y to h ig h · level requirements. The rem ai ning sleps arc described the nex t chapter, on dctcu led requirements.
11.7.1 Step 1: Know Your User ThIS step invo lves understandin g the narure of th e applicatio n's eve ntual u ers. Figure 11 . 10 outlines ome of the fac tors Involved The c heck lis t IS a way of ensunn g that we know the ba IC c haracteristics of the anticipated u ers, and that we documen t our as: umptions. These characteristics determine the nature of the
user interface. In genera l, users with less educa ti on, trainin g. skill , and moti va tion rcquir~ grca t~r simplicity, more explanation , and more help. This may have to be traded o ff against ef~de ncy and speed. It is 011<11
desirable to provide several levels of uscr interface, dependin g o n th e leve l
01
the user.
11.7.2 Step 2: Understand the Business Function ThIs Slep requires the d esig ner to understand th e purpo e of the particula r proposed u or interface in I.nms of the application's overall purpose. For example, If th e busines purpose is the stocki ng of. warehouse, we may
SPECIFYING USER INTERFACES: HIGH lEVEl
• u,vd of knowledge and experience • Computer literacy (high; moderate, low) • 5) tem expenence (h igh; moderate, low) • Experien e with Imdar application (h,gh , mode ra te; low) • Education (h igh school; college; adva nced degree) • Read,ng level (> 12 years schoolmg, 5- 12; < 5) • T yp ing skd l ( 135 wpm; 55 wpm; 10 wp m ) • Characteristics of the user's tasks and jobs • Type of use of this ap plication (mandatory, dIScretio nary ) • Frequency of u e (co ntinual; fTcque nt, occasional, o nce .in .a-lifclIme) • T umover rate for employees (h, gh , moderate; low) • Impo rtance of task (h igh , moderate; low) • Repetitiveness of task (hig h; moderate; low) • Training antici pated (extensive, self-trainin g through manuals; no ne ) • Job category (executive; manage r; pro feSSio nal; secreta ry; clerk, etc. ) • Psychological characteristics of the user • Probable anitude towa rd job (posi tive; neutral; negative ) • Probable motivatio n (hig h , mo de rate, low) • Cognitive style (verbal vs. spatial , analytic vs. intuitive, concrete vs. abstract) • Physical characteristics of the user • Age (young; middle aged, elderly ) • Gender (male, female ) • Handedness (left, ri ght, ambidextrous ) • Physical handi caps (blind, defective vision ; deaf, mOlOr handicap)
Figure 11 .10 KnOw your user when developing requirements Sot.rce: Adapted from GaUtz. w.. '''Tl'Ie fsse"t~1 Guide to User Interlace Oestgn: Ar11nvoauClJon to GUI pnno ples and technIQues: ' John Wiley & sons, 1996
want the user interface to reflect the layout of the warehouse floor. The seque nce of screens that appear typica lly reAects the manne r in which use rs no rmall y carry out their tasks for thc business at hand. Sometimes the execut ion of a program ca n b e e nvisaged by displayi ng a se ries of C UI images . For exam pic , OAe could provi de a fair co ncep tion o f Encounter by di splayi ng a seq ue nce of scrcen sh o ts. Figures 11. 11 a nd 11.12 arc exa mpl es of preliminary C UI sketches forsc lling the qua lities of an Encou nter character. Upon being show n C Uls, the customer typicall y realize that he needs more or wants o meth ing different. In the exa mple how n in Figure 11.11 , it could well occur to the cus to mer tha tthc C UI for c hangi ng
Ouallbes
Value chosen
11.11 Preliminary sketch of user Interface for setting game character qualities
255
256
CHAPTER 11 ANALYZING HIGH·lEVEL REQUIREMENTS
Name 01 adjacent area
Name 01 adjacenl area
Name of adjacent area
Name of adjacent area
Figure 11 .12 Preliminary Encounter screen shot SOOrCf!- GraphKS reproduced WIth permiSSion frorn COfet,
the value of qualitIes is awkward because the total number of points may not change. The cu tamer would also probably observe that the CUI is no t visually appealing. The process of Rnalizing the CUI is very interactive. The detaIled requirements provide precise CUI specification , as explained in C hapter 12.
11.7.3 GUI Transitions Applicallons typica lly involve multiple CU ls. The high ·level requirements describe the required mouse aCllon that take the user from one CU I to another. Figure 11 . 13 shows a useful way to represent the transitions between CUls. When a particular CU I IS present on the monitor, the application can be co nsidered to be in a partIcular ,tal,. Changing from one CU I state to another is ca lled a l,a" ,;l1o" . States a-nd tran itl ons are actually more general concepts, and are described further in Section 11.9.2.
Indicates slart stale /
cricJc 'slock OVO"
An event
(usually a
___- - - - - - - - - - . - - . . ., mouse action)
GUI (a stale)
StockIng DVD GUI
GUI
Transition Hit ·commlt" butt""
Figure 11 .13 GUI transitions for video store application Introduction SOurce' copvrfpn .I. E. J 0l1Ude. Jdll Whey & sons. 2003.
SPECIFYING USER INTERFACES: HIGH !.£VEL
Select ------~-;:==== "stock OVO'
Select
•
',egi;;s;:;te:,---:::7L..-:.~-::=====:: ~---~
customer"
Select
Se/ect "egis/ef
' check our
customer"
•
Se/ect
Chac:Idng Out DVD
' check our
• Hit "commitbutton
~~~~. ____________•__~CI=='I=~=.;lg~l_n_D_VD __~
FIgure 11.14 GUI transitions for video store application Source: Copynght
E. J Braude. JOhn WIley & SOns, 2003.
A typical CUI/ transition diagram for the video store example is show n in Figure 11 . 14 . While a particular CUI is being displayed , an application is said to be in a particular , 'aic. We explore states further in Section 11.9.2 . Figures 11 . 15-11 . 19 show rough sketches of the CUls referenced in Fi gure I 1. 14. The deta iled requirements provide compete detail.
Select Procedure StockDVD
@
Register customer
(0)
Check out DVD
@ @
Check in DVD
Figure 11 .15 Rough sketch of "Select Procedure GUI" referenced in Figure 11 .14
Stock DVD ntle
I
I
Number 01 copies
fl&ure 11 ,16
Rough sketch of "Sketch of Stock DVD GUI" referenced In Figure 11 .14
257
2S1
CHAP~R 11
ANAlYlING HIGH·LEVEL REQUIREMENTS
Register Customer First name
I
I
Last name
I
I
Figure 11.17 Rough sketch of " Register Customer GUI" referenced in Figure 11.14
Check Out DVD DVD name
~
I Customer
~
I
Figure 11 .18 Rough sketch of "Check out DVD Gur' referenced in Figure 11 .14
Check In DVD DVD name
Figure 11.19 Rough sketch of "Check in DVD GUI" referenCed In Figure 11.14
11 .8 SECURITY REQUIREMENTS Many security requirements can be dfeC1ively expressed at a high level because we can express security goals without having to anllcipate all of the specific breaches that can OCCur Here is an example from the Eclipse project. The Eclipse Platform should provide the basic framework for a security mechanism that can be used by all plug· ins. Including a simple credentials store and u er authentication Additionally,
SECURITY REQUIREMENTS o ConAd~ntiality o
"C'
D.t3 passed not vi,Ible to the unauthorized.
o Nonr~pudi.tion
o
• Pani~ can prove the eXistence of agreement!:.. Integrity "I"
Ability to alidate no tlaltered in transit. o Auth~ntication "A" o Ability to vahdate user's ident Ity . o Authorization • P~rmi sion to deal with the subject . • Availability o
o
For example, a compromised by denial-or-service anacks
FIgure 11 _20 Common security requirements key pans of the Platform itself should be secured , such as the abi lity to onstall plug-ins, whIch might need to be restricted in certain products or (or certain users. I Standard c1assilkations for h igh-level security requirements are shown in Figure 11 .20_ They are mmetimes collected into the acronym "CIA." which stands for "Confidemiality , Integrity, and Authentica tion ." Figure 11.20 add 1I0llrtpud,alloll , which is the ability for panics to a eomract to prove reliably that the contract was indeed made _ It also adds nlllhonZailoll , which specifies who may access what panicular information, and availability, wh,ch speCifies reaction to denial-of-se rvice attacks. Denial -of-service attacks are activities, such as Aoodlng a Web site automatically with requests, that make i difficult for anyone else to access it. We ensure that these propenies are satisfied by suitable corresponding requirement at the detaded level. However, ill-meaning perpetrators devise ways to compromise systems by explOIt ing combonations of propenies that the sy tem does 1101 possess. To explain th,s, consider a (non -software) set of requ irement that were already devised to ensure that ,he funds in a prominent Irish bank werc secure. These required that two bank managers, each possessing a dIfferent key, were required to unlock a major safe. TI,ey .1 0 reqUIred COnstant guards for the managers. Both procedures wcre fa ithfully observed . It is important to understand ,hat for perpetrators, exi ting sccu rity mcasures simp ly con titllte a set of constrain, wilh,n which they work, elling them to seck opponunities that the constr.ints do not cover In the case of the bank example , there wa no requltement for guards on the f.milie of ,hese two officia ls. Observing th is combina tion of prope nies that the system did "01 po seS5, enminals took ho>to go the famil ,es of both managers and by this mean ocrced the officers into obtaonong the bank's cash on their behalf_ PrIVacy is often hnked with or considered part of ,ccurity . This is because the purpose of many exp loits" to gaon accts, to data to whIch the perpe trator" not entit led , thereby compromising its pro a _ One t:Xamplc of priva y regulations IS the Health Insurance Ponability and Ac ount.bility A t of 1996 (HIPAA ), whIch regulate> hea lth inlo mla tlo n rea ted o r maIntained by health care prOVIders who CI1!l"llt in tksignated e lectronIC hea lth care tran a tlons _The Department of Health and Human ervlCes IS respon ,ble for implementong and enforCIn g HIPAA The a t took cHeu on April 2003 _ The main thrust of HIPAA I to en>ure that an ,"dlvldual\ health infoml.,ion 1< u,ed lor health purp
259
260
CHAPTER 11
ANAL YlING HIGH·LEVEL REQUIREMENTS
• n,e H ea lth Insur.ln cl' Po rt abilIty and A counl abiltl y Ac t passed In 2000 a nd 2002 ; 2003 compha" e • Regu lales health information c rea ted o r mallltalned by health care providers • U Department of H calth and Human rrvlces rc< po nslble fo r Im plementin g
•
and enfo rCi ng
lalll thrust· Ensure th at an IndI vIdual's hea llh In fo ml . tl o n IS used only for health pu rpo
Figure 11 .21 MaIn poInts of HIPAA Source HIPAA Act of 1996
pertaini ng to an indi Vidua l is housed (·Iectron icall y an d/or is rrtm mitted over telecommunicati o ns system s!
netwo rks. The standard mandate safeguards for ph ysical stora ge and maintenance, transmission, and access to IIldividua l health info rmat io n. EntitIes reqUIred to co mpl y with the standard include any health care provider, hea lth care clearing house, o r health plan that electronicall y maintaIns o r tronsmils health information pt'Ttaining to an in divi dual · Figure II 2 1 ummarizes these poi nts.
11.9 USING DIAGRAMS FOR HIGH-LEVEL REQUIREMENTS Acc o rd ing to D avi [6 ) and WIegers [7 ), no SIngle VIew o f requirem ents gives a complete understanding, and It IS o h en hel pfu l to represent hig h ·leve l req uire me nts usi ng dIag rams. What IS o ften needed is a combination of text and dIa g rams to convey a complete pic ture of the Inte nded apphcatlon . We introduce two types of dI agram used to descnbe hI g h . level reqUIre men ts: da ln flow and ' Ialt lra tl,illotl dia grams. We are using them he re to express requ irement . Thcy arc often used to ex press deSIg ns as wdl , and this can be confusing. The dIffere nce to watc h fo r IS not so much th e fo rm of ex pressio n as whe ther th e attempt IS to express ' what" (requ ireme nts) o r "how' (desig n)
11.9.1 Data Flow Diagrams Some requirements are na turoll y described as th e flo w of data am o ng processi ng e leme nts. Fo rexample, imagllle that our customer is tryin g to explalll what he want fro m an ATM banking applicatIo n, startm g with depo It and affecting accounts at several locations In a Jain flow dlagra .. , the Hod" , sho wn as CIrcles or rectangles, represent processing Untts. ThearrolDS between nodes deno te th e Ao w of data . The arrows are annotated wilh the data's type . Dalll , to,rs-places where data reside, such as databases arc den o ted by a pair of honzontallincs enclosing the name of the data store. ExIt""" a9C>1CtCs such as the user and printers arc represented by rectangles. For the ATM application , the dtpo,il functi o nality mig ht get the deposit from the user and check tht deposit tronsawon to ensure that It IS legitimate. These '"nnions arc represented by clfcles In Figure I I n . Next , the type of data Rowing between the functions is noted on the figure- the account number and the depOSit amount. The user IS involved. too, and so IS represented A function to create a ~lI",mary of account'S, 10 give another example', requires input from a store, as shown .
A more complete data flow diagram for the ATM requirement would be as shown in Figure II 23.
UStNG DtAGRAMS FOR HtGH'lfVEt REQUtREMEPlTS Processing 81811.801
Input Get deposit
i-----UIIr
ACCOUnt no.
Direction of data now
and deposff
Outout
Dala type
Prtnlet I
•• • •••
Validate deposit
Balance
query
I Data store
Account
Account __ dala
Create account summary
database
figure 11.22 Data flow diagram explanation of symbols
The complete diagram of Figure 11 .23 includes the "member banks" data score , which is a list of banks allowing a deposit at this ATM. It also shows the data Aow for the response to a query, in which details about an account are displayed. ExpreSSi ng these requirements in text form only would be marc difRclllr than using a data Row diagram to help describe them . Notice that data Aow diagrams do not show COnlroi. For example, the ATM application does not indicate what function occurs first . Standards used for the symbols differ among organizations (e .g ., rectangles ca n be used for the processi ng elements rather than circl",,). Whether or not data flow diagrams are helpful for expressing requirements depends upon the application . For example, the ATM data Aow diagram in Figure 11. 23 clarifies for many re.ders what behavior the application is mcant to exhibit, whereas video game requirements would probably not be
Member banks
Get deposit
I
Bank nDtnB
User
Error
Inquiry
Account
..-
Account II & deposll
Get
j
Error
account display
Validate
Validate deposit
Inquiry Account II
Account II
Display
Make
account
Inquiry
Prfm'
& deposir
Account
dar. Do deposit
transaction
BaIanC6 query
'\J
06po!U Account "'"""unl 1,.n08elion _.- _. database -- 00/8
11 ,23 partial data flow diagram lor ATM application
Create account summary
261
262
CHAPTER 11
ANAL ¥ZING HIGH-lEVEL REQUIREMENTS
descnbed well uSin g a data now diagram . When usinM these dia gra m' for require ment s , peClnc.tlon, there i~ a "snlAcant dan ge r of hpp inl! into perfo n"in g desig n ,"stead o f analyzlnB reqUirements. For example, If an appitcatio n IS reqUired to tra ck the now o f o rders within a compan y, then a data now diagra m (DFD) shOwing thl proces at a h ig h level would be an appro priate form for hi g h-level reqUi re me nts because the DFD " nceded to ex press the o utcomes O n the other hand, consider an application that is required to apply a complex formula . A DFD explain,"!! the calculation process would be part of the design , but nOt the req Ui re me n15- the fomlula would be uffi cient for expressing the requirement . We will r<-vislt data Aow d iagra ms in Pan IV, the de ig n ectlon of the book.
11.9.2 State Transition Diagrams Sometimes, an application, or pan thereof, is best th o ught of a being in one of several slalrs. The Sta te of an application is its si tuati o n o r s tatus. States are sometimes called "phases" or "stages ." Although a state often correspo nds to a CU I and vice versa, the state concept is more general than C Uls_The idea is to divide the applrcatlon into sta tes so that the application is always in o ne of these states. Note that the states we arc de fi ning arc based o n the requirements of the appl,c.ation-not its software design . For example, it might be useful to think of an o nlrne sho pper at a bookselling si te as being either in "browsing" state (looking at book info rmati o n) or in "purchasing" state (providing credit card information , etc.). A diagram that depicts the different states and the transitions between states is ca lled a sial, lrallsilion diagram . There arc several pOSSible Enco unter states,
• 5,l/mg up· the stare during which the game is being set up • P"ilOring. equipping th e players character with qualities such as "strength" and "intelligence" can be performed as lo ng as no foreign c haracter is present
• Wa iliHg. noth ing is happe ning in the ga me th at is experienced by the user • Engaging the state in which the player's character and the foreign c haracter arc exchanging quality va.lucs The e sta tes arc sh own in a UML state transi ti o n diag ram," Figure 11 .24. For eve nt -driven applications, diagrams Irke this can be an effective way for the custo mer and developer to obtain a shared concept of how the: application IS meant to work . After identi fyi ng the states, the Imn silions between states are added. TranSitions, denoted by arrows, arc each labeled with th e name of t he ro," 1 that causes the object to change from one state to another. Events arc
Preparing
_~ Setting up
,
,••
(initial state)
I
Player clicks quaNties
Complete setup
I I
,I
menu •
(final state) , •
Wailing
ForBign character __--j ' - - - - enters 8f8a
Figure 11 .24 Partial Encounter state transition diagram
,, ,
Engaging
USING DIAGRAMS FOR HIGH-LEVEL REQUIREMENTS
Stale EY..~
Coodilioo
Player
moves to
adjacent ~ 8rea
{foreign character absent]
{foreign character present]
Engaging SIal9
Condition
Figure 11_25 Using conditions In Slate transilion diagrams occurrences that can cause a c han ge in the object's state . A t)'pical eve nl on a CUI is a mo use c lick. The soli d circle denotes the startin g state. The final state IS d e pic ted by the solid circle inside another ci rcle. States and transitions ca n apply 10 entitic at many levels. For example, a ship ca n be in one of several stales, such as Sailing , Docking , or Dock,d . Parts of the shi p ca n be in evera l states, For example , a cabin can be in Occupied or Unoccup"d state. Sometimes, when an objec t is in a give n state and an eve nt occurs, the object can tran itlOn to one of
several states, depending on a condition . For exa mple, when thl- player decides to move h er character 10 an adjacent area, the ga me tranSItions rTOm th e Waitillg state into one of two states. O ne possi bili ty is to transition back to Waili"g state (if the foreign c haracter is absent from the e ntered area ); th e o ther is to transition to the Engaging state (if the fo reign c hara c ter is prese nt in th e entered area ). In UML, co nditi o ns arc de noted b y square bra cke ts, as sh ow n in Figure 11 .25 . The complete state transition d iag ra m for Encounter is sh ow n ID Figure I 1.26 O nce the player has fi n ish ed scumg up the Encounter ga me , the latter transitions from s,lIillg Up state into Waiting state. If Encounter IS in
Se\1Ing up
Ptayer dismIsses
Reporting Setting qualltle$
report Player completes setup
window
Player set qualities window
requasts status
Foreign chartJcter
enters area
enters area
moves to adjacent area
{foreign choracter pro.ent]
• Fleur. 11 _26
requests to __- set qualities
Player
Playor quits
Player
Encounter sUite transilion diagram
Engaging
~-===
263
264
CHAPTER 11
ANAL VZING HIGH·LEVEL REQUIREMENTS
\\fmfl"9 ,tatc and a forc l!!1l harac ter e llterl, the n Ellco""ler trln,itlo n, IIlto E1I9a91119 sta tc F,gurc 11.26 ,nd,catc, th.t th c pro c-; . of setlll1g qual ity va luc< .nd the pro e» of repOrllllg the re,ldts of an e ncounter ca n b<: int el1\Jpted by thc amv.1 of the foreI g n c haracte r The laller allse< a new encounte r to commence Immcdiately. A sta te Iransltio n 1110 del is a good way to explaIn the o llce pt of opera tI o ns of Encounter State tran Itio n model arc commo nl y used as de Ig n 100is a well (sec hapter 16 ) Whe ther o r no t they should b<: used to exprcss 11Ig h . level reqUlremellts, as we are dOlllg here , depends o n the apphcation in questIon and h ow helpful doi ng so IS fo r the custo mer. Tim ma y require ome edu cati o n of the cu tomer. For man y app1.catl oIlS, each tate correspo nds to a C UI H owever, there .. a wide variety III what we may de Rne as a state . ll,e tate d iag",m in Figure 11 .26 corre po nds rOll ghl y to the pre cnce of VIsua l artifacts on the mo nito r, but thcsc are no t C Uls. Fo r example, when the foreign ch.",ctcr FreddIe appear o n the monitor, the app1.catlOn t",nsltio ns to E1I9n91119 tate, but rreddie is Just an additio nal g",ph,ca l clement, not a scpa"'te CUI.
11.10 CASE STUDY: HIGH-lEVEL SOFTWARE REQUIREMENTS SPECIFICATION (SRS) FOR THE ENCOUNTER VIDEO GAME
Note to the Student: Using a standard 10 write the SRS helps one to cover all of the aspecrs of requirements that readers need to know about, and provides a recognized structure. Seve",1 standards are avail· able , but we WIll concen""te on the IEEE Stan· dard. The complete IEEE 830·1998 standard can be found in [8). Most organizations allow modi · fkation of the standard to tailor it for their own use In fact, the template used below modi Res the standard by omitting some less important sec· lions and by addlllg sections on concept of ope",lions and use cases. The reader can com· pare the case study headings with the standards shown III Figures 8 and 9 of Chapter 10. In the case study portion of this chapter, Sections I and 2 cover the high .level require · ments. The remainder of the document, Sections 3 and 4, containing the detailed requircillents, IS
provided in the case study at the end of Chapter 12 . Recall that customer requirements are not intended to be detailed enough to develop the design and implementation thi is the purpose of rhe detailed reqUIrements.
History of versions of thIS document,
1/ 19/98 Hal Furness Initial draft 1/29/9 8 Karen Peters: Reviewed for technical accu",cy, changes made throughout
2/ 1/98 Hal Furness: Entire document reviewed for small improvements 2/ 19/98 Karen Peters: Document reviewed and suggestio ns made 2/29/98 Karen Peters: Moved use ca.ses to Section 2.2 3/ 1/98 Hal Furness, Improved thro ughout; sense not changed
wording
5/20/04 Enc B","n, Updated to 830·1998 standard 14/ 20/08 Eric Brannen, Edited to improve as· sorted clarifications
1. Introduction 1.1 Purpose The purpose of this entire document (not the purpose of the application ).
This document provides all of the reqlliren1cn~ fo r the Encounter video game Parts 1 and 2 are II1tended pnman ly for customers of the ,pplicatlOn, but will al
tended primarily for
be 01
mtcrt: t to
ustomers.
CASE STUDY: HIGH-LEVEL SOFlWARE REQUIREMENTS SPECIFICATION (SRS) FOR THE ENCOUNTER VIDEO GAME
1.2 SCOpe (The Iospccts of the application this document is intended to cover.)
Thi document covers the requirements for release 0.0. I of Encounter. Me ntion will be made throughout thIS document of sele ted probable fea . rures of furure relea es. The purpose of this is to guide devdopers in se lecting a design that will be able to accommodate the full ·scale application .
Encounter is to be a role-playing game that simulates the lifetime of the player's main character. It should be of interest to both men and women. The measure of 'success' in playing Encounter is up to the player. Typically. success will be measured by the ' life points' maxImum attaoned by the player or by the ability of the player to live as long a life as possible. Some game characters arc to be under the contro l of the player. The rest. called "foreign" characters. are to be under the application's control. Came characters will have a fixed total number of points allocated amo ng qualities such as strength. stamina, patience, and so o n. C harac ters encounter
1.3 Definitions. Acronyms. and Abbreviations See Table 3.3 .
1.4 References Software ConHguration Management Plan (SCMP) for Encounter version 1.0 Software Design Description (SDD ) fo r Encounter version 1.2 Software Project Management Plan (SPMP) for Encounter version 1.2 Software Quality Assurance Plan (SQAP) for Encounter version 1.0 Software User Documentation Plan (SUDP) fo r Encounter version 1.0 Software Test Documentation (STD ) for Encounter version 1.0
1.5 Overview Intentionally omitted.
The author of this document felt no need for this section. and ontends to cover the overview in Section 2.
2. OVerall Description MAke this !leneral enough so that it oS unlikely to chanllC much in future versions. Avoid tC&lelllcn" that are repeated on later sections.
each other when they are in the same area at the same time. and may then engage each orher. The result of the engagement depends on the values of (heir qualities and on the environ ment in which the engagement takes place. Engagements are not necessarily violent or adversa nal. Players have restricted opportu nities to reallocate their qualities . One of the player-controlled characters will be referred to as the "main" player character.
In early versions of this game. there wi ll be only o ne player·controlled character and one foreign c haracrer. The eventual nature of the characters is 10 be determined fro m insights gained from surveys and locus groups. It is expected that initial releases will not have anionation Encounter should eventua ll y be hig hl y customl zable. so that users can eit her start with predefined games . substitute predesig ned char· acte rs and rules of engagement. or devise their own characters and ndes of engageme nt. The design shou ld support expansio n into a fa mily of games. including Intemet ·based multiple playoc versions.
2.1 Product Perspective In this secti on. Encounter is com pared with other related or competing product . This os a useful way to prOVide perspective on the application . Subheading 2. 1. 1 of thos section h.s been changed from the IEEE standard to accommodate "concept of operattons."
265
266
CHAPTfR 11
ANAL Y2ING HIGH·LEVEL REQUIREMENTS
· n OUnter IS Intended to tu lAIl the need (or prog",mme'" to have a g rea ter IOnuen c OVer the ntent o( video ga mes with additiona l program · ming It IS al 0 intended for a somewha t mature clientele Encounter is IOtended to appea l to bo th ge nders . The de iBn and documentation (or Encoun · ter will make it convellient to expand and modify the ga me. It IS anticipated that Encounter will be used as a legacy application for expansion IOtO applications such as o ffice Interaction simulati o ns .
2.1.1 Concept of operations This section conveys the overall concept of the application by whatever mea ns are most natural for doing so. In the case of Encounter, the requirements developers deci ded that state/transitions best convey the concept.
the sta ndard IEEE head lOg ' u.>er in terfaces" 10 empha ize Ihal the«: arc not the detailed C Uls
2 .1 .2 .1 Area User Interface Concept The areas In whic h encounters take place sha ll have an appear· ance very ro ug hl y like that shown in Figure 11. 12. 2 .1 .2 .2 User Interface Concept for Setting Quality Values When sctti ng the values o( game characters under his control, the player uses an In terface o( the form sketched approximately in Figure 11 . 11. The scroll box i u cd to identify the qua lity to be SCt, and the tex t box IS used (or setting the value.
2.1.3 Hardware Interfaces None. Future releases wi ll uti lize a joy tick.
2.1.4 Software Interfaces No ne .
Encounter can be 10 o ne o( the (oll owing states (also shown 10 Figure 11 .26), • Setting up. The state set up by the playe r
10
which the game is bei ng
• Reporting. The system is displayi ng a window sh owi ng the sta tus of the players character(s). • Se tting qualities. EquipPing the players character With qualities. Thi s process consumes arbitrilry
amounts o( time, and can be perfo rmed as long as no torelgn character i pre cnt
• Engagi ng . The state that app lies whenever a for· cign character and the player's main character are present in an area
3t
the same time .
• Waiting. The: player and the (oreign character(s)
2. 1.5 Communications Interfaces No ne . Future releases wi ll Inte rface wi th the Internet via a modem.
2.1.6 MemoryConstraints Encounter sha ll require no more than 16 MB of RAM and 20 MB of secondary storage (see test plan < test refere nce to be supplied ».
2. 1.7 Operations No rmal and special operatio ns required by the use r, uch as modes of operatio n, da ta proc· essing support functio n , a nd back up and re· covery operations .
• are not actIve.
This state/transit Ion is tested by integration test < to be supplied> .
2.1.2 User Interface Concepts The followlOg figu,..,. are preliminary sketches of key I'ser i nl~c(s o nly , used to proVIde PCISPCC· live o n the producl. All lhe user int., laces are ~pccifi.ed in derail in Section 3. We have modified
It shall be possible to ave and re trieve a game.
2.1.8 Site Adaptation Requirements Req uiremen ts for execution o n a particular installat ion; versions in various la"B"lIcs (e.g., French, Japa nese, panish ). No ne.
CAse STUDY: HIGH·LEVEL SOFlWARE REQUIREMENTS SPECIFICAnON (SRS) FOR THE ENCOUNTER VIDEO GAME
2.2 Product Functions
I. Player h its hyperlink connecling displayed area to adjaccnI area
Summary or the major funcltons of the applica. tion. This section is more detailed than Section ' .5, but does notattemptto supply all details, as doM in Section 3. The writers of this SRS ckcided that use cases are an appropriate man. ner in which to specify the overall functionality
of Encounter.
2. Syslcm di plays (he indIcated adjacent arca Including player's c haracter
2.2.3 Encounter Foreign Character Use case ActOr: Player of Encounter U sc case: I. System moves a foreign game character into the area occupied by the player, or Player moves into an area containing a foreign character
This section specifies Ihe required overall func . tionality of the applicalion, but is nOI Inlended to provide the complele specifications. Sectio n 3 pro. vides the requirements in complele detail
2. Syslem causes the two c haraclers to engage
2.2.1 Initialize Use Case
4. If eilher the player's characler or the foreign charac ler has no pOinls, the game terminates
Actor: Player of Encounter Use case: Figure I 1.27 gives the lexl of Ihe JnitJalizt use ca e. The use case is shown in con text with the Eneo"nl" foreign ebameltr use case and the Sri ",It, use case. Initialize is Ihe typica l sequence users execule at the beginning of a session. This use case cOfT~ponds to test < Iesl referen e to be supplied> in the Software T eSI D ocumeOia tion.
2.2.2 Travel to Adjacent Area Use Case Actor: Player of Encounlcr U se case:
Actors
Travel 10 adjacenl area Encounler foreign charaCler
Designer
5. O therWise, Syste m moves the player's character to a random area different from that in which Ihe encounier tOok place, and displays it there
2.3 User Characteristics Indicate what kind of people the typical users are likely 10 be. Examples: novice, software professional , accoumant with five years of computer usage, etc.
Initialize Initialize
Player
3. Syslem displays the result of the engagemenl
Sal rulos
11 .27 Initialize use case (or Encounter
- - 1. Syslem displays playefs main character In the dressing room. 2. Syslem displays a window 'or setting his charactefs qual~les.
3. Player allocates the qualities his main character. 4. Player ohooses an exit 'rom the dressing room. 5. System moves playefs main character Into the a_ on Ihe other side of the .xlt.
0'
267
268
CHAPTER 11
ANAL VZING HIGH·LEVEL REQUIREMENTS
The u cr IS expected to be approXImately 203 ye.n; o( age
the devel o pers. It IS antIcIpated that they WIll be part o( a futurc release "OptIonal" requITement. will be Impleme nted at the dI scret io n o( the developers.
2.4 Constraints These are all conditions that may limit the developer's options. They can onginale from many sources.
Encounter shall operate o n PCs nlnning Windows XP or later at a minimum peed o( 500 1Hz. Java shall be the implementation language.
2.5 Assumptions and Dependencies (Any assumptions being made future hardware.)
(or example,
11.11 CASE STUDY: HIGH-LEVEL REQUIREM.ENTS FOR ECLIPSE
Note to the Student: This section discusses published requirements for Eclipse. There is no single requirements docu· ment (or Eclipse the requirements arc spread over multiple documents. The authors have reconstructed a partial requirements document from thesesourcesata single pointin time, p.lacing them roughly in IEEE fonnat for the sake of comparison. The result is necessarily incomplete, and illustrates a shortcoming of many 0 pen source projects. Most of the material below is quoted directly (but selectively, of course) from the Eclipse documentation online at the time.
o ne
2.6 Apportioning of Requirements (Order in which requirements are to be implemented .)
The requirements described In SeC1ions I and 2 of this document are referred to as "customer requireme nts"·, those in Section 3 are referred to as "detailed requirements ,f The primary audience for customer requirement is the customer community, and the secondary audience is the developer commu nity. The reven;e IS true (or the detailed requirements These two levels o( requirements are intended to be consistent. Inconsistencies arc [0 be logged as defects . In the event that a r('quiremcnl is stated within both the customer req uirements and the detailed requirements, the application shall be built (rom the detailed requirement version since it is more detailed . '"Essential'" requirements (rdefred to in Section 3) are to be implemented (or this ven;ion of Encoun · ter. "Desirable' requirements are to be implemented in this release i( possible, but are not committed to by
'The Eclipse Project is an open source software development project dedicated to providing a robust, full.featured, commercial ·quality, industry platfonn (or the development of highly integrated tools. The mis· sion o( the Eclipse Project IS to adapt and evolve the eclipse technology to meet the needs of the eclipse tool building community and its users, so that the vision of eclipse as an industry platfonn is realized: ' 'The Eclipse workbench consists o( lOim/olDS. Each window contains part,. Each part can be a vittD or an wilo,. A pmPte/iv< is a physical conRguration o( pans. Figure I 1.28 shows a typIcal Eclipse screenshot: ' This example is a Java perspective (as indicated in the shortcut bar). This pen;pective consists o( a Windows Explorer-type of view, an editor, and other parts, including the console view.
This panicular window is used merely as an example, to make the speci6cation more understandable not as a detailed spedRcalion-
, From http://www.eclips• .orWp.oJcc.slindex.h.ml. • Ibid.
ECUPSE PLATFORM SUBPROJECT (FIRSl OF THREE!
..,
P .... 'ucth •
.. . ... l
•
~.r
1u,,11
J...
.. To Ch&l\ir ql.u 9"eT. t'ld ~ _ , 'JO t .o : WHY' . , Pr.,faaac: ' C E bit:T. t ~ ca,.cod " aDI1 " . ~_ ••
•
~::~1
. . .
. .. , 7
7
)"otu ,U
• • ••. \\ )Mo ......
,.y...
.El.... ueut .. C""' 1109 ..
l S part. )."tuI "log bordC1" .. " ."port , •••••• 1 l1'9 . . ... l ..
.. "'It • •
Ho,90'tuLt
#-.o.Q
~ .P.£ SF«
, lb..,lIctJ ..)
J
5 1"'091 1 hllll Lc_ • _ . S tr t"9l
SUuri J e!ht,lt.c-.• • aew S t r\lr9{ c .... r ( I hId "tcu' . II '0' c ....r l J eo:hlS!:. :n:t cu t a ' Z J
-1
!.J( -u....,......• _._"
..
·c
n
.
•
- Cu , '
---
_.erE
0Copf
lotu.h""
Agure 11 .28 Eclipse GUI SOUrce: Edlpse, flttp :JIWWW e<:lrpse org/articlesJAttic~UI-GoidellneslJndex.hltnl.
The following three sections are quoted from Eclipse documenration WIth some adaptanon .
11 .12 ECLIPSE PLATFORM SUBPROJECT (FIRST OF THREE) Note to the Student: Since Eclipse IS organized around three sub· projects, it is natural to org.nize the summary requirements in the same way . With l ~ each project, summary requirements are organized ilround """,,cral "themes." Th,s IS a way to orga· nize the (high· level ) reqUIrements and allow latitude at the samc tIme The the mes do pro · vide content , but they avoid pecifying d etails.
The Eclip e Platfo rm provIde. the fun dam ental building blo ks of the Eclip e projects Plan tasks arc new features of the Ec hpse Platfo rm o r igmhcan t reworking of exi tlng feature lany of the hanges under con. iderallo n for the next release of the Echpse Platform addre s three majo r themes, a follows · • U ser experience theme. ImprOVIn g Eclipse from the poin! of vIew of the e nd u e r • Responsive UI theme . Making it easIer 10 wnte EcI ,p e plug· ,ns that keep the UI re ·pon"ve • Rich client platform theme. Ce nera hzl ng Echl',e into a platform fo r building no n. ID E appJ.ca tlo ns In addtno n, there are Impo nant E itp<e PI.tfoml Improvement, that do not natu rally ht IntO a ny of the above themes The<£: are a tegori:ed as f 1I0w< •
ther E IIp e PI . tfo m1 IIems
269
270
CHAP I ER 11
ANAL YlING HIGH -LEVEL REQUIREMENTS
Belo w a", examples elaborating upo n these .
User EXperience Theme Th, the me incl ude, Imp rovi ng bo th the "o ut o f the box" experience
0
th at new users arc producti ve
too lbars, and le ng thy nat l, sts of preferences Th .. pro blem IS aCllte In large Eclipse-based produ cts. The Plat fo rm sho uld provi de add itI o nal ways fo r control _ ling wo rkben h clutter, such as funher menu and toolbar custo ml za bil ity, d isting UIshing be tween novIce and ad va nced func tio ns, suppanln!! d.rfc rent de· veloper roles. and ma rc speci fic o bject contributions fo r panicular me ty pes ., ( 37929)"
fas te r, and fi nd ing bellc r ways to scalc up to large num bers of plug .ins witho ut overwh e lmin g the user.
Committed Items (Eclipse Platform subproject, User Experience theme) The requ irements h ere arc grouped by priority. ' Commltted" IS the highest priority. The o thers are · proposed" and "deferred." Completion of a requirement is denoted with a green
c heck mark.
Improve UI scalability "Des pIte dfo n s to e nsure UI scalabili ty WIth a large base of avai lab le tools, the Ecli pse wo rkben c h still Intim idates ma ny user'S wi th
II_pm·
The number given above in parentheses is a link to the following bug cntc",d in Eclipse's BUgzilia bug database, https/ /bugs.eciipse.orglbugsl show_ bug.cgi7id =37929. This and other requirements are managed in the same way as defects The reason is that both deRne work to be done on an existing application. Each Bugzilla location contains extensive discussion about the requi~ . ment and the progress made imple",enting it. This amounts t'O the detailed specification. common way of specifying detailed requirements in open source projects. The begiAning of Bugzilla Item 37929 is shown in Figure 11.29 and Figure 11.30. We w;1I rerum to the subject of requirements tools in Chapter 12.
long menus, wide
ht l7nf r;-.. ....,!mp:tO'l' m.... '.)
&.aLiK &:It.!!IIcn.~ ... .. ,....,
~
¢'«nt.,.
w.... t .
• C' .f!! .." ~
r."': , "' "'" .. ,~ • ;: ' .., ~'" 1t'~I:DI'·'" :hI I
"''''"It
Figure" .29 USing Bugzilla in Eclipse to track bugs and detailed requ irements, 1 of 2
ee•
ECUPSE PLATFORM SUBPROJECT (F(RSf OF THREE) Leaw as RESOt VB» m Rn (' a.opmbvj r Marie. bua as VERn I F I) (" Mark hue as CLOSEn t:'
Vltw Due Acdvll)' I Format For Pabidn& Description:
- - AdduJCnaJ CO" ....'"
!!l. Prom.hm.us RN..,.s200J..Oj.21 1/.·/ 8 - •••
--AddlhOnaJ Co,.""", !!l. From MorPMus 200J·Q6.08 14..40 - -
I ~ olad af ter ceadlDO the [cllp3e Pr o) e c ~ Dratt 3.0 pIon tha t 1n ecl l ~e 3.0 that tble bUQ q01QO to be a4dre3~ed , but I a130 V&nt tbe peo ple who 13 going to eusdce~5 t.h13 bUQ to pc ovld.e Cop 1 ' ~ t o do ~bC' lIICnu and t. oo lbar cU3t.D:lll ECot i o n ( 1 ,e, 01108 u.s to remove WlVDJlt.ed IIICQ\,I 1tc....., peoor" "Q~ l c ally ) • It .,..... .. a .. a
~"
...... r .... '; .... ~ ... ,.. r _ ... .. . ; ... . . . ...... " .... .-.-. . .. .. _ _ .. ......... r ,..,. . ........
_ "'_,.v
FIgure 11.30 USing Bugzifla in Eclipse to track bugs and detailed requirements. 2 of 2
Improve initial user experience Users who are new to a n Eclipse·based product ca n find the ir first experiences with it overwhelming , even dauntin g. The initial experie nce would be improved if a product cou ld preconfigu rc the work · bench to show o nl y the subset of function that a new user really needs; welcome pages could be personal . ized for part icular use rs roles or levels o f ex perience . . " (37664 )
Improve U/ affordances . , . (3767 1) "Work romp/tId
proposed Items (Eclipse Platform subproject, User Experience theme) The ' proposed" category is the second most im · portant priority. Note that these requirements are expressed in an exploratory, less specific, manner. Requirements analysis still has to be performed to transform these into commil1ed items.
Th e fo ll owi ng work items are being ac tively Investi gated , but we arc no t yet ab le to promise any solutIOn for th is rolea c .
Allow editors to open files outside workspace This is a way of tracking the status of requirements.
A ommo n reque t is to be able to use Ecil psc to open a fi le that i not part of the workspace, or " erhap' even o ne o n a remote ys tc m, In add ilion, appli ation
271
272
CHAPTER 11
ANAl VZING HIGH-LEVEL REQUIREMENTS
would like to provide fi le exte nsion associa tio n so that doub le -cl icking o n a Ale in th e 0 de kto p would open th e assoc iated Ecli pse edi tor. The o perat io ns and capabi lities ava dab le o n th ese 'outsi d~ of the workspace" Ales wo uld need to be deA ned . (37935 )
Improve workspace synchronization with file system . ... De tails o mitted
(. recently deferred item) Provide a general purpose navigator (36961) ... These arc just a few examples Ihat illustrate the organiza tion o f th ese documents.
Other Eclipse Platform Items The foll o wing are examples from the Eclipse Platform subprojec t within this "theme."
Content-type-based editor lookup. ... Details o mitted
Deferred Items (Eclipse Platform subproject, User Experience theme) The Ecl ipse project t racks requ ire ments that may never be imple me nted. This enables them to be revived , provides history, and discourages th e m fro m bei ng pro po ed again. It helps to clarify th e project's directi o n.
These items are next In line fo r chis release. As comm ltters complete th eir assigned tasks or add i· tiona l help becomes available , some of Ih csc items may be comm ilted for Ih is release:
Add table of contents support to wizards (36947) .. . D etails omitted
Add project templates (36960) . .. J - .. (. recently de-committed item) Aid ongoing learning (37666) More tracking the status of requirementS. "Decommitted" means, dfectiv¢ly. "dropped'
Design Constraints: Compatibility of Release 3. 0 with 2.0 and 2.1 Thissecti o n is qlloted from note'. It consists of no nfunctional requirements, and one example is expanded here. A "breaking" change is one that preve nts some applications from executing on the new version that did execute on the old one. N o te also that this paragraph contains po licy elements for requirements rather than requirements themselves.
' Ecl ipse 3.0will be compatible with Eclipse 2.0and 2. 1 to the greatest extent possi ble. The nature and sco pc of some of the key plan ilems are such that the only feasi ble solutio ns wo uld break compatibility. Since breaki ng changes are a di nlption to the Eclipse commun ity, they ca nno t be taken lig htly. We (the Eclipse PMC) wi ll have an opcn d i cussio n with the community before approving a proposed breaking change for inclusion in 3.0. In other regards, Eclipse 3.0 will be compatible with 2.0 and 2. 1. W e also aim to minimize the effort requi red 10 po rt an existing plug-in to Ihe 3.0 APls. We wi ll provi de a comprehensive EeU"" 3 .0 Port"'9 Guide that covers all areas of breaking AP I c hanges and describes how to po rt eXisling 2. I plug-ins to 3.0. Up-to-date drafts of Ihe Eclipse 3.0 Porting Guide will be included with miic-slo ne builds so that It'S possible to climb .baaed the 3.0 rel eu e wago n at th e earl y stages. o r to estimate the amou nt of effort Ihat wi ll be involved in eventually porting exisling plug-ins 10 3.0'• hu pJ/www ecl ipse oeg/e Ilpse/developmen t! cc hps<-proje l_pl.n_L0..20040 130.htm l.
CASE ST1.JOY: HIGH-LEva REQUIREMEIflS FOR OPENOFFICE
11.13 CASE STUDY: HIGH-lEVEL
REQUIREMEN I S FOR OPENOFFICE
nather than to SpeCify its requirements. The follOWing is found at http jlwww.openofflce org/productlwriter.html _
This s«tion is intended to give the reade r an Idea of the O~nOfflce requirements. No~ 10 the Student,
The prose below has been adapted by the iUlhol'5 from httpJlwww.openofflce.org/prod _ uaJ which was written with a partially marketil18 Ravor. For example, we have replaced "WRITER is a powerful tool _. _" with "WRITER is a tool . _ ... "You can easily integrate images" has been replaced by "It facilitates integrating images.' OpenOffice requirements are decomposed at this top level as shown next .
OpenOfflce consists of the following , • WRITER is a 1001 for creating profeSSional docu ments, report , newsletters, and brochures. It facil itates integrating images and c harts in doc uments, creating everything from business letters to com plete books with professional layo uts , as well as creating and publish Web content. • CALC is a spreadsheet that facilitates the absorpti o n of numerical information . It e nables users to calculate, analyze, and visually communicate data. Advanced spreadsheet functions and decision making facilitate sophisticated data analysis. C harting tools ge ne..,te 20 and 3D charts. • IMPRESS is used for the creation of multim edia presentatio ns. It allows specia l effects, animation , and drawing tools. • DRAW faCilitates the pro duc tio n of everything from si mple dia gra ms to d y nam ic 3D il·lustratlo ns and special e ffetts. • The Da tabase User Tools faci litatt'S day to day database work in a Simple preadsheet-like form Th<-y su ppo rt dBASE databases and ODSC or JDBC
High-Level Requirements for WRITER It appears that th e: o nl y hi g h -level desCription of WRITER IS wntten in a style to attract users
"WRITER ha everything you would expect from a modem, fu ll y equipped word processor. It's si mple enough for a qUic k memo, powerful enough to creale comple te books with conte nt , d iagra ms, i ndexes. elc. You're fTee to conce ntrate o n your
message, while WRITER makes It look great The Auio-Pllol takes all the hassle out of prodUCing sta ndard documents such as letters, faxes, agendas, minutes. You arc of course iree to create your own templates. The SIyI,SI puts the power of srylc sheets IntO the hands of every user. You're free to add words and phrases to the Aulo Corrcc1 dlClionary, which can c heck your spelling as yo u type Aulo ompltlt suggests com mo n word_ and phrases to complete what YOll are ty ping Ali loFormal takes care of lhe fo rmatting as you write, leavi ng you fTee to concentrate o n your message.
Trxl fram" and linking mean you arc free to lay o ut newsle tters, Ayers, etc. exactly the wa y you want them to be. Increase the usefulnes of your lo ng, complex docume nts by generatmg a table of contents o r mdexing terms, bibliographical references, dl uslr.! tl ons, ta bles, and o ther objects. You are free to choose yourow n email sofrware-","' RITER offers direc t connection to email sohware . Make your documents freely available with WRITER's HTML expo rt to the Web, o r publish in Portable Document Format (. pd to g uarantee that what YOli write IS what you r reader sees Of cour;.c, you are free to u e old Microsoft W ord docume nts, o r save your work in W o rd format fo r end ing to people who are still locked int o Microsoft product>.'
-
We would ex press these mo re following .
like the
WRITER s hall be a fu ll -feot ured word proce, · or It hall all ow Ihe crea ti on o f "nlple d and complete books With o nte nl " d,.gr>n" Ifl dexe , e tc An e.amplc IS sh o wn In FI~lIre I I , I
273
27.
CHAPTER 11
ANAl YlING HIGH-LEVEL REQUIREMENTS
""""'-.4. ..
.... " .... t..
1'10
~
.~
M
"urn.", (,,, t
M"'~
'1lI0I'I''. 6: =rlo. d IN ,• • ",om CDs, ,.I m!"~ ........ rtd I ~om
Of
""" ,,.nch. collO", ~(. T"t'II!' o,eftO'!U.OI" fP1'\"\hEl)' h.I~ WI tt..IMdb .. d:, bed Ibn bu, IdOI~ . "oud WI _ _ c. ~" L l
bat,..
~UII'P LJ ~G)e ' . _
...
""".$ "'" ~ ,.06:. t:JCIi,,..... Ltd ... _
o8lcw .....,."7 ... Ja" fl. MI kI _
Ow 1IICII1' dltU ,..'
.
I\u 001_n btoUt '
...
Hi g'"
.an' ••
~ !MeDte aM .f~ u l
IsIh Is
RA y.A/'.... IttJOI."",, ·ou todqMfd~Itt . . . h
bllJ_rsMWIplluavws.rs
. . . J.,,_I'I(
Mfl&
COI$
~~f'>fI
"U' H>,dIMtOWltl1ls
fir
£N.'
fo,,,.,.
51)01 _ _ ii4iJ'ld
~.s OIl 'Cu £V0*
Figure 11 .31 Example of document open in WRITER SOUrce OpenOfflce. htUll /WwW ~ce orgIprodUCVplxtwriter-Oig.png.
WR ITER's Aulo-P,/OI feature shall fac ditate th e creation of standard doc uments such as letlers, faxes , agendas, mimHes. The ry/is l featu re shall allow th e user to easdy vary th e sryle of a docume nt. The Aulo omel dieliollQr), feature shall check spell ing duro ing or afte r te t entry The AuloComp/crt feature shall uggests common words and phrases to comple te a partia ll y typed sentence The A"loForma l feature shall handk formattmg while th e u er e nters text. Tht lext fram es and /ill/UII9 feature shall all ow the user to Ae xi bl y fo ml at newslellers, Oyers, etc. WRITER shall generate a table of contents, mdexes, bibliogra phiGlI ",ferences, Illustrations, and rabi es. It shall prOVide dli~ct connL'C!ion toe-mail software, export KTML to the Web, publish in Portable Document Format, and save work 111 M,crosoft Word fom,.t We will skip addItional reqUIrements for O~nOffice . It carries man y of its detailed
requirem e nts in an app licatio n coiled (rather unpoe tically ) /,,"tzilla . Issuezi lla consists of "issues ." An issue could be a bug but it could also be a task . This is similar to Eclipse's use of Bugzilla . Some Ope nOfnce projects have created
more careful
requirements
documents. For example, the OpcnOffice PROJECT Management Toolset (draft a, ') and the OpenOfflce Bibliographic module (draft at .) .
, h"plloopm openofll e o rgiR lesldocument 171/ I S43100PM_Requoremen"_D"cu,,,on_DraftJ\ I. pdf os of 2005. h t t p J1wv..'W .gCOCII jC'S.com/ma nI ;;h_k.....1grJwaVBi blio_ h'ml a of 2005 6
rtq
EXERCISES
11.14 SUMMARY Thi chapter has described the process whereby the high . level requirements for a product arc obtained and rKorded ,n a manner ctear to the customer and developing organization . High.level requirements describe the purpose of an application. its intended functionality. and Its bencht . The high ·level requirements arc documented on a form uch as Sections 1 and 2 of IEEE 830· 1993 Software Requirements SpecIfications. Variou techniques for ell itlng ane:! record ing high .level requirements are used Onc way to gather requirements is to interview stakeholders and potential customers. A combinatIon of text and diagrams is used to document the requirements. The following guidelines can be used to choose the appropriate form . • If a requirement is simple and stands alone, express it in clear sentences within an appropriate sectio n of the SRS.
• If a requirement is an interaction between the user and t'he application, express it via a use casco • If the requirement involves process elements, each taking inputs and prodUCIng outputs, U e a data Row diagram . • If a requirement involves states that the application can be in (or parts can be on), usc a statc transitIon diagram. States often correspond to CUls. Use cases are Widely applicable for describing customer requirements because the y capture user application interactions. If a state transition diagram expr~sses what the customer wants and needs and the customer understands the diagram, then its use is appropriate . The sa me ho lds for data fl ow d iagrams User interfaces arc speCified as part of the high . level requirements . Two importa nt principles for defining high. level user interfaces are to ( 1) know your user and (2) understand the busine s function in question . High.level requirements for agile projects arc collected continuously through most of the life of the project. Each requirement is expressed with a US" slory. A u er story is a high. level piece of reqUired functionality as secn by the anticipated user.
11.15 EXERCISES 1. Describe In your own words the dIfference between custo mer "mills and custo mer IItcds. PrOVIde an na mple that illustrate the difference . • 2 list four of what you consider to be the most impo rtant h ,g h. level requirement~ for an appl, atlOn that tracks bar·coded InvOIces withIn a compan y
3 IntervIew two separate people about their hi gh. level requlrement< for the bar·code appto ation speCIfied in Exe rCISe 2. mparc the requirement gathered frnm each interviewee How si molar or dIfferent an apphcat lon dId each of thtm e nvi sio n ~ How c1,d It o mpare with the h, gh. level requirements you I!e n erate d ~ Wrote a paragraph summarizIng the sunolarlto c< and dlffere n es, thl' importance o f Intervlewln/( different stakc hold ." for their viSIon of a o ftwa re al>pll ~tion, and how you might re( on ile the diff ren cs
275
276
CHAPTI:R 11
ANAL YlING HIGH·LEVEL REQUIREMENTS
\,(t hat I a usc ase) I the following a usc case) Why or why not) 'Tho sys te m shall provide advice for Ih e beginning Windows user on how to execut< Windows operations." 5. Write a usc case for one of the hi gh. level requiremenls " sled ,n Exercise 2. 6 Why is II importanl to show customers preliminary sketc hes of C Ul s as early in the development cycle as possible) Cive what YOll consider 10 be o ne o r two of the most important reasons. 7 . Your customer needs to specify u er interface •. Discuss twO o r three of each of the pros and Cons of the fo llowing means for doing this in the conte xt of the application (large o r small ) and the nature of the C UI (complex or imple). a. Ske tching using ha nd drawings, your own o r draw n by a gra phic artist b Sketc hing using graphiCS tools, such as Paint or PowerPoint
c. Using the C UI ·building features of the target la nguage of the application 8. D raw a data flow diagram to ex press the high.level requirements of an application that tracks the flow of orders wit h in a company. 9 . Consider an application that manages patients in a docto r's of Ace. Patients call for an appointment and thei r information is entered into the application . Patients ca n call to reschedule or cancel appointments . Afte r a patient is seen by a doctor, the patient may be referred to ano ther doctor for treatment' if necessary. Draw a state · transition diagram to express the h igh. level re quirements for this application.
TEAM EXERCISES TI 1. 1 Write the high·l evel requirements for a n application decided upon by the ream. Follow tho form of IEE£830·1993. Track the a mount of rime spont doing this exercise. Decide what fraction ofth. requirements are understood by the tea m. Estimate how long it wo uld take to obtain 95 porcenr of rhe requi rements. State how the process you used could have been improved. Be speci fic, a nd provide examples. TIL2
a. Identify an individua l outside the team who needs a modest a ppl ica tion. You will be gathering high· level requirements from this ind ividua l, thcn showi ng thcm to him or her. b. With yeu r ·custome r: identi fy metric, for how he or she will evaluate yo ur high· level requirements. Also determine the time limit fo r an interview (e.g ., a half hourl. c. Interview the customer, and write th e high·lcvcl requirements. d. H ave the customer evaluate and com ment on your high· lcvel req uirements in accordance with the
chosen metrics.
BIBLIOGRAPHY I
~OntS. AI.,n. &~n. Wixom, 3.nd DaVid T eg3rdcn , "5)'5,,"j AMI)'lJ1IHld On'I" wi th UMl. Vffl)OfI ] 0 AI' Ol,«f.Ortt14r.cJ Ap~,OItCb. · John
Wlln"
Son~. p
139, 1005
BIBUOGRAPHY l. JoooI>wn. Iv... · Ol,od 0M0"" So!..,." E.gl• .m,,/' A U.. C." On·... App,..cb." (Addison. W«ley Obj
277
Analyzing Detailed Requirements
~--
Matntanence
The Software Development Ufecycle
Rgure 12.1 The context and learning goals for this chapter
•
What ways are there to organize detailed requirements?
•
How do you express user interfaces in detail?
•
How do you express security requirements in detail?
•
What kinds of error conditions can be specified?
•
What is traceability and why Is It important?
•
What ways are there to prioritize requirements?
•
Why associate requirements with tests?
•
How do agile methods relate to detailed requiremen1s?
•
How do you use tools for requirements analysis?
THE MEANING OF DETAILED REQUIREMENTS
ft~r luSh -level requIrement are spe Ifled , tYPI ally (or an iteration , the next ste p in rcquorcments i is to define the deraIled req uirements. The purpose 01 de taIled requirements is to provide the reader WIth absolutel y .lIth.t's requored of the application . W,th o ne exce pti o n, the re i no where cI e fo r the team to state <XiI Ily what thIS conSIsts of. For e ample, if we do no t state here that the title of a VIdeo mu.t appear In • t6-poont font on th e mo no tor, then we aSSume that thos will no t appear In the produ ct The "exception" mentio ned above refers ro the pOSSIbility 01 eother stat Ing each detail ed requ irem ent as a comment In the so urce code or of expecting source code and its unit tests to effectively specify the requirement. Thi tends to be the approa h oI agile projects, which we discus ed previous ly. Ag ole projects do not rule out the kind of documentation char we di scus In this c hapter, but they value working code ahead of Sll
h separa te documentation.
This chapter concenrratcs on wriue n deta iled reqUireme nts. However, whe ther o ne writes down d~tailed requirement in these ways o r not , there is no c hOICe but to eventua ll y think them thro ug h. In fact , they fo rm a common currency of app licatio ns, as it were Detail ed requirements arc usuall y d ivi ded on to sectIons, including funct io nal requirements, no nfunc ti o nal requirem e nts, and CUI deta ols
12,1 THE MEANING OF DETAILED REQUIREMENTS Detailed requorements provide software e nginee" with a ba is lo r deSIg n and Implementatio n. n,ey are sometimes called "specific requirements," "functi o nal speCificat io ns," o r "developer requirements." Detail ed requirements consist of a complete liS! of specific prope rtI es and functionality th a t th e application must possess, expres ed In complete detail. Eac h of these requ irements is labe led, and tracked thro ug h imple· mentation . Detailed requirements a re consistent wit h, and e laborate upon , the h Ig h -level req uireme nts _They ar< inte nded to be read primarily by developers -h owever, customers are inte rested in the m as we ll , and should be able to understand and commen t on them wi th few exceptions. Recall that the primary aud ie nce fo r the h ig h ·level re.q uire m ents consists of customers. As the case studies in this book demonstrate, when it comes to software e ngineeri ng, "the deVIl is In the deta,ls: For example, in 1999 NASA lost a weather sa te ll ite wo rth a rep o rt ed I $125 mill,o n, reportedl y because control data they had assumed to be in metric fo m, was no t [ I J .. the root cause for the loss of the M eO spacecraft was the failure 10 usc metric unit s in the coding of a ground software file , "Small Forces," used in trajectory mo de ls. SpeCIficall y , thruster performa nce data in English units instead of me tric units was u ed in the software app loc.toon code titled SMJORCES (s mall forces). A fi le ca lled Angular M o me ntum Desaturation (AMD ) contained the o utput dara from the SM JO R ES so ftware. The data In the AMD fi le wa< require d to be III me tric units pe r existing o ltw.re Intwface docume ntatI o n, and the trajectory modelers assumed the data was provided in metric unIts per the requireme nts.' This descri ptIo n ,mpl,es that the req uireme nts stated the need for metnc un Its but the oftw.rc d id no t Implement the requi re me nts correc tly A fascinating fact os that thIS defe twas Ide nti ,ed with", mere day, afler the d,saste r. Th, s mea ns thai it may not be hard to loc.te a defect o nce we kn ow it I present. The pro llcm is often OUr Ignorance o( liS presence The d etailed requi rements lo rm the first lone 01dde nse agilln tthe corruption r OmIssion of dcta ofs Far fro m beIng the mindless ac ti VIty that it mig ht flrs t appear, !;e tlln g all the requ Irement' down In complete detaIl Inv'Jlves the d ifficu lt tasks 01 orga ni zo ng people and the " th u"ht proce" . To understand this challcng~ , Imag Ine the task of or)(anlz lng a 20-volume req uo re me nt< document (' t , " c1lectlve nllp jinc"" bbc en uk/ l /hJ", ,"cd"5 14 76~ tm , hp j/ltp hq no .. 80y/ puiJ/paoircpIlrt
279
280
CHAPTER 12
ANALYliNG DETAILED REQUIREMENTS
that a N A englOeer, for example, would know cxa tly where to add o r look (or a
12.2 ORGANIZING DETAILED REQUIREMENTS Requirements c hange constantly, and so written reqUIrements should be well ·orga nized a nd easy to update To apprec Iate th e value of carefu ll y o rga nizi ng de taIled req uire me nts, consi de r the following rather random attempt at wrillng detaIled reqUire ments for the Encounter game. No te that these requireme nts are still raw and arc no t in pected . Every c haracte r in the Encounter video game shall have a name. Every game c haracter has the same set of qualities, each with a floating po int value . Encounter shall take less than a seco nd to ~omput e the results of an engagement. Each area has a speCIfic set of "qualities nceded." For example, combat areas require strength and lamina ; li ving rooms require sensi tivity and intellect.
Whe n two Encounter game characters are in the same area at the same time they may either choose or be obliged by the game to e ngage each other. Every game ch arac te r shall have an amount of life points. The sum of the values of qualities of a game character relevant to the area in question shall be referred to as the character's area value. In an engagement, the sys tem compares the area values of the characters
and computes the result of the e ngagement . The name of any c haracte r in Encounter shall have no more than 15 letters. A It grows, an uno rganized list hke the o ne above quickly becomes unmanageable. • Its very size makes It hard to understand as a unit even before it grows into the hundreds, if not thousands. • The reqUIrementS arc of mixed types, performance requirements must be dealt with differently from functiona l requireme nts , (or example.
• Some reqUIrements naturally belong with related o nes.
• It is d ifficult to loca te a speCific reqUIrement. Functional detailed requirements can be organized acconding to several claSSifications, including by feature , use case, CUI , state, and class. We describe each method in more detail in subseque nt sections. Tools for managing requirements can help a great deal. Nevertheless, the decision as to how to organize detailed requirements 111 the first place is important because teams reler to them continually if the document is well done. The IEEE standard 830-1998 provides document templates for several ways to classify the detailed requirements. Figure 12.2 shows the conventional and the object,oriented classification templates of the IEEE 830. 1998 standard. The object-oriented claSSIfication uses classes/objects as a me thod of organizing the functional requirements. The SRS is often tailored to corporate or team needs by adding or modifying sections as appropriate. For example, the 00 organization lacks a section equivalent to 3.4 in the non-OO organization 10gical database requirements." The Encounter case study uses a modi Red form of the IEEE 00
ORGANIZING DETAILED REQUIREMEIfTS 3. Specific ""quirements (non-OO) 3 . I External interfaces 3.2 Functional ...,quirements 3.3 Performance ""quirements 3.4 Logical database requirements 35 Design constraints 3.5 . I Standards compliance 3.6 Software system attributes 3.6. I Reliability 3.6.2 Availability 3.6.3 Security 3.6.4 Maintainability 3.6.5 Portability 3.7 Organizing specific req u irements 3.7. I System mode - or 3.7.2 User class - or 3.7.3 Objects (sec right ) - or 3.7.4 Feature - or 3.7.5 Stimulus - or 3.7.6 Response - or 3.7.7 Functional hierarchy - or 3.8 Additional comments
3. Specific requirements (00) 3. 1 External interface requirements 3. 1. 1 User Interfaces 3. 1 2 Hardware interfaces 3. 1.3 Software Interfaces 3. 1.4 Communtcations interface 3.2 ClasseS/Objects 3.2. I Class/Object I 3.2. 1. 1 Attributes 3.2. 1.2 functional reQutrcmen ts 3.2. 13 Events . •
••
3.3 Performance requirements 3.4 Design constraints 3.5 Software system attributes 3 6 Other requirements
Figure 12.2 IEEE 830-1998-specific requ irements, 00 and non-OO organizations SOUtce: IEEE Std 830-1998.
style and includes a sectIon for usc cases. Fi gure 12 .3 maps the detatled requirements section o( Sect Ion 3 to the requirtments ca tegory it describes. It may be advisable to o rga nize detailed reqUIrements int o a comb",.lio" of lasslficatlons For example, a feature· based organization could be used within the co"figllring, txcculmg , and backing liP tates of an accou ntIn g application . The requirements for a factory automation system cou ld be orga ntzed at the h, gh. t levd by function (i ntake, part manufacturing, and assembly), they co uld then be o rga ni zed by clas withIn eac h. This means the metho d o( organizing detailed requirements is somellmes related to the probable architecture or implementation of the appitcation For example, if the deSIgn is :0 be object-onented, detailed requirements organtzed by use case or class should be considered because they faclittatt traceabtlity. If the application lends itself to an obvious functional breakdown, then o rga ni ztng the requirement by (.>lUre hIerarchy may be appropriate.
12,2,1 Organizing Detailed Requjrements by Feature The oldest manner of orga nt ZII11( detaIled reQ Ulrement< IS by feature . This amount to prOVIding a SImple Itst of functional,ty such a< the fo ll OW Ing , f'Or th e Encounter VIdeo game Many (eatures are defined bv J IImulus . and-response pa", as for requirement 12 7.
211
282
O1APTER 12
ANALYZING DETAILED REQUIREMENTS
3. Specillc requlremenlS 3.1. EXie mal inlerlaee - - - - - - - Inlerface requ lrome nts requ irements 3.1.1. User inlerlaces 3.1.2. Hardwa re inlerfaces 3.1.4. Communications interlaces 3.2. ClassesiObjecls
Funct10nal requirements
-see section tbd3.3. 3.4.
3.5. 3.6.
Performance requirements ... Oesign constraints ~ Othe r n? nrUnclionai Sofiware syslem altribules ~l requirements Other requirements
Figure 12.3 IEEE 830· 1998-specific requ irements, 00 style interpreted as functional and nonfunctional detailed requirements SOUrce. IEEE Std 8JO. 199S .
125 . The re shall be a SCI of hy perlinked locat io ns at eve ry exi t to every area. 126. The fo reig n c harac te r shall move fro m area to adjacent area at ra nd o m times, with an average of three seconds 127. Whe n the use r clicks o n th e "Set qual ities" butto n, the window in fig ure xx appears on Ihe mo nitOr. Arra ngi ng req uire me n ts by fea ture has Ihe advanta ge o f simpli ciry but the di sadvantage of in· accessibi lity ; th is is because it all ows jumpin g fro m a feature in o ne pan o f th e applicat io n to a feature In a com pletely d iffe re nt pa rt. For example , if we wa nted to c han ge the manne r in w hich the fo rei g n character moves about, we wo uld have to de termin e tha t th e relevant requirement is number 12 6. H ow would we kn ow
w h at o t her req uire me nts are affec te d] Searc h tOo ls can help a g reat deal. Ano th er disadvantag e is the lack of traceabi lity. For examp le , what pa rt (s) o f th e cod e does requirem e nt 12 5 map ta l One wa y ro im pose o rd er o n fun c tio nal feature lisls is to arran ge them in a fun c tio n hitrnrcby (i .e., by dec o mposing the ap plicati o n into a set of h ig h . level fun c tio ns, and th e n Ihese into subfunc ti o ns, etc.). For exa m ple, the requ ireme nts fo r a ho me b ud get program could be d ecomposed into ( I) dJeckill9 functi o ns, (2) sa viN9s func ti o ns, and (3) i"" " 'm,,,t fu nc ti o ns. The required ChlCkill9 fu nc tio nality co uld be furth er decomposed into checkbook fu nctions, reconcilwtio" . and rcporlj"g, and so on.
12,2.2 Organizing Detailed Requirements by Use Case US( cam (Intro duced in C ha pte r I I) ex ploi t th e o bservati o n that many requ irem e nts occur naturally in o perati o nal seq ue nces. Fo r exa mple , an ind ividual requ ireme nt suc h as "a video sto re applicat io n shall allow ente nn g th e title of a new vid eo" ty picall y takes place as pan of a seqll,"cr o f transactio ns . A usc case diagram sh OWing a collectio n of usc cases fo r a vi deo store applicat io n is illus trated in Figu re 12.4 . The auth o rs ad vocate provid ing use cases fo r hi g h · level req uire ments . O ne may have the o ption of usi ng this same organi zing p rin ciple fo r d eta iled requ ire men ts. In this case we would gTOUp the detailed requireme n ts acco rd ing to eac h use case, Aes hin g out the ste ps o f each use c ase in complete detai l. The fo llo w ing is an exa mple of how o ne suc h groupin g o f req uire me nts wo uld appea r in the SRS. 3.7. I C hecking in
DVDs
Th is is a deta iled versio n o f sec tio n xx. (N o te I,
ORGANIZING DETAILED REQUIREMENTS
9
/' Clerls
Activate
2. System displays main menu
-
Check in DVD
1. User swipes bar code
2. Sysr... II displays due dala 3 . .,.
Check out DVD )
Y -( Stock DVD
Buyer
1. User hits arry key
}---
( ........ .)
,.. . . . 2. 1. User obtains
"
·slocl( screen 2. User enters name of DVD 3 . . ..
IL
Figure 12.4 Organizing requirements by use case for the video store example
The applicatio n shall provide the following capabil ity to interact wIth store clerks. These requirements assume that the main scree n is on the mo nitor (Note 2) 3.7. 1.1 Step I , Chtck III button (Note 3)
The clerk shall be able to hit the Chrck III bulton , whereupon the (b,ck In screen WIll appear (described in section xx above). 3.7.1.2 Step 2, Filling in fields (Note 4) The clerk shall be able to fill in the following text fields In the (b, k In s rcen
•
3.7. 1.2. 1 Video name field
This field shall allow for 30 alphanumeric characters, including blanks. •
•
•
Note I , This paragraph corresponds to the Chrd:in9 in DIID usc case described in the hlgh. level requirements .
Note 2, This section introduces the usc case and states prrcondlrions. if any. A preco ndition I a fact assumed true at the inception of the usc case. Note 3, This corre ponds to the nrst step of the use case. Note 4, Since these are the detailed requirements, they must specify the requirements completel y. The details will not be speCified elsewhere. The Unified Software Development Process favors orga ni ZIng all requirements by u e ca e . Aglie methods de ·emphasize detailed requirements in favor o( workong code , but they emphaSIze organization of requirements by user tory.
12.2.3 Organizing Detailed Requirement by GUI ApplicatIons display CUI , and thes" are the means by whIch users think o( them, 0 It ca n be natural to prOVIde requaremcnts organIzed In thIS way . Using thI S style , rhe requaremcnt (or the Encountt"r video g"me would be ,omethonll like the followIOIl ·
33
284
CHAPTfR 12
ANALVZlNG DETAILED REQUIREMENTS
I Are. CUI , Arca C Uls shall have Ihe appe.rance shown in figure xx. When the user clicks o n the ' Set qual,ties" button , the wi ndow in figure xx appears o n the monitor. When the user clicks o n ... . 2. Dungeon C UI . . . 3. Living Room C UI 4.
•
•
•
et Qua lity C UI ....
5 Vicw Q ualities Window
• • •
The advdntagc of organizi ng requirements by CUI is its direct connectio n with the usc of the application . Anot her advantage is traceability, we have a good chance of tracking the requirements associ ated with a given CU I class. One disadvantage of rhis means of o rganizatio n is that it ofren fail s to cover all of the requirements. ln the Encounter example, we need to describe the requirements for the interaction of the player's character and the foreign character. No C UI paragraph is a natural container for this. Perhaps the closest is "Area CUls: However, this is not a uitable place for specifyi ng the manner in which characters exchange points. Another disadvantage IS rhat given functionality is often associated with several CUls. As an example , Figure 12 .5 illustrates an organization of the video store requirements by CUI. Specificatio n of individual CUls is discussed further iA Section 12.3.
3.1 Sslecting Procedures
S'ock oVo
The GUI for selecting procedures shall be as shown in Agure 1. 1\ shall be possible to select from the following procedures by clicking on a radio button. followed by the "go· button .... Select Proc edure Slock OW Af95 '" CUSIOmef'
Cte " ous DVD Choc:II. In OVD
@ @ @ @
I Nl.nIber 01
Figure 2
roc: .,
1 :1
'--' I ~~-
3.3 Checking out DYDs Figure 1
9
The GUI for checking oUl DVDs shall be as shown in Figure 3. 1\ shall be possible to ... Checl< DIJ. DVo
avo """'" Figure 3
1 i ........ _
,
-- .'-
,
3.2 Stocking DVDs The GUI for stocking DVDs shall be as shown in Figure 2. 1\ shall !>e possible to enter a DVD Into the systelll using the GUlln figure ... The application shall save the title expressed In up to 30 aJphanumeric characters and the number of copies. The laner shall range between 1 and 100. inclusive. •• •
3.4 Registering Customers
... -. Regtster Customer Fw.tnl me
1
I Figure 4
Figure 12.5 organizing requirements by GUf, for the video store example
ORGANIZING DETAILED REQUIREMENTS
12.2.4 Organizing Detailed Requirements by State This styl.e consists o f collec ting In o ne place the deta iled require ments that apply to each state. For example. the reqUIrem e nts fo r an appl icatio n that control a c hemical process might be best classified by the states in whIch the process c an Rnd it e lf (sla rlin1 up, " aclin9 . coo/in9. etc.). With in each state classiflcation the """IS that affee.t the applicatio n while in that state are listed. Classificatio n by state c an be approp~ate when the I"'C'qulrements fo r each state arc qu itC' di tinc t. For example , an accounting system may be required to behave
entirely difkre ntl y de pe nding o n whe ther it is in the confi9 urin9 , ex,eu Iln9 , o r btlckin9 up state. Although the Encounter case study requ ire me nts could be o rgan ized by state , we decided that there are more advantages to organtzlng them by class, which we describe next.
12.2.5 Organizing Requirements by Class In the object ·oriente d (o r "cia s') style lo r orga nizi ng requirements, a ca tego rizatio n is fi rs t perlomled equivalent to selec ting clas os; then the individual requirem e nts arc placed into the resulting classes. C lasses used to categorize th e requirements arc kn own as domain cl asses. D omain cl asses represent real· wo rld objects
or concepts in the applica tio n . Fo r exampl e, a banki ng applicatio n would have do ma in classes such as bank mslomt!', cbrckin1 accounl, and savings balm",. A commo n first Step in ide nti fyi ng doma in classes is to ga ther the nouns or th~ir equivalent used in the high · level requirements W e then make ea h fu nctional detailed requirement correspond to a functi on in the target language. Th is promotes one-la-one traceability from
detailed requirements to metho ds. Agile meth ods use a si mtlar approach in that detai led requireme nts are organized by tests 01 classes. One disadvantage o f organi zi ng requ irements by classes IS the risk that we later c hange the cl asses, thereby breaking the correspo nde nce between require ment and design. ThIs is d IScussed by Jo rdan, Smila n, and Wilkinson in [2]. In fa ct, some develo pers use classes lo r o rga nizing the require me nts but do not seriously aim to usc these classes fo r the desig n. In this case, traceability is compromi sed , but there IS Ie s pressure to identify lasting classes ve ry earl y in the process. Ano ther disadva ntage of th is classincation is that it requ ires us to select classes very earl y in the develo pme nt cycle , and man y argue that we a re effectively perlorm ing design in doin g so. Let's look at the fll cou nl, r game case study as an exa mple. Picking classes such as Play,rebamelt! and Arm at re quire ments time is harmless since the Implem enta tio n is very likel y to use these classes. On the other hand, it can be reasonabl y argued that having the ArmConn" 'lolI objects refere nce the Alta objects that they connec t i a design decisio n. The great advantage to o rganizing requirements by classes th at will be used in the desig n is that it promotes tight corres po nde nce be twee n req uireme nts, design, and Impleme ntatio n. This is a key be nefi t fo r using the 0 0 paradi gm in a ny case. In add iti o n, cla ses that correspo nd to real ·wo rld concepts are muc h more likely to be reu sed than those th at do no t. For many appl ica tI o ns, the benefi ts o f usi ng a cl ass·oriented classincation meth od o utweigh ItS drawbac ks in the authors' o pinions. A ty pIca l seque nce fo r obtai ning fu nc ti o nal de tail ed requ ire me nt UStO g the 00 style is a fo llo ws, I. List the concepts me nti o ned in the u e cases a nd othe r hi gh . level requireme nts (usuall y, man y of the
nouns). 2. TI,e resulting collect Io n 01 classes is tY PI call y incomple te . T ry to uncover re mai nIng "do mai n" cl asses. Th IS proce~s is ex pl ai ned below Inspect thl collecti o n o f classes. 3, For each o f the cl as es obtaIned , Wrtte down all o f the req uired fu nc tio nality of the app ltcation pnman ly penai nm g to tha t class, as shown In the Enco unter ase stud y This I do ne In the fo rm of at mbute. and fu nc tl o ns For exam pl e , "every c usto me r s hall have a namc" (an anrtbute ltsted under paragra ph Cllslo,"rrs )
285
286
CHAPTER 1i
ANAL YlING DElAILED REQUIREMENTS
1. Obtain domain classes and objec18 Irom use requirements diagram,
r
ca,., and high. level
,
2. Add additional 8I88ntlal domain Inspect the resulting c:ollec1lon 01 classes
3. For each class, speclly the required attributes specify the required lunctlonalily speclly how Its objects react to events dra« test plans lor each inspect the results 4, Inspecl against high-level requirements 5. Verily with customer where possible When complete:
16.Release I
Figure 12.6 Road map for detailed requirements using the 00 style
and "the appli catIon shaU be able to compute the tota l assets of each customer" (a function listed under ( 1I510rn,,, ) In the (req uireme nts) document that you arc writing, avoid usi ng the term "class." Use ord inary, no ntechni ca l English. Specify the events that the o bjects of the class arc requi red to handle. 4. Inspect the detailed requirements as the process progresses . 5. Idea lly, test plans for each detailed requireme nt should be devised at the same time, as explained below. 6 . Inspected the detailed requireme nts against the hi gh-level requireme nts. 7. Verify the detailed requ ire me nts with the custo mer. 8. Rel ease the requirements , or return to Step 1 ror more requirements.
Reca Jl that the primaJY audience for de tailed require me nts consists of developers. However, customers are vitaJly interested in the deta ils, too . Figure 12.6 summari zes these steps. It is a commo n error when classifying requirements by class to use the language of uesign instead of plain English. For example, the foJlowing language is acceptable .
It shall be possible to o btai n the number of days delinque nt o n any account. The following is 1101 acceptable in a requirements document.
•
g"D,/illqu'IJ IDays() returns the numbe r of days delinquent On the accou nt. In other words, object-orientat ion is u cd here o nl y as an or8a n izin~ pnnciple for the req uirements. Th< use o f 00 for design and implementation is I>crfonned later.
ORGANIZING DETAILEO REQUIREMENTS
Player
(') flSl
"vel)'
le.son'Ne
IExit II Combat I you candidal" closs can think of IEncounter I (this 11s1), then IMap II Result I down (2) drastically cut to a lew IRoolI' I ~ essential classes. IScore I IConnection Hype~ink I
IForeign Character I IGame Character I IPlayer Window I IExit Choice Window I IQuality I IGame I IOoor I
Figure 12.7 candidate doma in classes for the Encounter video game We ide ntify the classifying class~s carefull y and co nservatively, identi fyi ng th e d o ma in classes of th e application . As an additional example, the d o ma,n of an applicatio n simulating a bank mig ht conta in classes Bank Cuslom" (the corresponding class name in Java o r C • • can have no blanks, of co urse) and Tell" but no t Filr or DatabQ st-not even Cllstomrr or Tm"5action . Th e latt er arc not specia l to the applicat ion in question . Our goal is to identify a minimum but suffici ent set of do ma in classes that include all of the speCific requirements. Each CUI usuall y results in a d o main class . As another example of d o main class selectio n, consider an appl icatio n th at manages visi ts to a Web site. Some candidate domain classes are Sitt Visitor, Sile Visit, and Silt Missiou. Requirements pertaining to the visitor (e .g., data about visitors, and functio nal ity such as displaying vis itor profi les ) wou ld be collected wit h the Sile Visilor classification . If the application fCquires us to track the reaso ns fo r each visi t, thcn a d o mo," class Sile Mission would be appropriate . The corresponding requ ireme nts would be coll ected w,th in Sile Miss,on. Fo r example , the requirement on the applicatio n co uld be that visitors submit a form stating th e lf goals in visil1 ng the site. After identifying classes from the use cases and other hi g h · leve l requiremen ts, an effective way to complete the identification of key do main classes is to use a '·Iist and cu t" process. Th,s co nsist' of (Step I ) listing every reasonable candidate class you can think of, and th e n (Step 2) agg ressivcll' paring down th e list to a few esse ntial classes. We elaborate o n th ese Sleps nex t. (Step I) Figure 12.7 s hows candidate classes for the Encounter game elected from the te.xt of the h ig h · level requirements. The UniRed Modeling Language (UML) no tat io n for a clas is a recta ng le containing the class name. (Step 2) We now Riter th e classes identi fied. Note firs t that il is fa r easier to add a clas later than to remove one that has become embedded in the design and implementJtio n, so that if there is d ou bt about the usefulness of a candidate clas we eliminate it. The rationale used fo r the fin al se!cc t, o n of do ma in cI.ssl"S fo r the case study is given ne xt.
En,oun'", Change to EncouHlcrGnm, to make its purpose clearer (we may also need th e plain "encounte r" conccpl as we ll ).
Game: Not a domam class-toO ge nera l (,YO mal' rc,ntro duce this later when scek'"8 useful generalization ).
Ga .. , Ch.r.cler: Too ge neral to be in the do ma in (we may re '"tro duce this later when seek,ng useful ge neralizations).
217
288
CHAPTER 12 ANAL YlING DETAILED REQUIREMENTS
Pia cr: Plny,r
Foreign
barnelrr
IS
a preferable name (mo re speciAc to the domain ).
I,.raner: OK (foreig n char.c ters aC I
In
w.ys tha I arc differenl from player c haracters).
Eneoullirr O,atan,,: OK (ge nera lization of PlayerCharacl" , Fo"i9n Charnet", CIC., of the app lic.tion )
IS
still wllhin the domain
Qua/lly: O mi t-try to h.ndle as si mple attribute of Enco unt" Characl" . Room : O m il- not sure if we need th is; already ha ve A"a . 000, : Omi t- no t sure we'll need it .
Exit: NOl sure if we need Ihis; leads
lO
neighbo rin g area. T ry as si mple attribute of A"a
o mit for now
Rult: Omit-not sure we'll nee d it. Arta : O K (The .stulc reader will note th.t this decisio n is defective .) EligagrmMl1. OK Passageway. We do need to connect are.s, bUI we do not yet know what form these connections will rake . U sc EtiCo lmtrrArcnCOntH'ction instead.
Resuit : Omi t-iI's vague.
Combal: O mit-no t sure we'll nee d it- already h.ve Ellgag""",1.
5 Ort: Omi l- try .s attribute of o ther classes. Playrr Quality Window : This is needed to express the Initi.lize use case. EXit Goier WilidolD: O mit- not needed
clic k o n exit hyperlinks.
Map : Omit-not requi red at this Slage (maybe in a future versio n). Engagrmtlll Display: OK-needed by usc case tho ugh will try to postpone by substituting a command line ir:tcrface .
The resulti ng classes arc shown in Figure 12.8. The figure includes the inheritance relationships present among these classes denoted with a tria ngle. UML no tation is covered in de tail in C hapte r 16.
EncounterCharaCler
En counterAreaConnection
If PlayerCharacte,
ConnectionHyperlink ForeignCharacter
(1) list every
reasonable
I Playe!OuaJltyWindow I
IEngagement I I EncountelGame I ~~~ I EngagementDisplay I ICey
Figure 12,8
IA ...."
., d r, ';>. &I'd code, b&ank:a I t! I'W\IIIfd
candidate class you can think 01 then (2) drastJ. cs1ly CUI do .. " 10 B few 8ss&ntiBl e'e ..ss (Ih/s /1st).
I
crasse-; for the Encounter video game, showing only Inheritance relationships
ORGANIZING DETAn ED REQUIREMENTS
Th~ classes in Figure 12.8 may relate in ways besides inh~ritance. For CJGImple, EHCo"nler Arc. ConHeclion will probably .ggreg~te two Arta objects. However, our concern here is only wilh the core application classo<, using them to organ .ze the requirements . Relat.onsh lps among classe, arc , hown where necessary. Using Inheritan e enables some degree of leverage. For example, after 51ating the requirement' for EHCO"nllr Characler we do not need to repeat these requirement' in describing Player Cbaraeler and Forti9n Characler. The Eneo"Hlrr QaracltT class is shown in italics in Figure 12.8 becau,e it i, abstract- thi, declare, that there will be no actual characters beside player·controlled and foreig n c haracters. The IEEE 830· 1998 SRS standard designates a place where the purpose of each class is stated, together with its key attributes and fu nctio ns. The stan dard ca lls for uSIng the decimal numbe ring system fro m each class (e .g ., 3.2.5) to eac h of its attribute requirements (e.g ., 3.2.5 . 1) and each of its function requirements (e.g ., 3.2.5.2). In stead, we will arrange classes alphabetically to make it easier to add and
~move classes. Such insertions are necessary as the applicatio n grows. It is important to number requirement.s, however, in order to be able to manage the m, so we do this within each class as show n in the case study. Sometimes, only "essential" requirements are numbered since onl y they mllSt be tTaced for now. A good reference for this style of organizing specific requirements is Jordan , Smilan, a nd Wilkinson [2]. T o assist in trac;ng detailed requirements it can he lp to give a name to each o ne, a in the case stud y. For example · 3.2.A. 7 Preferred qualities
[essential] Each area shall favor a set of qualities. Including "desirable" and "optio nal" detailed requireme nts is beneRcial for several reasons. First, the scope of the application can be co ntrolled by implementing the requ irements in a planned order. Second , ~tati ng future requirements provi des directi o n to designers, helping them to create designs that can accommodate fuiure features . One technique for indicating which requirements have actually been designed for and implemented is to start by including a disclai mer with each , as in the follow ing exa mple. When organizing deraile d requirements by class, .t's sometimes a c hall enging issue to decide under what class to state the requirement. Consider the following require me nt example, Every Encounter character shall have a name ... This requirement shou ld be classified with "Encounter C harac ters," We wi ll explain below the relarion of this with a CUI requireme nt. The following require me nt «quires more consi deration. Whenever the player's main cha rac ter en ters an area , rhat arca and all the characters in it shall be displayed o n the mo nitor, Class candidates to classify this function are Playrr haraelrr and Arro . TI,e requirement effectively calls for an event h an dl er A na tura It n'gger'lng c lass fo r handling the entry event would be lhe area e ntered . because . .It IS aware 0 f W' h Ie h c h aracters .'" h ab 1't I' t. The area entered could display itself and the c harac ters It contaons, the requirement stated above could rea o nabl y be classified under Arm . . 0 d ' to dcal with /I.diu;d""/s. 099"9al;0Ils , and GUis ce ntered o.n a SIng le theme. For W eo ften lin It necessary example, for a video tore manageme nt application , we need to deal with the followon!! . \0
•
' d I V.' dual D VDs7 For exa mple, what are the l en~ th lim.tallons of lhel r Wh ilt are the reqUire d properr'1e~ 0 f on titlc\7
2"
290
CHAPIER 12 ANALYllNG DETAILED REQUIREMENTS
• What are the required propertie of the co llecti o n of DVDs? For example, what is the requirement for stocking new CUls? • What are the specincations of a CUI that displays info nnauon about DVDs? For example, what are the limitations on the text shown? (CUI speCifica tions often change Frequently.) TI,inking ahead, we recognize that the e will be separate classes when we come to design time, so we organize the requirements document paragraphs to anticipate this. It is u ually best to begin with lhe paragraph that describe the requirements o n the ",JiviJuals: in thi case, DVD . This speCifies the required degree of detail that the application is required to store . It is referenced by other paragraphs. 3.2.DV DVDs • • •
3.2.DV. t Attributes of DVDs 3.2.DV. I.X Director's Name The application shall retain the name of the director of each DVD . This shall consist of the director's la t name, in a fonn of between I and 30 characters, which can consist of a·z, A·Z, and a hyphen . In the case of multiple directors, only the first alphabetically shall be retained. •
•
•
3.2.DC DVD CUI The CUI displaying a DVD shall have the appearance of figure xx. •
•
•
3.2.DC. 1 Attributes of DVDs •
•
•
3.2.DC. I.X Director's Name Appearance The director's name shall be dispiayed in the location shown in figure xx , in accordance with requirement 3.2.DV. I.X, but limited to the first 20 characters. . .. •
•
3.2.DC.3 Events Pertaining to the DVD CUI •
•
•
3.2.DC.3.X OK Button When the "OK" button is pressed •
•
•
•
•
•
3.2.DI DVD Inventory • • •
3.2.01.2 Functionality of DVD Inventory • •
•
3.2.D1.2.x Stocking a DVD The application shall allow new DVDs to be added to [he inventory, up to a maximum of one million . ... • •
•
USER INTERFACES: DETAILED REQUIREMENTS
rgaOlzmg
pnncipl.
Advontage<
))1Sadva11lage<
By Feature
©
® Docs
By U se Case
© ©
Mops well to why we ore bUIlding the appl,ca ti on Easy to understand Easy to understand
By CUI
©
Easy to understand
By State
© ©
Easy to understand Design th Inkin g begins early
By Class
not map well to 00 code
® Hard to locate random requirement
® U c cases may overlap ® Hard to trace to deSIgn and code ® Coverage IS hmited ® Not every function appears in a CUI ® Functionaliry of C Uls overlap ® Hard to trace to design and code ® ClaSSification can be unclear to the cus tomer
® H ard to allocate requirements to state ® C1assi 1catlon can be unclear to the
© Easy to trace to code © Easy to locate random
cu)tomcr
requirement
©
Design thinking begins early
Figure 12.9 ways to organize detailed requirements advantages and disadvantages
12.2.6 Classification Methods: Advantages and Disadvantages Figure 12.9 ummanzes the d iffe rent way to organize fu nc tio nal detailed requirements that we discussed the previous: sections, along with th eir relative advflntagcs and disadvantages
12.3 USER INTERFACES: DETAILED REQUIREMENTS Recall the follOWing ste p in specifyi ng user IOterfaces. Step 1 Kn ow your u er Step 2, Understa nd th e bu
10
question
Step 3, Apply pnnClple of good scrcen dC<1gn Step 4 Select the appropnate kInd of windows Step 5. Develop system menus Step 6
elect th e appropriate devlce ·b.,cd contr I
Slep 7: 0100se the appropriate s rcen -ba<ed control, Step 8
rganize and layout w lndow<
Sl<:p 9
hoO\e appropnate colors
Step 10
rcate meanIngful Icons
Step 11 J) rovlde c (fclive me>sage, fe" dl" , k, alld
"llId"n~c
D
In
291
292
CHAPTER 12 ANALYZING DETAILED REQUIREMENTS
• En~ure consl ten cy amo ng the Screen. of d es l ~ n a tcd "PPloc.t lons, and among
• Provide captions Figure 12.10 Principles of good SCfeen deSign Source GaJItz. W • • :"e E.ssenbal GOlde to user Interlace DeslgJ1
An IntroouctlOO 10 GUt Prindp~ and TechniQues," JOhn Wiley ~
Sons, 1996
Steps I and 2 were descnbed in the previous C ha pter I I since they apply primarily to hi g h ·level requ irements We now describe the remai nin g steps fo r specifyi ng detailed user interlace requirements, whIch are esse ntiall y a detailed descriptIOn of each C UI screen.
step 3: Apply the principles of good screen design Figure 12 . I 0 li sts some majo r clements of good scree n design. The figure includes several lac tors that often app ly to mak In g an interface pleasing Alth o ug h these serve o nl y to introduce the subject of visual effects, th ey arc nevertheless usa ble by the average software e ngi nee r. As an example, we app ly some of th ese principles to an example o f a sClcen used to input information about customers and the ir accounts. An ini tial attempt at a C Ul,s show n in Figure 12 . 1 I. To improve the interface, we start at the to p left . placing the most impo rtant clements firs t, and grouping like elements. Figure 12. 12 illustrates Type:
checking 0
Branch:
Main SI. 0
Privileges
First name Middle name Last name Street City State/county
Elm SI. 0
newsletter 0
I I I I I I
mml o
savings 0
CO o
High SI. 0
discounts 0 quick loans 0
I I I I I I ,
.
4 _ ...........
•
-'~
-
~
•.
..
~
• ..
Figure 12.11 Applying principles of good screen deslgr>-"Before" scuu: GaDa. W • ''lne ESS 'ltial G'oOt to user Interface ~ All introduction to GVi PPrIInIt<~' ' l anct Ted~." JOI't, 'Mtey 3; SOns.. 1996
USER INTERFACES: DETAILED REQUIREMENTS
,--, -.
New Customers
-
Branch
•
. -. - ' . •
r Account type
0 Main St.
r Privileges
0 checking 0 savIngs
0 Elm 5 1.
0 newslener 0 discounts
0 mmf
0 High 51.
o
0 quick loans
CD
Figure 12.12 Applying prinCiples of good screen design-" After"
the improvement that the applicarion or th ese p n nciples can bring. Figu re 12 13 shows where so me of rhe principles of good screen des ig n were applied.
Step 4: Select the appropriate kind of windows Each user interface purpose can be served most effectively by o ne ortwo panicular types of windows Figures 12. 14 and 12. I Slisr five common CU I purposes and a window type thai sarisfies each olthem The Window types employ Windows™ terminology, but are typical.
-----·~w..Qustomers ""' I
I
M ~hg,a li~~ ~/(l.rl1~!1t~ Last
p '- ---
I
o Elm SI. o High SI.
-:r ~ City I r~ StatQ/co
o (. '- SvmmQUJ! o I .. , . .. o CD
GfOUQ
J/kBRIBroeOIS
--4
SI,eet
Branch - Use capr/ons Account type o checking o Main 51.
Fl&ure 12.13
EXQBCted position
----- ~dOre~ -
- Name
First
dl!~~a
ProQOoioo
How principles of good screen design were applied
~~e.J<9~tmJq
::::J
I
I •
Border around like elemenrs r Privileges
o newsletter
o diso 6il1~
o
quick loans
293
294
CHAPTER 12
ANALYZING DETAILED REQUIREMENTS
I . Purpose: display properties of an enllly - property window
Propertie s u f autumobile 18g
Brand Model ~ID=----_ _ 893·8913·789014
2. Purpose: obtain additional information so as 10 carry out a particular task or command •. dialog window Help Word
This screen 0
All screens 0
Figure 12.14 Types of windows, 1 of 2
Step 5: Develop system menus Some rules for the creation of main menus, provided by Calitz [ 3], arc shown in Figure 12. 16. Users require a stable, comprehensible anchor for applications, hence the need for a constant main menu The number of Item on thIS menu sho uld usua lly be between r,ve and nine, because most of us feel comfortable with chOICes of thi size. For example, the word proce sor with which this book is being typed ha nrne m.rn menu items F,lr, Edit , \I"",, III Strl , Fonnat , Tools , Tahir , Willdo"" and Hrlp . The number of items could have been far higher, Since there IS plenty of space for more . However, we would probably have to 3. Purpose: provide information - message window
ABC alerl message
Caution: "age" must be < 120
~
4. Purpose: present a set of controls - paleNe window
5. Purpose: amplify infonnation
- pop·up window
This Is • pop-up window, designed to
provide on·t/le-fty
am~ification
Figure 12.15 Types of windows, 2 of 2
• Provide a main
meflU
• Display all relevant alternative (only) • March the menu structure to the tructure of (he application's task • Mmimize the number of menu levels Figure 12.16 Developing system windows
USER INTERFACES: DETAILED REQUIREMENTS
continually search the l1sl for the option we require, and this outweighs the benefit of increasing the choICes. The main menu items arc determined by the bUSIness at hand-in this case the processi ng of texL Thus, for example, gTaphics command are placed o n a secondary menu.
Step 6: Select the appropriate device-based controls "Device· based contro ls· are the physical means by which users communicate their desires to the application. They include joysticks, trackballs, graphics tablets, touch screens, mice, microphones, and keyboards.
Step 7: Select the appropriate screen-based controls "Screen· based controls" are symbo ls that appear o n th e mOOIto r, by mea ns of which the user no tiRes the application of his or her input and intentions n1CSC include Icons , buttons. text boxes, select ions, and rad io buttons. The rule for arranging screen· based cont ro ls in a Window arc Virtuall y the same as those for screen design in general (see Figure 12 . 10. Their numbe r is, agai n, ryp lca ll y berween five and nine. Th is number can be increased, however, when a hierarchy is used . For example, In Figure 12. 13 th ere are rwc nry o ptions to select from , but the interface is manageable because th ese Iwen ty items arc orga ni zed 1010 SIX grou ps.
Step 8: Organize and layout windows The rules for layi ng out multiple windo ws are si mil ar 10 Ihose for ind iVidua l screm desig n (involvIOg symmetry, proportion, ctc.) as in Figure 12. 10, but Ihey IOvo lve arrangemen ts such as til ing and cascading. The latter terms 3re illustrated in Figure 12. 17.
Step 9: Choose appropriate colors When used with skill and taste, color ca n enhance displa ys. Colors do no t aUlo malicall y make a user inlcrface more uschll or more attractive, however, and they can ca ily worsen It. According to ren owned designer Paul
~C~a~s~c~agdrrm~guw~m~d~O~w~S! --------lcon
,-
Tiled
t - windows --I
First
I
Last
I
I
Account type ·
Radio __
checking
0 savings
button
o mml Button - - Acure 12,17 COmmon GUI terms rnc;u teproGuced WIth
pe4iiifS31()n It om
corel
r - -
I
Screen
- Name
Text bOX - - - .
~
I
New Customer
+\ CIInceII
I
-.:J
& I .....a
boc'
Privileges
o
newsletter
q. discounts
-
~AAIIY...
" IJ.QIr
C1J.~k
29S
296
CHAPTI:R 12 ANALYZING DETAILED REQUIREMENTS
r
Rand , ·co lor is comple. ity person, ,cd" 4) oftware e ng,nc"" who do not have a profe'slonal desIgner with whom to work .hould be very panng aod On<ervallve about the u c of co lor. Try black and white ~r
12.4 DETAILED SECURITY REQUIREMENTS \'qriting the detailed requirements for security measu res is a maftcr of being entirely speciRc about the n«ded secunty measures. Some of these are shown in Figures 12. 18 a nd 12. 19 When II comes to security logolls, for example, we may want to requITe that if there is no keystroke o n the application for ten minutes, it logs off auto matically. Audit tra,ls for security breaches arc important. Some of these requITements are easy enough to specify but difflcult to implement. For example, how would an application know that it has experienced a security breach)
12.5 ERROR CONDITIONS For each requirement, we ask what would happen if ,t were to take place under erroneous circ umstances. As an example, let's take a requirement example put forward by Myers [5]. as shown in Figure 12.20.
1. U ser id entification capabi lities • Rules on IDs, name clashes, restnctions, etc 2 . Person or entity au the ntication capabilities • Exact requirements permitting acces to resources
3. Security logoff • Measures to prevent unattended or unusual usage 4 . Aud it trails of security. related events • Type, outcome, state at the time , date and lime, Source
Figure 12.18 oetalled security requirements. I of 2
5. Password speciRcations • length , composition, allows characters, etc. 6 . Controls to en ur. data integrity 7 . Retrievable record of encryption methods 8. Information on security attributes of the system
Figure 12.19 oetalled security requirements. 2 of 2
,
-
/
TRACEABILITY OF DETAILED REQUIREMENTS
AjtnCclto" lballtlls w!xlbtr Ihr,. "","bm produCt all equilalerallriangle (all sides equal), an i,osceles I'ia ngle (exactly !wo sid~ equal), or a sca/en, lriangl, (all sides different),
fIIu1'e 12,20
Requirement example, without necessary erro,s
A junclion lI,al Idls wh,lI", a lriplel oj nu",bm prodllc" , 1. an ,qui/alera/lriangl, (whose ,id" are all 9rea ler Ihan zero and etlllOl). in which cast .1 oll lpul, 'f' al Ih, prompl, or
2, an isoscel" lIian9 /' (whoSt ,id" are grealer Ihall uro, exaclly Iwo oj which are eqllal, and Ihaljorm a lriangl,), in which cast il oUlpul, '/' al Ih, ,ysltm, or
3, a sealen, Iriangl, (whoSt ,id" are all grealer IIJan zero, which jorm a lri,,'g/r, m.d Ihal is n,ilh,ttquilaleral nort,o,etl,,). ill which caSt il ollipuis '5' al Ib, prompl. or 4. no Irian91" ill wbich caSt il oulpuls 'N' a l Ih, prompl. FIgure 12.21 A more complete version, accounting for errors
This requirements specification is not complete because it does not account' for error conditions. The version in Figure 12.21 is more complete . A lack of error conditions in requi rements specifications becomes
especially g laring when the function is tes ted, si nce the tester forces error co nd iti o ns and needs to know ,,,hat the required output is. Sound requirements analysis does not tum a blind eye to "illegal" input: it deals with th em directly. For example, it IS tempting to assume that a C UI for the triangle requirement d oes nOt perm it th e input of negative nUiTlbers, and so the function docs not have to deal with erroneous data . Such an assumption is unwise because it transfers the "legality" part of the triangle require ment to reqUirements o n code clients of ou r triangle htnction , This increas~ the dependence among parts of the applicatio n, whereas we always try to obta in independent parts. Although it i, good practice to trap invalid user input at the CU I leve l and to o blige the user to e nter o nl y legal va lues, this does not subsl'itute for good requirements and error recognitio n elsewhere . The auth ors recommend requiring the trapping of incorrect data at many , if no t all . possible points. Th is is equivale nt to a long-established engineering practice of practicin g redundancy to pro mo te safety,
12.6 TRACEABILITY OF DETAILED REQUIREMENTS Chapter 13 di scusse the qualities that we want requirements to possess , an d metrics fo r meas"ring them . We will call out o ne property he re because it is fundamental to how we think about req uirement<'
IraClabtlily . Imagone an application with 1,000 speC ific requirement , Without, clean tTa ce fro m each requirement through the deSIgn o f the app li cat.o n to th e actual code that Implement s it, it IS very dlmcult to e n ure that such an application remains In compliance wHh th e requirements , When th e reqUIrements change, wh ich i safe to assum e , this becomes eve n mo ,e dtfficult The capaci ty to map each detailed requirement to .tS rtl<:vam pan ts) of the design and implemen tat Io n is called Ira ea btli ty . We Rrst di cuss the tra eab.h ty of functional requirements, th en nonfu nc ti o nal req uire me nt<. One way to help a ompllSh traceabi lity IS to map ea~ h functIona l d e tailed req UIreme nt to a Specl function o f the target language Th .. t 'c hn.qu e is used III th e Encounter a e stud y. FIgure 12 22 .ho" '$ rart<
297
298
HAPTER 12 ANALYZING DETAILED R
QU IR~M ENTS
Design
:..----=--=----::---:0
Code Implementing MY-D-Aequireme:=n:::t Code Test plan
My-D-Aequirement
Test plan inspec1ion Test report
r,.:e~po~rt:,=i~~~~=~':":':===::....J
=
key Iraces •• 0 - ; delailed
Figure 12.22 A thorough trace of an invidivual detailed requ irement
of the project that we would like to keep linked to have comple te traceability. Achieving and maintaining this deg ree of tra ceabili ty durin g devel o pment is a major c hallenge . As an exa mpl e, co nsider the fo llo win g functional require ment for th e Encounler video game case srudy \'(Ihen a foreIgn ga me c haracter e nters an area co ntaining th e player's main c haracte r, or vIce versa, they engage each o ther. The m ea nin g of this stateme nt is clear. What re mains to be seen , however, is what part or parts of the desig n and code will be respo nsi ble for implementin g this requireme n t. Whe n usi ng thc 00 paradigm we can link this requi rement to a speCific function of a speCific class. The issue of w ha t class is responsible fo r a function is not trivial , and it ari ses repeatedl y when usin g the 00 ty le . For the above example, ArrD objects would be able to recognI ze that an engagement i to take p.1ace s ince the y would presumabl y be aware of th ei r inhabitants. In particular, th IS requireme nt wtll be traceable to peclhe event-handling code for th e Arra class. As the project proceeds, the requ irements d ocument hou ld be kept consistent with the d esig n and the implementation . When requirements are hard to trace through desig n and code , however, d evelopers tend to avoid updating the requirements d ocument when mak ing c han ges to the ource code becau. e of the extens,,'e effor! required . Ultimately , such a deteri o rati o n of documents result in escalatin g development and mainte nance expenses. ThIS pheno menon is illustrated by th e following example.
Dnxloptr Bill j, ask,d 10 make cbang" 10 1/" implemnllallon /.Jill find, il difficlIlt to COlln,, ' Ih, cod, b, j modifyin!J to 'he corrtspondiJlg pflrts oj tht rtqu;rrmtttis documtnt l cotlStqurnl/y. ht flllls to "pdale rlx
Devtloper CD n"," i, task,d 10 m"k,
"CU, modific,, 'ions. Sh,
dOCUmN1111110Pl
imp'''"'"1s 'I(", cod•. Irsl, il. "nd b,gi", Updali"!J lbe rt4uirtmrnls documrnl. Howrotr, rtltryOtlt Itlls htr "0110 botbtr, 1>0lnting oul IIl(lltht rrqUlrt'"rtt ts dOClfn't"rtt is out oj dal, in ,ever. I pltlCCl affd no Oil' lrusls il"ery milch They ber il makes "0 Sm,' 10 lake II" I,m, 10 ptrJ«1 her pm' w/"" /10 01/' will "tid Ih, Jocumenl ."y",ay So Carmnl mo"" Oil 10 do 011", programmill!J n,. '/I<",,,,,"nrs b(hocttl fht rt4U1rmttJIls JocufTItn' find the codt ('O" ';"U( 10 Wldttl
,,1/
TRACEABIUlY OF DETAILED REQUIREMENTS
Regu,,,,,,,ent 1783 178 4
Module 1
Module 2
Module 3
getimerestO showAccountO
computeSa lO showAddressO
showNameO showNameO
FIgure 12.23 Example of a requirements traceability matrix
When a requirements document as a whole is untrustworthy. even the most conscientious developer
balks at properly updating his or her particular part. On the other hand , when the documents are clearly crosS' referenced, and management makes documentation a job performance requirement, engineer< do keep them in very good professional shape. In other words, the system used to match detailed requirements with the designs, and code thaI imp lement them , must be very clear and co ncrete. When the code implementing a requirement needs to exist in several parts of the implementation,
tracing is achieved by means of a requirements lracmbi!ily ",alrix of which Figure 12.23 is an example. Here, requirement I 783 is implemented by the action of fun cti o ns 9rll"lm,10 in module I , compIII,Ba!O in module 2, and ,howNa"" O in module 3. A change in this requiremenl necessi tates a change on o ne or more of these functions. This must be carefull y managed because Ihese func tions may participate in satisfying other requirements (e .g .. ,bowNa",,() is used to implement requirement 1784 as well ). As a result, changes made to satisfy one ",quirement may compromise another. Since many· to· many relationships are difficult to manage , we try to make the mapping between requirem ent and function one-to-onc.
We want each detailed requirement to be traceable forward and backward . The preceding discussion concerns forward traceabiliry of functional requirements from detailed requirement to implementation. Backward traceability of a detailed requirement means that the requirement is a clear conseq uence 01 one or more high .level requ irements. For example, the detailed requirement Foreign characters should move fTO m area to area at intervals averaging 5 seconds can Ix: traced back to the fo ll o wing hi g h . level requirement, which was part 01 Section 2.0 in the SRS . The rest [of the c haracters), called "foreign " character<, arc to be under the application's control. This backward traceabiliry is a basis for the inspectio n o f detailed requirements. Compiete traceability is Obtaoned when each detailed requirement is Ionked to a spedRc ekment of design , and to a unit test, as suggested by F'gure 12.22 . lt indicates the advantage of a ti ght trace (correspondence) between each individual functional requ' reme nt, the part of the design Inte nded to handle the requ irement , and the pan of the code that implements it. These are coupled with the focused tcst lor the requtreme nt , ca ll ed a 1..,;llrsl. Unit tests are the subject of Chapter 26. The preceding discussion concerned functional req uireme nt , but how do we trace nonfun ctional requireme nts1 This ca n be dimcu ll because more than o ne pari 01 th e design .nd implementation may contribute to satisfyi ng a nonlun tiona I rcqutremcnl. For example, a req uireme nt that every En Olonter t n!!"gem"nt com plete In less than o ne second could involve ode in an Ellgagr",ml class, .neVor a Gill'" b.,mcl" class, . "eVor an A"a clas<. ur oblccti ve at requlremen ls tllne is 10 specify nonlun tlo nal require ments. clearly as possi ble . In o rd er to larify nonl"nctlor.. 1 requ ireme nt , we will al,o lo uch o n des,s n and tmplementafion issues.
299
300
CHAPTER 12
ANALYZING OEl AI LEO R(QUII1EMENTS
InspOCI
- - - - -••......1,mPlemenlatlon l
,,-/
t
,/
I I
,/
,/
I
,/
I
,/
Relevant
.,/
components
Implemented by whole application
tests ...
,/ ,/
,/ ,/
I I I I I I
Nonlunctional Requirement · - - - tested by - - - - • System Test Figure 12.24 Tracing and testing lunctional vs. nonfunctional requirements
O ne goa l of the design phase is to isolate each no nfunctio nal requirement
In
a se parate design clement
In the case of performance reqUirements , an iutempl IS made to isolate time -enrical processing units
Appropriate , inspectab le, nonfunctional comme nts accompany each function that is aHected by performance requirements. Preferably, these are quantitative, as in "must complete in less than one mollisecond In the worst case ." Simila rl y , in cases where storage constraints arc spec lfled , we identify functions that generate the most stora ge. Expenence shows that a relatively small percentage of function s in an application account for most of the processing, so searching for a few principal time ·consuming ones can be fruitful. Let's return to the "one· seco nd" performance requirement example for Encounter engagements mentioned above . At design and implementation time, we seek typica l rime-consuming components in the computation of engagements
These components include loops, graphics displays, and netwo rk communication . Loops and commUnication arc not involved in computing engagements, and a test is implemented to ensure that the graphics and CUls required for an engagement execute f.. st enough . Probably, the function that consumes most of the time is either the function to "e ngage a foreign character" of the E"9a9"""'1 class, or the function to dISplay engagement results. To validate nonfunctional requirements we therefore tic each ohhem to a test plan, preferably at the time of writing the requirement . Figure 12.24 illustrates the typical relationship of functional and nonfunctional requirements to implementation and testing, discussed above. It illustrates the fact that several elements may contribute to nonfunctional requirements, and that system or integration testing is typically required to validate nonfunctional requirements because verifying them (i.e ., prior to execution) can be dimcult.
12.7 USING DETAILED REQUIREMENTS TO MANAGE PROJECTS Detailed requirements can be considered the "currency" of 3 project because they track the amount that' been accomplished. For example, a project manager can track the project as in Table 12 1 Recall that It's import.nt for developers to qUickly Rnd rclevant requirements sections to enable them to easily keep a requircll1.-nts document up-to-date. In the IEEE requirements format, functional requirements arc III ection 2. If we ,,'ere to number the paragraphs 3.2. 1, 3.2.2, ... , It would be time-consuming to locate the paragraph pertaonlfl/.! to a CU51.",,, class, for example. For this reason , the authors usc an alphanumeric labcll n8 uch 3 2. U for Customers, 3.2.DV for DVD<, ct .
PRIORfTlZJNG REQUIREMENTS
301
Table 12.1 Example of a table that facilitates the tracing of a rCQulrement with video
12.8 PRIORITIZING REQUIREMENTS It is usuall y diffic ult- if not impossible-to imp le ment oil desired fun c tio nah ty of an appiocat lo n o n sc hedule and within budge t. As discussed in C hapte r 8 , one may trade o ff copabilily , schedll le , qual.ty level , a nd COS I. Thus, the schedule , budget , and quality leve l can no t be chan ged, the o nl y alternative is to vary ca pabd ity-th at I to reduce the:: requirements that are implemented . Thi s reduct ion prace One techniqu e
IS
S IS
.r ,
perfo rm ed in a planned manner.
to prioritize the specific requirem ents. Rank ing all requirements is usually a waste of time
Instead, many organizatio ns classify requirements in to three (sometime fo ur) catego nes. \'I/e wi ll ca ll th em -essential ," udesirable," and "optio nal." The usc of three categories
IS
an applicati on of triage des nbed In
Chapter 5. We fi rst implement all of the esse ntial requirements. The de irable and o pllo nal req uirem en ts indicate the direction in which the app licatio n is headed and thus inAuence th e des.g n F.gure 1225 gives an example of req uirements prioritization .
Some specul ate that as muc h as 80 percent of the real benents of man y appiocatio ns accrue fro m as fe w as 20 percent of the requireme nts. Thus, if prioritization is perfo rmed well (e.g., calhng ro ughl y 20 percent-no mo re- "essential"), o ne can possibly achieve most of an appl.catio n's be ne fit with o nl y a frac tio n of the wo rk. Th is is a useful point to keep in mind if the project begins to run o ut o f time. The preliminary draft of a n SRS sho w n in Figure 12.26 co nrains so me pri o rnized deta.led requiremen ts fo r the first release of Encounter. They are provided here, "warts" and all , to g .ve the reader a feel fo r i<sues that mu t be dealt with. Some of the "desirables" wi ll become "esse nt ials" in future releases. The requirements are in dr.l ft form and are clearly in need of reorg anization. They arc improved upon later In this chapter and in the ca e Stud y The prioritizallon of requirements usually re lat es to the itCr.llio n that wi ll .mpl ement them Fo r ",
[essentia l] Every gnme cho,"el" ',as II" sam' " , of qual.,irs . [deSirable] Each ar(Q hns 0 5<1 of preferred qllal"irs [optional ] Th, play,,'s characler sholl o!l' w.lh tv'ry nlCou"ler. Th((lge rale call bt " , 01 5
FIgure 12.25 Exa mple of prioritization of detailed requirements
302
CHAPTER 12 ANALYZING DETAILED REQUIREMENTS
PREUt>.IINARY I RAFr I FnUlU I11c r de laried rcqulI'c ,n e nt' (n,e , e ~re no t e l (lrHJ nlzed , , ce th e ca e , wci y (IIr an lIl1proved form ,) (no t rn'pcucd ll c, se nl ml l Every ga me c h.l rac te r In th c Encounler video I!amc
[ I10 t "'
IS
o nne ted to ol her areas by eXIts
(no t In< pecred )( e se nt ia l] Whenever ~n EI1 o unter ga me c haracte r e nle " an arca cont.,nrng anot her game c ha racter and o ne of them is pla yer- o nlro ll ed, th e c hara te" may c lthe r c hoo
value 01 the player's stamllla , Assumin g p, + p, > f, + f" we wou ld ha ve p: = p, 1/2, Ia' = f/ 2 where x' de no tes the value of x after th e transaction ,
+ f/ 2, p; =
p.
+ fJ2, f:
=
[ no t inspected][optiona l] Encountershall take less than a second ro compute the resuits of an engagement. [ not inspected ][ o pti o nal ] The player's c haracter shall age with every e ngagement. The age rate can be sel at e rup rim e , Its default is one year per engagement. [ no t II1spected](o ptio nal ] Playe r-controlled c haracte rs lose o r gai n th e values of their c ha racters at the end o f every engagement at the rate 01 +2% when und e r 30 and - 2% when ove r 30_ Figure 12,26 Preliminary SRS fragment showing prioritization and status of deta iled requirements
ro compute th e resul ts o f an engagement" in rhe second iteration , it could appear with h ig her priority in a subsequent iterati on. Th e requirements for an iteration arc maintained in an identi fi able manner. TI'1 helps In unders tandin g subsequent requirements.
12_9 ASSOCIATING REQUIREMENTS WITH TESTS As each de tailed requirement is written , tesrs for the rcq urrement
AGILE METHODS FOR DElAll ED REQUIReMENTS
T est input for Requir<:ment NNN
Harry
X
Ex pected o utput
H arry X
" " (bl ank)
,. (bl ank)
1234567890 12345 1234567890 123456
1234567890 12 345 1234567890 12345 . ...
. .
'
"
Figure 12.27 Example of association between detailed requirements and their tests
To rake an e xam pi c, o ne of Our req uire ments is as follows, Requ irem e nt N N N . Every ga mc c haracter in the Encounte r video game shall have a unique name containin g be tween I and 15 c haracters. Requirements of th e attnbute type like th is rea ll y specify get- and set · fu nctions, so that Figure 12 27 constitu tes the begi nn ings of a test plan fo r th is requirement Part VII covers these teSts In detail.
12.10 AGILE METHODS FOR DETAILED REQUIREMENTS • In an agile project, th e de ta il ed requ ire me nts arc u uall y expressed In terms of in ·code comments and '"11t tests rat her than be ing writt c n ex pl ici tl y in a se parate docume nt. For examp le , conside r a traditiona l requ irem e nt such as th e fo llOW ing . Customers sh all be able to e nte r th e name of a D VD in th e text box, up 10 20 alphanumeric characters. The appl icatio n shall check th is, wll h punctua lio n marks replaced by blanks, Wllh the DVD inventory , a nd d isplay accordin gly "Sorry , we don't stock thIS DVD" or "Added to your Ii t." Th is is replaced with o nc o r mo rc lests as show n in lisling I , aug mented by code comments and eqUivalent data e ntry in the correspo ndi ng CUI. Assume that the se tu p code in the unit test contains the followIOg
1: Example of JUnit testing. typically used in agile methods
DVDSearch dVD Se a rch = n ew DVDSe a rch() ; public void t est Lookup ( ) {
/1 "Gone Wi th Th e Wi nd ' , should be present dVDS e arc h . d oSearch ( " Gone With Th e Win d " ) ; a sse r t Eq uals ( dVDSear ch , searchResu 1t , true) ; a sse r tE q uals( dVDSearch . outputMessage , " Added to your list " ) ; II " War a nd Peace ' , should be absent dVDSeaICh . doSearch( " War and Peace " ) ; a ssertE quals ( dVDSealch . sealchResult , false) I
303
304
CHAPTER 12 ANALYZING DEl AiLED REQUIREMENTS
assertE qual s( dVD Searc h.outpu t Message , " Sorry , we don ' t this OVO' , ) ; •
•
•
•
stock
•
•
}
Fi gure 12.28 "lImmarizcs lhls discuss ion. The adva nt" g~ o f uSing tes ts as a requirement is that thi s i concre tc , th e d Isad va ntage is th at It IS not complete. There i. nothin g to sto p us from including th o ro ug h d eta iled req uirements with the un it tcst. ho wever, thereby gainin g agi le and, to some ex ten t, no n.agile ad va nla gcs Thi i show n in Figure 12.29
-.OJ
o Z
C ust o mer shall be able to enter rhe name of a OVO ,n rhe tex t box , up to 20 alphanumenc c harac ters. The app hcation shall check rhi s. wi th punc tuati o n marks replaced by blanks, with the OVO inve ntory , and display accordingly "Sorry, we d o n't stock this OVO" o r "Added to your liSt." (Excerpt from requirements d ocument. )
-.-
public void testLookup( ) { I I ' 'Gone with The Wind" should be present dVDSearch. doSearch ( .. Gone With The Wind" );
CD
«•
c:
OJ
CD
«
•
•
•
I I ' 'War and Peace' , should be absent dVDSearch.doSearch( "War and Peace" •
•
);
•
Figure 12.28 Unit tests and code comments as detailed requirements in agile processes
I· Requirement 3.4.2: Customer s shall be able to enter the name of a DVO in the text box, up to 20 alphanumer ic char acter s . The app licat ion shall check this, with punctuat ion marks repla ce d by blanks, wi th the DVD inventory, and display accordingly' 'S orry , we d o n't stock this DVD" or , 'Add ed to your list. ' , -I public void testLookup() { II ' 'Gon e With The Wind" should be pres e n t dVDSearch. doSearch ( .. Gone With The IHnd" ) ; •
•
•
I I ' 'War and Peace' , should be absent dVDSearch. doSearch ( "War and Peace" •
•
);
•
Figure 12.29 Comblnlng agile and non·aglle methods In handling delalled requirements
USING TOOLS AND THE WEe FOR REQUIREMENTS ANAl. YSIS
, . Understand next requirement
o. Understand high-level
5. Refeetor code 10 clean uP. ele.
2. Refactor code base 10 prepare for Ihe requirement, jf necessary
requirements
4. Modify code
base 10 pass Ihe test
3. Write tests validating the
F'tgUre 12.30 The agile programming cycle
When unit tests arc used as detailed requirements, [hey are some times written btJort the code is written This style is known a !<sf-dn"nl drur/opmtnl. It bui lds upon the existi ng code base, and IS ca rried out in the following sequence. I. Understand the required new or modified functiona lr ty.
2. If needed, refact o r the code to prepare it for the new func ti onality. Rdactoring preserves the code's functio nal ity, ne ither increaSIng nor dec reasi ng its actual h'llcti o na lity. It IS discussed in detar! In Chapter 24 3. Write test code that would test thIS functiona lity If It eX Isted . This is usuall y done with a tool slIch a J U nit This te t will fa d initIall y beca use the functiona lity it tests does no t ye t eXIS t 4. Add to the code base until th e test pa ses. 5. If necessary, refactor the code base to make it clear and coherent. Test ·driven development IS described funher in C hapter 27. Recall that agile development co nsists of the cycle shown "' F,gure 12 30. Refact o ring, de cribed In Chapter 24 , IS esse ntia l to the pro ess In two ways. It IS u
12.11 USING TOOLS AND THE WEB FOR REQUIREMENTS ANALYSIS Tool, can htlp th e process o f ca ptunng and managIng r ·q urrcment<- for example , hy >o""n~ , ,ltegon z; n!:. p"oritizlng, asslgnlns , and tracklnu them One be neA t o f >uc h tool, i> to kn o w who" worklllg on what requirement at what tIme Ton" <.a n also help to o nt",1 '·fea ture crce p'· -the pr t" by w h, c h leatur~s that ire not r.ally nece.sary are add ed to th e app lrca tron W,th th e approprI"te t 0 1<. a projec t !tader can more eaSIly asseos the tatu, "f r.qUlrt·ments a nal y", I or exa mpl e , th e leacler an N" ly d e tcII'lIOl' the percenl"!!"
305
306
CHAPTER 12
ANALYZING DETAILED REQUIREM ENTS
j:ilatuB
edPd1¥
aQlllOOlllllWl QUmb.or
Essontlol
"T
No.
OpUonol
slor1od
Ooa.gned
F,oC'tJon wmplOIO Roady lor
' /3
213
lor
'nopoction Inspoetod
Ooslroble
Imogr••lon UN'
'I liad
tested
8&§PQQsible QDgIO~Q[
T
-t
Figure 12.31 Example spreadsheet lor tracking ;equlrements
of essenti al deta iled reqUire ments implemented and full y tested by QA. Bugz ill a (someti mes in a version with the unappealing name "Issue zi ll a"), an open sou rce too l for manag ing reqUi re men ts, was descnbed In .he Ecl ipse hig h· level requi reme nts case
12.11.1 Simple projects For simple project , much of this can be performed usi ng a si mple Web ·bascd spread sheet, as illustrated In Fi gure 12.3 1. Howeve r, fo r most reasonabl y sized projec ts a req Uire men ts tool is esse ntial. The "deSigned for" desi gnati o n in Figure 12.3 1 ind ica.es that the require me nt is accounted for in the desig n. "Un it tested" means that the code implementing the req uireme nt has unde rgo ne testi ng in stand·alo ne fash ion . "IntegratIOn testing" means that the application has bee n tested to verify that it impl ements the requ irement. A table such as .hat in Figure 12.3 1 is mai ntai ned as part o f a project s'atus document that can be attached to the SPMP The e lls in th is marri x could be hyperlinked to releva nt parts of the project's documents, thereby preserving slngle·source documen.atio n for detailed req uirements (i.e., e liminating duplication ). For example, ,.. ____ _ Hvpedink from Jaya Source I to CorresQonding 0 • Reauirement Using /ava doc
t
ro ,.I
"'
The purpose of this melflod Is stated in SRS. The purpose is not repealed with the source!'!'fIe.
.,.
public engageForelgnCharacter( ... ) ( • •
•
•
•
)
FllUre 12.32 Hyperllnk from Java source to corresponding detailed requirement using Javadoc
USING TOOLS AND THE WEB FOR REQUIREMENTS ANALYSIS
h)'JlCrlinks from the ourcecode to the corresponding detailed requirement can be accompli hed with toolssuch a Javadoc.J.""doc converts certain Java source code comments into an HTMLdocumcnt describing thc classes and Iheirmethods (sec, for example , [6 ]). By insening hyperlinks to the SRS within the e commenlS, the HTML document produced by Javadoc hyperllnks to the SRS. This IS illumated In Figure 12.32 , where the detailed requirement corresponding to the method CllgagtForrig. Characttrf) is hyperlinked from the document that Javadoc produces from the ouree code. The usc of dodtts make thIS process increasingly convenient. The trend is for continual improvements in the process by which prog rammers will be able to more easily go back and forth between the SRS , the deSi g n, the graphical user interfaces, and the source code.
12.11.2 IBM's Requisitepro™ For substantial projects, professional tool s are needed to track reqUIrements. The shee r number of detailed requirements usually make this necessary. One example is IBM's Requ is llePro™ product. The fo llowing figures, describing it, are taken from hllp.//www.lbm.com/deve lo perwo rk ra tio nailli braryl53 47 html F,gure 12.33 shows a window for sClling the properties o f an Individual detai led req uirement RequisitePro allows various views o f the requ ireme nts as a who le This helps projec t managers and software engineers to manage and track their progress FI gure 12.34 is o ne example .
I
W •• I
I
....."or T,..·
.
,
:' :
I
...
t
!lr:
U
'0,
--
I
ned",
-
I Cb
f.
J r,IT;.~h~E.'---------------~iJ
\It
Ic
As&!
:a::
U 11
• c
..
Figure 12.33 Setting properties of a requirement In IBM'S RequisitePro"" SlraoonaVliDra1y!S247 htmt
Figure 12.34 A view of a collection of reqUIrements In RequlsltePro SoI¥ck IBM, hUDHYMW_iDm comIde~eIoptNo'Of'tslrttiOMlllibrbfYJ'5.247 htrnl
rM
307
308
CHAPTER 12
ANALYZING DEl All D 11EQUIREMENTS
,'2'
't
1$9
•
•
, 0 _II/ll,,.d,. 1.0. J m t
erell-"I
-
-
~I
Figure 12.35 History of a requirement In RequisitePrc™ Source 18M, hupJ/www Ibm cOlTVde\IeloperworkSlrotlonaVllbraryl S247111mJ
It is possi ble to query this requ irements database-ill other words, to obtain all requirements satisfying a desired criterion , su h as those pertaining to security As individual requirements are wo rked on
by softwar~
engineers, tools hke RequisitePro,.M .IIow the "history" to be tracked, a sho wn in F,gure 12.35 . H,story refers to an account of the work perfomlcd to sa ti sfy th e requirement at various points in time .
12.12 THE EFFECTS ON PROJECTS OF THE DETAILED REQUIREMENTS PROCESS Once detailed reqUIrements have been coll ected, the project documents can be updated to reflect the improved project knowledge. We w"l take as an example the reqUIred updates to the SPMP , which can be updated as sh own In Figure 12.36. Detailed requ irements are placed under conA guratl o ll control. One issue to be addressed is what level of detaIl should be counted as a software conn gura tion item (CI ). ertainly , Section 3 as a whole ("SpecIfic requ"ements") of the SRS (using the IEEE standard ) could be a CI Each class could be a CI. Individual requ"ements are typIcally too nne· grai ned to be Cis. \'qhe n the list of requIrements grows into the hundred , i"cotfSIsttHCltS Can easily arise . Oassifying requirements by classes, classe; by packages, and packages by subpackages, and the like becomes a necesSIty. The packages typically correspond to subsystems in the ove rall organizatIon of the application. Although rompl","css is a goal for which we strive In collecting requirement , it i usually an elusive goal For substantial applications, there is seldom a natural "last" requirement-just the last one before requirements freeze . For th is reason , we strive for self·complctcncss: ensuri ng that all of the requirement!' necessary to accompany each requirement arc present.
Large ·scale projects require increasi ng organizational fomlality (not to be confused WIth formal method» . The SRS may have to be divided into separa te volumes. A single section on Our (tiny ) case rudy could <"xpand IntO a 700· page volume. Extensive management work is required to schedule the development and onspection of detailed requirements. PrOjects WIth hundreds of spednc requ"ements need requIrement manallement tool The suecc<sful WIdespread usa~e or thdava package< ha shown, however, that I.rge collections of reqlllrementlo are manageable when the functionality IS organized by well·deRned po kalles, oubpa kag.: and la c> The rewards of good requirement< analY>ls arc sub tantlal onvcrsely, the penaltl<'S or poor requirements are substa ntial too. For examp le, Faulk [7], repom on • Covernment A counting Of c study of the C heyenne Mountain Upgrade project on wh,ch "reqllirements· related problems· ulted on. 600
STUDENT PROJECT GUIDE: REQUIREMENTS FOR THE ENCOUNTER CASE STUDY
- latus after Initlol draft
R"ull of updating afltr higl!.lrod
Result of updating .fter detailed
rtq,Hrrmt"'S
reqUirements
•
Milestones
Initial
Mort d,'ai/,d
More detailed
Risks
Idenl ify
Relire t'isks idrn·
Retire risks identiAed. ide ntify more ri sks
lijI,d P,roio",/y, serk mort risks Schedule
Personnel
Very h ig h
Prtlinmwry pro)-
level
,el leh,d,,/,
D esignate C-
£"9111(((S dcslg . "a I,d fo, D·
requirements
Cost Estimation
engin~ers
rrqu irrmrols mUllySIS
Crude
Firs! csritlln l(s
eStimates
baltd
0"
CO ll 1(")1 1
job
Mo re det.ailed, shows c1.ss and method development ta,klng DeSig nate softwa re architects
Improve d cSlimalc using more specific function points and/or past experience with similar requirement
Figure 12.36 updating a project upon completion of detailed requirements ana lYSIS
million cost overrun . an eight ·yea r delay , and dimin IS hed capabilit y. Debates continue abo ut the perce nta ge of large projectS that turn ou t badly versus the percentage that turn out well. Many large projects do a fi ne job of requirements anal ysic;. Th e author can arrest to thi s fro m persona l experience
12.1 3 STUDENT PROJECT GUIDE: REQUIREMENTS FOR THE ENCOUNTER CASE STUDY This section illustrates how the requirements princi ple . covered III this book arc translated into practice, by u ing the video game case stud y as an exa mple It use the o bJec t-o ncntcd sty le of expresslll!: reqUirements Recall that thiS organiZing style has the advantage of improved tra cea bil ity and the disadvJnta ge o f diminished readability compared with o ther organizations such a. by use casco11,e ca« study IS continued III
1. Preparing Hal Furness, haVi ng bee n elected the requirements leader. wa< re<po nsi blc for o rgan izing the anal y
by preparati o n Interview, WfllC · Up, and review The I1l clrics they chose were dl tJtcd mo,t1 y b l
company policy. and were a< follows • Time taken • Pagei of hlgh . level req uirement> wn ll e n
309
310
CHAPTER lZ ANALYZI NG DETAILED REQUIREMENTS
• - eif ,. " c"I1lCIH o f Ih · artlfa t, On a < ale 01 I- I! (nut rn anJuted by ,,",pa ny po litY)
• Dele tS lound dunn" ""pc tioll' . a, appli~:tble The ~a dcr IS referred to SectIo n 4 01 thi s guide to ,cc the,e metfl (' arran Ke d In tabu la r fo rm a~n made ,ure that the sy
At a weekly meelin!!, H al prese nted a plan for requ rrements analysis, as fo llows, Week 1, Hal and Karen , Interview Betty, begi n draft ing h ig h · level requirements . Fern and AI: Seck o lhe r candidates fo r requrrem ents input Week 2 : Fern and AI: Report candidates
10
weekly mee ting .
T ea m, Selec l o ne o r two addil ional people
10
supply requirements.
Hal and Karen, Complete draft of high . level requiremenlS, e ·mail to Betty for comments; arrange to interview the deSig nated additional people; c· mail existi ng specifica tion to them; c reate a complele requireme nrs docume nt fo r iteration t ; place under conAglirat io n comro l.
Week 3 : T eam , Approve the SRS for iteration I. H al and Karen: Interview deSignated people. edit and expa nd the specification; c·mail to all interviewees; collate respo nses, edit docume nt, leaVi ng selected issues for team resoluti o n; plan detailed requirements analysis (sec the Part V 01 this book). Week . : T eam, Provide input on the draft SRS; approve plan fo rdetailed req uirements analysis (see Part Vol Ihisbook) Hal and Karen, Write up SRS and e·mail to all interviewees.
Week 5 , Hal and Karen: Resolve issues raised by interviewees, write up results; e ' ma,1 to team, begIn impleme nting detailed requirements process (sec C hapter 13). Team : I~ spect h'lIh . levei requirement•.
STUDENT PROJECT GUIDE: REQUIREMENTS FOR THE ENCOUNTER CASE STUDY
Despite the expense, Hal felt .t impon.nt to have the cntlfe team inspect the high . level requirements because of the do ument's importa nce In general , the team planned to use thrce·perso n inspection teams. Hal heduled the first interv.ew with Betty .n Room 1428 of the Stewan Building from 10,00 a.m. to 11 :30 o.m. He .·moiled h er a bnef write ·up of the project's history, and created the foilowoog very simple agenda. 10:00 a.m.-l0: 15 a.m. Hal : motives for the project 10: 15 a.m.-l 1,30 a.m. Interview of Beny: customer requirement Hal decided not to introduce more details because he wanted BellY's requirement to influence the rcst of the meeting.
2. Interviewing the Customer Hal and Karen arrived at the interview with Betty, equipped with good sound recordoog equ.pment. Betty could not understand why anyone would want to build a video game unless it competed with the best available. Hal explained that this was just a firs t step. to provide the team with expenence in this kood of programming, to get an idea of the scope of work required, and to show the investors what could be accompli shed with a given amount of funding . Other motives were to dctermine whether there was any merit to the ideas that v.deo ga mes have potentially wide appeal , and arc applicable to educatio n. Aftcr this, the meeting became more focused The tape recorder was turncd on and Hal and Karen began to take detaded notes. Betty's contention was that role·playing games (not action games) held the most promise for broadening the playcr community . She disc ussed the minimum capability that a prototype would need . Th i in luded areas where the game characters would engage , ways to get from one area to the ot her. ways to cause intoractions among characters, and what wo uld happen when ,he c haracters engaged . Hal and Karen ,ned to separ.te the issues and features as they arose . into "c rucial for the first itera tion," "can be post poned ." and ' other (Le., they used a triage method). The importance of the requirements lis,ed in "other" would be determined later. Given the script.like nature of ,he requirements Beny described, Hal focused on ob,a'OIng use coses fro m her. He asked her to describe typical scenari os for the game. Be'ty de cribed wha, happens ,vhen two characters interact Kare n took no 'es and expressed thi s as a use case-a sequence of action 13ken by the player and/or the game-a nd then read it back to Beuy . Beny couldn't- think of any o ,her scenarios . Hal felt that there IOU t be more, and a_ked how the ga me gets staned. This resulted .n a second use ase. The third use case th.t they recognized explained how the pla)'cr mOves his character from one area to another. These three use cases seemed '0 be a satisfactory begin ning. Hal and Karen felt that there mig ht be additional essential use cases, but 'hey would have to gather ,hcm la,er. Berty , Kare n , and Hal sketc hed a few screens together. One showed a typ.cal encoun,er, .nd another showed a screen for en teri ng the qualities of ga me ch arac'crs. The re was considerable d i cussion of the perspect.ve that the player wou ld have. Betty wanted a player perspec'ive where the vicw shown on the mon i,or is the v.ew seen by the player. Karen felt ,hat 'he reqUITed complexi ty for ,h .. view would rake ,hc proJec, well beyond their modes, initial budget . It was agreed ,ha' a modified fro m·above view would be adequate for the prototype. The screen sketches reflected ,his. TI,ey agreed ,h>! conSIderable re lIlement of the user .n,erface would be required Because of the in,erfaces that ,hey sketched, Karen fel ' that 'he go me could reall y be underst od an i b), meaM of states Betty was not famoliar with th. tem" but she was comfortab le describing ,vha' he called ,he "mode<;" of a typica l role . play.ng game, wh.ch ,urned o ut be the sa me oncept. Karen ond Hal ,hen ,ke t hed out the requ.red ,ratc' of the gome, and rev.ewed w.th Kare n h ow ,he Rame golS from One s'a'e to all ,11 r
'0
311
312
CHAPTER 12
ANALYZING DETAILED REQUIREMENTS
H ~ I bro II ctll",d 'n:d cI~rofy ", !! the gJl1le lurther by analyz ing lhe lI"w ,, ( data, but , oon (cal,~d that the data Ilow I CI" lll'C live added httle va lue Karen I" vlewed he r no tes with the o ther, A (ew pOlOt ' nceded carre tl ng, but th ' re wa, lIene ral :lgrecmcn l on the de~ ripti n.
3. Writing Up the software Requirements Specification Hal and Karen diVided the task o f WfltIOg up the RS by ,ec tio ns They used the IEEE R standard, $cctlons I and 2 ( eetlo n can I>t> o f the detJded requirements, the proce s (or whic h" d, >cus,ed In the Stude nt Project C",de for h ~pter 4). T o avoid onOicling wri te·ups, they made ,ure that their sect io ns wc re as Independent as possible. Hal remembered IllS previous project, where the team pe nt sa muc h time reconciling pieces written by different people that It would have been quicker for one perso n to pe rfo rm the entire tas k alo ne They disclls<ed how to proorotl ze the req",rement" becau Cit wa, becomin g lear that o therwise the list of requirements would become fa r larger than the team could handl e. Hal ,.anted to rank the m all , but Kare n pointed out th at the effort Invo lved would be large ly wasted- most of the top -ranking reqUirements would ge t done anyway , so the ir exact order would not be important. Almost none o f the botto m ones wo uld get done , a the lime spent ra nk ing them also would be wa red . They deCided to use a tTiage method to rank requirement into essential at o ne extreme, optio nal a t th e other, and desirable for the middle category (which simply means neither essential no r optional) . They felt that it might be necessary to rank the deSirable reqUireme nts later. Th IS saved a grea t dea l of useless debating time. They de cribed their claSSification scheme 10 ectio n 2.6 of the SRS ("Apportioning of reqUi rements") . Section 2. 1. I (concept of operation , containing the sta te diagram fo r the game) took Hal the longest time to write because he had to translate Berty's info rmal comme nts into a concrete fDim . They tried to cross-reference appropria te sections of the SRS with correspo nding ,,'Sts even though the teStS we re still sketchy This helped to clarify the requirements themselves. however. When Betty looked at the test for Section 2. 1. 1, she recognized that Hal and Karen did not understand some of the issues. In particular, whe n the game is in Reporting state and the foreign character enters the area contai ning the player's character, the tcst did not expect anything to happen Betty saw thi< as detrimental and as a way for the player to effectively halt the game. The defect was added to the list of defects wi th a "major" categorizatio n. nt Karen sketc hed the user inte rfaces using PowcrPoint a a draWing tool , rather than building them wit h Java, the target lan guage. She considered PowerPolnt adequate because the Uls in thi s part of the SRS are meant to be sketches-the de tailed Uls are specificd in Section 3- and, in any casc, they wcre liable to be c hanged a g reat deal ThIS helped Hal and Karen to show the sketches to Betty and the o thers, obtain feedback , and then specify the Uls exactly for the de tai led req ui re ments.
4. Following Up The SRS Sections I and 2 we re .·mailed to Betty. She realized that Hal and Karen had included o nl y twO o f the three lise cases, and the third use case describing moveme nt of the player's character was absent. Thi defect was logged with a high priority. Betty was surprised to see that the SRS did not reAect several is ue that she thought he had made clear were importa nt , and was humbled to see that the SR reflected ' requirements" that he had offhandedl me ntioned but now realized would be a waste of time. The latter IOciuded the ability of the player to change outfits while an engagement is progressing. She had numerous comme nt , mOSt of which Hal and Kanen responded to, and some of which were added to the list of defects, Hal e ·mailed the R cction I and 2 to the team to e nable the m to prepare for an inspection . Team leader Ed had learned about Arlan Howard , a market ing executive who wa very familiar With the video game industry The financial backers were willing to fund fun her requirements analysis at the customer I ~d, and Hal and Karen pre pared to mee t with How~rd The I~tt er wa. no t able to ~r.nr them more th. n half
STUDENT PROJECT GUIDE: REQUIREMENTS FOR THE ENCOUNTER CASE STUDY
-
thiS projcct II
Writ,,·up (results 01 insp"ction)
organization
norm
Preparation
I ntervi"w
Review
TIme spent (minuteS)
200 minutes
170 minutes
270 minutes
250 minutes
... TIm" sp"nt
250/ 890 = 28 %1120%
170/ 890 = 19%1123%
270/ 890 = 30%1127%
200/ 890 = 22 %112 9%
Quantity
TOIllI 14.8 hours
15 pages
procluced Productivity (= TIme! qldntity)
xlf·assessed
15/ 14.8 = 1.01 pgs/hrll 0 .9 5 9
5
9
2
quality
( 1-10) IXI
Process improvement
1.3 per pagel/ 1.0 I oer page Spend ~20% less rime • prepanng
Spread inter· • vIew time more evenly among people
Check mate · rial morc (hor· o ug hly priorto
Spend ±30% more time revIewing
inspection
F"lgUre 12.37 Example of postmortem data and analysis an hour since he was very busy. Karen developed a prioritized list of questions and topics and mailed them and the existing draft 01 SRS Chapters I and 2 to H oward . They planned to wrap up the high . level requiremenlS with Howard. The team also planned the process of developing the detailed requiremenrs .
5. Metrics and Postmortem for High-Level Requirements The high. level requirements were ubjected 10 an inspection by the enri re team and the defects were recorded. For the next weekly meeting, Hal and Karen sum mari zed the metrics as shown in Figure 12.37 . The team agreed on the postmortem ob ervatlons shown .
6. Preparing for Detailed Requirements Hal and Karen had completed their write · up 01 lhe hi g h .level reqUIrements, ba ed o n di cussion and Intervlcws with Betry Sims and Arlan Howard. Th ey used the IEEE standard, whose headings prompted them lor the nonfunctional requirements such as CUls, performance, and hardware platfol'lllS Now they had to Identify the manner In which they would organize the fun tiona I Detailed Require me nts. They antiCIpated haVing to revisit and update Ihe S R many tim es, coordi nating the de
R$, lhe deSig n, and the code.
313
314
CHAPTER 12 ANALVZING DETAILED REQUIREMENTS
11, y 11,; , dis lIs' cd orHa", z i n ~ ,he de,ail ed rC'1uorcmcn" by ,late< and a~ '''H'' , bJ,cd on the "at · "anSlllon d1J81-:lm de,c nbed "' ,he h'/lh .!cvc! requiremcn» Thl< or/oCallizatlon me thod would <-" nmt o( al.\t I,he .K,ions that a player would take, , uc h as hck,nl! an eX it hyperhnk o n an area , (o llowed by the effects o( th" a tI n They both agreed thai till wou ld be an undef\tandable organization, bu, dec ided that It would no t 'nce to the nnplemcn,ati on a, well as rhey wanted They began ,earch,ng (or other way' In whic h to rganize ,he detailed requiremcn,s. Hal wa- ,n (avor of organ lzi n!! the funct ional detailed reqlllre men ,s by use ase, especia ll y Since he wan ted to loll ow the Llnl ,ed Software Devciopment Process H e sa id ,hat , at tillSstage, the Video game could most cas d be thought of In terms of the srlth'9 up u~c cas.e, th e ,"OVfI19 lUHOIIg tlJt ga mt OfClU u~c case, and the MI9"9"'9 thtJortigll bflraclrr lise case . He point'cd out how co nvcnit:nl ll would be to use JUSt these three use cases as the to tal e"ent of rhe (unctiona l requirement . He was also ex Ited about the prospect o( perhaps being able ' 0 reuse these u e ca e, for specifying future games Karen agreed tha, the requirements would be qui te easy to understand if orga nized by use case , but she had several 01 jections. The first wa that some requirements would be pan of more lhan one use case. An example is what happe ns when an exit fro m a room is clicked . T hi s could be pan of a ll of the three use cases they had ide"tined, and so it would nOt be clear where to look lor i, Karen's ot her o bjection was the fact that mapping from the usc cases ' 0 the code would not be as clean a ,he orgaOlza,ion she had ,n mind. Finally, she pointed out that the organization was no t yet equipped to properly archive use cases for future reu e. Karen wanted to orga nize functional use cases by class, which , she aid, faCi litated traceabiliry (rom requirements to implementatio n. She wanted to pick ,hem ca refully enough to ensure that they would be used as part o( the design (and Implementation). Hal pointed out a disadvantage of thi approach · the fact that it (oFCed them to deCide very carl yon some o( the classes tha, they would u e II11mpie mentIOg the application . He was worried about the pOSSibility ,hat they ma y later c hange their minds about the selection . After further discussion , they deci ded that o rgani zi ng the detai!cd requircmenls by class had more benents lhan drawbacks, and they committed to this method . They decided ' 0 be very co nse rvative about class se lection , however.
7. Classifying the Detailed Requirements Hal and Karen firs t took each usc case, and identified what object o( what class In"iated the action and what object has the responsibi lity (or carrying out the action . This process prompted them to create andlor identify classes. They fou nd it necessary to ca ll Betty and Arlan several times to clarify use case steps they thought they had understood but really didn't. Hal listed the classes and objects mentioned in the usc cases. They then brainstormed , couring every aspect of Encounter they cou ld reasonable ima gi ne for additional po sible classcs. As a Rnal step in the class selection process, they dras'ically cut the list down to an essenl i. 1 few , but taking care to pre erve all of the clas es referred to in the use cases. The final list consisted o( Arra, E"COIIMI,rCharn I", En co"nlrrGam" En9a9"'I(>11 E"9a9rnomlDisplay , Con",elio"Hyprrl;"k , Forri9"CJ,ara clrr, Play,rCl,ara Irr, and PlayrrQ"alily Window. They now Rnalized the headings of the SRS in Section 3.2 ("SpeciRc requITements"). They collected the delailed requirements related to areas in Subsection 3.2.A, corresponding to th<' Area class. They ordered these subsectio ns alphabetically because they anticipated adding classes later. They sumllSed that if they were to have ordered topics by number (e.g., PlayrrCbara I" being 3.2. 14), then locating an individual rcqll1rement would have been more difficult, because the user of the SRS would have to search many of ,he 3.2.N subsections be(ore Rnding the one applicable. The next class being EncolonlrrArra 0" "relion , they numbered the next . ubsecl10n ' .2. EAC, and so on . W ithin each cla.ssiRcat·ion, they crea ted subsection$ for al/rib"I" , nltiti",].IM lionlll,ly, and n.... l$ .
8. Writing the Detailed Requirements Karen and Hal wrote Section 3. 1 on uscr interfaces by Riling in derail, On the sketches the had made forth. h.gh. level requirements, then aski ng Oelty, as well as the human factors dep.nment, to rev iew them. Know,"s that thiS would be the Anal document from which the<" were to be bUilt, the>' hod ,he Cll tomer .g"-'" on e"ery detoll
CASE STUDY: DelAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME
Thcy checked their interview notes with Betry and Arlan as to the properties ("attributes) of each classification (cia s). For ex~mplc , thcy asked what propenlcs we re required for the connections between cwo Encounter areas. (One property of such co nnec tio ns was "the first area" connected , and another was ' the second area.") For each class , they asked themselves what entities (instances of the class) were required for thc game . For exa mple, there would ha ve to be a dressi ng room arca and a courtyard arca They then asked what functionality the class had to possess . For exa mpl e, a functionality of each Encounter character is the ability to configure the values of it·s qualities (requirement 3.2.EC.3 .2). Finally, they listed all of the events that In tances of the class were req uired to rcspond to (fo r example , clicking on an exit from an area l. Onc aspect that di turbed them was the time reqUired for new va lues to take effect. They realized that this wa a key aspec t to the ga me, if no time were to e lapse , the playe r would si mpl y set the qualities pertaining to the current area to a maxi mum , and little skill would be required to play the ga me 11,e delay made the game interesting , but the problem was, h ow much delay should there be) 11,cy con ide red stati ng "to be decided" for the durat io n, but finally concluded that th is would no t help. They deCided to specify fo ur seconds, feelin g that changing this amount should be straightforwa rd . Karen was concerned about the iml'recision of some of the requirements, espeCially those co ncerning the manner in which qualiry poi nts shoul
9. Following Up: Metrics and postmortem on Detailed Requirements The requirements analysis team asked Be lty, Arlan, and Ihe res I of the team to Ins pect Ihe detaded requirements. They performed thIS inspeclion primarily agai nsllhe 11Igh -level reqUIreme nts by ensuring Ihat every part of Ihe high-level requiremen t were elaboraled upo n by delai led reqUire me nts. They also e mployed a c heckli Ilike the one described in Table 13.3 of Chapler 13. Several defecls were fo und, whi ch H al and Kare n recorded and repa"ed . The resu lts of thiS proces were Similar to Ihose de c ribed In Figure 12 37.
12,14 CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME Th,s seclion compleles the requirem e ntS sjJeclRca ·
3.1 Exte rn a l Interface Re qu iremen ts
tlon of the Encounter vid eo ga me in IEEE format.
3.1.1 User Interfaces 3, Detailed Requirements Note to the Student. The IEEE term u.ed in this hcadJllg IS ·speclfic" requirements We have substituted the te rm 'ck~lled" to be ~onslstenl with the lext
Section 2. 1.2 in the SR for the En ounlcr VIdeo lIame showed o nly ketc hes of u cr interfa In order 10 proVide product p
31 5
316
CHAPTEI! 12
ANALYZING DETAILED IlEQUIREMENTS
Note : Each part of Ihls Ilgure Is s pecifi ed - - - sepa rately In Section 3.
COURTYARD
living
dressing
room
room Elena
Current hfe
points: 56.38
(SelQU....... )
Value
1~'2i·1
16.18
Figure 12.38 Detailed requirement for Encounter courtyard GUI Source. Gtaptbcs reproduCed WIth pcrmlssK>n from Corel.
be given in this section. Since we are using the object style of specification in this case study, the details of each window arc packaged with their classes In Section 3.2.2 in the SRS. In any case, this section should explain the physical relation· ships among graphical elements (e.g ., cascading, tiled, superimposed).
same lIser interface is used to
ho w the statuS
of the player's c haracter. An interface of ty pe a above will alwa ys be present on the monitor. When called for by these requ irements, inte rfaces of type b o r c will be superimposed . This requirement i teSted in Software Test Docu · mentation (STD). < test reference goe here > .
3. 1.2 Hardware Interfaces Encounter takes place in areas. Figure 12.38 shows a tYPical screen shot of the courtyard area , with a player.contro lled character, a foreign charac · ter, and the results at an engagement. This interface
The hardware that Encounter (which is a software application) deals with
takes up the ent ire monitor scree n. Areas have
connections to adjacent areas, labeled by hyperlinks. Clicking o n one of these hyperlinks moves the player's character into the corresponding area. The entire sct of '"te rfaces is as follows : a. One user interface for each area, specified in Section 3.2AR below . b. A uscr interface for
None (I n a fUlur~ release, Encounter will be control· lable by a joystick.)
3.1.3 Software Interfaces Other software with which Encountler must '"tlerface: an enmplle would be a prin~r drwct None
CASE STUDY; DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME
(In a futu~ ~Iease , Encounter wtll be playable from IntergalactIC Internet Gaming Slle .)
3.1.4 communication Interfaces one (In a future release, Encounter shall Interface with the Internet via a modem with at lea t 56 Kb/s.)
referred to elsewhere in the project, could not be disrurbed. TI,e requirements would not be alphabetically ordered. As a ~sult, one would have to go through the requirements one by one to locate a particular one.
3.2.AR Areas
3.2 Detailed Requirements by Category The IEEE uses the heading "Classes/objects" for Section 3.2. Th,s assumes an audience that knows object orientation. It is necessary to untkrstand 00 to create this section but it is not necessary in ordeno read and understand it.
Since we ane classifying the detailed requirements by class, we first list the classes that we have (very carefullyl ) chosen . These are not all of the classes that will be used by the application merely the core classes pertainmg to the domain of the application , which arc adequate for organizing all of the requirements. In this case, for example, all of them are aspects of the Encounter video game.
Categories for the Encounter video game suffi cient for expres.ing the requirements arc Area, EncounterCharactcr, EncounterCame , Engagement, EngagementDisplay, ForeignCharactcr, PlayerChar. acter, and PlayerQualityWindo,,, .
The nunlbering "3.2.Area.N .N ... :' etc. u ed in Section 3.2 makes it easier for us to insert, remoye, and locate nequirements by organizing alphabetically the classes that contaIn them. ThInk in terms of hundreds of require · menls. If we were 10 number the classes usong -'3.2, 1 .. ""'3.2.2 . . ,If elc. , then in crting nh' classes would have to be done at the end of the I'$!, sincc exlslln8 numbenng, already ,o j
F,rst, we de cribe what the class (i .e., this classification of requirements) refers to.
An area IS a place viewab le on the monitor. All aCllvities of Encounter (I ncluding engagements) take place in areas. Rooms, gardens, and courtyard are examples of areas.
3.2.AR.1 Attributes of Areas Here we tell what properties each object (specific entity) of the class must possess.
3.2.AR.1.1 Area implemented)
Name (essential;
not yet
The statement above in parentheses indicatcs the priority and the sta tus of the requirement. Once the requirement is coded and tested, the statement "not yet implemented" is either deleted or changed to "implemented." "Essential" requ;rements are implemented first. Once a requirement has been designed for and Implemented, "essential" can be removed. This is one technique for tracking the state of the application and its relationship WIth this SRS. Another technique is to specify the iteration to whIch the requirement applies.
Every
n ounter area \yill have a lIfl1quc nJme
con"sting of I to 15 chara tcrs . Acceptable hara te" ,hall onSl
317
318
CHAPTER 12
ANALYZING DETAILED REQUIREM ENTS
TC~l plan
< Idcrcn
C 1'0 t(' ..,1
goe, he re >
E. l13ttnbute.type requirement map5 to a pairof get· and set· fun lions. TI,i. document suggests how ea h requirement can be hyperlinked to a lIllIt test in the Software Test Documentallon.
alternative would have becn to express these requirement a, (un lio ns: for example, "Encounter
3.2.AR.1 .2 Area Image (essentia l; not yet implemented) There ,h.1I be an image to display eac h Area object on th e enllre momtor. The image ,hall fill the enllre mo nitor
3.2.AR .2.1 Courtyard Area (essential; not yet implemented) There sha ll be an Area object with the name "courtya rd" requiring the quailtlcs stamina and strmgth . The preilmlna ry courtyard Image hown III Figure 12.39 IOcludt·s a map of nearby arca5 .
3.2.AR.1.3 Area·Specific Qual ities (essential; not yet implemented) O nly some game character quali"e shall be applicable in each area. The spec i~c qualities required for cach area are spcci~ed in Section
3.2.AR .2 .2 Dressing Room Area (essentia l; not yet implemented) There hall be an area With nam<.' "dressing room" requirin g no qualities. Its
preliminary image, shown in Figure 12 .40, include a map of ncarby areas.
3.2.AR.2 .
3.2.AR .2 Area Entities We designate specific area objects that muSI exist wi th in the appl ication. This section has been added to the IEEE standard. The
3 .2.AR .2.3 Dungeon Area (essential; not yet implemented) Th ere shall be an area with name "dungeon" reqllirin g the qualities stam ina and pa -
tience. Its preliminary image shown in Figure 1241 includes a map of nearby areas.
kitchen
COURTYARD dressing
living
room
room
--I I".-1
"*"11 ,
IGot
lEnd ....1
Figure 12.39 Encounter courtyard Image
"","""" 0"
'lQ fOOo" Doj~ I i)I'I
""'" fOOOItO
.....
CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUi'lTERVIDEO GAME
DRESSING ROOM
I
ID1ngflQn
...
IOktoIrt
eo..,...
'"
1'1\)
IOJIIi CUIoI:lfl
Figure 12.40 Encounter dressing
...., ...., 10'0Wl1
room image
E. J. Staude• ..IOhn \\Iiley & Sons. 2001
3.2.AR.2.4 Kitchen Area (essentia l; not yet implemented) There shall be an arca with name "kitchen" requi ring the quality concenrrati on. The preliminary kitchen image shown in Figure 12.42 Includes a map of nearby areas.
3 .2.AR.2.S Living Room Area (essential; not yet implemented) There shall be an area Wllh name "hv i ng room" rcquiri ng the quali ti es co ncen tra ti o n and
stam ina Its prelim inary image show n In Figure 1243 includes a map of nea rby area
DUNGEON
dressing room
stl!d v
'00''' IClUih
Figure 12.41 Encounter dungeon Image
319
320
CHAPreR 12 ANALYZ1NG OETA1LEO REQUIREMENTS
KITCHEN
...
I
GoUla...
I
ISelqt"~
lEnd gem. I
I'C«IWI
Courtyard
I
,-
Drou '''IQ
""""'~.
""'"
01.1 'IQ' t;II ,
""""
.oom
Figure 12.42 Encounter kitchen image Source COpyright, E. J Braude, John WHey & Sons, 200 1
3.2.AR.2.6 Study Area (essential; not yet implemented) There shall be an area with the nam e "study" requinng (he quality concentrati on. Its pre -
liminary image shown in Figure 12.44 includes a map of nearby areas.
3.2.AR.3 Area Functionality This is the required functionaliry that pertains specifically to areas. Every functional
LIVING ROOM
courtyard
study
.
('o ' ....
00 , ' ... 00.
Figure 12.43 Encounter Illiing room Image
7~
0 M
-
u PI '-. ..
- , 'I)
CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME
Living
room
STUDY
DUDgfOD
-
00
eo..n,..!
'0 1--
-
.....
Figure 12.44 Encounter study Image
capability of the application should belong to one of these sections.
No ne
3.2.AR.4 Events Pertaining to Areas
3.2.AR.4.3 Interrupting Engagements (optional; not yet implemented) Players are able to interrup t e ngagements on a rando m basis. On ave ra ge, the playe r ca n stop o ne of every te n e ngage· nlents by executing the proced ure to set qualities. The u er tries to inte rrupt an e ngageme nt by at · te mpting to set the pl ayer's qualities. If the ga me doe no t all o w th iS, no indi catio n is give n; th e ga me
proceeds as if the attc mpt had not been made. We separate the events that pertain to are as from the attributes, objects, and metho ds. An event is an action that occurs to the application and is instigated from outside of the application.
3.2.AR.4.1 Display on Entry of Player Character (essential; not yet implemented) Whe nevcr the player's main c hara te r e nte rs a n arca , that a rea and the characters in ,t ha ll be displayed on the mo nitor. fIlli ng the mo nito r.
3.2.AR.4.2 Handling Engagements (essential; not yet implemented) W he n a fore ,g n ga me character e nters an a rea conta ,n, ng the p layer', maon ch.aracter, or Vice versa, th ey engage co h o ther.
3.2 .AR.4.4 Pressing the Set qualities Button (essential; not yet implemented) W he n the user presses the S{I q,wlilirs bUllo n, a w,"dow for selling the va lues of qualities a ppears superimposed o n the area, provi ded th at the re is no fo reign c harac te r in th e arca. Sec 3.2.PQ fo r the speciHcat ion of th is wondow.
3.2.AR.4.S Pressing the End game Button (optional; not yet implemented) W hen the user presses the £ull g(Jmt butto n, the gil mc [c ml inalCS. No add itio nal scree ns a ppear.
The previous sentenct, an inverse require· me nt, was fe lt to be necessary because games o ftc n do display a summary o f • se slon.
321
322
CHAPTER 12 ANALYZING DETAILED REQUIREMENTS
3 .2.AR .4 .6 Pressing the Get status Button (opt ion al; not yet implemented) When the user prc" cs the Gti sla/us bUllo n, In engagement display willdow appears shoWIIl8 thc Statu< of thE player'> haracter before and aftcr the last cnllage menl.
Kitchen courtyard
living
room
DreSSing
room
Oungeon
Sludy
3.2 CH Connection Hyperlinks Between Areas Conne tlon h)'pe rllll ks arc hyperlinks placed at each arca eXit, show ing the Mea to whic h it I S connected
Key
I . """"""'"
Figure 12.45 Encounter area configuration reqUirement
3.2.CH .1 Attributes of Connections Hyperlinks 3.2.CH .1.1 Connection (essential; not yet implemented) Each connection hype rl ink corrcsponds to an area connect ion
3 .2.CH.2 Connection Hyperlink Entities (essential; not yet implemented) Thc re are two co nnectio n hyperl inks corresponding to each are. connection, one in each area of the co nnec ti o n.
3.2 .CH .3 Functionality of Connection Hyperlinks None 3.2.CH.4 Events pertaining to Connection Hyperlinks 3.2 .CH.4.1 User Clicks on a Connection Hyperlink The effect of clicki ng a connection hyperli nk is th.t th e player's character is displayed i n the area on the other si de of- the area connectio n.
3.2.CO Connections between Areas Characters travel from area to adjacent area by means of connections. Each of these connects two areas. Figure 12.45 shows the required connections among the areas. 3.2.CO.1 Attributes of connections between Areas 3 .2.CO.1.1 First and Second Areas (essential; not yet implemented) Each connection shall connect a pai r of areas, which we Will ca ll the "first" and "second" areas.
3.2.CO .2 Connec tion s Entities 3.2 .CO .2. 1 Dressing Room-<:ourtyard (essential; not yet implemented) The,. shall be a con necrion between the dreSSi ng room and the courtyard 3.2.CO.2.2 Dungeon-Study (essential ; not yet implemented) There shall be a connection betwee n the dungeon and the srudy. 3.2.CO .2 .3 Study-Living Room (essential; not yet implemented) T here shall be a connection between the study and the living room . 3.2.CO.2.4 Courtyard-Living Room (essential; not yet implemented) There sha ll be a connection between the courtyard and the living room. 3.2 .CO .2.S Dressing Room-Dungeon (essential ; not yet implemented) There shall be a connection between the dreSSing room and the dungeon 3.2.CO.2.6 Courtyard- Kitchen (essential; not yet implemented) There shall be a connection between the courtyard and the kitchen 3.2.CO .3 Functionality of Area Connections None 3.2.CO.4 Events pertaining to Area Connections 3.2.CO .4.1 Moving a Character throug h a Connection (essential; not ye t implemented) onneetlons are disp layed J< h perlink, .t the borders 01
CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME
areas whenever the player's charactcr i in thc area . When the user cI.ck such a hypcrlink, the linked .re. is displayed with thc character in this area.
Elena
Cunenllile points: 56.68
3.2.EC Encounter Characters
Value 16.18
3.2.EC.1 Attributes of Encounter Characters 3.2.EC.1.1 Names of Encounter Characters (essential; not yet implemented) Every game character in the Encounter video game shall have a unique name . The speciRca ti o~s for names shall be the same as those for Area names, speCified in 3.2. AR.I. 3.2.EC.1 .2 Qualities of Encounter Characters (essential; not yet implemented) Every gome character has the same set of qualities. Each quality sha ll be a nonnegative floating po.nt number wit h at least one decimal of precision. These arc all init.al · ized equally so that the sum of their values is 100. The value of a quaiory ca nnot be both greater than 0 and less than 0.5. For the first release the qualities shall be concen· tration, intelligence, patience, stamina, and strength. 3.2.EC.1 .2 Image of Encounter Characters (essential; not yet implemented) Every game character shaH have an image.
Palience
Figure 12.46 Required user Interface for status SOU/ceoCraphlcs reproduced with permiSSJon from COre(
equal to the sum of the quality values. The values of the remainin g qualities are automatica lly adjusted 0 as to maintain their mutual proportions, except (or
resultin g quant ities less than one, wh.ch are replaced by quality values of zero
3.2.ED Engagement Displays (essential; not yet implemented) There shall be a window displaying the re ult of engage ments. The format IS shown .n Fib",re 12.46 . 3.2.ED.4 Engagement Display Events 3.2.ED.4.1 Dismissing the Display (essentia l; not yet implemented) When the user hits OK, the display disappears.
3.2.EG The Encounter Game 3.2.EC.2 Encounter Character Entities The characters of the game arc described among the types of Encounter characters. 3.2.EC.3 Functionality of Encounter Characters 3.2.EC.3.1 Living points (essential; not yet implemented) The Encounter game shall be able to produce the sum of the va lues of any charac· tds qualities, ca lled its livinS pointS. 3.2.EC.3.2 Configurability of Encounter Character Quality Values (essential; not yet implemented) Whenever an Encou nter character .s alone in an area, the value of any of .t qu.iotlCs m.ay be set The va lue chosen mu' t he le<> than or
The requirements in thi s secti o n penaln to the ga me
as a whol e. 3.2.EG .1 Attributes of the Encounter Game 3.2.EG .1.1 Duration (optional; not yet implemented) A record shall be kept of the durat.on of tach game, timed from when the playcrbegi ns the game. 3.2.EG.2 Entities of the Encounter Game 3.2.EG.2.1 Single Game (essential; not yet implemented) There shall be a .ngle s,me Future rdea es will allow several ver<.ons of the game to run at the same t.me
323
324
CHAPTER 12
ANALYZING DETAILED REQUIREM NTS
3.2.EN Engagements All c nfotJ ~(" m 'nl
h3"Ct r hJra ter
h Ih(' II1l cra<.tion between J p:a nlC o ntrollcd by the rla yer and , fo rc.w.
3 .2.EN.1 Attributes of Engagements 3 .2 .EN .2 Engagement Entities pemlancnt cng"semcn l
To take .. nU111e n al exam pl of a n cngllg ment in tim area If the pl. ye r\ ,tam.na w.lue " 7 and ConCe f1lra110n value" 19. and Fredd . - the fnr ' I!ncr'~
No ne
There arc no
Playe r, , tanllna 7 + I 112 = 12 .5 ; co nce ntrat.o n 19 + (0.6 )/2 ~ 19 3[0 ]
ent iti es .
1 1/ 2 = 5.5; co ncentral10n 0 because (06)/2 .5 less Ihan 0.5
3 .2 .EN .3 Functionality of Engagements 3 .2.EN .3.1 Engaging a Foreign Character (essential; not yet implemented)
This particular requireml'nt is mathematical in nature and so Ihere is no attempt to replace the mathematics with natural language, which would risk compromising it~ precision . The use of natural language to explain the mathematics is a good practice, however.
3.2.FC Foreign Characters A fo reig n charac ter .s an Encounter characler not under the players control 3.2.FC.1 Attributes of Foreign Characters Sec Encounter character requirements. These are initial ~
ized to be equal.
In future releases, foreign characters may mu When an engagement takes place, the "slro nger of the two c haracters is the o ne whose values of area_reciAc qual ities sum to the greater amount. The system transfers half the values of each area -speCIfic quality of the weaker to the stronger No transfer of points takes place
if
neither character is stronger.
If ei ther c haracler has no poi nts after the value reallocations arc made, the game ends. If the game docs nOI e nd, Ihe player's c haracler is moved to a rando m area and the results of the engagemenl arc d.splayed . As an example of the value reallocalions, suppose that the player engages a fore ign character in an area preferring stamina and concentration . If p~ is the value
of the player's stamina , and assuming p, + p~
> J. + fe.
tate into new forms.
3 .2 .FC.2 Foreign Character Entities
This section tells that there is only one foreign character.
3 .2 .FC.2 .1 Freddie Foreign Character (essential; not yet implemented) Therc shall be a forc.gn character named "Freddie: who e image IS shown in Figure 1247. Th.s character shall i01lially have a total of 100 POlOts that arc d1
we would have p: =p. + i/ 2, P: =P. + i/ 2.1: = i/ 2, andi: = i) 2.
3 .2 .FC.3 Functionality of Foreign Characters
The reader will recognize th. delect in the last equation, which should be = // 2. We will leave the defeci Inlact as an example.
i:
3 .2.FC .3.1 Foreign Character Movement (essential; not yet implemented) A long as It is alive, a forc.g n character should move from area to adjacent Mea '" rand om interval'\ J,vt:ragins t~·o seconds. After being present in an area for J rando m
CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME
/' ,. ,I
,!
called the "main" character. The nature of this con· trol is subject to the restrictions peclned in the remaining requirements. ThIS character shal l initially have a lotal of 100 POints that are dislnbuted equa lly among its quailtie 3.2.PC .2.2 Additional Characters under the Control of the Player (optional; not yet implemented) The player shall be able to introduce characters other than the main cha racter that the player con trols. Detads are to be decided 3.2.PC .3 Player Character Functionality 3.2.PC.3 .1 Configurability of the Player Character Quality Values (essential; not yet implemented) Whenever all fortlgn players are absent from the a·rea containIng th e player'" main character,
the player may set the value of any quality of the main character uSing the Player Quality Window shown In Figure 12.49 The value chosen must be less than or equal to the sum of the qua lity va lue Th e values of th e remaining qualities are automat i-
ca lly adjusted
0
as to maintain their mutual propor·
tions , except for resulting quantities It:ss than 05 ,
Figure 12.47 Foreign character Freddie image requirement SOUrce Grapnlcs reproduceo with peofmlSSlQn from corel.
amount of time averaging o ne seco nd , all of the character's life pOint are divided among the quail ties relevant to the area , such Ihat the va lues of each quality arc as close to equa l as po Sib le
3.2.PC Player Characters These are Encounter characters under Ihe conrrol of the play("!" 3.2.PC.1 Attributes of Player Characters ee EncOUnter characLCr aunbutts Player character Im age Un be sdected from one of the Images in Figure 1248
wh ich arc replaced by quailty value of zero 3.2.PC.3.2 ConfigurabiJity of the Player Char· acter Images (desirable; not yet imple· mented) The 1>layer shall have the option to choose the image represenllng hiS or her maio charac ter fro m at least two Images These o ptions
are shown
III
Figure 11 48 .
3.2.PC.3.3 Aging of the Player Character 1m· ages (optional; not yet implemented) The main player character hall automatica lly IIlcrcase each quality b), a percentage for the Irst half of hi or her hfe, then decrease each qua llt)' by the same percent · age for the second half Delails arc to be deCided
3.2.PQ The Player Quality Window Thl ...
I
a Window from ,,,h leh the pl ay er
Ill')
JlloCJtt"
3.2.PC .2 Player Character Entities
the va lue< of hI> or her h,racte"
3.2.PC.2. 1 Player' s Main Character The playt'r shall have (.ontr,,1 over a parll lIlar U3me (. haracttr
3.2.PQ.1 Attributes of the Player Quality window The wlndnw for ,ett"'~ the qllahtlC> 01
325
326
CHAPTER 12 ANALYZING 0[1 AILED REQUIREMENTS
•
Elena
Boris
Sean
Figure 12.48 Player character image options Source' GraphiCS rcoroduCed wlttl permISSIon from COrel
a player ch>r.cter In Encounter is shown by means of • typical example in Figure 12.49. The g.me charac· ler icon appears In the center, and Its name appears at the left top of the screen. The character's life poi nts .ppt.r in the center. On the left center is a li st box
displayi ng four of the qualities at a time . Cltck.,ng on one of these qualities allows the player to sdect a va lue for It in the text box o n the right. An explan · ation of how the arlthmelic
IS
performed
Choose the quality _ _
Image
you wish 10 set
Choose Ihe value 01 _-, the quality selected 16.3
Explanation
"r"'he valuos of the~quC:a:-:,n;:;io~s~n~o:-:t-:sp=ec~lfi;;:ca:::;;lIy7c:;h::o::s=en~r.::m~a:-;in""'ln-:t::-h.-:-sa-m-e-- proportJon to each other. Values less than 1.0 are counted as zero. E.g.,
be(Qf9: Slrenglh = 10.0 . endurance = 60.0 . intelligence = 30 ,0 . pallance = 0 0 (curront hfe poInts 100 + 60.0 ... 30.0 + 0 = 100 0) change: strength trom 10.0 to 20.0 after;
strength
.c
20, endurance == 53.33, intelligence
Figure 12,49 User Interface required GUI for setting quality values
sour"
GraphlCl reprOduCed wllJ'I pe.,nlssb'l Irom Corel
shown
10
a pale yellow box in the lower part of the screen
Currenllile points; 100.0
Shawn
IS
:r
26.66
CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME
Color backgrounds for the name, life points, and value boxes are to be pale turquoise. 3.2.PQ .2 Player Quality Window Entity 3.2.PQ.2.1 Window for Allocating Qualities (essential; not yet implemented) A window hall be avai lable under the conditIOns de cribed above to all ocate the value of the player character. The willdow 'hall have the appea rance of the C UI hown in SectIon 3. 1. 1 2 of this specificatIon. 3.2.PQ.3 Player Quality Functionality 3.2.PQ.3.1 Initiating the Display (essential; not yet implemented) The player quality menu shall be able to display it elf. 3.2.PQ.4 Player Quality Window Events 3.2.PQ .4.1 Displaying the Value of a Quality (essential; not yet implemented) When the player clicks on a quality in the li st box on the left. the value of that quality sha ll be disp layed in the text box on the right. 3.2.PQ.4.2 Setting the Value of a Quality (essential; not yet implemented) When the user enters a legitimate value for a quality and hIts the -enter" button, the value of that qua li ty is set to the amount entered. If the value is invalid, an error window shall appear stating "invalid value: try again ." 3.2.PQ.4 .3 Dismissing the Window (essential; not yet implemented) When the user hits the OK button , a time of four seconds elapse , after which the window disappea r . At th e end of this time period (i .e., if there arc nO interruptIons) the va lue allOCations are made .
3 .3 Performance Requirements Pcrfom,ance reqUIrements include required speeds andlor tIme to complete. Unless docu · mented in a different section of the SRS, they may also include memory usage (RAM andlor disk), noted either statically or dynamically (i.e., memory required at runtime). TI,e applicatIon shall load and di play the Initial image In less than a minute.
Engageme nts shou ld execute III less than one second. TI,ese requirements are te ted In STD < refe r· ence to lest goes here >. 3 .4 Design Constraints This section speCifics restnctions on design . If there is no material in [his section , designers
are free to create any (good) desig n that satisnes the requirements. For example, we can add the design constraint "one·story" to the fo ll owi ng: "A house with four bedrooms. all of which are less than a thirtY·second walk from the fami ly room ."
Encounter shall be desi gned using UML and objec t·ori ented design It shall be implemented in Java . The software shall run a a Java application on Window 95. lt shall be designed a way that makes it relatively easy to chan ge the n.tles under whIch the
tI'
game operates so that o r-hers can customize the game.
3.5 Software System Attributes
3.5. 1 Reliability 3.2.PQ.4.4 Interruption (essentia l; not yet implemented) Upo n Interruption of the dl play of the quality value window, the window van l hes Note that interruption s , hall be aused by a forei~n character entering the arca . Note also in thi s case that the qualtty value are not hanged and th at an engagement takes place.
Encounter shall fatl not more than o nce III every 1,000 encounter< T est documentatio n < reference to te t goe here > 3.5.2 Availability En ou nter hall be ava tl able for play on an I n.tn ni nR \'(11ndows 95 onI (i.e ., no ot her appl icOl lo n
327
328
CHAPTER 12 ANALYZING DETAILED REQUIREMENTS
'Im U h;)" CO ll~l y ) , T COr"t dOCUmClllt'lli On
rderence to
4,
supporting Information
te,t goe, he re >. NOlie
3.5.3 Security
4.1 Table of Contents and Index N o t Inclueled
Future release will allow access to saved ga",es only with a password .
4.2 Appendixes Not 1I1c1uded
3,5,4 Maintainability Appendices may Include
3.5.4.1 Changing (essential)
Characters and Areas It
characters and areas.
3.5.4.2 Globally Altering Styles (desirable) It
(a ) Sample VO formats, deSCflp110nS of COSt analysis stud ies, or results of user surveys (b) Supporting or background Informa-
tion that ca n help the readers of the
shall be straI ghtforwa rd to globally alter the style of the areas and connectIOns (Style changes reAect dif, ferent levels of game play in the same environment. )
SRS (c ) A description of the problem to be
3.5.4.3 Altering Rules of Engagement (oP-
solved by the software (d ) Special packaging instructions for
tional) Rules of engagement should be relativel y easy to c hange. 3.6 Other Requirements
the code and the media to meet security, export, initial loading, or other requirements State explicitly whether or not each appendix is to be an official part of the SRS .
None
12.1S SUMMARY Detailed requirements ("developer" or "detailed" rcquirements) arc written primarily with designers and developers in mind. They are created from hi g h · level req uirements, as well as from conti nued customer Interac tio n . Detaded requirements must be testable, traceable , and consiste nt. Since they become numerous they must be classified systematically. There are severa l ways to orga nize de tailed requirements including b featu re , use case , CUI , state , and domain class. Agile projects tend not to create documents separate from the code and tests with detailed requirements Detailed req uirements must be traceable to the desi g n and implementation that realize them and to the tests that vahdate them. Without a clean trace from each reqUIrement through the design of the appli atlon to the actual code that Implements it, it is very difficult to en ure that such an app(,catlon remains in compliance with the requirements When the requirements change, which i safe to a sume, this become< even more difficult. Detailed requirements must also be traceable in the o ther direction , to the 11Igh-level reqUIrements they arc derived from , fa ensure that all arc fully specified. Since it is difficult to Implement all desi red functi o nality, requ irement are often prionllzed . Jtegones such as ",roliol, d"irablt . and opilo""1 are used to deSl gn.:e pnOrities. OrganizatI o n, ommit to dd,vc ring essential functionality, and if there is time they Implement desirable and then o ptional feJtu,,:
EXERCISES
Once detailed "'qulrements have been collec ted, the project documents are updated to reAect the improved project knowledge . For example, schedules are updated with more accurate dates and risks arc ,..,tired and more info rmation is learned.
12.16 EXERCISES I. To what audience arc detailed requirements primaril y targeted, 2. Name five wa ys of o rganizing derailed requirements. 3. What is wro ng wirh rhe fo llo wing Derail ed requirement , Ex pl aIn how you wo uld fi x them. a. HomtBudgtf shall di splay a co nve nient interface fo r entering personal data. b. SalCoHlro' shall compute the predicted tim e it takes to c ircl e the Earth o n the current orbit, and the actual time taken to circle the Earth o n the previous orbit. c. /II v<sIKin9 shall determine the best investment stra tegy . 4. What are three advantages and three disadva ntages of o rgani zing delailed req uirements by class rather than by feature, 5. Suppose that you are definin g the requirem ents fo r an applicatio n that simulates the movement of customers in a bank. list fi ve classe, that can be used to o rganize the req uire ments. 6. Provide detailed requirements fo r each class identi fie d in Exe rcise 3 by describong o ne attribu te and one function corresponding to each class. 7. When identifyin g do main classes (as in Fi gure i 2.8), wh y is it usefu l to denote the rel atI o nship between them (i.e., inheritance, aggregatio n), 8. Applying the principle of goo d screen desig n outl ined in Step 3 of Section 12.3 sketch good C UI screens fo r a ho me finan ce applicatio n that , a. displays a summary of a user's fi nanc ial ho ldings, o rganized by ty pe of ho ld,ng, and b. allows a user to input rhe details fo r a new ho ldi ng . r I'sted 'In Exerc ise 6 , assign a priority (e .g., essential , desi rable, I 9. For cac h d etal'1e d requorcmen o ptional ) and explain wh y you chose th em. · '1ar t 0 F'19u re 12.27 Ihat spccines test input and output fo r o ne o f the attribute 10. C reate a c h art SImI identified in Exercise 6.
IEAM EXERCISE
SRS . If YOll are u In s an iterative , t h e SRS fo r your a p pl 'lca rio n · Use o r mod ify the IEEE W rotc .standard " apprQac h , try to .In d 'Ica te what requirement< arc to be Impl emented In each itera tIo n.
329
330
CHAPTER 12 ANALYZING DETAILED REQUIR EMENTS
Tra k the t me SpCIlI o n thi' by individuals a nd by the "roup Hrcak thl ~ tIme Into appro prtate o tl vi ties Measu re the effec tivene, o f you r effort. (Feci free to develop yo ur o wn mctrics, sec also tea m exercises III previou< c hapters ,) Indi ate ho w the pro CS5 yo u u
( I ) Degree of clarity
(2) Exte nt to which the plan includes all relevant del'ai ls and excl ude, irrelevan t materia l (3) EffectIveness o f your <elf· measurement and process imp roveme nt descrtption
BIBLIOGRAPHY I Booch. C r.:ady . "Ob} ,-Qnt'll lcd APlIII)'lls (mJ Dwgtl Ull ih ApplicaIlOrtJ,"Add lso n. Wc",lcy , 1994 1 Jordan, R. hard, Ruth Smllan, .lnd Alex Wilkinso n, -Sut'am IIll1n8 the: Project Cycle with O bJect-Onc nted ReqUIrements,· OOPSLA Co"JruPlcr PfOCttil'"9s ( 1994), pp. 287-300. 3 Cahtz, W , "The ES).t'rl hul Glmle 10 Uw Irt,nfaa Df1j9" At! '"'rOdUf flon 10 CLiI PnrtnplN arlll Tcconufuf1," John Wiley Sons, 1996
uality and Metrics
Planning
The Software Development Lile Cycle
Requlr.II,ents .RIIIy'"
•
What is meant by the accessibility 01 requirements?
•
Comprehensiveness?
•
Understandability?
•
How do you assess the degree of ambiguity of requirements?
•
Consistency?
•
Prioritization?
•
What is meant by the degree of security in requirements?
•
In what sense can requ irements be complete?
•
Teslable?
•
Traceable?
•
What melrics are suitable for these qualities?
Figure 13.1 The context and learning goals for this chapter
This chapter deSCribes measures of q uality In requirements expresses what the customer wantS and needs, the h ighe r Its quality less Important than the "bl!! pic ture ," but a misSing requirements numerous case studlcs show Recall , fo r example, th ove rlooked COnversion that dispatched a $ 125 million spa ecraft to obli Vio n
The \Vle u de tail de ta il
mo re a requireme nts docume nt uall y think of de tails as being far ca n se n ously affect projects , a o f metnc-to- no nme tnc dl>tance
332
f tAPTER 13
Hm
QUALITY AND M ETRICS IN REQUIREM ENTS ANAL VSIS
a ccssible I ~ ca h rcqum.~ rn c nl '
•
· · .. · · •
•
o mprc he nslve I, the SR ) unders tandable I> caLh req Ui rement ) unambiguous IS each reqUIrem en t? onsistent "the R ) effec ti vely prioritized arc the reqUirem e nl<) secure IS the requirement' self·co mplete IS the SR ) testable is each req uirement ( traceable
I S ell
h requirement ]
Figure 13.2 Attributes of requirements analysis that promote Quality
To he lp e nsure that the requ irem e nts are indeed covered, we foclls on qual ll Ie, that requirem ent< should po oss They sho uld be complete and consiste nt; eac h one should be capab le of being traced through to the design and impl eme ntatio n , tested for valid,ty, and implemented accord,ng to a rational pri omy, Figure 132 Iosts these attribu tes and tells what we sho uld look for in good requireme nts. We can systematically revIew and inspect req uire ments based o n thi s li st . For example , a set of co nsistent requi rements is fa r more Iokel y to express wha t stakeho lders want and need than a se t with contradic tions. Th is c hapter disc usses ho w each of these qualities ca n be mea.sllred . "Targe t va lues" refers to the numerical goa ls set in the project relative to various metrics. Metrics are most useful when their target values arc pecihed i. advancr. For exampl e , we could state in advance that , based o n experie nce o n past projects, requirement will be considered ' complete" whco the rate of modinca tio n and addition is less than t percent per week. Projects are greatl y improved when the QA organization is Involved in rhe requirements a nalySIS stage. In particular, QA ve rifies that the intended development process is being execu ted in accordance with plans QA sho uld participate in inspec ti o ns o f requirements docume nts. They tend to have a healthy perspective bec ause they lInderstand rhat they will ha ve (0 validare the product based on the requirements. In poorly o rganized projects, QA may be handed an appl ication with little or no req uire ment documentation and asked to test it Th is begs the question , "what is the application supposed to do)"
13.1 QUALITY OF REQUIREMENTS FOR AGILE PROJECTS Before d,scussi ng the attributes of req uireme nts analysis qualoty lIS ted above, let us discuss the quality of reqUirements for agile processes. Th e primary process for requirements here consists of el iciting user stories
from th e customer, along with acceptance te ts, and then subjecti ng the imp le mentatIon to th ose te t upon completion. In addition , the custo m.er must feel satisRed with the result. Thi s mayo r may no t be supported b significant documentatI o n. Quality has to be assessed , if not measured acco rdon g to th is sta ndard. Th,s entaIl computing the fraction of acceptance te sts passed and making an assessme nt of th e custo mer' rcaclIon. possible via a que stionnaire . Si nce the customer-usually in the foml of a team member rcpre entatlVC' ISo part of the developme nt effort, requirements assessment include the performance of the customer Given the nature of req uireme nts analysis, this is all to the good .
13,2 ACCESSIBILITY OF REQUIREMENTS To deal with a set of req ui rements, we should be ab le to access the o nes we want, when we want them ThIS IS til.
COMPREHENSIVENESS OF
• Ea" of getting
REQUIREME~S
to statement of detailcd requirements .
• Metric: 0, tX'III.tly /o,,!/ aotrag, access Ii",' (compand ",ilb Ih, orga Hizalion, Horm) to: aOtfagc acctss rime as fasf as Ca H be rxptC'tJ
flCUre 13.3 The accessibility of requirements
We do this by num bering them in same way . A good numbering system allows uS to kn ow whe the r the requireme nt has bee n imp le mented , for example, and to trace it to the code that actually carries it out. A projcct's requirements change continually throughout itS life cycle. For example, when a programmer tries without success to implement a requirement and explains this to the customer, the latter freq ue ntl y Rnds mi sing pam in the requirement . The SRS must then be accessed to ascertain whether these mi sing requirements were present, and included if they were not. Taking an example from the video store case study, the CUSfOmer (i n this case, the video store) may question why a DVD's play time does not appear o n the mo nitor. The developers and the customer will want to know whet her this wasspecified in the SRS. Where in that docume nt should they look to determinc this7 Rummaging through poorly organized documents is time ·co nsuming and therefore expensive . H cre is a c hecklist for improving the accessibility of requirements: • Do you know where the h igh -level requirements arc stated7 • Do you know w here t he detailed requirements are lis ted? • Arc the detailed requirements o rganized in groups, preferably with each gTOUp correspondin g level requirement7
[0
a hi gh -
• Are all of the detailed require ments orga nized infO a list, o r a clearly understood Ii t of list 7 • Can you look up requirements by keyword7 By subject matteO By use case7 By G UI ? By uscr type7 • Can you look up requirements by other cri teria relevant to the particular app licatio n o r pfOJec t7 One accessibility metric is the avtragt time ,aken '0 access (J dtta il('d mtuim11M1t. To measure {hi . a sampJt: would be taken of exi ting and missi ng requirem e nts, and severa l people would be timed fi nding these or ascertaining that they are absent. Statistica ll y speaking , 150 is a good sa mple size . Smaller sample sizes are unreliable but are probably better than nothi ng . In selecting a sample , one uses a process that is as rand o m as time allows. For example, o ne could ask eac h of a group of people fa miliar with the pro posed appli catio n to contribute ten potential detai led requ ireme nts, then pick at random fro m the combined hst to obtain samples
to seek. AcceSSibili ty IS summarized in Figure 13.3.
13.3 COMPREHENSIVENESS OF REQUIREMENTS A quality SRS e xpresses all of the require ments fo r a produc t. By co",p"hrns,.""",, we mean the exte nt to ",h i h the customer's wants and needs arc included. An appropriate metric would thus be pcrccIJI"9c oj Ihc cli slomc,S rcq.irrmtllis aPPtJlriHg iHIb, SRS. An o bvio us way to e nsure thi S i to have the ustOl1lcrvalidate it , but th i i not a simple matte r, as the poi nt in Figure 13.4 sugges t. The comprehe nsiveness of requi rements fo rms an elusive and vague goal , and ye t the co",pl e~enc<~ of requirements is key to the successful o mplc tion of a pro lcct and the Ira king of progrc ' Each Itcra tlo n
333
334
CHAPTER 13
QUALITY AND METRICS IN REQUIREMeNTS ANALYSIS
• Not cnotl ~ h resources LO ~a t isf cvC".'ry c.. u\lumer wl.; h • Prlonll zc '0 Ihal cOl11prehenslve within each bat h of reqUirement, • ustolllcr can ttlwon't read en tire RS • I\bkc R J< to lollow • U sc a ,tandard • "Read" SR to custo mer • limitations of self.inspectlons • lIbject to peer Inspe ti o n • Con tradictory s takeholder requirements need to be s. ,isfted • Apply diplomatic kills and expec t compronll<e
Figure 13.4 Issues in attaining comprehensive requirements
make the requirement mo re comprehensive. One way to deal with the evolVing set of require ments is to Include requirements of h,turc iterations and of all priorities In measuring comp leteness. An example IS s hown In Table 13. 1. Thi s perspective helps us to assess how close our plans arc to sa tisfyi ng the customer's wants and needs. A mo re tractable measure is stij.compl","tSS, in which the requ irements contain all materials th at its partS reference. However, this is somewhat different , and is discussed bel ow. Here is a checkltst for improving the comp rehensive ness of requirements: • Summarize, or give a very short preliminary description of needed requirements that have not been
included yet. • Is the customer satisfied that the requirement' reAect all of his or her needs and wishes • What fraction of the listed requirements are slated for implementation in the current release releases )
Future
Figure 13.5 shows two useh, I comprehensiveness metrics . The IEEE define a rather complex measure of completeness in 982 2· 1988 A3S. 1. This is a fonnul. involving 18 observed quantities (e.g ., "number of condition optio~s without processing") and 10 weights (e .g., the relat ive importance of "defined functions used") . It measures the degree to which there are loose ends within a set of detailed requirements.
Table 13.1 Including future requirements Requirement NO.
1780 781
782
Priortty
~
Every DVD record shall contain the title. up to 60 alphanumeric characters
2
3
Every customer record shall include the customer's credit card number, consisting of 16 digits.
1
2
Description
,
..
UNAMBIGUITY OF REQUIREMENTS
Lrt T = total numb~r of documented derailed r~quir~ments (all priorities, all iteration )
ME [RIC: %
Requir~ments ;mpl em~nted
=
100 .. [no. of requirements Implemented]
T
METRIC: %
R~quirements Curr
*
100 [( no. of requirements implemented)+ (no. of top priority reqUIrements in current iteration )]
T Ftgure 13.5 lWo useful comprehensiveness metrics
13.4 UNDERSTANDABILITY OF REQUIREMENTS Understandabi lity appears to be a hi g hl y subjective qua lity because it depends o n peoples' o pIni o n. However, it can be measured . For example, a random set of people from an appropriate population can be asked to express on a form their opinio n 01 a requirements docum ent Table 13.2 is an example of an opinion form-in this case applied to a u or interface . Here is a c hecklist fo r imp roving the compreh en · siveness of requirement s.
• Are the requirements written in language that its ty pical reader would understand7 • Do they use the vocabulary of the cl ient problem domain 7 • Do the requirements describe only external behavi o r-that is, as seen from the user's POlOt of view l ("U ser" can include external sys tems rather than just people .) • Do the requirements avoid stating ',010 the problem is to be solved, what tec hniques are to be used, o r ho'" the application is to be designed7 (The except io ns to this are when such peCl fica tio n are indeed req uited up front .)
13.5 UNAMBIGUITY OF REQUIREMENTS Unless a derailed require m e nt is written cl earl y and unambig uo usl y , we wo,,'t be able to detcmllnc whether It has been properly implemented . Figure 13.6 illustrate an e xa mple of an ambiguous requ lte ment , fo llowed by an Improved version . The o ri ginal requirement seems to allow the player to c hange the qualitIes 01 a ga me character at any time durin g the game This would take the hlO o ut of the ga me , because the player would simply set quality va lues to their larges t possi ble re levant values and there wo uld 1><: little room for tryIng •
various strategics_ Here is a ch eckl iSt fo r improving the no nambi guity of rcqL1lremcntS
• For each reqUIreme nt, IS there o nl y o ne way that
0
ty pica l reader would IOterpre t "
• Fo r each requ irem e nt , arc terms aVOIded that could be underswod
10
mo re than o ne way7
F,gure 13.7 shows a me tric for ambi g uity that de pe nds o n a trioge meas ureme nt deCIde whether the d.:talled reqUIrement ha e xac tl y o ne clear meo ning (score of 2 ), o r mony mca n1l1gs ( corc 0 ), o the " vl
335
336
CHAPTtR 13 QUAUTY AND METRICS IN REQUIREMENTS ANALYSIS
TIlt ~lu rr ",m "(lilt lilt. qurr/lll N of Ell OUl.ltr d)arntl(~
X At
tim e) Prol>,bl
nut. W ould have to te,t under , 11 IrcumStJIl CS, mJny nOt intended , incurnng unn c:tessary ex pense and produ Ing a wrong re,ult all
Better vers ion .
Wb",w" all /orei911 playm Olll(1j'II"19
rh( play,,)
cballg, Ib, q"al,ly
ItWit I
are
ab,,"1 fro", II" arM
Iwrt,
"til,,,, 0/ 'h"
lu, flu
pfaYfr may
ham ''', kuPlll9 Ih,
s'Wn tolal oj 11)( qUf,lily vailllS Iwd){ltIgtd n Jr Playe rQualityWindow , ( " 5«11011 tbd ) is
""d
for Ihis purpo". Chall9" Ink, ,//rel /o14r "collds afl" II" "OK" b,,/loll is press"l. Figure 13.6 An example of ambiguity ,n requ irements
A metric (range: 0 to I 00) 100. 2:: lunambiguity 01 each detailed requirement (0- 2))
2.lnumber 01 detailed ,.quirement.)
o=
could have man y meanings, 2 = clearl y cne meaning
Figure 13.7 A metric for unambiguity
13.6 CONSISTENCY OF REQUIREMENTS A set 01 detailed requirements is cOIISllI",1 if there arc no contradictions among them . As the number of detailed require ments grows, inconsistency tends to become difRcult to detect. Inconsistency is illustrated by the three requirements in Figure 13.8.
Requirement 14. Oilly basic food slapl« sball b,
carri,d by gam, char.elm •
• •
•••
Requirement 223 . f",ry 9am, charael" shall carry wdlu.
. . .,. Requirement 497. Flour, bull". mill!. and sali shall b, co.sid",d ,''' only basic food slapl«.
Fl&Ure 13.'
Example Of Inconsistency In reqoirements
PRIORITlZAnON OF REQUIREMENTS
Means: No contradiction , in whole or in part Example: .,
...
..... The DVD
~
classificatlon order shall be the order of preference of the customer. ...
OVOS shall be classified alphabetically as drama.
comedy, ho"or .....
Metric: Percentage of contradicted requirements Figure 13.9 Consistency in requirements
The object·oriented style of organization of requirements helps to avoid inconsislenCle by classifying detailed requirements by class and by decomposing the m in,o a si mpl e form This IS not a guarantee of consistency, however, and so requirement inspections include a c heck for consi ,ency. H ere I a checkli , for improving the consistency of requirements, • For each requ iremen" are there olher requirements that could lea d
'0 co ntradicting or annulhng i,)
• For each requirement , are there other requ irements that arc very similar and so can reate Inconsislencles?
• Does each requirement avoid a chair. of conseque nces tha, ca n', be readily fo ll owed )
A consistency metric is Ih, prrc,"lag, oj d,lail,d rrq llir",,,,lIs partly or wholly cOlllmd,clcd r/5<whrrr. T o ob,ai n such a metric, one would consider a sample of de ,ailed requirements - I 50 would be appropria,e-and investiga,e each one in tum determine whether i, is co ntradicted elsewhere in ,he document.lllis en,ad, comparing" to all of the remaining detailed requirements . Figure 13.9 prOVides ano,her example. This measure is imperfect because it accounts on ly for pairs of Inco nSIS tent reqUIrements A Figure I 8
'0
illustrates, inconsistency can fesult (-rom a se t
of requirements
13.7 PRIORITIZATION OF REQUIREMENTS Since qua lily is ultim ate ly de Aned by customer sa lisfacllon, the re qUirements ana lysIS proce, "con tinuall y directed toward the customer's conce pl of sa ti sfacll o n . T eams 'YP lca ll y show stake holders Interim a com· plishments, and stakeho lders then IIlnutnce lhe course of the work accord ing ly . Be ausc of thIS. ,h,' priority of requ ireme nlS and thus the order In which requirements arc Im plemented , as de cnbed III hapter 12makes a SlgniAcant d iffere nce in the custo mer's sa ll sfa tion In math ematical lan guage, ,hi IS a non · commutat ive operation si nce the SRS seque nce impttP1m1f rcquirrmrll l A (hen pllHf fa Implnllcnl
frqUlrCII1(Ht
B
rC'qulf('moll
A
may well produce a dilferent produc t from irnplrmOl I rrquJrcmtnf H then pi,," 10 ,,"plnnrll'
337
338
CHAPTER 13
QUALITY AND METRICS IN REQUIREMENTS ANALYSIS
-''>lIme three prioml zatl o n . IJlgIJ, In,Jium , and low Me tn Vanatl o n fro m . IJi!lb = • ,"til""" = • IOlv Let T = to tal number of de tail ed requl ,cmems
100. [T -IT / 3 - l1I gh l - IT / 3 - nledium l-IT /3 - lowl] T
o=
worst; 100 = best
Figure 13.10 A metric for measuring the quality of prioritization
There are effective and ineffective prio riti za tio ns. Fo r example, g iVing most req uirements the hIghest pn o rity Indicates poor planning. Ranking low . prio rity requiremenlS IS usuall y a waste of time because they are unl ikely to be all im plemented. As me ntio ned , when stake ho lde rs see the Impl eme ntatio n of reqUIrements, they tend to change subsequent requirements. An effective priori tizat ion tries to account fo r these faccars
H ere is a c hecklist fo r improvi ng the prioritization of re q uirements. • Is it clear what requirement sho uld be worked o n (irst] Seco nd ) • Arc the prio rit ies at a hi gh level consistent with th ose at the detai led leve l) • Is there a pnoritlzation process in place such that it will remain clear what is the ne xt importan t requ irement
that sho uld be wo rked o n) • Is the prioritization appropriately matched with customer expectations?
• Is the prioritization appropriately matc hed with project risks? As ume that each req uirement is in o ne of three priorities. H ow would we measure the quality of the prioritizationr
A good quality prioritization categorizes requirements into equal parts, indicating that no
category has been neglected. Figure 13. 10 sho ws a metric fo r this. For example, if 900 requirements arc very well prio riti zed, each category would contain 300 requirements and the fo rmula would g ive 100 . [900 - 0 - 0 - 0 V900 = 100%. O n the o ther hand, if 700 were classified as h igh priority, 100 as medium and 100 as low, the me tric would yield 100. [900 -1300 - 7001-1 300 - 1001-1300 - 100111900 = 100' 100/900 = 11.1 % Th e low percentage indicates poor prioritization.
13.8 SECURITY AND HIGH-LEVEL REQUIREMENTS Security ca n be dea lt with a an actual (explicit ) requirement or as on at~ributo of require ments. For example. "All passwords shall be unavailable except to the system administrato." I on explicit requirement of an application. On the other hand . 'The requirements in our SRS will cause (ewer than 10 security brea hos of level I or greater (defined elsewhere) in a century of COntinuous operation under the threat e nvII'Onmcnt of 2009" is not a requirement in the ordinary sense. It is an attribute of the requirements. Security In requirements is a special case in that It deal s with deliberate explOIts o n the p.ln of o the l'S to misuse It. Traditional requirements, after aH, are intended to specify what an application sbowlJ do, and have not
SEl.F·COMPLEI ENESS OF REQUIREMENTS
.ddJtssed misuse. This i changing . To an increasing extent, requirements documeOls are addressing the security ~ by including such content as misus< casts. These arc similar to the idea , me ntioned earlier, of inverse requirements. The following are examples of misuse cases use cases that the system is required to disallow. An automated user of the application eMters a known user ID and more than 10 password per second. A user accesses more than 30 customer records in a si ngle si tting and transmits these to another address within 10 seconds of accessi ng the m. Here is a checklist for improving the security aspects of req uirements, • Consider the places in the pro posed application where intrusion appears to be possib le. Are concrete security requ irements stated fo r those places] • Has the conRdentiali ty of data, where applicable, been specificall y required] • Has the security of user identiry been speCified] • Has the security of passwords been ex plicitly call ed for] • Has the ownership of Rles or access been speciRed ] • Has encryption been called for when appropriate l • Have speCific, known security exploits ("hac ks") been speCified aga insO An example is "SQL Injection shall be prevented." (SQL injection is a mea ns of unautho ri zed database access.) Ha ve speCific and po tential exploits been speciRed against vi a misuse cases]
13.9 SELF-COMPLETENESS OF REQUIREMENTS TypiCally, a requirement depends o n o ther requirem e nts. A set o f requirements is " If·com plttt If it contai ns every part whose inclusion is necessi tated by parts already present. Figure 13 II illustrates an incomplete et of «quirements. Without the speci Rcatio n of how a video is to be "displ ayed," thi s se t of requi rements is incomplete as a unit. As anothe r example, suppose that the SRS for a ca le ndar application contai ns the fo llowi ng requi rement.
Th, applicalioll ,hall rttain all ",jormatioll t>ltrrrd by tht "'" jor tach appoilltmtllt.
REQUIREMENTS I. Tht applicalion lhall di,play a DVD ill slock Ivbtll a lilk i, mtrrrd at Iht prompt, ot""wi" il ,IJall di,play
"OUT OF STOCK. " 2. Tht applica llon shall display all oj Iht ,10"" DVD, by any dirtclor whost las t namt i, ", Iurd at Iht promp t Thts< ,hall bt di,playtd Ollt by 001t Advall ill9 tlJrollgh Iht DVDs ,hall bt con lrolltd by Iht lorward artOI/1 kry I'..:o",pktt: Lacks s pcc ,f, atl on o n how to display a videol Fi&ure13.11 An example of self·lncompleteness In requirements
339
340
CHAPTER 13 QUALITY AND METRICS IN REQUIREMENTS ANALYSIS
'\
h~n
J
rc"QlIIrCI1lCnt I~ pre se nt,
,n mu~l tJlI tho~c
nc e'SllJled h y II, pre'en e A mcln
(0
= best, I poor, no theoretical upper li mi t)
[number of mi ssing necessa ry associated requirement s]
Inumber 01 detailed requirements present] Figure 13.12 A metric for self·completeness
The prese n e of th is requirement ncce sita tcs a requirement describing means forentcnng apPointment information
meaning
It also necessitates a reqUirement explaining means (or displaying this Information . TI,is IS the
01 "sell-completion ." Here is a c hecklist lor improVing the sell-completeness 01 requ iremcnts
• For eac h requirement stated, are all th e requirements prese nt that it rclers to] • For each requirement stated , arc all the requirem e nts present that It depends on ] To measure sell·completen ess, we look a t each detailed requirement and note any necessary associated reqUirement that is missing . An appropriate metric is shown in Figure 13. 12 .
The number
01 miSSing requirements is determined by sampling.
13,10 TESTABILITY OF REQUIREMENTS Each detailed requirement must be leslablt; that is, it must be possible 10 definitely validate that the requirement is operative in the finished app lication by testing lor it. Figure 13. 13 provides an example 01 a non testable requirement, and sh ows what it would take to make the requirement testable.
TI" sysl,", shall display Ibt differolCt ill salary b,lw,," Ib, clioll mid 1/" worldwidt aocra9' for Ih, snmt Jradt.
X
ca n't be tested because the average mentioned cannot be determi ned (even th oug h it exist ).
Better;
Th, syslt'" sl,a/J display 1/" d,f}","" ill salary b,lwtrll Ih, eli",1 alld II" "Iimaltd loorldwid, .",ragt for Ih, ,am, Irad, as ~"blishtd by Iht Ulliltd Nalloll' Oil {IS Web ,ilt www.tbd al th, limt of Ih, display . Figure 13,13 An example of testability
•
TESTABIUTY OF REQUIREMENTS
Table 13.2 Example of a user satisfaction questionnaire User satisfaction
o = of no value; 5 = average satisfaction; 10 = a pleasure to use Quality
Score
1. OVerall appearance 2. Layout of text areas 3. Layout of buttons 4. Readability 5. Ease of entering data 6. Degree to which erroneous data entry is prevented • •
•
• • •
Requirements that are no t testable arc of negligi ble va lue. It would be impossible to assess whether such a requirement has been attained. This is an all·or.no th ing property. The re is lit tle value in the "degree of testability" of a requirement. Testability can sometimes be used to specify a detailed C UI requirement. Fo r example , instead of specifying a CUI in complete detail we may prefer to provide a test suc h a the following , The CUI for entering DVDs shall ha ve the Rclds and butto ns listed in figu re xx, and its deSign shall score an average of at least 8.5 out of l Oon the user satisfactio n questionnaire In Table 13.1 . An effective way to ensure testability and to ensure the clari ry of a requ irement at the sa me time is to include tests with the requirement. Figures 13 . 14 and 13 . 15 illustrate an example. Agile programming applies this test orientation but sho rt ·ci rc llit's the prose by e ncodin g the test up front , usi ng it as a requirement, in effec t . A reasonable testabil ity me tric IS the fo ll owi ng,
The percentage oj dr,ailed requi"",en" ,ha' are accompanied by a '" , Even when a requirement is tes table , executing a test may be d ifficult o r time-co nsum ing. T o be complete, we sometimes need to consider the cos, oj as part of the considerati o n. A very h igh cost
',,'i"9
The video store app lication s hall impl eme nt a discount program as follows, • • • •
One DVD , no di scount Two DVDs, 20% d isco unt fo r the second DVD Three DVDs: 40% di scount for the second and th ird DVD All videos beyond the th ird are dl counted at 40% . 13.14 Including tests witlh requirements, 1 of 2- the requirement
341
342
CHAPTER 13 QUAUTY AND METRICS IN REQUIREMENTS ANALYSIS
I 2
U\lo me r
we" Jo nes re nt, o n ' OVO He b c hJrl(ed the rq!ul. r rc nt31 o( $ 5 00
ustomer T r re," Edward, re nts two OVO, $4 00 (20% d" ounl ) (o r the e o nd .
he i, c h3rgcd th e rc~ul ar rel1t31 o( $5 .00 fo r the f,m and
usto me r ll,eodo re L, sl renlS Ihree OVOs He, c harged the regul ar re ntal of $500 for the nrst, $4 00 (20% d,s ounl ) (o r the second , and $3.00 (40% d i ount ) (o r the thIrd . 4.
usto me r Fred Harari rent < !lve OVOs. He IS c ha rged Ihe re~ul a r re ntal o ( $5.00 (o r the first, $4 00 (20% di s ount) for th ~ seco nd , and $3.00 (40% d, s o unt) (o r Ihe third. The fo urth and nfth OVOs are harged at $3.00 (40% dlScot'"t ).
Figure 13.1 S Including tests with requirements 2 of 2- Ule tests
inAuences our c ho ,ce and pnoriry of requirements. For example, suppose that we cons,de r adding to our online video service the follOWing requirement:
Fo r each movie entered by the customer, the appltcation shall di splay a number from 0 to 5 that provides the ystem's estimate o( how much he will like the movie . This e t,mate 's based on the , .. .
customers past viewing ratings .
ThIS can be tested, but the expense of doing so properly ma y d,ssuade us from making it a hi gh prio ri ry Reco mmendation algorithms have become a competitive activity amo ng providers, with large rewards provided fo r the creators o f the most (measurably) effective ones. like this one, many requirements are strongly associated with business decisions.
Here i a c hecklist for improving the testability of requirements, • Is Ihe requirement clear enough to devise inpu t/output data samples lhat exercise it) Specify the tests. • Is there a set o f tests that, if passed. provides significant confidence that the requirement will have bee n satisfied? • If one reasonable person in the cuSlomer community proposed a set of tests for the reqUIrement, would another probably agree that it tests the requirement?
13.11 TRACEABILITY OF REQUIREMENTS T raceabiliry was defined in Chapter 10. Our concern here is how to measure a .et of requirements in th, respect. A requirement is traceable if it maps in a completely clear manner to the design clement that accommodate it. the code that implements it, and the tests that test ,t . \'(Ihen the 0 0 or "class" organizat ion o( requirement writing is used, the mapping to the class within the des'gn and to the code can be comple tely clear. It requires work and clear th"'king to mainta", such clariry, however. For e ample , a Cuslolll" paragraph that speCifies the rentals that each customer can have could compromise traceabili ry The design would probably have the clas«, C""O'"" , DVD, DVDRrtJlnl , and DVDRrnlnls. The requirementS orgal1lzallon should reAect this. Organizing cla.scs by funclIona lt ty, CU ls, use cases, and so on has vanous advantages, as dis u sed "' Chapter 12 , but traceabiliry is 110t a strength for most o( them . One would have to pen,« cach deta,led requirement and ask whe ther a will clearly map to a class.
METRICS FOR REQUIREMENTS ANAlYSIS
(Range: 0 to 100) tOO'
L: [traceability of each detailed requirement (0 -
2)J
2 . [number of detaIled reqUlrementsJ 0= untraceable, 2 = clearly traceable to a specific class F1gUre 13.16 A traceability metric
Here is a checklist for improving the traceability of requirements: • For each detailed requirement . is it clearly conceIvable that an ide ntifiabl e part of the code base will Implement it? (It's ideal when a single method implements a SIngle deta ded requirement. ) • Is it clearly conceivable that a ing le, identifiable pan of a software design ..nd implementatio n could contain itl (A detailed requirement that must be spread over several probable main modules is not easily traceable. Traceability can be measured as in Figure 13. 16. Usi ng 2 as a measure allows the appl,catio n of triage for a give requirement , where 0 = u,,'raccablt, 2 = Jldly 'ra ctablt , J othtnVlst .
13.12 ME I RjCS FOR REQUIREMENTS ANALYSIS The previous sections of thi s chapter described metri cs for a number of requirements qualities , acceSSIbility, comprehensiveness, understandability, unambiguousness, consistency, deg ree of pri omizatio n, secu rity, se lfcompleteness, testability , and traceabi lity_ Additio nal metrics ca n be considered . The fo llowing li st of quality assurance metrics includes requirements analysis metrics in IEEE Standard 982.2-1988 ("IEEE Cuide for the Use of IEEE Standard Dictionary of Measure to Produce Reliable Software"). Some measure the qualities we have already discussed in a different manner. • Percentage of unambiguous speCIfic requirements (IEEE metric 6) • Degree of completeness (IEEE metrics 23 and 35 ) • Percentage of misdassined detailed requirements (in the object. oriented sty le, thIS measures the percent· age allocated to the wrong dass ) • Traceabil ity (IEEE me tric 7) • Degree of atomIcity (indIvisible
1010
smaller parts)
• ConSistent with the re mai ning reqUIrem ents (IEEE metries 12 and 23 ) • Measures of the effectiveness of reqUIrements inspectIon • Percentage of missIOI! or defec tI ve requirements found per hour of in spection • Musures of the effectIveness of the requirements analy is proces • Uxt per det-a ded reqUIre ment • On a gross baSIS (!'Ota l lim e spen t/number o f dctoded ,.eq ulfe mcnt ~ )
343
344
CHAPTER 13 QUALITY AND METRICS IN REQUIREMENTS ANAL VSIS
• 0 " a In a"~ ,,,al b"" (
oq
10
He t one more)
reqlllrcrncnb arc
- rnodifled - elimlnaled - added •
1easure of the degree of o mpl e tcncss of the requIrement, . ThIs can be e't lmated from the rate, after the official "nd of dctarled requirements collectio n, a t whic h specIfic requrrem e nts are . .. - mod ified - added
13.13 INSPECTING DETAILED REQUIREMENTS The reader is referred to C hapter 5 for a descriptio n o f the inspection process In general. Detailed requirements are the Arst software process documents that ca n be inspected agarnst pnor docum e ntatio n (the h igh.level requirements). Inspectors prepare For the inspection by reading over the hIgh . level requirements and companng the detailed requirements with them. It ca n be very productive to Inspeci requ ireme nts against each of the qua lities and metrics listed above . The rest of thi s section proVides an example of a detailed requirements inspection. H e re is an un inspected versio n of detailed require ments For the Encounter video game case study o n which we will perfo rm an example inspec tion, entering the results in a table (see Tabl e 13.3 ). We empl oy the technique of auto mati cally adding the "no t inspected yet" comment to each . It is removed when the inspectio n takes place. The Anal versio n of these requirements, re sulting from the inspecti on, is shown in the accompanyi ng Encounter case study.
Arm R'4u ir"''''11 I ("Art. name"). (Not inspected ye t) Every area shall ha ve a name of up to t 5 characters.
Art. R'4uir"""11 Art. object.
2
("Art. image") . (Not inspected ye t) There shall be an Image in gif fo rm to display each
Art. Rr4ui"'''''11 3 ("Display area method") . (Not inspected yet ) Whenevcr a player character enters an arca, that area and the c harac te rs in it shall be displayed. Art. Rr4uir"""11 , ("Courtyard object"). (Not inspected ye t) There shall be an Art. o bject with name "courtyard: Its image shall be that shown in Figurc xx o n pagc xx. Art. Rr4uirrmrnl 5 ("Dressing room object"). (Not inspected ye t) Therc shall be an Area object with name "dr<ssing room" and blank background image. The dreSSing room shall be adjacent to the courtyard area.
Encou,,'er Rr4uirrmrr,' f ("Engaging a foreign character"). (No t inspected yet) When an engagement takes place, the Following computation IS performed, The sum of the values of qualities of a game char.Jcter relevant to the area in question shall be refcrred to as the characters area value. (In this release, all qualities will cou nt as equal.) In an cngagement, the system compares the area values of the characters and ITan fer< to the stronger, hal fofthe points of the weaker. For example, suppose the pl.yer cn!!ages a foreign character In an area requiring stamina and attention span, and ps is the value of the player's stamrna, et . A Imlog p., + p. > f, + f" wewould have p,' = P. + f/ 2, Po' = p. + f/2 , F,' = (,12 , fo' = f/2 where xl is the vallie 0 x.fter the transaction.
Table 13.3 Example of a foml used for the Inspection of detailed requirements Traceable forward Note 14
NO.
Requirement Description
Traceable backward
Comprehensive Consistent
Feasible unambiguous
Clear precise
1001
Area Requirement 1
Note 2
Note 1
Yes
Yes
NO 1
Yes
NOl
N02
No 1, 2
Yes
1002
Area Requirement 2
Yes
Yes
Yes
Yes
N0 3
Yes
No3
Note 3
Yes
Yes
1003
Area Requirement 6
Yes
NOle 5
Nole 5
Yes
N03
N03
NO S
Yes
Yes
Yes
1004
Area Requirement 3
Yes
Yes
Yes
Yes
Yes
Yes
NOle6
Note 3
Yes
Yes
1005
Area Requirement 4
Yes
Nole 7
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
1006
Engagement Re.9ulrement ,
NOle2
Yes
Yes
Yes
Yes
Yes
Yes
Nole 3
Yes
Yes
1007
Encountercharacter Yes Requirement 1
NOle 1
Yes
Yes
No 1
Yes
NO 1
N0 2
No 1, 2
Yes
1008
EncounterCharacter Requirement 2
Yes
No 11
Yes
Yes
Yes
NOl e 8
Yes
N06
Yes
Note 9
1009
Encountercharacter R~ulrement 3
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Note 3
Yes
Yes
1010
EncounterCharacter NOle " R~ulrement 4
Yes
Yes
Yes
Yes
NOle 12
NOle 12
No 7
Yes
Yes
1011
EncounterGame Requirement 1
Yes
Yes
Yes
Yes
Yes
Yes
NOle 13
Yes
Yes
Yes
Yes
NO8,9
Yes
Yes
Yes
1012 1013
Yes
foreign Character Requirement 1
Note 11
Pla~er Character
Yes
Yes
Yes
Yes
1015
VI
m
Plaler Character Requirement 2
Yes
Pla~er Character
Yes
Requirement 3
-z
."
Yes
Yes
Yes
Yes
Requirement, 1014
Modifiable Testable
Yes Yes
Yes Yes
Yes Yes
No 12 NOle 10
NO 10
Yes
NO 12
NO 12
Nole 10
Yes
Note 15 Nole 3 Yes
Yes NO 12 Yes
Yes Yes Yes
n
:::t
z
C> 0
~
... ~ m
0
'"Dmc -m '";::: m
~
VI
~
346
CHAPTER 1J
QUALITY AND METRICS IN REQUIREMENTS ANALYSIS
Ell 0,,"1, I),,,,, I" R,qlll"'","1 , ("Name of ga me haracld '). (NOI ,nspecled yel l !- very game charac tcr ,n lhe En o U/ncr video ga me shall have a uni que name o f up 10 15 chara l e r~ E" 0""1,, I ,",' c har. ler has 1001n, where pa lie n C, and
Rrq,,;rrmn"
("Qua lities of !;,me charac lers''). (NOI Inspec led yel l Every game lhe same scI of qual ,.lies, each having. floating pOlin value These arc In'tialized 10 n is lhe Ilum ber of quali lies. The qua l'lie, are allentiOn 'pan , endurance , intelligence, strenglh . I"
1
E" 0,,"1, l>araelrr R,qlllrtl","1 J ("Image of game h.racler" ). (NOI In spe ted yel l Every game character w,lI be shown uSing all image that lakes up no mo re lhan 1/8 of the monilOr screen Elleo,,"lrr IJaracl" R'q,,;rnllClI I < (,'Engagemenl wllh foreig n haracler") . (Nol lnspcctcd yel l Whenever an Encounler ga me charac ler enters an area con lai ning anol her ga me c haracler and one of lhem is player. controll ed, lhe player c harac ler may either chao e or be obliged by lhe ga me to engage the olher characler \XI' hel her lhere is a c hoice o r not is co nrro ll ed by lhe game in a random way o n a 50% basis Elleollt"trGam, R,qlll"mClII Encou nterGa me objecl.
("Encounter game objec!"). (NOI
I
In
pecle d ye t) There shall be a Si ngle
("Freddie foreign characte r object") . (NOI inspecled yet ) There shall be a foreig n c haracte r named "Freddie," all of whose qualities have equal values and whose Image is shown in Figure 4.57.
FOrtl911Charaeltr R,q"",m,"1
I
PlaytrCh.,.eltr R,qlllrnllcIII
I
("Conngurability"). (NOI inspected ye ll Whenever all foreign players are absent fro m an area , the player may set the values of his o r her qua li ties us ing the PlayerQuall ty. Window , as long as the sum of the qual ity values rema ins lhe same.
Play,rCharaclrr RC4" irtnlCllI
("Main playe r character") . (No t inspecled yel l The player shall have complele control over a part icu lar game character called the main c haracter.
PI.yrrCharaelrr R'4"irCltl""
2
("liVing points") (Not inspected yet). Encounter shall produce lhe sum of the values of lh e charac ler's qualities, ca lled its livi ng points. J
We will show ty pical results of an inspection of these requirements. O ne inspection comment aboot thiS sel as a who le is that the requirements do not support enough expansion of the game into a competitive product. A more particular defect is that the requirements do no t properly specify lhe delay involved in settin g a player's quality va lues, during the delay the player is subjected to an engagemenl in an unprepared state . (If the delay is too small , the player simpl y se ts the qualities required fo r the area as high as possible and lhe game is not much of a challenge.) Let's inspecl the list of proposed detailed requirements one al a time Table 13.3 IS an example of a form that can be used for lhe mspection of detailed requirements. applied to the above list. Most of the melrics preVi ously described in lhi s chapter ca n be computed fro m th is table The table co nta ins "Notes" and "No" notes. H ere are the "No" no tes, I. Can a game character or arca have a name with no c ha racters? 2. The number 15 IS rigid. 3. Only o ncl 4. If the player controls several characlers, arc all of their areas 10 be displayed or does this have to do onl ' with the mam playe r characte r?
SUMMARY
5. Filling th~ cntire monItor screen7 6. It should ~ "asler to add new qualities o r remove them . 7 When is there a Freddie7 When does he appear7 S. In future releases, characters may mutate. 9. Clarify what stays the sam". 10. Can th" value of a qual ity be negative7 II. Ambiguous, because the player can't contro l everything that happens to the main character at all times .
12. Refine "complete contro1." The "Notes" are as follows , I. Is any k"yboard character acceptable7
2. Check validity with the customer. 3. It is unclear how modifiable this shou ld be. 4. It is hard to answer "complete" because it is unclear. See the note referenced in the "Clear" column fo r the issue. 5. We assume that the customer has some leeway in exactly what the "courtyard" will look Ioke . 6. Are there dressi ng room exits to any other area7 7. This is somewhat clumsily written, could lead to misunde rstandi ng . S. It is usually preferable to have a si ngle requirement match each attribute. Thi s doc not appear necessary, as the qualities will be treated alike. 9. Produce at any time] On request7 Show at all times7 10. These details arc not mentioned in the high · level requirements, check with customer. II. Clarify "50% basis," if possible.
12. For Internet versions, it may become necessary to have more than o ne instance of an EncounterGame object. We will not exclude this possibility in future iterations. 13. It is not clear in what directIons this could be modified. 14. Is the requirement wrinen in such a way that it will be possible to trace it through to the code that implements it7
13.14 SUMMARY The quality of a requirements document is reRected in how well it expresse customer wants and nec:ds. T o hdp ensure that requirements are of high quality, we focu s o n attributes the y shou ld posses . TI,ey Include the follOWing: • AccesSIble • Comprehensive
347
348
CHAPTER 13
• L1nJ",bl ~u •
QUAUTY AND METRICS IN REQUIREMENTS ANALY IS
liS
on~ls t cnt
• Pnontlzed •
cure
•
e1 f·complc te
• Testable • Traceable Requircl11enrs arc Inspccted aftcr they are writtcn . They are the Ar t softwa re process documents that can be inspected against prior documentation (the customer reqUirements). It ca n be very productive to Inspect requirements against each of the attributes listed above.
13.15 EXERCISES 1. (This is intended to bc a closed book exercise .) list the qualities that requirements should possess
(o ne example · precise). In your own words, dcscribe the meaning of each . 2. Explain why the following requirement fo r a book sa les site is ambiguous. Modify the reqUirement to make it unambiguous. "Orders that include speCia l edition books and overnight delivery or exceed $ t 00 must be processed ove r the phone." 3. Provide an exa mple of three requirements for an order entry system that are inconsistent . How would you modify thelll to make them consistent? -I . For the order entry system in Exercise 3, provide three requirement
that are not testable, and expla in why each is not testable . Provide a modified version of each requirement to make it testable.
5. Your instructor will pair up stude nt project teams. Conduct an inspection of the other team·s detailed requirements. Evaluate thc requirements against the list of metrics described in thi chapter Prepare a table such as Table t 3.3 to summarize your results.
Formal and Emerging Methods in Requirements Analysis: An Introduction Online Chapter
14.1 PROVABLE REQUIREMENTS METHODS 14.2 INTRODUCTION TO FORMAL METHODS 14.3 MATHEMATICAL PREliMINARIES 14.4 THE Z-SPECIFICATION LANGUAGE 14.5 THE 8 LANGUAGE SYSTEM 14.6 TRADE-OFFS FOR USING A B-LlKE SYSTEM 14.7 SUMMARY 14.8 EXERCISES
To access this online chapter please visit www .wiley.com/cottege/braude.
principles of Software Desi n
Planning
/:
Maintenance
•
What are the goals of software design?
•
How do you use various design
models for a single application?
Testing
The Software Development Life Cycle
•
What are use case model , class models, data flow models, and state models?
•
How are frameworks used in design?
•
What are the IEEE standards for
RequIrements
IIfI8IWsIs Implemelltation
-.;:::
expressing designs?
DMIgn
•
How does a team prepare for design in practice?
Figure 15.1 The context and learning goals for this chapter
A ·sorrware deSIgn" is a representatio n, o r model . of the software to be built. Its purpose is to enable programmers to implement the requirements by desi g nating the projected parts of the implementation . It i a et of document containi ng text and d iagrams to serve as the base o n which an application can be fully programmed. A complete software design should be so explicit that a programmer could code the application from it without the need for any other document Software des. g ns arc like the blueprints of a building that arc sufAcient for a contractor to build the required budding. They can be understood in two parts: high · level desig n, often referred to as ' software archite ture: which is ge nerall y indispensable, and all other design, referred to as "detailed design ." It can be beneficial to make designs very deta iled, short of being actual code. Th. is becallse engineers can exam ine a derailed design for defects and improvements prior to the creation of code rather than examining
THE GOALS OF SOFTWARE OESIGN
only Ih~ code The beneAts of a fully detaIled desIg n arc balanced agai nst the time: required to document and maintain detail~d designs. For large elfo"s, level s in between high level and detailed desIgn may be identified This chapter introduce the concepts, needs, and terminology of software design. It sets the stage for the ~m.jning chapters in thIS pa" of the book, whic h include various co nc rete examples.
15,1 THE GOALS OF SOFTWARE DESIGN The first goal of a software design IS to be sufjimtll for atlsfying the requirements. U ually, software designs muSt also anticipate changes in the requ irements, and so a se ond goal is jlrxibi/ily. Ano ther goal of software design IS rohosllKSS: the ability of the pro duct to anticipate a broad variety of input. These and other goals are summarized in Rgu~
15.2.
These goals sometimes oppose o ne anot her. Fo r example , to make a de ign effiCIe nt il ma y be necessary to combine modules in ways that limit Aexib di ty. In fac t, we trade off goals agai nst each other in ways that depend on the project's priorities A software design is sujlie;," 1 if it provi d es the compo ne nts for an Imple me nta tio n that satIsfies the rcquirements . To assess such suffiCie ncy , o ne needs to be able to understand it. This fact is obvious, but it has profound consequences. It can be d ifficult to create an understandable deSIg n for applications due to the large number of optIons that are typically available . Open Office, for exa mple, is a ve ry comple x applicatio n when viewed in complete detail. Yet Ope nOffke is simple when viewed a t a hI gh level, as consisting of a few subapplications: word processing, spreadsheet, presentations, and database. Modulnr;1y is thus a key to understandability . So ftware is modular when it is di VIded into separalely named and addressable components. Modular software is muc h easier to understand than mo no lithic software, and parts can be replaced without affecting othe r parts. It is easier to plan , develop, mod ify, document, and «-st . \\:'hen software is modular you can more easily assign different people to work on differe nt part . A design is a form of communication. In its most elementary form , it documents the res ult of a des igner's thought process, and is used to communicate back to h imself thereafter when he needs to know wha t he designed. Thi s IS fine if the designer is to be the o nl y person who has this need , but a projec t usuall y Involves several people throughout its lifetime . If a design is not ulldm lolldnb/, fo r them, it IS of lim ited val ue, and the project's health is at risk. Design implification , in particular, frequentl>' results in a better de ign . Understandability is usuall y achieved by o rga nizing the design as a progression fro m a high level w ith a manageable number of parts, then increasing the detail o n the parts. A good software archItect and designer forms a clear mental mo de l o f h ow the appl icati on WIll work al an ov"allievel , then develops a decomposi tion to match thI S mental mod e l. She firs t asks the key modularity
• • • • • • • • • • •
Sufficiency: handles the requ irements UndersliJndability: can be understood by intended audience Modularity: divided into well -de n ned parts Cohesion: organized so like- minded clem e nts are grouped together Coupling: organized to minimize de pende nce between elements Robustness: can deal WIth WIde va ri ety of input Flexibility: can be r<:adiiy mo difie d to handle c ha nge in reqUIrements . Reusability: can u e parts of the desig n a nd implementation 111 o the r app ll ca ll o ns Information hiding: module interna ls are hIdde n from ~tl:ers EffiCiency: executes wi thin acceptable lime a nd <pace IlInlts Reliability; execute< WIth acceptable fa dure rate 15.2 Principal goals of software design
351
352
CHAPTER 15 PRINCIPLES OF SOFTWARE OE51GN
=
High cohesion (parts belong together)
Component
Low coupling (mInimal contact)
Figure 15.3 High cohesion and low coupling-bridge example question such as: What Rve or six modules shou ld we usc to decompose a personal nnance applicatIon) What four or five modul e neat ly encompass a word processi ng application ? After decIding this, she turn ' 0 decomposing the components , and so on. This process is sometimes ca ll ed "recursive design " because i, repeats the design process o n design compone nts at successively fine scales. Software decomposition itsel f involves consideration of cohrsioll and couplillg. Cohesion within a module is the degree 10 which the module's elements belong toge,her. In other words, " is a measure of how focused a module is . The idea is no' just 10 diVide softwa re into arbitrary partS (i.e., modularity ), but 10 keep related issues in the same pa rt. Coupling descnbes ,he degree to which modules communicate with ot her mo dules. The higher the degree of coupling, the h arder it i 10 understand and change the system . To modularize effectively, we maximiz, cobtsion and 111illimizr coupling . Th is principle helps to decompose complex tasks inlO simpler o nes. Software engineering uses Unified Modeling u.nguage (UML) as a principal means of explaining desi gn. Understanding softwa re design concepts by means of analogous physical artifacts is helpful to orne, and we will employ this mean on occasion . Figure 15.3, for example , suggests coupling/coheSIon goals by showing an architecture for a bridge, in w hich each of the six components has a great deal of coheSion and where the coupling betwee n them is low. The parts of each bridge component belong together (e.g., the co ncrete and the embedded metal reinforcing it )-this is high cohesion . On the oth er hand, each component depends on just. few o,her components two or ,hree , in fact. This is low coupling . The "Steel truss" III F,gure 15.4, on 'he o,her hand , shows many component dependIng on each other at o ne place. We would question this high degree of coupling.
Component
High coupling
Figure 15.4 A Questionable architecture high coupling In a truss
X
•
lliE GOAl S OF SOFlWARE DESIGN
• Oblilinin.9
,"Ort
or
',,5 oJ wi,.,., alrtady prm,,'
Example: handle more kinds of accounts without nceding to change the existi ng design or code • Adding "tw killd, oJ Jllllcliollalily Example: add wilhdraw to existing dtposil function
• Cha"ging j""Cliollalily Example: allow withdrawals to create an overdraft
fl&Ure 15.5 ASpects of flexibility: ways in which an application may be required to change
Low coupling and high cohesion are particularly important for software design because we rypica lly need to modify applications on an ongoing basis. Compare the life cycle of a typical software application with that of the bridge in Figure 15.3: the likelihood that the software will require mod ,Rcatlon is many time greater. Low coupledlhigh cohesion architectures arc far easier to modify, since they tend to minimize the effects of changes. The number of top-level packages in an architecture should be small so that people can compre hend the result. A range of "7 ± 2" is a useful gUideline , although specinc projects ca n vary greatly from tim range for special reasons. As an example, OpenOfnce would be hard to understand if we decomposed it into 100 parts instead of four as follows : "word processi ng, spreadsheet, presentations, and databa e." The mind has much trouble thinking of 100 separate things at more or less the sa me time. The difference between small - and large-scale projects (such as OpenOfnce) is the amount of nesting of modules or packages. Projects rypica ll y decompose each top -level package into subpackages, these into subsubpackages, and so o n. The "7 ± 2" guideline applies to each of these decompositions. A design or implementation is robll" if it is able to handle miscellaneous and unusual conditions. These include bad data , user error, programmer error, and e nviro nmental conditions. A design for the video sto re application is robust if it deals with attempts to enter DVDs with wrong or inconsi tent information, or customers who don't ex.ist or who have unusuall y long names, o r if it handles late rental situations of all kinds . Robustness is an important consideration for applications that must handle commUnication . The requirements of an application can change in many ways, and as a resu lt a design must bejl""blt to accommodate these changes. Fi gure 15.5 illustrates ways in which an application may change. A set of previously used drsi9" partm" is a useful resource for flexible designs. DeSign patterns are discussed in Chapter 17. We design so t·hat parts of our own applications can be rr"ltd by others and ourselves _ Figure 15.6 lists the rypes of artifacts that often ca n be reused .
We can reuse .... • Object code (or equivalent) Example: sharing dlls between word processor and spreadsheet • aas~s in sou rce code form Example: Customer class used by several applications Thus, we write gene ri c code w henever possible • As~mblies of rdated classes Example: the java.awt package • Patterns of class assemblies
FIlii,. 15.6 Types of reuse
353
35'
CHAPTtR 15 PRINCIPLES OF SOFTWARE DESIGN
cI""
A an example of I." reli'>c, o n
15.2 INTEGRATING DESIGN MODELS The architectural drawings o f an of~ce bUilding comprise th e fro nt eleva tio n, the si de elevation. the electrical plan . the plumbing plan . and so o n. In o ther words. several diffe rent views are req uired to express a bUlldlng's arch itecture. Similarly. several different views arc required to exp ress a software desig n. They are ca lled modds Four important models are shown in Fi gure 15.7, and they are expl ai ned next. Several ideas here are taken from the Un iRed Software Develo pment me thod o f Booch. Jacobson. and Rumbaugh. Figure 1includes an example fro m the Encounter video gam e case study to illustrate the four models and how the fi t together. The subseque nt sectio ns o f th is chapter elabo rate o n these mode ls so that they ca n be contra ted and combined with each o ther. Subsequent chapters in th is parr of the book prOVide detailed examples of each
15.2.1 Use Case Model This section describes several levels o f use cases and related concepts. The " , follOWing four parts:
ClISt
",odd conSIStS of the
I. The ,,", i"61 " SC CQStS : a narrati ve fon11 . suitable fo r devcl opcr. to ·cu to mer commun i ation, descnblng the required basic sequences of ac tio ns
INTEGRATING DESIGN MODELS
To express requirements, architecture, and detailed design Use case model
Glass model
"00 this ... •
"wffh objects of these classes .. .' e.g .. with Engagement .. . classes
e.g.". engage foreign character
Target Application
State model
Data flow model
~reac t;ng
"'in this way ... ..
e .g .. character scores flow from .. . to ...
to these events ,.,.
e.g .. when foreign character enters • Video game example
Figure 15.7 Models to express deSigns (and parts of requirements) 2. Their re fi nement into regu lar u" cam. descnbed in Chapter I I 3. Their transfo rma tio n into "qu"'ctdiagrallls (covered in Chapter 16). which in rurn ca n be in stages of re fi ne me nt:
twO
successive
(a) With informal functionality desc riptio ns, at first lacking all details (b) With specific functio n names and howing all details
4. SCOtarios: instances of use cases th at contain specifics. and that can be used for testing. For example . a scenario of the use case step
( uslomtr cboosts accounl would be something like
John Q Smilh choosts ch,eking acco",,'
1234 5 .
The usc case model e xpresses wha t the applicatio n is supposed to do. as suggested In FIgure 15.8.
15.2.2 Class Models Classes are the building blocks -mo re preCisely, the ty pes of budding blocks of deSIgns Cia . mo dels consist of paekagts (a groupi ng of clas es ) that decompose Into smaller packages. and 0 on. whIch dccompo c Into classes. and these, in turn . decompose primarily into met hods. Thl IS shown in Figure 15 .9. We cover doso;cs in more detail in Chapter 16
15.2.3 Data Flow Models
The class modd descnbes the kind, of objects Involved; It does not show a
n,C
tual objects dalll jlo.' ,"oJd, o n the olher hand , shows specdi o bJcc t< and the type of data fl oWIn!! between them It IS related to the cia ,
355
356
CHAPTER 15
PRINCIPLES OF SOFTWARE DESIGN
Uso cue modol : BUlin•••
------------
u•• c•••
U.. ce.. ~ ; ~;
~; ~;
~~
~
~
~
~
~
~
~~
e laborated by _.
~~
Sequence dl.gram
r------------1 Target Application
Scenario.
I
Class model
..
State model '
Data flow model Figure 15.8 The role of use case models in design
model , because the objects invo lved must belong 10 the classes III the class model. We discuss data flow d,agrams in C hapter 16. Fi gure 15 . t 0 shows the parts of a data Aow model.
15.2.4 State Models Sta te models reflec t react ions to eve nts. Events incl ude mOllse ac tions and c hanges in variable va lues. Events arc no t described in class mo del s or component models, but they do occur in the state model. We in troduced sta tes in Chapter 11 as o ne way to describe the requirements of an application . The states in that conte xl describe the external behaVIOr of the application . The states we arc referring to here reAect the state of
Use case model
Class model
I
Package
~"
Consists
,,
of ...
Cla.s Terget Application
Data flow modol
State model
'--
Figure 15.9 The role of class models In design ~ JIt(;U:l5on. lVII, "Object oriented SOltwMe Englneerlna: A I.M case
DI'iven Approach," Addtson·wesley. 1992
FRAMEWORKS
Use case model
1 Class model
Target Appllmlon
Data flow model
State model
Processing eta"le"t
organized by ...
,,
~----1 ,
,,
,,
"
,
Data type
I
Data store
I
Subprocesslng eleonant
Figure 15.10 The role of component mOdels in design $OUt't'e.:
1aCObson, IVar, " Object Oriented Software Engineering: A use case Driven Approach:' Ad<3!son·WesIcy, 1992.
Use case model
Class model Target Application
Component model
State model : "reacting to these events "
I
States
~n------1
Substates
decompose Into ...
I
Transitions
I
I
Figure 15.11 The role of state mode ls in design Sourt:e: Jacobson, rwr. "ObJect Or~nted SOftware Englneenng: A use case Driven Approach, " AOdrSOfl·Wesley, 1992. elements in a software design . The role of stare mo del s is shown in F.gu re 15 . 11 . n,ey are described in more detail in Chapter 16 .
15,3 FRAMEWORKS
As we have secn, the rruSt of compo ne nts is a major goa l in so ftware development . If an o rga nization ca n't leverage its investments in the ski ll of it designers a nd programmers by usi ng their work severa l times over, competitors who do so will be faster to market with superior produc ts. Th e parts of an application that are particu lar to it and arc not reused arc often ca lled Its bus11ltsS log'c. Bus iness classes arc es ent.ally the doma.n classes d.scussed In Chapter 12. Where do we keep the lasses slated for reuse] H ow do we orgaOlze the m] Shou ld we build.n rela tlonsh.ps among thesc classcs] Do they control the application or does the app ilca no n co ntro l lhem ] n , e computlOg
357
358
CHAPTER 15
PRINCIPLES OF SOFTWARE DE IGN
--;::"=.-::...=-:..-.., - . -., ,.-. Aenloilioms
~u._._
Rontals
- -, RenialCuslomer$
'-_.
..
- --.~-.-
---
_...._ .. __
.R._~._
.-
•
'"
•
---~
Figure 15.12 A framework for rental applications
community ha learned from experience that merely making a list of avadab le fun ctio nality docs nOI necessanly result in reuse . We have learned . however, that arrangements like the Java AP I (co here nt se ts of classes) do indeed lend themselves to highly successful reuse. The Java AP ls (3D, 20, SWing , etc.) arc Jramrworks . A Jrm"rwork , sometimes ca lled a library, is a collection of software artifacts usable by several different applications. These ani facts arc typically implemented as classes , together with the software reqUired to utilize them . A framework is a kind of common denominator for a fami ly of applications. Progressive development o rganizations designate selected classes as belonging to their framework . Typically. a framework begins to emerge by the time a development o rganization develops its second to founh application . As an example , consider the Renlal fra mework shown in Figure 15. 12 that our video store application could use. This architecture divides th e clements into the items that can be rented (books, DVDs, etc.), the people who can rent them , and the rental reco rds that associate members from the first two pans. The individual classes in the fra mework will be suppl ied later. Frameworks like these are usually obtained in a combin ed botto m·up and to p .down manner; boltom .up by examin ing the tructure of actual application architectures such as the video store application, seeking more general forms; and top·down by conceptualizing about the needs of a particular family of applications such as rentals. Classes within a framework may be related. They may be abstract or co ncrete . Applications may use them by means of inheritance, aggregation , o r dependency. Alternatively, as we wil l see below, a framework may feel like a generic application that we customize by inserting our own pans. Figure 15. 13 shows the relationship between framework classes, domain classes, and the remaining design classes. The design for an application consists of ( I ) the domain classes (that are special to the F•• hb.wortlcl•••••
,---------I I I I I 1M dfJ,.,1ed "u/gn
I I I
I
/ The CI,•• Madl' .."
"'1 I I I I
I
DMIgn
cI8....
: I I I I I I I I 1
I
L _________ _I
Flpre 15.13 ClaSS model VI. architecture and detailed design
SUMMARY
1. Inb Oductlon ..' 1.1 Purpose ArchltectUN 1.2 Scope ,• '" ' .'. 1.3 Definitions, acronyms, f .... and abbreviations ! •• • • 2, ReleNnce.
• 3. Decomposition description
3.1 Module decomposition 3.1.1 Module 1 description 3.1.1 Module 2 description 3.2 Concurrent process decompoSition 3.2.1 Process 1 description 3.2.2 Process 2 description 3.3 Data decomposition 3.3.1 Data entry 1 description 3.3.2 Data entry 2 description
4, Dependency description 4.1 Intermodule dependencies 4.2 Interprocess dependencies 4.3 Data dependencies 5. Interlace description 5.1 Modute Interface 5.1.1 Module 1 description 5.1.2 Mod ule 2 description 52 Process Interface 5.2.1 Process 1 description 5.2.2 Process 2 descri ption 6. Detailed design 6.1 Module detailed design 6.1.1 Module t detail 6.2.2 Module 2 detail 6.2 Data detailed design 6.2.1 Data e ntity 1 deta il 6.2.2 Data entity 2 detail
figure 15.14 IEEE 1016·1998 SOD example table of contents
application ), (2 ) some of the fram ewo rk classes (generall y speaki ng, no t all are needed ), and ( 3) the remaini ng classes needed to co mplete th e design , w h ic h we are call ing simpl y "desig n" classes. The design classes consist ofthose required fo r the architecture and th ose that are not. The latte r a re effectIve ly the detai l design classes, requ ired to comple te the d esig n. These three co nstitute th e class mo d e l fo r th e application . All of the domain classes are in the de ta iled d esig n because th ey are very specinc. The fra mework classes used are part of the application's architecture. The framework classe s used in th e desig n a re part of an a ppl icati o n's arc h itecture , as show n in the figu re. The domain classes are usuall y part of th e d e ta iled d esig n si nce they arc speCific to the ap pl ication and are not architectural in nature .
15,4 IEEE STANDARDS FOR EXPRESSING DESIGNS The IEEE So ftware D esig n Docum e n t (SO D ) sta ndard 10 16· 1998 provi des guid e lines for the documentation of design. The table o f con ten ts is shown In Figu re 15. 14 . IEEE guideli ne explain how the SOD could be organi zed fo r va n ous arc h itectural styles , most of w h ich are deSCribed above . The case study uses the IEEE standard, WIth a few mo d ifica tio ns, to account fo r a n e mphas is o n th e o bject·on ented perspective As show n In F'gu re 15 14, Sections I t hrough 5 ca n be co n id ered software arc h itecture , and Secllo n 6 ca n be considered the detailed design, to be covered in th e next c hapter.
15.5 SUMMARY Softwa re desig n 's a mo d el of the ,ntended oftware appllca " on , as spc , Aed by its req uire me nts A software design is analogous to the b luepri nts of a house. Good software designs should ex h,b,t the fo llowing c haracteri tI d; , u nders tandab diry, modu lar· ,ty, high cohesion , low coupl, n!!, robust ness, flcX lb d,ty, reu,abi l, ty, ",forma tio n I" di ng, err, ,en y , and re habll l!}', Whe n expreSSI ng a software dcs l!!n, ill S he lpfu l to use evera l d iffe re nt conne ted VICW , or mo dels use .. se model de nbes what the app hcatlon I< ,ntended to do from the po,nt of view of th ~ 11 er _ eql1en e
359
360
CHAPTeR 15 PRINCIPLES OF SOFTWARE DESIGN
d,agra m< arc de ri ved fro m u\e a es and de< rlbe ubJecl' and the
•
<.:ustom tzal Ion.
1S.6 EXERCISES I . Write a pa ragrap h deSCri bi ng what a "so hwa re de ig n" is, and why it IS impo rtant . 2. In YOllr o wn wo rds, defi ne th e goals of software desig n and ex plai n why each goal is important. 3. In yo ur own wo rds, de Ane the fo ll OWin g term s; nl odufnrily , coh" io" , and coupli"g. Why is each a desirable property of software designs7 4. Ca n a design be cohesive and exhibit a high degree of coupling7 Explain your answer and provi de an exam ple .
5. H ow might coupl ing and reusability be relatcd7 H o w might cohesion and re usabi lity be related7 Explain your answer and provide o ne example fo r each . 6. In your own wo rds, expla in what is meant by robus/II"' . Belo w is code fo r a meth od dioid,(). Make the method mo re ro bust in at least two ways.
public double divide ( Double aNumerator, Double aDenominator ) {
return aNumerator. doubleValue ( ) / aDenominator. doubleValue () ; }
7. U si ng the Internet, research o ne of the many Java API framewo rks (e .g., Sw ing, JMF, 20 , 3D ) In a few paragraphs, describe the design of the framework and how it accommodates re u e. 8. Provide a modulari za tion fo r an appl icatio n that advises clients o n stock picks, and enables them to tra nsfer funds am o ng vari ous stocks and savi ngs accounts. Expl ai n yo ur solu tio n. Hi" k One reasonabl e solutio n employs fo ur packages.
Language
Planning
y
- j Maintenance
•
Whal is Ihe UML notalion lor classes and packages of classes?
•
How does UML represenl class
relahonships such as Int:lentance,
• The Software Development Life Cycle
Requirements analysis
aggregallon, and dependency?
•
What IS a sequence diagram?
•
How do UML achvily diagrams relale 10 lIow charts?
088lgn
Figure 16.1 The context and learning goals for UliS chapter
Reca ll that a "software des,gn" I a reprc
gra phical reprc ~c nt a tl o n of oftwa re deS ign, la<"" , lor exa mple , now needcd I" he rq I'l'
362
CHAPTER i6
THE UNiFiED MODELING LANGUAGE
Canister ~-- Class name / _- -..- n-u-rn""'C"'a- n-;l""' st:e--rs-:7In"t- - numWafers: int - - Anribute: type .. :Vlsible . size: noat Irom without .. dlsplayO ~_ _ Operations , _ ' . getNumOpenSlotsO .. setStatusO ResponSibilities: -- describes each
canister unde rgoing fabrication
Place for ~--
comments
Figure 16.2 Class details in UML
Croup consortium of compa nies (www.o mg .org ), and ta kes hundreds of pages 10 formally specify. As a result, UML tends to be incl usive (some say too muc h so), incorporating da ta flow and , in effect , flowcharts; but It contains much more that we do not have s pace in this book to include . The part> that we do cover, however are adequate for m ost of o ur needs . UML is an excell ent ste p in the direction of imp roving software engi neering, but wi ll probably be improved upo n as the d isc ipltne evolves. The c hapter describes class relatio nships in UML, includin g inherita nce (Class Models, Section t 6.2 ) a wa y to represent control among fu nc tio ns (Seque nce Diagrams, Sectio n 16 .5 ), diagrams of state , events, and transitions (Section 16.6), its moderni zatio n o f fl ow c harts (Ac tiv ity Diagrams , Sec tion 16 .7 ), a nd finally data flow diagrams (Sectio n 16 .8 ). Section 16 .9 shows an exampl e that combines these.
16.1 CLASSES IN UMl Classes in UML are represented by rectangles o ntain ing the class name at a minimum . The detailed version includes attribute and operatio n names, signii Nres, visibility, return types, and so o n. Figure 16.2 shows a clas from the detailed design of an application that controls the Aow in a chip man ufactu nn g plant of canisters holding wafers Not all of the attributes need be specified in the class model. Wle show as much detai l as nceded, neither more nor less. Showing more deta il clutters a diagram and can make It h arde r to understand. Some required attributes may be left 10 the discretio n of the implementers. It is also commo n to o m it accessor hrnctions from class model (e .g ., gelSiu() and sctSize()) si nce these can be inferred from the pre ence of the corresponding attributes (,m). As an example of a class , co nsi de r an application tha t as ists the u er in drawing a Simple figure of a person using geo metric shapes. We'd probably want a Rectangle class for this with attributes such as 'm9th and h".dlh. Since the app licatio n is supposed to be smart, we'd want it to use the concept of a foot (e.g., to kno'" where feet bel o ng), so we'd probably want a Foot class. By int rodUC ing these c1asse , we arc improVing the cohesion of related parts, such as the attributes of a foot , the understandability of the dl" Ign , and ,ts mo dularity . W e are also hiding information until it's needed . Thi example will be explored a \~e go through this c hapter, and will be described as a whole in cetion 169
16.2 CLASS RELATIONSHIPS IN UMl This sectio n discusses the way In whIch UML collec t< cla«es and such rel.tionships call ed associations.
In
packages It .lso inllod" es
CLASS RELAnONSHIPS IN UMl
and
" ,
pllClulge of classes
-"
.. -
myPackage
mySubPackage
.
" '-
-
class MyFIrstClass ( ... )
'w,, _ •
1
MyClass
.I·
....,_ . .
_..
-•
package myPackage.mySubPackage; class MyClass ( ... )
subpackage / - hidden-
MyFlrslClass -'
./
Bcccess/blllty of classes from outside package -'---
IC visible »
•
public package myPackage; class MySecondClass ( .. . )
-,
MySecondClass
/
~
Figure 16.3 UMl notation for packages and Java implementation
16.2.1 packages The U nified Modeling La nguage uses the te rm Pllckng, for collecting desig n elements suc h as classes. UML packages can contain subpac ka ges , or an y material s associated with an applicatio n, Includ ing source code, designs, documentati o n , and so o n. Figure 16.3 shows the UML nota ti o n for packages a nd sub packages. Classes within a package can be speCified as access ible o r as inaccessi ble fro m code external to the package. "Package" also happens to be the nam e of collectio ns of Java classes. Java packages trans late into file directories; thei r subpac kages decompose into subd irectories, and so o n. The Java implementation of this is shown in Figure 16.3.
16.2.2 Associations Attri butes arc o ne way of sh owi ng the properties of a class, and arc ge nerall y used to de no te si mple types such as integers o r Boolean s. Msocia lioll is an additi o nal method of indi ca tin g clas properties, and is commonly used to denote that objects of two classes de pend on each other in a strucnlra l way . ASSOCIations are drawn with a solid line belween two classes. We ca n a nnota le th e relati o nsh ip, which may be o ne- o r two·way . Twoway associa tions are problematical because we nee d to be sure lhat bo th e nds of the implied info rmat io n are kept consistent. This is illus trated in Figu re 164 . Consider a n application that a Sl tS the use r In drawin g a Sim ple fig ure of a person . We ma y want a FooISb.", class if the sh ape of a foo t needs to be described (promoting the "sufflclc ncy" of the design ). There wouJd be an association between FoorShap, a nd FOOl , indicat ing coupl ing be tween the two Th is example i described as a whole in eClio n 16 9
363
364
CHAPTER 16 niE UNIFIED MODEUNG LANGUAGE
employs
~
Employer •
IS
employed by
,---il
Employee
class Employer ( Employee! J employees; •
• • • •
) class Employee ( Employer! J employers; •
•
• • •
)
Figure 16.4 UML notation for associations
/
16.3 MULTIPLICITY The ends of an association line can be annotated wirh "lI/hipliClty, which describes the numerical relationship. or the number of instances, of each class. For example , consi der the Employ"IEmploy" relationship as shown in
Employ" indicates that each insta nce (object) of an Employ« can be assoCiated w ith 1-3 Instances of an Employ". Conversely , the " I. .• " next to E"p/oy" mean that each instance of an Employer can be associated with a minimum of one Employtr (with no maximum ), In ocher words, the Fi gure 165. The "1..3" next to
I
multiplicity next to a class indicates how many instances of th;n class are associated with one instance of the class at the other end of the association line. A single value ca n be used to indicate an exact number of objects,
If a multiplicity is not present neXl to a class, the assumed value is I . This is also illustrated in Figure 16.5 , which shows that one Employee
IS
associated with exactly one PcnoPlalInfo instance , and vice versa.
16.4 INHERITANCE In UML, illbmlancc desCribes a relationship between classes in ..... hich o ne class assumes the attributes and operations 01 another It is often thought of as an "is·a" rdation ship. Forcxamplc, since an
Employ" "i.-;," Pm"" , we can express their relationship with inheritance by saying thal an Employee inherits from a Person . U"I,L
Employer
employs
1..3
•
~
is employed by
1..•
Employee
, Personallnfo Figure 16.5 Multiplicity of associations In UML •
INHERITANCE
... and
"'-
MyPack8ge package MyPackage: abstract I MyAbstractClass . . . . MyAbslraclClass ---I-~Inheritance
package MyPackage: class MyDerivedClass
MyAbstractClass
r l---. int atl; •
• • • •
void myFunctlon( ReferencedClass r ) (
•
00
)
}
MyDerivedClass an: Int
- - attrllwte
Lm2yF:..u:::n.::c:.:ti::o:.:n~()_....::.°cperatlon
""':::===:::'_-"'/
Figure 16.6 Inheritance in UML and Java implementation
indicates inheritance with an open rriangle. We refer to the class being Inherited from (e.g . PmoH ) as a basc class, the class dOing the inheriting (e.g .• Em ployu ) is a d"ivd class. Figure 16.6 shows an example of a package consistin g of two class. ; MyAhstractClass and MyOmv,dCla ss . with MyO,rivcdClass inheriting from MyAh,tractClass . Abstract classtS-that is, those classes that ca nnot be instantiated into objects are denoted with ital ic . [H !!ifacts are collections of method prototypes (name, parameter ty pes. retum types, and exceptions thrown ) Classes rraliu interfaces by implementing the methods that the interface promises. The UML notatio n IS shown 111 Figure 16.7 It is customary to arrange class models 0 that base classes are physicall y above derived cia se H oweverl this positioning is not necessary in any technical sense .
UML Notation ......
Interiace MyAbstractClass . ...
Interiace
,~ --- - -- - - - -------~, : Mylnterlace :, : myMethod()
.
i
'------7\..------' --------
rsallzsllon I
class MyClass imple,ents Mylnteriace
,,
(
-----------------.. • • • • •
)
I I MyClass myMethod()
Fllllr. 14.7 Interfaces In UML and Java Implementation
365
366
CHAPTER t 6
THE UNIFIED M ODELING LANGUAGE
on
16.4.1 Aggregation Aggrr9alion IS a type of a soci al ion Ih al can be Iho ug hl of as a w ho le- part re lalio nshi p . It IS d e no led wi th an ope n diam ond nexl 10 th e aggregat o r (wh o le ). Agg regalio n ind icates Ih e Slruc lU ra l Inclusio n of objects of o ne cl ass by ano th er, and is usuall y imple me nted by mea ns of a cl ass (w ho le ) ha vi ng a n attribule whose type is the Incilided class (part). Agg rega tio n is sho wn in Fig ure 16.8, w llh bo th Company and Employ"Dirrclory each co nsi der
I
belween Fool and FoolSbapr probabl y turns OUI. mo re specificall y. 10 be an aggregatio n of FootShapt by FOOl. T h iS exa mple is descri bed as a who le in Sec ti o n 16.9
t
16.4.2 Composition Compo' i/ion is a stro nge r fo rm of aggregati o n in wh ic h th e aggregated o bjecl exists o nl y duri ng the lifetim e (and fo r the benefi t o f) th e composi ng object-n o o lher o bject may refe rence it. T he composed obJecl is created and destroyed whe neve r Ihe composi ng objecl is creal ed and de
Company
---
1:
{
Elhpk,yse amp;
,
---
aggreglltlon
-
dB'S
EmployeeDtr. "tory
/\
amp
{ Employee amp;
in! 811; )
'\ ~-
dass Company
•
•
"-
/
• • •
I
Employee
•
emp
my Function()
•
I
aggreglltlon
att: int
f.-..
I
101 a1l;
EmploveeOlrectory
• • • • •
)
att: int
/
"
myFunctionO
fllu re 16.' UML representation of aggregation and Java Implementation .
1
INHERITANCE
Company
composition
att: int , , , , , , , , , , ,
myFunctionO
Employee
,,
• composition
~
/
/
/
emp
"
/ dass Company
class Employee emp: { }
...
• • •
EmployeeDirectory
class EmployeeDirectory { class Employee emp:
{
(.
att: int
. .)
myFunctionO
• •
}
• •
•
•
•
}
/
/
/
/
"
Figure 16.9 UML representation of composition and Java implementation
16.4.3 Dependency
Drp",d",'Y,
denoted with a d o tted line arrow, means t hat o ne class depends upon another In the sense that if
the class at arrow's end were to chan ge. then thi s would affect the dependent class Stnctly speaking, dependency Includes association, aggregation . co mpositio n , and inheritance. However, these relati o nships have their own notati o n , and we usuall y reserve dependen cy to indi cate that a metho d of o ne class utilizes another class, and to relate packages. Thi s is shown in Figure 16. 10.
Dependence: UML Notation ... and ... Typical Implementation MyDependentClass att: int
u
u
•• u
••
_
u u
MyReferencedClass
u
• dependence
myFunctionO
f-------"";"
(reference to s class)
cl... MyDependentClass ( • • • • •
void myFunctionl( MyAelerencedClass r)
•
( • •• )
I
_ _ _ . _ _ __
t.
, --
paramete,
I
MyAel.rencedClass myFunction2( ... )
( . .. )
I
- , - - -- -' or relum type
void myFuncUon3( ... ) I MyAeferencedClass m ...
)
·~I_______ ~~~
~
or local variable type
)
Figure 16.10 UML reprcsentatlon and Java Implementation of dependence (excluding Inheritance and aggregation)
367
368
CHAPTER 16
THE UNIFIED MODEUNG lANGUAGE
CustomerMailAppllcatlon
customer
goneraleMaliO getCuslomerTypeFromUser() malnO
CuSfomor
1
eleateMallO
r ,,_ I
I
... - - _
--,
',--
I
I
,
""
I I
""
- ---
DelinguentCustomer
MountalnCuslomer
createMailO
crealeMaliO
--- ---
--
RegularCu stomer creat.Mail()
Cus1omerMailApplication
generateMaliO getCuslomerTypeFromUserO malnO
customer
1
Customer eleateMa/tO
Figure 16.1 1 Exa mple of a class diagram (class model) for a customer mall application
16 .4.4 Class Diagrams Class diagrams help us to vi,ualize the des'gn of applicatio ns. They describe the ty lX"S of objects in the application, thm amibutes and ope"'tions, and the sta tic rciatio nsh ips between them I l l. Co nSIder an applica tio n produCIng e· mail text fo r various kinds of customers. A possi ble UML class diagram IS show n in Figure 16. 1 1. It says that the class ( uslommvlmlApp"Ca llo" has a variable named customer, which is of type Customer. Since ( £Islam" is abstract, the custom" va nablc IS either a DclmqunltCuslomrr, MOttntainCU51omcr, or RtgularCuslom« When nUlomcr.ma frMnil() is called, o ne of the three versions of crwfll\1ailO is called, depending o n the class that cu, 'omer belongs 10. The stre ng th of class diagr.m s is that they help us to envisage th e buildtns blocks of an application . Note , howeve r, that they do no t indicate the way in which the appli cari o n execu tes. In the C usto me r Mail Appl ica tion class model , fo r exa mple, there is no way to tell w hat me th od execu tes after mai.t(). Sequence dtagrams, d iscussed in Sectio n 16.5, prov,de this capabi lity .
16.4.5 Object Diagrams An object diagram shows objec ts and th ei r relat ionships. A n objec t is a particular realization of a class , so
object models arc dCTlved from class model s There .re many possi ble o bject model s deriving from a class model. Fo r example, let's retum to th e class mode l in Figure 16.4 . Figure 16 . 12 ho ws o ne objec t mo del that derives from it . Wh c:: rc::as class models are compile -time rel atio nships, object model s are us ua ll y runtime: relationships. Figu re 16. 12 shows that the o bject njaxCorp Co,"pa"y employ th e objects ,"c,Employ« .nd joe, Employ« It .Iso sh ows that the o b ject ahcCorp·Compa"y employs th e objec t Joc.Em ploy«.
16.5 SEQUENCE DIAGRAMS
Use cases arc a good complement to classes because they de fi ne steps through wh,ch a use r and an ap pltcation transi tion . To use them i n design, however. we refine them into a more:: technical fann So that class and
methods that enable them can be ident,fied. In .ddition , there arc many «que nce of 'C(,on ' th.t applications
I
SEQUENCE DIAGRAMS Class Model
IEmployer I
t ..n
1..3
IEmployee I
One Particular Derived Object Model
sue:Employee ajaxCorp:Employer jjOe:Employee abcCorp:Employer Figure 16.12 Example of a class model and a particular object model in UML derived from it
need to be designed for but are not use cases. The number of possible sequences o( (unction ca ll s even common ones-is very large, whereas the number of use cases is kept relativel y small (4- 20 (or small jobs and at most hundreds for extremely large ones). Sequence diagrams are graphical represe ntati o ns o( control Aow, and are particularly useful for describing executions that involve several object" as found tn the sce nario of a u e case. Sequence diagrams rcquire us to think tn terms of objects and funct io ns. The lifctime of each object involved is shown as a solid vertical line, with the name of the object and ItS class al Ihe top . Each tnl eraclio n between objects is shown by means o( a horizontal arrow from the objecl initiatJng Ihe service to Ihe objecl sup.plying the servicc. As an example we develop a sequence diagram (or Ihe Ch"k 0 141 use ca e for Ihe video store appl ication. Figure 16. 13 shows a beginning sequence diagram (or Ihe usc case. Note 2 Clerk
Originates 'rom use case:
:MainScreen
:BarCodeReader
bar code 2. Applicalion prompls
1. User swipes
order
for rental duration 3. User enters duration ...
doCheckoul0
:Checkoul0ptionDisplay readO I
Step 1 01 use case
NOle 3 :Checkout
,
Step 2 01
usecas8
InltlaleO Note 4
NOle 1
I
ShowO
I I I I I I I
•
flcure 16.13 Beginning of a sequence diagram for Check Out use case In Video store design
369
370
CHAPTER 16
THE UNIFIED MODEUNG LANGUAGE
The (01l0w\I'8 no te explain the cOlTCspol1ding (ca tllrcs o ( the d,a grn rn ' a te I · In a
o tc 2 U sc cases Jrc 1Illtliltcd either by the use r, as thi S o nc IS, or by (In o bj ec t I nitiation bcgin at the to p Icft of the dia g ram , a nd a solid verti ca l linc be neat h thIS sy mbo l IS drawn to ,nd,ca te that thc e ntit ), alread y eX ists W e ca n uppl y preconditions to specify assumpti o ns that apply at the incep t ion of the ,equencc. Note 3· cqllc ncc diagrams sho w the initia ti on and execution
or il sequence or functions. The
obj ec t at th e be gi nning of each arrow {t1 ilra lC5 work , the objec t a l [h e en d of the arro w ca m(s Old the
wo rk 0 1 th e me th o d Ind icated . Eac h clo ogated recta ng le den o tes the execu tio n of a meth o d o ( the ccrrc~ pondlOg o bject In o ur Ch,ek Q", seq uence diagra m, the clerk initiates the seco nd (un c tion by swipin g the bar code reader over the VIdeo. \Vle then determ ine w ho o r what should execu te th e respo nd ing function . Since a
bar code reader recognizes a swipe, we may decide that a Bar od,Rtadcr o bject would be approp riate (or d ealing With actions relat ing to the ph ys ical re ader, and th at th e requ ired fun ction o( Ba,Cod,R,adcr will be nam ed "adO. There will be o nl y one BarCodcRcadcr objec t (or the entire application, so the no tat io n ",BarCodcRcadcr" to rep rese nt th is o bject is su(RcierH . There is no need to nome a BarCod,R,adcr object; we ma y deCide la te r to make the "adO method o( 13a,Cod,R,adrr static, in whic h case no actua l BarCod,R,adrr object would be invo lved Note 4· We can ca pture the c h eckout process with a Grekoul class. The BarCoJ,Rcadrr o bject then c reates a Grekoul o bject. We h ave used a fac tory meth od iHiliat' O here to create and initia lize the
:MainScreen
User
I
:BarCodeReader
:CheckoutOplionDisplay
doCheekoutO
I
1.
:Checkoul
II
:Account
I
2. t inlliateO
2.2 ereateO 2.3 showO 3. setDuralionO This sequence diagram originates from Use case:
t. User swipes bar oode 2. AppllC8tion prompts lor rental duration 3. User enters duration 4. AppllcaUon
stores record
5. Application prints C\Jstomer's account status
--
Figure 16.14 sequence diagram for Check Ouf use case In video store design
4.
storeO
I
I
SEQUENCE DIAGRAMS
Player
ncounter
Game
Ireddie: mainPlayer· ForeignCharact er Character. PlayerCharacter I I I I I I I create and display I move
I I I I
create and display move
I
U
figure 16.1 S A sequence diagram showing concurrence
Chtcko"t object. The method j"jtlat'() then creates a display for choosing checkout optio ns and shows it on the co nsole . A comple le sequence diagram for the usc case is given "' Figure 16 t 4. In the previous sequence diagrams, the solid arrow head indica te s)"I(I](ollo"s method ca ll s, meaning that the caller receives control back when an operation is comple[c. Sequence diagra ms show aSYJlcbrollous
messages using either stick arrow heads o r half·arrows. An asynchronous message means that the caller does not wait for an opera ti o n to complete. InSlead, control returns immediatd y back to the caller and th e result . if any, is processed at a later time. The called method executes in a separate thread, either by spaw r.ing a new thread or executing wi!hin an existing thread. The elongated recta ngle at the end of the arrow represents a thread that executes in parallel. As an example , we migh t want the game characters of Encounter to move independently from area to area during the action . This is shown in Figure 16. 15 with both a PlayrrClJaractrr and ForrigilCharactrr runn ing in epa rate threads . Figures 16. 16 and 16. 17 summarize the steps needed to create a sequence diagram . When the initia to r is the user, a simple label at the to p suffkes, rather than a rectangle. Note that the object responsi ble for executing the method named o n the arrow is at the O ld (no t the begin ning ) of the arrow. 1. Identify the use case whose sequence diagram you will build (il applicable) 2. Identify which entity initiates the use case - lne user, or - an object 01 a class
." . "... . ..
myObject :M Class
'
'
• name thO ob;oct, if posSJb&e
"
3. II not the user. draw a rectangle to represent Ihls Initiating object at lelt toP .. ........ .. .. , • - use UML ob/«l:C/sss notallon ~ ~ : 4. Draw an elongated rectangle beneath this to represent ' Ihe execullOn 01 the operation I n ~iating Ihe process • • 5, Draw an arrow pointing right Irom it • •
'.
Fl&ure 16.16 Steps for building a sequence Oiagram, 1 012
•
371
372
CtiAPTER 16
THE UNIFIED MODELING LANGUAGE
operation initiated
.
myObJeC1 1 ;MyClass l
myObJect :MyClass
6. Identify which onilly handles tho
I I
.... ..
- an objOCI 01 a claM • l'\llmo Ihe Cl.lss
ClPOra6onO
• name tM OOIOC1
7. Labellhe arrow With the name of the operation .... '"
.... ...
,
8. Show a process beginning. uSing
an elongated rectang le
. .....
••
.. .
..
. •
.•
•
'
.. .
"
I
•
• •
9 ...... ConUnue with each new statement of the use case
Figure 16.17 Steps for building a seQuence diagram. 2 of 2
16.6 STATE DIAGRAMS We intro du ced th e co ncepr of state and transi tion s In C hapte r 11 as a way lO some times express requi reme nts A slale diagram shows the states of the objects of a class , the eve nts to which th e object arc sensitive , and the resultin g transitio ns between rhem , State di ag ram s are also kn o wn as sfa lc-Iransihou diagrams o r Slllftcharts .
16.6.1 States and Substates In UML. sub>!ates of a statc arc Impl y show n as nested rounded rectangles. Figure 16. 18 sho ws the states and su bstatcs th at ma y be present '" an O. /i",Shopprr class. It shows that while a sho ppe r is c hecking out , she can be having her c redit valida ted . The stall" 1l1complclt indIcates tha t the shopper has signaled a readiness to check out but has not yet subm itted credIt card info nmation. The black dot and arrow ind icate that O"/"" S/JOpp,, objects are initiall y In the Browsi.9 statc.
16.6.2 Events In the context of state models, an wrnl is somethin g whose occurrence affects o bjects of the c1uss in question, Exa mples of eve nts arc a butto n click o n a Bultoll o bject or (], chJnge in the value of an o bject's variable.
Browsing
( ltemsChosen )
CheckingOut ( IncomPlete ) ( CreditUnderValidation )
[ CreditDonied
1
Figure 16.'1 States and substates for OnllneShOpper class
[ Complete
1
STATE DIAGRAMS
{credit card ~ data Incomplete]
Incomplete I- Hit Sub;'it _ __ bunon
{credit card data complete]
.. ( CreditUnderValidation )
Figure 16.19 Conditions on events in UML and the resulting difference in transitions
16.6.3 Transitions An event may cause an object to !rtmSlrio" from its current state to another state We denote a tran si ti on with an
arrow, labeled with the name of the event causmg the transi ti o n. Fo r example. when a S/'opptr o bject In IH complcie state subm its valid credit card informati o n, It transi tions from IH comple'e state to C"d,tU"d"lIalidatio" state Sometimes, when an obj ect is in a gi ven stJte and an event occu rs, th e object can transition to one
or
several states, depending on a co"diho" . For example, when a sho pper submits credit card Informallon (by clicking the mouse or hirtlOg r"t" ), the resulting tran sit io n depends o n whether o r not the d ata are compl ete. As shown in Figure, 6. ' 9, conditions arc deno ted by square bracke ts In UML.
16.6.4 OnlineShopper State Diagram Example A complete state · transition dia g ram fo r the O"li",Shoppcr is sh o wn in Figure' 6.20 When the Shopptr o bject enters the ChcckingOut state, It automatically en ters the substate Incomplete (mo re preCisely, Ch, kingOul.
IH compl"c).
select item
put back last item
Browsing _ _ _ select item - -
(credit card data
ltemsChosen
Hit checkou' buNon
Incomplete hit
hit Submit button
)I
Duit hltDK
{credit card da'a complete]
Credit Unde rValida,ion denial received
validation
hilDK
received CreditDenied Comple'e
F1gur. 16.20 State· trans !Jon diagram for OnlineShopper class
373
374
OiAPTER 16
THE UNIFIED MODEUNG LANGUAGE
16.6.5 The Relationship between States and GUts When an oppllcalion IS displaying a CUI , o ne can think 0(" as being in a particular statc Mouse or keyboard OCtion- arc romls thot affect this state. Although we ma y well want to define , totes that do not correspond to CUls, and vice versa , , State-CU I correspondence ca n bc made (or many appi
16.7 ACTIVITY DIAGRAMS Flowcharts arc among thc oldest graphica l met hod (or depicting the Aow o( co ntro l o( algorithm' The UML uses an extended fo nn of Aowchart called Activity Diagram s. The no tali o n (or activity diagrams is shown In Figure 16.21 . This example includes parallelism, shOWing the aClivitles Do" Ta,k and Do AMol/", Ta ,k operating in parallel. Control is no t passed to Do fum Mort until both have completed. Figure 16.22 containS an activity diagram (or a sclNaln'O method , showing the most commonly used Am.chart constructs; decisions (diamo nds ) and proces es (ovals). The fo llowing example shows on act ivi ty diag ram involVinG two classes . It describes the backward chaiOlng algonthm (or expert systems , and illustrates how Aowcharting can be helpful in exp laining complex algorithms. Experl arc usua ll y based on knowledge In the (arm of rules. which take the (orm
,y,',m,
tltltcrtdmt AND QulcccdrJ11 AND . .. AND (wtcccdrtl l
~ cO lI scq utHf
",here Qtllcccd(J1 IS and cotlscqumls arc Jacls. For example . animal is mammal AND QtII"wI
IS
stn'pcd
=> animal is zebra
OUf facts will si mply be string such as "a nimal is mammal."
0 0 Something
00 Something More
[condition true)
OoA Task
0 0 Another Task
else
In
parallel
00 Even More
Agure 16.21 UML actMty chart n01anon
ACTMTY DIAGRAMS
else
Parameter and settings make sense
Nominal pa th
Set name to · delauIlName·
Output notification to console
else
Parameter name 100 long
jkOfeCIIld fN/void SSIName{ s/rifl(JJJName) ( II Check IeQitimacy 01 parameter and senings I/( (1IN.lile = null ) 11 (maxNumChsrs/nName(j <= 0) II (rrwtNumClIars1nName() >a/III meUmitOINameLM>gthO ) ) ( name ;: new String( -ds{aultNa",. - );
S)sta II.out.printin
Sel name to parameter
Truncate name
( ·clelau/lNllme seIecIed byGa/n8Chamcter.selNameO·); }
Me II TruncaIB IfaName too long l/(aName.lBngthO >maxNumChsrs/nNameO ) name = new Stnng ( aNarne.fJ6tBytesO, 0, maxNumCharslnNamoO ) : else II assign the pammeter name name = new Strlng(aName };
}
Figure 16.22 Activity diagram example
The pro blem is to build a program that, given the fo llow in g,
B, 0 , and • a ilst of fact s, such as -A, -
.
• a list of rules such as A..R=:-L, - AkB=:-C, - and B.. C=:- -R det
We will store the current list o f known facts as a static Vrclor of Fa I ea llcd jacILi" , ond Ihe ),st of known rules as a static Veclor of Ruf, called ",frllasr . We wi ll simplify the elup of these lists by hard coding the example given above In the Facl and Rulr cla« es. T il i, Is hown in Figure 16.23. O ur emphaSis IS o n the harder part · the "backcha ining" algorithm provrBack() fo r establishing whether o r not a given fact, wh ic h we Will name sou9/' IFacl, call be deduced from the given facts and rules A 1I0wch,rt '" thiS algorirhm is shown In Figure 16 24 Th is aCll vlty d' .lI'am he lp< to Si mplify an o d, erw lse complex algofl th m. An in pc tlo n 01the ,el1 " "" diallram mlg hl un ove r th e fa t lh . I " fads to tenTI ln.tc If Ihere " a "u lar haln In the ru le b.'1: su h a< X =:> Y and Y ~ X
375
376
CHAPTER 16 THE UNIFIED MODElING LANGUAGE
static ruloBase
slaUc I.CILIsl ~ Facl conlent addFaclO proveBackO
1
consequent
l..n
antecedents
Rule addRule() proveAnlecedenls() lorwardChaJnO
I
--------------------- )
Sel Facl.laclLisl 10 Ihe known lacls and a Rule,ruleBase to Ihe known rules, Creale Facl objec1 soughtFacl Execule soughIFact,proveBack( ruleBase );
Figure 16,23 A class model for chaining rules In expert systems
Facl
I I I I
Rule else
I I I
in lactUst
I
I I
I I
I I I I I I I
Another rule R exists with sough/Fact as its consequent
Apply R,prDveAnlecedents() •
else
Report FALSE
I I
I proof succeeded
else
I ,--_ _--, I
RepMTRUE :
• Prove that every
antecedent fact is true
• Figure 16,2 4 Activity for soughlFact.proveBackO involving two classes
16.8 DATA FLOW MODELS D.ta Aow models wer< intToduced in Ch.pter II when we discussed requirements, Rec.llth.t they consi t of aclia", . each of which takes place at a "odt . The UML not.t,on for thIs is exemplofied in Figure 1625. Each node ha s Input and ourput pi"s indicating the corresponding data type . Data stores are shown with rectangles
and a data"o", stereotype,
A DESIGN EXAMPLE WITH UML
Parts lisl
Parts lisl Part order
Process
Price lisl
part order Credil card dala
Charge credit card
Ship part order
Charge amount
.. datastore .. Charge amount
Figure 16.25 Data flow models in UML an example source' ADopted f,om Jacobson. IVar, Grady Booch ana James Rumoaugh. "The UnIfied SOftware Development Process," (AOOISOIl·Wes!ey Object Technology seria). AMISOn-WE s!ey, 1m
16.9 A DESIGN EXAMPLE WITH UMl As an example that illustrates several parts of the UML notatio n in this chapter, consider a graphics studio specializing in drawing stick peop le. A CUI for this is dlustratcd in Figure 16 .26. We will focus only on the "foot" requirements. Certainly, there is a need for Rtela"gl, and Elll psr clas os. The first question is whether we need a Fool class. When we drag a rectangle near the end of a leg, the application has to know that we want it to be placed at the end o f that leg In a standard positio n. Althoug h it may well be possible to do this without the application ·'knowlI1!;·' about leg- and fee t, it IS muc h c'asier to
D 0
0
Facilitate dra wing stick figures
0
Drag to vicinity to auto-complete
0
Feet can be rectangles or ellipses
o
(Rest to be specified)
0
6
Releasing dragged Ilgure anywhere In this area causes illo appear in posltlon al end 01 lell leg
Fllur. 16.26 Specifications (or figure.-drawlng example appllcallon
377
378
CHAPTER 16
THE UNIFIED MODELING LANGUAGE
Rectangle
Ellipse
Fool Figure 16.27 Bad attempt at class model for "A foot Is either an ellipse of a rectangle" Rectangle
Foot
"" RectangleFool
El hpse Fool
Figure 16.28 Better attempt al class model for "A foot is either an ellipse of a rec1angle" cany out if Ltg and Fool classes arc used . (For exa mple , a lLg object would aggregate a Fool object). The next quesllon IS h ow to re late the classes FOOl, R,clnngl" and EII, plt. Co nside r the pOSSIbility sh ow n in F,gure 16.27. n, is class model says that a Fool object is bot h an e llipse and a rectangle, which is not co rrec t. A berter optio n is th e class model in Figure 16.28 . This mod el is at least not incorrect as the firs t anempt was . It IS a little clumsy , however, in that it prohferates classes (ElIip,tFoot, Rtclangl,Fool, elc.). Th is is nol te nab le (do we need RtaClaJlg/,Ear, elc.I) . It also uses multiple inherita nce, whic h is problematical In general, and not available In Java . Now consider the option shown in F,gure 16.29. This is a reasonable solution excep t fo r o ne very awkward ISSUC : it makes every ElIips( in our application a kind of FoolSbape, a nd likewise fo r every Reelallg/,. For o ne thin S, thi s cenalnl y lim its the reusab ihty of the Ellipst class. For anot her, It is rather strange to Ihink of ellipses as FoolShapes in any case. Finally, if we continue with thi s, Ellipst ma y also have to be a HnJldShnpe objec t etc. One way to deal WIth t hese problems i fo r FoolShape to depend only "lightl y· on Elliplt and Reclangle as sh own In Figure 16. 30. Foot
FootShape
...-..•. ".
....v
.-
Ellipse
.'
./
/' , .' " ",
..... . .~
'"
"
'.
I Reclangle
Figure 16.29 Another atremp, at class model for "A foot Is either an ellipse of a rec1angle" FootShape I drawAsE llipseO drawAsRectangle(h
Foot drawO I I
, Ellipse draw()
\ \
Rectangle drawo
Figure 16.30 Best atteillpt so far at class model for "A foot Is either an ellipse of a rectangle"
A DESIGN EXAMPLE WITH UMl
Area releaseCursorO
,, ,,
~-------------
-
"- ,
,
- - - - - - - GeometricFigure ~~
leg
,,
,,
,,
/
~
~
FoolShape drawAsEilipseO drawAsReclangleO
Fool draw()
,, Ellipse drawO
~
---
, ....
-- ---
-- --
....-~ ........ ....
-------------
/
-- /
/
/
/
'~-..,
p OSition ,-:
'
"-
....
....
.... . . ..
" - - - - - - - - -....
Reclangle drawO
Figure 16.31 A class model showing all dependenc ies in drawing application class model
This class model shows that the restrictions o n the shape of Fool objects are rentcted in the methods of FooIShap, . They reference only Ellips< and Rtclallg/, at this point , but can readily be augmented to accept other geometric shapes. We can no w fill in more detai ls, as shown in Figure 16.31 . The Area's rt/,as,(ursorO method handles the auto-placement (at th e end of legs in the cases shown ), and this information is passed along to the anatomical object (Fool in th is case ); olherwise the drau10 of Ellip s, and Rtclallg/, are used to do actual drawing . The class Posilion could be avoided . It contain the x- and y -coordinates. For example, drawAsEllips,(Posilioll oPosilioll) in FoolShap, cou ld have the following form .
void dr awAsEllipse ( Posit ion aPosition ) {
Ellipse ellipse: new Ellipse ();
II the dependency shown in the
ellipse _draw( aPosition ) ;
c lass model II the actual work drawing the ellipse
. . . . }
Showing a ll of the dependencies in a class model can make for a complicated diagram , and for this reason dependencies are often omitted. (This i< perhaps like swee ping thinSs under th e rug l) The sequence diagram in Figure 16,32 specifics how the classes and methods work together, and show< details aboUl parameters The sequen e diagram speclAcs that when a geometric Agu re IS dragged to an area and the cursor It released , the "ttllS' u" orO method of Arm execu tes with Ihe C,om,'n',Fig"rr as parameter The At,a Obll'Ct deduces which anatomical obje t IS Involved (Fool in thiS case), <0 It ca lls upon that obie t to dra, ",elf, It als o knows whar gcometn form IS required
379
380
CHAPTER 16 "!'HE UNIFIED MODEUNG LANGUAGE
:FoolShape
:Fool
:Area
: Ellipse I
-----+.,., releaseCursor
( GeomelncFigure aGeomelncFigure)
draw ( Leg .Leg, GeometrlcFlgure aGeomelrlcFigure)
drawAsEllipse'
( PositIon aPosition) draw( aPosihon)
I I I I I
, or drawAsRectangle() ...
Figure 16.32 Sequence diagram lor figure drawing application
16.10 SUMMARY The Unified Mo deling Language (UML ) is a widely accepted graphi cal nolation for expressing object oriented designs. UML defines several ways classes can be related TI,ese are sum marized in Figure 16.33 . UML models are diagram that show either th e cla.sses of a software design and how they are related , o r the Aow of control 01 a design . Figure 16.34 summarizes the UML models covered in this chapler.
• Package • Group of related classes • Inheritance
• Take on attributes and operations from o ther classes • "is-a" relationship
• For example, an Employee "is-a" Person • Association • Structural relationship between classes
• Aggregation • Structural mclusion of object on one class • "whole -part" relationship
by another
• Composition • Stro nger rorm of aggrega ti on • Included object is created and destroyed when including object is created and destroyed • Dependency • One class depend on another • Changes to depended ·on class aHect dependent class
Figure 16.33 various relatlonships between classes that can be shown In UML class diagrams
/
EXERCISES
• Oass Modds • class~s of a design and their ~ I ation sh ip • Obj«t Modd • obj«ts of a desIgn and their relationship • Sequence Diagrams • seque nc~ of method ca lls among object • usually corresponds to a usc ca e • State Diagrams • states of a design clement • transitions among states caused
by
events
• Activity Diagrams • Row of contro l • si milar to Row charts • Data Flow Model • show processing elements and the data that Row between them Figure 16.34 UML models
16.11 EXERCISES I. Name three major re lati onsh ips that could eXISt between classe A and B. Describe them in your
own words. Express each
10
UML and in a typical Java implementation
2. Explai n the difference between aggrega tIo n and composition. Cive an example to support your answer. 3. Which of the following classes inherit irom whic h7 Exp la In YOllr reasoning.
WOnt1. Ellips<. Al1ilnal. 2DF,gurt. Circ/, 4. D raw the class diagram for the fo llowing code . Explain the correspondence between the code and the diagram .
abstract class A ( ) class B (
B( ) ( ) )
class C extends A (
B b = new B ( ) ; )
5 A library ha, a aile li o n of 'tcm< (boob and magazine ) avai lahle to loan patrons Forea h 'tem ,n the ollection . the system mJ,nt"", dDta about 'IS t,tle, au thor, and unique ,eI In adel,t,on , the
381
382
CHAPIER 16 "!'HE UNIFIED MODELING LANGUAGE
cop right year is malntolned (or books , and the edit io n number I; mo intalned (or magaz ines. Draw a UML clas. diagram representing the library item;. Be sur< to include the required attributes. HI.' U sc in heritance
In
your model
6 Show a class d13 gram (o r an application that displays automobiles. Depending o n the user's request, It dl plays a tYPical Ford, T oyota, or C he vy, tOset herwith Interactive pages o( In(onnation about each We want to be able 10 easil y add new auto mobile brands to the application in the fulUre and to reuse parts o( the deSign where possible. 7. Suppose that your car has a buill ' ln applicalion that dISplays the status of Ihe cngi ne parts at all times. Draw a UML stale diagra m (or Ihe 5larl" class that describes the automo bile's starter o nl y. Explain your reasoning.
N o te that the starter is some times connected to and sometimes disengaged from the car's motor The ~tarter react s to actions involVing the car key. The key ca n be in one of three positions:
vertical , 90·, and I BO·. B. ConSider an applicalion used at a doctor's office. The application schedules patient appointments and maintains patient medical hi stories. Suppose the application design contains an Appomtmrn ! class to lrack appoi ntments, and a Medica /Hillory class (or each patie nt. H ow would yo u draw Ihe U ML class relatio nship between these two classes)
9. Consider Ihe fo llOWing use case for a web e·commerce app lication, Use Case Name, "Select Item" Actor, Shopper Precondition : Actor has req uested product list Sce nario:
I. 2. 3. 4.
Applicati on displays product list User selects item on product list User cl icks "add item to shopping cart" bunon System acknowledges Item placed in shop ping cart
Draw a UML sequence diagram (or this use case. Explain your reasoning. 10. Draw a UML activity diagram for the "Select hem" usc case
In
Exercise 9. Explain your reasoning.
BIBLIOGRAPHY I Fowler, M :mm, "UNLL DIJftIJcJ A Bnt! Ci1Aldt 10 1lH- SwnJnrJ Ob}tcl MoJtli"9LA"9~"gt.~ 3rd ed Addlson-Wnl cy. p 99 , l~' ......... 2. )KOOwn, Ivat. Grady Booch .nd ) OImes RumbOlush, 'Th U'UfitJ SoJIv'4rt DtlHloplflt'n1 P~m." (Addl~n- \\:/ec; lc y O bJcct T C'Chnology Sene'S), Addison · W(1.I~ . 1999
MaIntenance
TIle Sof~vare Development Ufecycfe
Requirements analysis
•
What are examples of a recurnng design purpose?
•
What are ·creational" design patterns?
•
What are "structural'" design pattems?
•
What are
•
Can design panems be thought ot,n
~ behavloral"
desIgn patterns?
terms of roles and basic forms ?
Figure 17.1 The context and learning goals for thiS chapter
DesIgn pauerns co ncern class co mb,n all o ns and accompanyong algonthm, that fu lfill com mOn desIgn purposes Eac h desIgn pallern cx prcs es a desIgn co ncep t rath e r th a n an onllcXlble da , combination The aecompanylnj( algonthms cxpre the pauern's b."e opera ll o n Thl c hap te r" Intended to famolianze the reader w Ith th e purpose, of de
Camma "t al [ I ], th e clas"c ref ·re nce (or the su h) ee t hapt e r I dc
384
CHAPTER 17
SOFlWARE DESIGN PATTERNS
17 .1 EXAMPLES OF A RECURRING DESIGN PURPOSE 17 .1.1 A Simple Example ll,crc are m.ny applica tio ns In whICh w~ defIOe. clas bu, for wh ich oilly onc In"an c wdl be needed As an cxa m pic. householders arc forevcr co n,ernpla'ing ,he moderOl z. " oll of ,helf kl ,chen<, or.en usi ng software '0 vISualize 'he posSibili',cs Usi ng a K,rcim, class would be nalUral. Now suppose ,ha' a reqUirement IS that the applica'ion does not allow ma rc than ooe kllchen to be under conSi derati on. It IS always. good idea for an apphcallon to enforce what it mtends, so the patt ern needed here IS rhe enfo rce ment of th e o ne· in lance .onl y
reqUirement The Singleton design pauern . describcd in ec tl on 17.5. 1, fits th is bill.
17.1 .2 A More Complex Example Let's con 'lnue wi ,h ,he kllchcn application, which we will call Kirch", V"u>tr. "enables ,he user ' 0 first layou t th e parts of a kit chen \v' uhout comm itting to a style. The overall interface
IS
shown in Figure 17 .2.
Here is a usc casco
Layo ut a Kitc hen Preconditi o ns: No ne I.
U5(r clicks o n ,he "wall cabinet" icon.
2 AppllClltiotl displays a wall cabinet in the center o f the work area.
3 Usn reSizes the wall c abinet.
Uscr drags ,he wall cablnc,
'0
a posi tion "' ,he upper half of ,he work arc • .
0 Wall cabinet
menu
.!1 l1
Counter
./ display area
0
styles
Floor cabinet
~
""
Modem
11b[I.,.,;;c;;;;laSS;;;;;;;, ICdl~
,
Anllque
Figure 17.2 Graphical Interface to the KltchenVlewer example application
I~ Arts & Cra". I
EXAMPLES OF A RECURRING DESIGN PURPOSE
UStr rdease the cu~or. 6. Appfiralio" places the w.1I abinct In the nearest conforming position . 7. User clicks o n the "Aoor cabine t" icon . 8 Appfirallo/l display a tloor cabIOet ,n the center o( the work area.
9.
•
••
Once the layout process IS complete, the kitchen appea~ as in the example hown in Figure 17 .3. After a kitchen has been sketc hed 10 the above ",anner, Kilchen V Icwer allows the user to try various styk-s (or the wall cabinets, t100r abine ts, and countertops . When the user selects "Antique," for example, thc design appea~ as in Figure 17.4.
Counlerlop
I 0
,
\
I
0
0
•
\i
0
I I
,,
II
,
I 0
0
0
,, ,I I
I 0
0
0
/
, •
Agure 17.3 An example of a kitchen being deSigned with KitchenViewer
. 1. I ,, , "
r -Arts Fllllre , 7.4 selecting an antique style using KltchenViewer
& Crahs
I
385
386
CHAPITR 17
SOFlWARE DESIGN PATIERNS
What are our specific de Ign purposes for Kitchen V,cwcr7 The procedure o f re ndenng the va nous " ylcs IS baSically the ,.me, rega rdl cs, of the style, and we should "01 ha ve mo re than o nc copy of thi S procedure In Our application. In particular, we shou ld avoid code , u h as .he fo ll OWin g
Counter counter = new Counter ( ) ; draw( counter);
This is because no amount of added codc wtll enable thIS to draw va mble rypes of counters at runtime. Better deSign thinking than thIS IS required, and it is usuall y set up ' 0 all ow po/ymorpi",,,, , a Single block of code then executes In severa l possible ways , de pending o n the context O ne approac h IS to dC'sign the kitchen appitcatlon so as to provide a method such as rrndtrKllrbrn(mySly/t}, somehow parame .e riz ing the rendering procedure With a requ ired srylc. We would need to Agure o ut what kind of a thing mySIyI, sho uld be , and how mld"K,lrbm() uses It. Thi . kind of design purpose recurs, and we ca n descnbe it a fo llow . An application mus' ("oPis/ruet aJamily oj objects al nwfin1c; TI}t JfSigtl mu sl mabie dJolCt omO.19 srorral farnilltS oj styks.
ThIS purpose can be approached wi th the Abstract Fac tory des ign pattern , which is dis cussed in Section 17 .5 2.
17.2 AN INIRODUCTION TO DESIGN PATTERNS To illustrate how patlcrns express ideas, think about how yOll might describe your housing prefere nces to a realtor. The term "ranch style," ror example, denotes a usefu l hOllse pattern . It conveys an idea rather than a
completely specific de ign.
17,2.1 Example Application: Without Applying Design Patterns As an example of a so ftware deS ig n pattern , let's rcturn to the Kitchen V icwe r example . Reca ll that we wan1
to be able to provide a method such as rtlldtrKllrh,"(mySIy/,). Now we need to ela borate on what mySIy/' means
The method 'rnd"Kirrb",() uses the classes K,lrhrn , \VaI/Cab""I , and so on, and we wtll make it a member of a class called 0,,,,1. If we temporarily forgel o ur purpose of parameterIZing the style, the method rtlldtrKilrhrn () would look somethi ng like listing 17. 1. This code would have to be repeated (or every style , result ing in more error. pronc and far less
mai ntainable code . (Sooner or later, code that IS supposed to be duplicated becomes different places.) A class diagram for this would look like Figure 17.5.
In
different
The result is reJ>('tltl vc and complicated. As a result . it is inflexi ble , hard to prove correc t, and hard to reu e.
17 .2.2 Example Application: Applying a Design Pattern Now let's fulfill our KitchenVlewer design purpose by applYing the Abstract Factory deSign pattern. ~ ell assume that some object will have the rcsponSibiliry for creating .he kllchen. Here IS the Key, Instead of that object directly creating AIIriqu,Wal/C,bi.,r objects, for example, a parameterized version of mldtrKil "'"0
AN INTRODUCnON TO DESIGN PATIERNS
17.1 : The method renderKifChen{j in KitchenViewer
II
VERSION IGNORING OUR DESIGN PURPOSES
I I Determine the style · . . I I case statement? II Assume that the antique style was selected .
I I Create the ant ique wall cabinets Ant iqueWallCab inet ant iqueWallCabinet 1 = new Ant iqueWallCab inet () ; Ant iqueWallCabinet ant iqueWallCabinet2 = new Ant iqueWallCabinet () ; •
•
•
II Create the antique floor cabinets AntiqueFloorCabinet ant iqueF loorCabinet 1 = new AntiqueFloorCabinet () ;
AntiqueFl.oorCabinet antiqueFloorCabinet2 = new Antiqu eF l oorCabinet () ; •
•
•
I I Create the kitchen object, assuming the existence of
add()
methods
Kitchen antiqueKitchen = new Kitchen(); antiqueKitchen.add( antiqueWallCabinetl, . . . ); II rest of parameters specify location antiqueKitchen.add ( antiqueWallCabinet2, . . . ); •
•
•
antiqueKitchen.add ( antiqueFloorCabinetl, . . . ) ; antiqueKitchen. add ( antiqueFloorCabinet2, . . . ) ; • • •
I I Render •
•
antiqueKitchen
•
ddegate. their creation , replacing phrase. such as the foll owing,
nell Ant iqueWa llCab 1net ( "
//applles o nly to antique style: Replacet with the follo'W'lnq.
myStylo. getwallC~b inet ();
Ilapplles to the s tyl e c hosen at
runtia\C~
AI nuntime, the class of ,.ySlylt determines lh e version of gtlW,,1/ nbilltl() executed , th ereb ' produclllg Ihe approprrate kind of wall ca binct To carry out tl", dclc~at lo n of re<ponsibility, we Introduce a new do s, ,.,hich we'll all KlichtHSlylt, supporting methods gtIWnI/Cn hllltl(), gtlFloor "h,"tl(), and <0 on Kllcht. I It Will
387
388
CHAPTER!7
SOFTWARE DESIGN PAlTERNS
Chent (onderK.tchenO
---- - - - ---
---- --
___ __ - -
Kitchen
WallCsbinot
;
;
;
;
;
;
;
;
;
;
;
;
;
;
I I
/
I
/ /
I
/
I
/
I
/ /
I
/
I I
/
;
/
\
\ \
FlOOrCobFnel
\ \ \ \ \
\
I
/
ModernWaliCabtnet
\"
/
/ ;
I
/
;
;
1\
~"'/
",/
;
;
-- ..,.
I
AnllqueWal1CablnOI
" I I
I I
\
I
I
I I
ModemFloorCablnct
AnlJqueFloorCabinel
Figure 17.5 A design for KitchenViewer without design patterns
have subclasses, which we'll name Mod,,,,KSlyl,, A"'iq",KS'yl" and so o n, each supporting se parate imple · mentatio n of g,llVaIlC,bi"ct[), g,IFloorCabi",'(), and so o n This is show n in Figure 17.6. Recall that, due to polymorphism, executing ",yStyk.g"FioorCah",,,() has di ffere nt effects when "'yStyk is an object of ModmtKStyk vetsus an object of AHliq",KStyl,. The class model in Figure 17.7 is a more complete vetsio n. Notice that th e client code rdere nces K, Ich,", K,'ch",Styl" WaliCabi"ct , an d FloorCabi",' , but docs not rde rence pecinc wall cabinet sty les or Ooor cabi net sty les. For example, the class A"liq",W"IlCabi",' does not appear in the clie nt code. T o sec how th is wo rks, let's assume that at runtime, "'ySlyl, is an object of the class Mod,,,,Sryl,. In this case, when the method ","ItrKilch",() executes a statement such as
WallCabinet wallCabinet7 = myStyle, getWallCabinet () ;
WaDCabinet
FIoorCabln8t
C;
lI"IFIooiCabi""'1I
...
AnllqueWallCablnet
,,
gelWatlCab1nelO getFloofCobOnelO
,.,--,---':'::_"'1' ;
getWalICablnel() '
;
AntlquoAoorCablnol ;;
, ModemKSfV1e
.. ....J
.... ,-
gelAoorCabinetO
I AootC'tNl getFlootC.~1() I rerum r4N .'cdllfoRoooc.btnlIO: ) Figure 17.6 The Idea behind the Abstract Factory design pattern
;
AN INTRODUCTION TO DESIGN PATTERNS
Cl"",'
. ..
rendef1(ltChOn( K1tCl'lenSty1e)
,, KItchen
,,• ,
--
~Wo!!('·, ... 1(1
AoorCaolnot
,
I '--...n I'lIIiW U:OC'l.,hrwl.O.
M odemKS!y!e
ModcmWallCtlbln81 • •
•
'. •
Anllgue KStyie getWauCablnel()
••
• • •
.- - - ' - -
•
•
•
•• • • ••
,.
AnllqueWaUCabinet
••
•
••
••
...
••
gelFloorCablnelO
AntiqueAoorCablnel
Figure 17.7 The Abstract Factory design pattern applied to KitchenV,ewer the metho d grIWaIlCab"1(rO is the ve rsio n defined ,n the class ModrrnSry/r, and so it actuall y returns a
Mod,rnWa/iobject.
Th. metho d rt1,drrKirch", (Kirr/m,Sry/r n,ySry/r) looks Itke li sting 17 .2 Th is version of rmdcrKird""O is much morc versatile than the pre vIous version since It IS not written fo r any particular sty le . Figure 17.8 de cribes Ihe Abs trac t Fac tory desig n pattern in ge neral.
Ustlng 17.2: The method renderKltchen(KitchenStyle myStyle) in KitchenVlewer
II Create the wall cabinets : Type determined by the class of myStyle WallCabinet wallCabinetl = mYStyle . getWallCabinet () ; WallCabinet wallCabinet2 = myStyl e . getWallCabinet ( ) ; •
•
•
I I Create the floor cabinets : Type determined by the class of myStyle II Create the kitchen object (in the style required) PloorCabinet floorCabinetl = myStyle. get Floor Cabinet () ; Floor Cab inet floor Cabinet 2 = mySty le . get Floor Cab inet ( ) ; •
•
•
Kitchen kitchen = new Kitchen(}; kitchen . add( wallCabinetl , . . . } ; kitchen . add( wallCabinet2 , . . . } ; •
•
•
kitchen.add( floorCabinetl , . . . } ; kitchen . add ( f loorCabinet2 , . . . J ; • • •
389
390
CHAPTER 17
SOFTWARE DESIGN PATIERNS
--
------
Style 9O/CompoilentAO go/Compollom80
CUenl doOper.tion( Stylo mySlylo)
--" -" --.",.
-"-"
""
,;'"
I I I
Collection
\ \
I
\ \
\
I
\
I
\
I
\
I
' " ComponantA l
, Stylel
getComponentAO getComponenLBO
,
ComponentS
,
L,
Style 1CompcmentA
,• , , ,,
,1
Styte2COmponentA
---- ---- -- ' ,- -- - - - --- , --, , $tyle2 ,,
gelComponenlA 0 getComponentB 0
.., Style ! COmponentS
--- -- ------- -- --- --- -- ---
Style2ComponentB
Figure 17.8 The Abstracr Facrory design pattern
The client method JoOpcralloH (Style myS/yle) builds an inslance of Collecrioll in the style indicaled by myStyle by calling mySryle.getCompoH".tAO and myStyle.grtCompolln.tB() . If myStyle is a Styl" object, for example, these two operat.o ns produce Styl" Compo"",tA and Styl" CompolI".tB objects, respectively. The pattern thus ensures a consistent style throughout We have mentioned that desi g n panerns , ho uld no t be rega rded in a literal manner. For example , the desig n," the above figue< could also appear as shown in Figure t7 .9 . In this alternative. Collerrioll aggregates Sty I" CIi",r docs nOl rderence Style directly, doOprratioll O takes no parameters, and Collertioll has methods for getting the vari"us components. Collerrioll', aggregated Styl, obJeci is instantiated at runtime . perhaps with separate se tup code . When JoOprrarioll O calls grtCompolI",tA() in Collrerioll , conlrol is de legated to getCompolI",rA() in the aggregated Styl, object. This is still the Abstract Factory pattern . The Abstrac t Faclory palle", is described in more delail in Section 17.5.2.
17 .3 SUMMARY OF DESIGN PATTERNS BY TYPE : CREATIONAl, STRUCTURAL. AND BEHAVIORAL Gamma et a!. [ 1] classified deSIgn patterns in one of three ca tegones, dependmg upon whether with one of the following , • Creating a colleclion of objects in Aoxible ways (
It
has
10
do
SUMMARY OF DESIGN PATIERNS BY TYPE: CREATIONAl., STRUCTURAl. AND BEHAVIORAl
Client
doOperatlonO
--- -- "-
-
StylB gBtComponentA O getComponentB{)
/
/
Collection
/ /
gelComponentAO gelComponentB()
/
/
,, ,, ,,
/ /
ComponentA
,, ,
CamponentB
7J: , , ,
"'i Style 1ComponentA , ,
Style 1 , Style2ComponentA , getComponentA() , , getCamponentBO - --- , -- - - - ~ ,- , - -- - . - - , Style l CamponentB , Style2 ,, getComponentAO getComponentBO --- -------- - - - ------- --- - Style2ComponentB
---
-
Figure 17.9 The Abstract Factory design pattem alternative
These categones arc useful for recognizing when 0 panern may be needed and as the beg.nning of a guide to sciectlng which one may be appropriate. Next , we wi ll elabo rate on each uSing exam ple applications
17.3.1 Creational Design Patterns Creat.onal design patterns help us to flexibly set up co llecti ons of o bjects for subsequent processing. They allow the creation of seve ral possible collec t.o ns fro m a single block of code, but wllh properties sllch as· • Creating many versions of the collecti on at runtIme • (0"llra'"'"9 the objects created: for exa mple, ensurin g that there' is o nly instonce of its class
Table 17. 1 summanze the use and nature of key creat. ona l dcs.gn pallerns The ab tract factory and SIngleton pallerns are descnbed .n more detail .n sub equent seCll o ns.
17.3.2 Structural Design patterns Structural des.gn pallerns he lp us ' 0 arra nge co lkc llo n of o b,eCt in fo rms such a hnked lISts or trees They are u.dul when we want to manage omplex dala conSISting of ossa iatcd o bject . Table 172 summanzes the u~ and nature of k(1'
de'."
10 wb\Cquent scCClonr. a .. rcprc~e nlallvc: examples
of Slru Ctllfil l
dC:'S18n pattcrn~
391
392
CHAPTER 17 SOFlWARE DESIGN PATTERNS
Table 17 • 1 A summary of key creatlonal design patterns Example Application Purpose Satisfied by This Pattern Design Pattern Name
Approximate Design Purpose Satisfied by This pattern
Design for the following requirements without repeating code unnecessarily. Make the design easy to change.
Outline of the Design pattern
Create objects at runtime WIth flexibility that constructors alone cannot provide.
From a single version of control code, generate mail messages tailored to vanouS custOmers.
Create desired objects by using methods that return the objects.
Create coordinated fam ilIes of objects at runtime, chosen from a set of styles .
Display a ki tchen layout, allowing the user to select a style at runtime. (See Section 17.2.2.)
Encapsulate each family in a class whose methods return objects rn that style.
Prototype
Create an aggregate object in which selected parts are essentially copIes.
Display a kitchen layout. allowing the user to select at runtime a type of wall cabinet. or a type of noor cabinet, etc.
Create the objects ofthe type by cloning a prototype.
Singleton (see Section 17.5.1)
Ensure that a class has at most one InstantIation, accessible throughorJI the application.
Build an application to evaluate the results of a lab experiment Ensure that there is exactly one Experiment object at runtime, and ensure that it can be accessed by any method in the application. (see section 17.5.1.4.)
Make the constructor private and obtain the unique object by means of a public method that returns it.
Factory
Abstract Factory (see Section 17 5.2)
Table 17.2 A summary of key structural design patterns Ex3mple of Design Purposes satisfied by This Pattern DeSign Pattern Name
Approximate Design purposes satisfied by ThlsPattem
Represent a tree of objects.
Composite
Allow client code to access uniform functionality distributed in the subtree rooted by any node.
Decorator
Allow objects and functlonafity to be added to an object 8t runtime.
Design for the following requirements without repeating code unnecessarily. Make the deSign easy to change.
Summary of the Design pattern
Represent the organization chart of a company. Allow client code to call prrntOrganizationOon any Employee object, printing the names of the employee and all subordinates, if any. Allow the additIOn and removal of subtrees at runtime.
Have compoSite objects aggregate other composite objects.
Allow the user of an online clothing store to see his or her Image dressed in a variety of clothes.
Link the objects using aggregation.
(continued )
SUMMARY OF DESIGN PATTERNS BY TYPE: CREATIONAL STRUCTURAL. AND BEHAVIORAL
TIllie 17.2 (continued) Adapter (see section 17.6.2)
Facade (see secuon 17.6.1)
Flyweight
Proxy
Ailowan application to make use of external (e. g., legacy) functionality.
Design a loan application from scratCh. but allow It to use any vendor's classes that compute monthly payment calculations.
intrOduce an inherited Intermediary class relating the application and the class with desired functionality.
Manage software architectures involving large numbers of classes.
Design the architecture of a student loan software application so that one group of developers can concentrate on the loan option database, another on the user Interface (simultaneously). and a thlfd on payment calculations. Minimize coordination problems.
For each package, Introduce an object that IS the sole access to objects within the package.
Obtain the benefits of having a large number of Individual objects withoLit excessive runtime space requirements.
We want to be able to visualize a room with stenciling. There are five stencil patterns but thousaQds of potential stenCil marks on the walls. This might be easy to do if each mark were a separate object. but we can' t afford the memory required, and it's impractical to name all of these separate objects.
Share objects by parameterizing the methods with variables expressing the eontext.
Some methods are remote, or require lots of resources to execute (time or space). Ensure that they can be executed, but no more often than necessary.
Assume that rendering an image consumes a significant amount of time and space because the image data has to be read from a file, fill a buffer, and then be rendered . If the buffer is already filled by a previous invocation of the method, then Invoking the function should not repeat this step.
Introduce a class standing between the requesUng methods and the resource.
17,3,3 Behavjoral Design Patterns When an application runs, much behavior generally occurs among the objects. An example IS when a method in one object calls several methods In an obJcct of a dlHerent class. Sometimcs wc want to control and label behavior 111 order to parameterize it or reuse It Each behaViora l pattern captures a kind of behav ior among a collectio n of objects Let's consider the follOWing example of mutual behaVior among
Ship and TlIgbonl objects
Let's say that we
want to cstimate the amount of lime required to bring sh i ps Into and out of a harbor and tran pon them to dry
dock
for maintenance, based o n their Size, and 0 on Imagine that thIS i, a omplex calcu lation ,hat requires a
systematic simulation o f the ,ransportation process !'igore 17. 10 suggests a configulUt.on The classes
Ship and Tugbonl
are natural closs ch Oices, blll obJcc ts of rhe e lasse, play different role ,
depending on whether 'he ship IS entering , leaVing, or head i ng for d ry d ock applications In which we ca n usc •
SI" p and TIIgboll l, we
111
e th erc arc many pOlentl.1
d o no t wont th e,. la'5e' to depend o n ca h o th er,
J,
"'88«ted by Fil!ure 17. 1 I We have a bchtlvloral design purpose h ere occa u,c we wan' to 'CI>Jfate the interd ependen t behaVior of
(hcse
objects from the objects them,elve, The Mediator design pattern doe, th". Figure 17 12 ,how, the
core Idea of Mediator
393
394
CHAPlER 17 SOFlWARE DESIGN PATIERNS
I
U"
,
~
-
,.-
;.--J hA
h~ obstacles
-- ""
Algorithms express mu tual behavior
'- • "
.,..
\•
,
~ 10 dry dock .;
Figure 17.10 Example of behavioral design goaf-tugboat and ship port entry
Harbor application
Ship
I
1..n
--......:......:- Tugboat
Customs application: reuse Ship alone
ILongshoreman I Figure 17.11 Avoiding design dependency in port entry example
In this deSi gn. Ship and Tugboal classes do not refer to each other Instead. the I.r.. IIIgPo,./ class contro ls how objects of
Ship and Tugboat behave to es timate the tim e for that maneuve r.
The full Mediator pattern allow (or the fact that the mediated clas es may need to com mun ica te (e.g., to respond to events on either of them). T o accomplish th is. the media ted classes ca n be made to subclass a bast' c1a~s that aggregates a genenc media tor class (PortNLsSlOt1 ) TIll S is shown in Figure 17. 13. a te that 111 Figure 17. 13 the Ship class docs depend on the class V",tI , wh, h depends on P0r1Ml5lI0n , so we can not usc the ShIp class wi thout these [Vo'o, These dcpcnclcn ics arc much more acceptable , however, than
Ship LeavingPort eSlimateTImeO
Tugboat Agure 17.12 The Mediator design pattern concept applied to the POrt entry example
SUMMARY OF OESIGN PATIERNS BY TYPE: CREATIONAL STRUCTURAL, ANO BEHAVIORAl.
PortMlssJon
Vessol
eStlmaleTImeO
-z;;
if Med1al0f base class
Ship
Tugboal
Ente ringPort
eSlimateTlme O
LeavlogPort estimate TimeO
-t-
8eingMainlained
eslimaleTimeO
Figure 17.13 Applying the Mediator design pattern to the port entry example having Ship depend for. 1I lime o n Tugboat Ships are always vessel<, and they usually have missions, but they are only someti mes assoCIated w ith tugboats. T able 17.3 summarizes th e usc and nature of key behavioral design pattern . The Interpreter, O bserver, and State patterns are described in more detail in subsequent sections as examples of strucrural design patterns. Table 17.3 A summary of key behavioral design patterns Example of Design purposes Satisfied by this Pattern Approximate Design Pattern Name
Design Purposes satisfied by This pattern
Chain of Responsibility
We want a collection of objects to exhibit functionaltty. At design time we want to be able to easily add or delete objects that handle all or part of the responsibility.
Design a GUI for a Web applicabOn to view automobiles with requested color, etc. The display Is dynamic, depending on the model. etc. chosen. Reuse the GUI parts among the displays.
Link objects to each other via aggregation. Each performs some of the work. and then calls on the next object in the chain to continue the work.
Command
Make the execulton of operations more flexible, For example, enable " undoing."
Allow users of an application to retract their last four decisions at any time (the " undo" problem).
capture each command In a class of its own.
Interpreter SectIon 17.7 1)
Parse an expression.
Design an application that takes as Input an order for a network of PCs, expressed In a standard syntax. The output consIsts of Instructions for assembling the network. (See Section 17.7.1.5)
Introduce a class to capture expressions, and allow expression classes to aggregate expression classes
Design for the following requirements without repeating code unnecessarily. Make the design easy to change.
Summary of the Design pattern
• (continued )
395
396
CHAPTER 17 SOFlWARE DESIGN PATIERNS Table 17 • 3 (contmued) Example of Design Purposes satisfied by This Pattern Approximate Design pattern Name
Design Purposes Satisfied by This pattern
Design for the following requirements without repeating code unnecessarily. Make the
summary of the Design pattem
~ Mediator (see above)
capture the interaction oetween objects without having them reference each other (thus permitting their reuse).
Build an application that estimates the amount of time required to bring ships into and out of a harbor, and to transport them to dry dock for maintenance, but ensure that the Ship and Tugboat classes can be reused separately.
capture each Interaction In a separate class, which aggregates the objects involved.
Observer (see Section 17.7 .2)
A set of objects depends
Keep management, marketing. and operations departments up to date on sales data. Each of these departments has different requirements for the data.
Capture the data source as a class. Allow It to loop through the observer objects, calling an update() method.
State (see Section 17.7.3)
At runtime, vary the effect of invoking an object's methods depends upon the object's state.
Customers fill out an order form on a Web site, and then hit the " enter" button. The result must depend upon the state of the form data: " Product Information Complete," " personal Information Incomplete," " Credit Check In Progress," etc.
Aggregate a class representing the state with operative method dOAction(j. Subclasses effect the reqUired actions of substates With their own versions of doActionO.
Template
Allow an algorithm to execute partial variants at runtime .
Organize the huge number of traffic light algorithms in a city by arranging them into a few basic forms, with variants tailored to specific locations.
Have a base class contain an overall method, but with functlon calls where variability is needed. Have subclasses implement these function calls to capture the reqUired variability.
on the data in a single object. Design a way in which they can be updated when that single object changes attribute values.
17.4 CHARACTERISnCS OF DESIGN PATTERNS; VIEWPOINTS, ROLES, AND LEVELS DeSign pattems are partially described by class d iagra ms, but they also ca n be th oug ht about in two ways. th e stolle and dynamic viewpoin ts of th e pattern. This secti o n cxplui ns these two view polIHs. It also describes th e' (fbstracl and non· abstract (concrclc ) levels of design patterns FI nall y I it' covers the ways I n which de ign patt~rn arc embedded In applications, The st'luic vs. d ynamic vicwpoim~ . ab tra ct '"S. conCret(' levels. and embedding issues are acwally characteristic of mOSI deSig ns, a nd are not Itm itcd to de ign patterns, These characteristics arc su mmarized in Figures 17. 14 and 17. iS .
CHARACTERISTICS OF DESIGN PATIERNS: VIEWPOINTS. ROLES. AND lEVELS
• Ifinopo,"ls-ways to descnbe patterns I . Sialic, class model (building blocks) 2. Dy>lumic, sequence or state diagram (operation)
• wls--
• Roles-the "players" '" pattern u age I. AppllCutloli of the design pattern itse lf 2. Oi,,,I, of the design pattern application 3. S,lup code initialize and controls FIgure 17.14 Some characteristics of design patterns. 1 of 2
(class O( classes)
1.-CII"", - - -role -- "-
_ --
I I I
I I I I
-- ---- --
-- --,..
3. Role: Application of the design panem A. Static viewpoint
B. Dynamic viewpoint
,-------, : A 8 ~ 0) Abstract level
,_-
',.L
:C
I
D
: (iI) Concrete level
DOD
•
_ _ _ _ _ _ _ _ .J
(sequence or stste diagram)
(crass model)
- - - -> : Reference dIrection
(class or classes)
Figure 17.15 Some characteristics of design patterns. 2 of 2
17.4.1 TWo Viewpoints for Describing a Pattern: static and Dynamic DeSign patterns arc dlustrated with class models. showi ng the cia ,cs "wolved and their mutual relation h'l)s, this IS a stallCviewpoint
orthe pallcrn
The function, of thc'\(" c1as .. cs execute:
In
panlCular sequcn c , ho \\revcr,
which class models do not illustrate Th is is the dyn"ntlC ViewpOint 01 the poltern . and reqUire, appropriate means of exprc~slOn .
We'll use the Kit hen V fewer eXJ mplc to IlIlI~lratc the: ~tatlC and dynanll viey,r po lIll\ The StJlI VI(,WPOlllt was shown in Figure 17.7. TIm ViewpOin t doc< not
PI
rure T () cxprc.., .. the
d y namiC VICWpO lIll ,
we often U~l' ... cquence
dlJ 8r.l 1ll'. J" IlIlI,lrillC
I In
397
398
CHAPTER 17 SOFTWARE OESIGN PATTERNS
Cllont
I
I
mvStyle.KlfchoflStyle
,,
rr __ ~m~YS~~~le~.~~~~ ~ Lf. gelWauCabinotO
- IFmyStyte BELONGS TO ModOmKS'Y'<>-
------, waltCablnet I Mode rnWallCa binOI
myStyte: ModemKSlylo
,, ,
rendcrKItcl'len (myStyte )
gOIWallCabinetO MOdomWallCabinotO
l1 I
- IFmyS'Y/o BELONGS TO AnllquoKStyt"', wallCablnel1 : AntlqueWaJICablnel
myS~I. :
AntiqueKSlyle
, ,I
:__~g~.~IW_'~I~IC~'~bi_ne~I~()__~ AnllqueWaliCablnetO
~
'11
I
Figure 17.16 Abstract Factory sequence diagram (or Kitchenviewer Figure 17 16. It shows the dynamic vIewpoint of the KltchenVicwer application of the Abstrac! Factory d«ign pattern .
17.4.2 TWo Layers of a Pattern: Abstract and Concrete allct: that within the KitchcnVlcwer Abstract Factory pattern application , some of the classes are abstract. In conformance with Gamma et al. [ I ] we wi ll ca ll non·abst ra ct classes "concrete." Figure 17. 17
, "
, , ,
" KlfchenSty/e
, , '
, ,"
, ' '
"
,
,
,
•
,
•
• • • • ••
,
-,
Waf/Cabinet
• • •
,
-,
"~ ~...
FloorCsb,oet
Abstract level •• Concrele level ...JO
+
KHchcnJ O
ModemWaUCab'nel MOdomKStyle
,, '
'-
,
" '"
'
" ,
'
"
AntiqueKStyle
AnllqueWaUCablnet
----
"
••
"
'"
• - ,P'.-
, , , , , ,
"
,
•
, , , , ,
,
,
•
•
,
ModemFloorCo.l)(net
-----. ---- ---- -- ---.
Figure 17.17 Concrete and abstract layers in design pattems
, ,
--
AnflqueAootCabtnGt
CHARACTERISTICS OF DESIGN PATIERNS: VIEWPOINTS, ROLES, AND LEVELS
",arrang~ th~ physIcal placement of cia C In F;gure 177 to e mphasIze the abstract and conc rete groupings ailed Ill),'" Th~ mterface of cl,ents with a design palte rn application u ually needs to be at the abstract la yer. This can ~ s~en in the code for rmd"Kitd"!l O, which is wntten in term s of KltchenSt)'le (and doesn', reference ModemKSryle o r A!lloqu,KSt),/e ), W.II .bl/ltl (not ModentWallCabl!lrl o r AHloqueWaIlCabm
17,4.3 Three Roles Involved in Pattern usage: Pattern Application, Client, and setup This section cxplains the th ree pans orroles-on volved in the usage of a desIgn pallem on a design. n,is dIScussion is designed to help the srudenl surmount common problems uSIng design pallerns. The thrce roles arc as fo llows, • The applicati o n of the desig n panem itself • The code that uti /o zes tim application (the "client role") • The code , of required , that inot ializes or changes the desig n panern application (the "setup ro le") These theee ro les arc shown on Figure t 7. 18, and arc explai ned next.
17.4.3.1 The Design Pattern Appl ication Role A design pattem-the desig" pa llcrn appllCn loo,,-involves a specific class model. For example , K,tchenVicwcr, described in this c hapter, contains an appl,cation of the Abstract Factory design paltern Th is is the ubstance of the d~ign pattern .
17.4.3.2 The Client Role Many pans of a program can potentially usc a desig n pattem application We usuall y rde r to these pans as eli", " of the paltem application. Each client is typicall y a method, but we often regard the method's class as the c/oent In
1. Deslgn PaNem Application
2. Client Rote
I Interacts with the design pat/em only through Its Interface r
3. Setull. Rofe No limitations
DPCllent
,,
-
, I, ,
, ,[}:;~--
-- --
Res' of the A[!()tication
,.
--, DPlnterface I
,
,,
, , ,
, ,,
,
Interface to the pattem (frequently abstract; possibly
I
several classes)
---- ------ -- --------.
------
0 0 0 0 0 Flsure 17,18 The three roles Involved In design pa ttern usage
-- -- -
--~
Rest of the design pat/ern application
J
399
400
CHAPTER 17
SOFTWARE DESIGN PA TIERNS
1<,
Ihe K,t henV,ewerd<""lln, for example, the ,,,,dlrK,1 ImtO method chen l of the de
17.4.3.3 The Setup Role The third role involved
the usage of design p.llems is not terribl y Significant. but o ne ca n get co nfused If o ne docs not recog 01 zc its pn:sc ncc: and necessi ty , It co nsists of the code that initiali zes o r hangcs the design pauern applica non code at runtim e. YOli ca n think of th is as a ja nitoria l or housekeeping-role In th e KitchenV,ewer des'gn , fo r example, cI,ents specifically do not reference particular styles, such as Mod,,,,KSry/, Reca ll that rrndrrKilc/'",O takes a Kilc/',,,Slyl, object as parameter, and deliberatel y docs not rderence any subclass of Kilch,,,Sry/c. How arc these speCific style objects selected and instantiatedl Th, s is the task of what we w.ll call the Stlup rol,. In the KitchcnViewer de 'gn, ,t is the code that r« po nd to cl icks o n ,he "Style" buttons ," Figure 17 4 by ,"Slantiallng a Kitcb",Styl, object and calling ,mdrrKitcb,"O wi th this parameter va lue 10
Setup code needs access to man y parts or the applicati o n, is no rmall y runtime inten ivc , and is ty pically no t Intended ror reuse Thi is becau e it tend s to be speci al to th e application and beca use it d epends o n too many other classes. O nc can think of the setup role as not overlappin g ei th er the client o r the design paucrn
application, although both arc possible.
17.5 SELECTED CREATIONAL DESIGN PATTERNS 11,is section dcscnbcs the SIOgleton and Ab tract Factory design patterns as examples of creationa l design pattems.
17 .5.1 Singleton
17.5.1 .1 Design purpose of Singleton •
Alt hough a typica l class allows the crea tion of many insta nct."S at nlntime. we ohen want a class to have exactly o ne instance throughout th e appli cati o n, and no more. For example, many applications maintain a profile of the use r. Often, there is no need fo r more than one U S(( instance at runtime . In f
DeSign Purpose Ensure that th ere is exactl y one insta nce of a class S. Be abl e to obtain the instance from anywht.·re In the appli ca ti o n DeSign Pattern Summary
Make the constructor of 5 private; define a private stallc .tt"bute for 5 of type 5, define a public accessor for it
Figure 17.19 DeSign purpose of Singleton
•
SELECTED CREATIDNAL DESIGN PATTERNS
We ",(er to the desired un ique instantia tion as the ""glrlo" of the class. and the class as a Smgltlo" class.
17.5.1.2 The Singleton Interface for Clients As an example. if an apphcation ha< a U", class as described above, chcnt mothods 'uch as ocrifyAcctSs() .nd snuIbn,,,IToU rr() would require a reference to the Si ngleton of Ustr To get the Si ngleton , they would con t.in • st.tement such. the following :
User user = User . getTheUser ( ) ; This requires that grln"Ustr() is a static method of LIm . NotICe again that a statement such as the (ollowing:
User user = new User () ;
would crea te a truly new U'tr object , fai ling to guara nt ee the require men t that th ere be only o ne U,,, instance.
17.5.1.3 TheS;ngleton Class Model The first issue is· where do we put the sing le insta nce of our class) We wi ll nam e the class in question S. A good place is within 5 itself, as a static variable. So far so good- but the problem is, what's to StOP another pan of the appliCation from including the following sta:emen t
S myVeryOwnlnstanceOfS = new S ( ) ; We prevent this by making thc const ructo r SOprivate. The o nl y remaining ISSUC is a way to obtain the singkton, to do th iS we include in 5 a public statIC acce sor meth od The Singleton design patlern IS actua ll y a specia l case of Factory in which the obje treturned I the o ne and only in tance of the class With the Factory met hod. Si ngleton IS thus in the Delegation form · the method getti ng the Singleton delegates ItS creation to the construc tor. The class model for Si ng leton IS , hown in Figure 17.20. Let's sum up thIS dl
MyOass grISmglrlo"OjMYC/fIl'() Our di'KuSSlo n on Inl(lcton doc not aU Io m.1I ally extend to clients operat ing "' parallel thread" needing a e" to a SlnK'c to ll abJeCl
401
402
CHAPTER 17 SOFTWARE DESIGN PATIERNS
Client
, I I
Singleton Design Pattern
I I I I
MyClass getSingletonOfMyClassO: MyClass
"
slngletonOfMyCla.. -static,.
1
FIgure 17.20 SlI7gleton class model
I . Dcnne a priva,. static member vari.ble of MyCiass of type MyCl.ss private static MyClass sing letonOfMyClas s
II:
new MyClass () ;
2. Make the constructor of MyCiass priv.tc private MyCla.ss () I / .
. . . . constructo r co de . . . . "' / ) ;
3. Dennc a public static mcthod to
.CtcSS
the member
publlC static f1yClass getSingletonOfMyClass ()
I ret.urn singletonOft1yClass ;
I
Figure 17.21 The Singleton design pattern, applied to MyClass
17.5.1.4 Example Singleton Application: "Experiment" Let's look al Ihe following example, An applicalion evaluates the results of lab experiments. The application for this phase does no substantive evaluation . takes no input, and always prints the (ollowlOg message to the console:
Tht analYSIS shows Ibal tin cxptrimrnr was n rtSo~"dj"9 success There is 10 be exactly one Exprri .."" objoct .t runtime, and it can be accessed by any mcthod in the application. Each time the method is called, it displays the following message on the console to verify it was called,
Noting thai the Exptn°".mt si"9'tfon rrjcrmc(d n limcs so
Ittr
The output would havc the appearance ,hown in Figure 17.22 . The simple c1.ss model for this experiment example is shown," Figure '7.20.
E_---
SELECTED CREAnONAL DESIGN PAffiRNS
Output otEng that the Expenmt", si ngleton referenced I tEmes so far The anal
SI
show that the experiment was a reliounding success ..
Figure 17.22 Output for Singleton Expe"ment example
E~ment IheEx~riment;
IClient f- - - - -
Ex
riment
theExperiment
analyzeO getTheExperimenr{): Experiment
.. static ..
reportResultsO
1
Figure 17.23 APplication of Singleton to Experiment example
17.5.2 Abstract Factory Now we turn our attent Eon to the creation ofjamilirs of o bjects. ThE S kEnd of problem was discu< cd En SectEo n 17. 1 using the KitchcnMasrer example.
17.5.2.1 Design Purpose of Abstract Factory Our design purpose here IS to create a fami ly of related o bjects, chosen at runtEme from several pOSSible families. You can ofte n think of a "family" here as a "style" choice . \VIc want to be able to ",nte code that appl ies to these families without committ ing to one parlEcular family . As an example, consider a word processor requirement that all ows th e user to view a document in everal styles Modern word processors all ow users to view documents in a variety of ways, for example, En outli ne form, shOWing only the headings. We w:ll si mpli fy this for Ellustration. TYP Ecal input to our pnmitive word processor i shown En FEgure 17.24 .
- Enter title , My Life
-
- Enter Heading o r '··done", Birth
- Enter Heading or "·done". Ad ulthood
Entcr text
I 8rew up playing in the wood
-+ Emcr text.
- EntC< Headi ng o r "· done· ·don(·
I was born In a sma ll mountaEn hut - Enter Headlni( or "·done·'· Youth
Flcure 17.24 Word processor Interaction,
(toll
1
of 2- lnput
""!ltd )
•
403
404
CHAPTER 17 SOFTWARE DESIGN PAITERNS
1
....
." .
» Enler Ihe style you wanl displayed:
» Enter tile style you want displayed:
big
small
Option 1
,
Option 2 My Lile
--- Title: MY LIFE ---Section 1. - BIRTH -I was born In a mountain hut ." .
Birth I was born in a mountain hut .... Youth
Section 2. - YOUTH ---
I grew up sturdy ".
I grew up sturdy ... Adulthood Section 3. - ADULTHOOD --•• • •
Figure 17.2S Word processor interaction, 2 of 2-output options
The application prints the document in a variety of styles. For si mplicity, we will use ,mall and big styles. In ,mall style output , all headings are in left-justified lowercase a nd end with a colon. In bl!! style they are capitalized with sectio n numbering, and so o n . The tide a nd the various subheadings appear differently in these IWO styles. \VIc can assu me that mo re sty les wi ll be required in the future . The o utput for "small" a nd "big" styles is shown in Figure 17 .25 . \Vle want a design with a clean separation into the wo rd manipulC)tion pan and the srylc choice part. We
capture the various kinds of headings wi th classes In general , a · style" In volves a fa m ily of classes. For example, CapitalStyle ,nvolves the classes Capit"ITit/e , CapilalLc"elrHcndin9 , Ca," laILevei2Hcnding , and so o n, so the proble m is to be able to c ha nge the fa mil y at run time . The purpose of Abstract Factory, as expressed by Gamma et aI. , is as shown ,n Fig ure 17 .26. The rest of this sec tion explains the pattern that fulfills this purpose
Design Purpose "Provide an interface for creating families of related or dependent objects without s pecifying their concrete classes .'"
Design Pattern
Capture fa mily creat ion 10 a clas comaining a facto ry meth od for each class in Ihe fa m ily . Figure 17.26 Design purpose of Absttact Factory
'Erich Gamma e( ai , "D~19n P;1t1C!ms, E1c.mc.'nts of Rcn~ablC' ObJC'cl ·OncmC'd Software: Addi~on . \'(I~.h~y. 1995.
--------------------------------~-------~
SELECTED CREATIONAL DESIGN PATTERNS
Client
Ensemble setAbSlraC1FacloryO doAFunclion()
'"
-"
-"
-"
-" -"
-"
-"
-"
I I I
I I I
\
I
\ \
I
\
\
I
Abstract Factory·
\
Sty leA Factory
......
"" "" ""
\
I I
\\ '<.,. . . . . .......... \ " .......... , "
StyleBFactory
AbstractFactory getAPanl0bjeciO getAPal120bjeciO
""
"
Style ....
..J
• relationships within panem apphcallon not shown
Figure 17.27 The interface to Abstract Factory
17.5.2.2 The Abstract Factory Interface for Clients Oient code has acce£s La the ent ily 10 be co nstructed wilh Ihe fa mll, es We wi ll name Ihis class EII s""bl, In general. The class AbslraclFaclory encapsu lates the sryle of Ihe EII" ..bl, pans. The Inlerface fo r the client has the appearance of Figure 1727 . For a discussion on a narrowe r intcrbce alterna tive using the Facade deSIgn pattern , sec SectIon 17.6. 1. I . Fo r our word processor example , the role of EIIs""bl, would be held by a class such a OocllmClfl, wh,ch
suppo rts methods dependent upo n Slyl, (our Abstract Factory). First the chent or setup code-ha to determine the required sry le, ty pica lly de pend ing o n use r input as in the fo ll ow ,n g
Style currentStyle; ... II interact with the user currentStyle = new SmallStyle ( ) ; _ . . or curren tStyle = new LargeStyle ( ) ; •
•
•
document . setStyle ( currentStyle ) ; O nce the ty le has been sc t, the client makes calls to OocII,"rll l uch do ""'rIIl dlSplay(J. A cia. model for thIS would have the appea rance of F,gure 17 28 . But what does a "sty le" cla.s look hke, and how does it ac hieve our purposesl
17.5.2,3 The Abstract Factory Class Model The Abstract Factory de
405
406
CHAPTER 17
SOFTWARE DESIGN PAITERNS
Document
Slyle
setStyle() display() /
// r---'---, r - - - ' - /' Small Style LargeStyle
/ / /
/
/
/
/
//~----:::-------
--- -r':'" ~~ /
/ //
"
/
•
•
•
• • •
•
/"
IClient
L _ _......:.A.::p:.::P:..li.:.ca.:.t:..io:..n_o .:.'.:.A .:.b:..s:..l.:. ra_C_1
_F._a_cI_o-,ry~
FIgure 17.28 The interface of Abstract Factory applied to word processor example
For th.e "ke of SimpliCIty we wi ll iliustTate this with just one sty le to beglO with . Let's call the class whose complex objects arc to be constructed, ElIsrmblt. pigllre 17.29 shows how E" Stmblt objects are constructed in a style encapsulated as SlyltA . E"s""blt consists of parts, Pari' objects, Pari> objects. and so on. The attribute abslraclFaclory of E" s""blt is instantiated with a SlyltAFaclory objec, 10 ,his case. When a Pari' objec, is required, the gtlAParl,Objtcl() method of abslraelFaclory is c,lIed . The virtual function property implies Ihat the gtIAParl , Objtcl() method of StyltAFaclory is actu,lIy c,lIed, ,nd it returns a ParifStyltA object. Similarly, when griParl2 0 bjtcl() of Ens""blt is called. it returns a Parl>StylcA object. Thus, all of the parts obtained are in the same style . 11,e p,rtial class model is shown in Figure 17.29. The full Absiraci Faclory class model . with two styles (AbslraclFaclory subclasses) is shown in Figure 17.30.
As dIscussed in t'he section above on client intcrf-accs, the client may interface with the AbsrracrFacrory ,nd PariX classes bu, specifically not with Ihe ,ubclasses of Par" . Pari> , and so on .
Ensemble r I 1 1
I
aMb.&::tFaclory
AbstractFactory gelAPan lOblectO golAPar120blectO
1
selAbstract FactoryO doAFunctionO
y Part2
I I
L C.
1 1
1
I I I I I 1 1 1 1
I 1 1
7'i
Part 1
-1
I
I
Part! StyieA
"
I 1 1 1
I I I I
Part2StyleA
1 1
,,
1
.........................
,,
, ,
-cr.e. ........
"
,
,
,
StyleAFactory
:.J:~panl0biectO
IAPar12Objoe'O I
------------ ---- - - ---- ----- - - - -- Client
Figure 17.29 The Idea of the Factory design pattern
I I I 1
I I 1 1 1
I I ----
SELECTED CREAnONAL DESIGN PATIERNS
-,
AbstractFactory 1 getAPartl0blecl() getAPart20blecl()
abstraclFaclory
Ensemble doAFunctlonO
1.. n
1..n
Partt
-I I ~
Part2
Part...
I I I
I I
I I
I I
Part1 StyieA I I I
I I I I I
"-
"-
Part 1StyieB
.... .... "-
"-
-creat... "
I
....
"-
,
"-
"
.... ....
.- " "
.... " ,,,' ," .... , , .... .... " .... ,- " "
Sty leA Factory
I I
Part2StyleB
Part2StyleA
""C"- _
,-
,-
,-
StyleBFactory
-- - --- --
I I
I I I I I
I I
Style ....
I I I I I
~
_ -'7
Client
-----------~
I1_______________________ _
Figure 17.30 Abstract Factory
17.5.2.4 The Abstract Factory Sequence Diagram A sequence dIagram for Abstract Fa ctory , including th e se ttlnB up of the parti cu lar "sty le" (the Ab,lracl Fa ctory object ), is shown In Figure 17.3 1
17.5.2.5 EXample Abstract Factory Application : Word Processor We now show the deSIg n of our Word Processor example USlnS the Abstract Fa tory deSIgn pattern The follOWing use ca es describe the app licalJon View a Docume nt Precondition : none I ApplICa tIon requests the tit le of the do umenl
2 US" provlde< th e litle
3. The "Headlngffext" usc case (see below) IS executed unttl the user enters "do ne"
4 AppllCa/lo" reque tS a style (r01l1 a lISt
5 UStr ent ' r' a sty le from the It,t 6 Applica tion ou tpu" th e do ument to the monitor In the sty le r" rdere n cd above
407
408
CHAPTER 17 SOFlWARE DESIGN PA" ERNS
:Cllent
:Ensemble
abstractFactory :StyleXFactory
r
abstractFactory :AbstractFactory
I , ~
Style XFaclo
...J
0' Selecting
a sryle
setAbstraclFaclory (abstracIFaclory)
I
I .,..
:Pa rU StyleX
I
doAFunctlon O
----
Assume that this method
requIres a
./
-
""~
/
ParUobject
getAPa rUO
I I
ge tAPa rUO
...../1
Part.J SlyleXO Virtual
function
,•I
,
Creating
a ParU
objeclln required styIe
+rl
•
j
property
Figu re 17.31 Sequence diagram for Abstract Factory
Provide Hcadingrrext Preco nditlons- user has provided the title 1. ApplICa ti on reques-ts a header 2. Usrr provides hcadcr tcxt
3 AppJlca lrol1 requcs ts text 4.
U", provides tcxt to fit with thc header Thc class modcl IS shown In Figure 17.32 . T ypical output is shown in Figure 17.33.
17.6 SELECTED STRUCTURAL DESIGN PATTERNS This seClion describes the Facadc and Adap
17 .6.1 Facade: Interfacing with a Collection of Classes 17.6.1.1 The Design Purpose of Facade In bUilding applications we parcel out sets of classes to separate developers Th is reqUires the clear modularization of the design Developers typically require the
SElECTED STRUCTURAL DESIGN PATIERNS
Document geIAH.ad,ngO gelATilleO grtDocumenlFromUserO
r-------,
gelAHeadlngO
I Displa yable I
gelA Tit/eO
:
dlsplayQ
---
--
O•. n
L
O••n
Text• __ "-_--I Heading value v value '---
D,splayable
1
'--7\""',-_.J
~
I
I I
I I I I
I
value
:--7\:--
,
LargeHeading
I~
d,splayO
displayO
dlsplayO
- - -
:
Title
SmaliHeading
'--~---Ioj create» -
Style
style
~
r
LargeTitie d,splayO
~-~-r-~-~-~-~~~~-~--~----- - -
c.:::.- -
~
LargeStyle
gelAHeadingO
gelAHeadingO gelATille()
gelAnlleO ~,
_.:::7
Client gelStyleF romUser() dlsplayDocumenl()
Figure 17.32 Abstract Factory applied to word processor
-
Enter the title of your document·
MY LIFE - Enter heading o r '-done', Birth ......,. Emc r the text: I was born In a mountain hut
- Enter heading or '-do ne'· Youth '"""'7
Enter the tex t·
I grew up sturd y - Enler headin g o r '-done' -done - Enter the
- -T,tle MY LlFESectIon I J
IlIKTH-
wac, b(}rn In a moun lain hut
•
Section 2 Youth- I grew up ,turdy
Figure 17.33 InteraC110n for word processor applica tion
-- - ----------- --~
409
410
CHAPTER 17 SOFlWARE OESIGN PATIERNS
Desig n Purpose Provide an IIlter(ace LO a packa ge of classes. Design Pallern Summary Denne a inglelOn tha, ",he o le means (or ob,alll lllg (un c 'ionali ,y (rom ,he package.
Nol<, The clas,es need no ' be o rga nlZl:d as a package; mo re ,han o ne class may be used (o r ,he (acade. Figure 17.34 oesign purpose of Facade
'0
for developlllg, so ,hat classes and packages ohe n ,elalC each o,her as clien! and server. The client a nd server portio ns are deve lo ped re la'ively independently-,he problem is ,h., services arc typica ll y in va rious Sla' es o( comple
content, o r perhaps wi, h none at all .) Clients o( ,he package have a conc rete reprosen,a'ion of 'he package's fu nctionality to use during development . Th is Jdva ntagc extends to maintena nce.
If maintainers can upgrade rhe way in which
functionality is coded wi,hou , d islU rbing the fa~a de , 'hey can be assured ,ha, all clients of the package are not affected . The Facade objee, is a ,y picaliy a singlelOn . Figure 17.34 summan zes the design purpose and technique of Facade
17.6.1.2 Interface for Clients of Facade Suppose ,ha' a package contains a collection of classes and tha, 'he cl ient code, extemal to th e package, requires a «rvice myCMtlhod() provided by a class C in th e package The c1 ,en' may interface o nly with the Facade object, which we Will ca ll Ih,FacadrOhjrcl. Thus, the clien' code calls a method suc h as Mrt/)odOjFaeaa,Q of Ih,Facad,Objtcl in order to accomplish this purpose.
17.6.1 .3 The Facade Class Model The Faead, class model shows c1ien" inlCrfaci ng with a single class of a package, bu, With no o ,hers. Actually, there is nothing to stop us from designaring more than o ne class as a Fncadt class. The non-Facadt c1as es a~ no' ac"<sible to code extemal to the packa ge. The Faeaar structure IS ,n 'he Delegation form since the Faead, object delcgales commands classes intemal its package. This IS Illus trated In Figure 17 35 .
'0
'0
SELEC I EO STRUCTURAl DESIGN PATIERNS
, 1
Client
"-
..
-
" "This cat! repla ced
by t an d 2.
Fat;;ade
""
Client can't
- exposed.. cMelhodOfFacadeO
""
reference C
I I I I
"
2
I-not eXPOSed-I
I- not eXPOSed- I
C .. not exposed..
I.. not e~posed.. 1
myCMelhod()
I-nol exposed-I
I .. not
exposed.. j
Figure 17.35 Facade deSign pattern structure
A call that ",ould o ther"" e refer to an o bject o f a class wIthin th~ package IS repl aced by a ca ll to a method of the Farad, object ThIS metho d ca n then referen ce the obJect'" que
:Client
:C
si ngleton
'--
:Facade cMethodOfFacadeO myCMelhodO
(return it any)
---- -- - - - - -(relurn If any)
- --- ----------
Figure , 7 .36 sequence diagram for Facade
4"
412
CHAPTtR 17
SOFTWARE DESIGN PATTERNS
MyGameEnglne
MyGame . '6CJJde IJ
MyGameCharacters
MyGameCast f.,fsellde"
MyGameEnvironment
MyGameEnvironment ,.fscs del>l
Figure 17.37 Using Facade for the architecture of the Encounter video game
17.6.1.4 Examples of Facade Applications
17.6.1.4.1 Using Facade for a videogame Architecture use o f FacJdc In the arc h itec ture of a vi deo ga me is shown In r:l gurc 17 .37. The ga me's classes afC divided Into three packages. One pe rta ins to thr c harac te rs that move abo ut, the seco nd co ntainS the classes thal desc ribe t he maze, and the third co nta ins the co ntro l of the ga me. Communica tion with ga me c haracters must occur via th e si ngle MyGamcClISt o bject. Refe rence to parts of the ga me's e nviro nment must occur lhroug h th e JvlyGamrE,wiro"mClf l o bject, and references to the game englOc mUSt occ ur 'hro ugh ,he MyGa m( object.
TI1C'
17.6.2 Adapter: Interfacing in a Flexible Manner 17.6.2.1 The Design Purpose of Ada pter Su ppose that a preex isting app li cation, o r eve n just a preexi ting object, prOVides functionality that o ur applicat io n req UIres. For exa mpl e , th e exis tin g appli ca ti on co uld co mpute the pnncipal Design Purpose Allow an app lication to usc ex ternal functionality in a rctargcta blc manner.
Design Pallorn Summary Write the application against an abstrac t versio n of the ex te rnal class, introduce a subclass ,ha, aggregates 'he exte rnal class. Figure 17.38 Design purpose and summary for the Adapter design pattem
SELECTED STRUCTURAL DESIGN PATTERNS
obtained trom \nVC ling .ll!pv<:n amOunt (or a given number of year In a pcclaltypc of Investment , and WC' want to u~c lhl) (lin [tonality In u~ing Ihi~ functionality . however, we want to modify our own
application as Imle a po<slblc . \VIe also w.nt to be able to easily witch to alternatwe ImplementatIon> of tht· required functlonaltty F,gure 17 38 ummartze the e purposes and the baSIC Adapter technIque
17.6.2.2 Interface for Clients of Adapter The "client" IS the apphcatlon that must 1I e the ex. ling funcnonahry We create a deSign
In
whICh the chent
doe not directly Interract' wtlh the t:XiSllflg fun uonalay, however In lead. It Interra cs with <:In Clbstracl
method of an app roprtately named ab trac t class. The laller must be In tan!tated al runtime with an object of a concrete ubclass. as exp lained next.
Let' call the ab,tract cia
AbslrnclClass . and ItS relevant method we need sta>ldllIForR
· -. - . AbstractClass anAbstractClassObject: ... .. II setup code instantiates ... nAbstrdctC!a.s"Ob)ect •
•
•
•
anADstractClassObject.clientNameForRequ1redMethod() ; Il usetheexternalfunctionality •
• •
• •
Setup code , tYPically executed at initialization , must in tanliatc cwAbslraCICltlSsOb)(ct at runtime In
somethIng like the fo ll owing manner.
• • • • •
if(
...
{ •
)
Ile . g .,
•
•
from a setup file anAbstractClassObj ec t = new ConcreteSubclassOfAbstractClass ( ) ; •
17.6.2.3 The Adapter Class Model The d ..s model for IIdapt" IS ba ed on ,he delegation foml because an Adapl" o bject delegate> the o mmand to the tars,;eted ommand , as
17.6.2.4 The Adapter sequence Diagram Adapter works by handIng off function ca lls to cilclltNllnt,ForR,qllll"iAI
413
.1.
CHAPTER 17 SOFTWARE DESIGN PAmRNS
alent
adaplee
( ad'poee.requlredMoUIOdO:)
I
Figure 17.39 The Adapter class mOClel
:Client
I :AbstractClass I
:Adapter
•
d 'entNameFotftequ1redMethodO
I I I I I I I I I I I I I
adaptee :RequiredClaSS
RequiredMelhodO
Figure 17.40 Sequence dlagram for Adapter
17.6.2.5 Example Applications of Adapter Lds consider a Rnanci.1 application that needs to use the met hod
computeValue( float years, float interest, float amount) of a legacy class Pn"cipit . We want to b<: ab le to e.sily switch to other impleme nt.tio ns of th is functionality if necessary. We write our applica"on by giving our own names to the function of interest, and the class/object that owns the function. For example , we can name a method as follows,
.mount ( float or iqinal"mount, float nllmYears, float intRate ) in the class F""",cial. This cia" is made abstract, as illustrated in Figu~ 17.41 .
SELECTED STRUCTURAL DESIGN PATTERNS
AI!~lIcation
., Ada~latJon
Legacy system
Financial amountO
Principle computeValue()
...J
Client
FinancialAda pter
IOO)cyAdolplee
amountO "
"
.-------~~~----. (
legacyAdaptee.computeValueO: )
Figure 17.41 An application of the Adapter design pattern
The Adaprc::r design pauern in this case co nsists of a class, which we wli l name: FlllulICltJ lAdap lt r here, ",hlch onherits fro m the application' c las (Flllllllnal on ou r case), and whIch aggregates the legacy cia s Pmlnpal. This could be Impleme nted as follows .
class FinancialAdapter extends Financial {
Pr incipal legacyAdaptee = null ; / / Constructors go here . . .
/**
This method uses the legacy computeValue () meth od * / floatamount (floa toriginalAmount , floatnumYears , floatintR ate) {
return legacyAdaptee . computeValue ( originalAmount , numYears , i ntRate ) ; }
}
The new application IS W,;ltt'l aga inst the clas ... Fmannai , but o 'cudcd at runt ime with
OJ
FmtH1CIaiAdapltr
object Setup code instantiates the Flt1tHlClfil obJcc t a'\ a FlllolicIfI1Adtlptr Insta n (' For example , the
be wflttt'n
w ith a method parametenzing Fmatl cw/ , such a~ th c
Ilcnt cou ld
roll0,o,I,ng
void executeF inanceApplica t ion ( F inanc ial aF inanc ial ) ; It cou ld ,hen b~ exe~utl·d "",h ,he followIng s" rr p 'tatement th"",,llZe' ,h e opprop""c ,ciop,cr obIt: t
executePinanceApplication( new FinancialAdaptcr () ) ;
41 5
416
CHAPTER 17 SOFTWARE DESIGN PATTERNS
octlonListencr
ActlonLislener Resull 0 1 bunon (!f§SS
MyBulton
MyClass
addAClIOnUslenerO
myMethodO ~
Mylistener ~
actionPerlormedO
Figure 17.42 Adapter and the Java API
'0
All ca lls the amo unlO method of Fillan,ia/ arc passed to the legacy method compulrVa/urO I. IScasy to adapt the applicatIon to an implementation ofamo,,"10 in a new class. We would on ly ha ve to change the code on FinmlCialAJllplrr. The rest of the applocallo n would not be affected. Being able to re target code by makong loealozed c hanges like this is valuable for development and maintenance. The alternative is making changes
In
mult iple locatio ns, which is error-prone.
17.6.2.6 Adapter and the Java API arc adapters for the following reason. Suppose that we want myMrlhod() in MyOaS5 to execute whenever myBllffotl is pressed.. T o do this , we introduce a class MyListrncr that implements thc ActionLslcncr onterface . The class model is shown on Figure 17.42 . The class MyLis lrtl cr IS the adapter class in thi s casco At runtime ....u: ca n insta nt ia te aclionLisltH" with an Acllotlustcntr subcla ss in lance slich as MyListtncr, according to thc effect we require when the button is clicked. nle code in Myl3ulto" rderenccs only Acliol1USlt1ltr, not any particular subcla s.
lava
liSlClftr5
17.6.2.7 Comments on Adapter • Instead of aggrega ting RrquirrdClass on Figure 17.39, we could onherit from it, as long as the language allows multIple inheritance. Thi s is shown in Figure 17.43 .
AbslractClsss
Cllen.
(
Figure 17.43 Adapter example inheritance version
requtredMethod():)
SELECTED BEHAVIORAl DESIGN PATTERNS
~ ' c m. , be .tlSfied to make Abslra 10alS an Interface If the language does not suppo rt multiple ,"hentJn c le g ,I.va) • Adapter
IS
often usC' d when we
reate an application U1\lng library c1as es. bu t where we want to retain the t other "brary clas e< For ~xampl e . we n1lgln use Verlo, In a Java application to store a
lle.,ib,l, ty to >ck· oilcctlo n, but find that It I> ,omcwha t awkward for the purpo e In question. \'(Ic could rhen de Ig n and code thc application so that It use. an Ideal class of ou r IIl ve nti o n to store a co ilec tl on (e g., AUlomobilts ,vith meth ods SlonA IIIO() e tc,), Then we wo uld incorporate a n adapter to fit th iS to Vrrlor \'(Ihen a mo re " " table o ilrc tlo n managemenr
l as~ appears, we could then ea
dy retarge t to
it , nceding to change onl y rhe adap ter
• Rewrntng (0 the fina ncial example, lO preserve the opti on to retarge t a1 runtim e , we cou ld rela in
FuulHClalAdap'rr, but Int roduce a new Adaptu class FlllmlClnfAdaptrr2 , inheri ting (rom FU1anCIai Whenever we want to targe t the application to the t(o nd lega )' SYCi lem , we wou ld execute th e applICatIOn Wit h the
following .
execut eFinanceApplication( new Financ ialAdapter2() ) ;
17.7 SELECTED BEHAVIORAL DESI'GN PATIERNS This seClio n describes the Interprete r a nd Observer d t's ign patterns as exa mpl es of particu lar behaVioral design patterns.
17.7.1 Interpreter: parsing Expressions 17.7.1.1 Interpreter Design Purposes and Examples Appl icati ons must somellmes deal wit h n:prcs5Io"S written Ir. J grommar. A comp lier, fo r example, must deal with r xpressions wntt'c n in the grammar of a programming languJge. Compdcrs are th e: most common example,
but the,. arc many other needs for the interpretation of g rammars, The following X/l.tL, for example , IS an expression, and the gram mar (ca ll ed a sci",,, • . no t exp liCi tl y g ive n here ) >pecii;e the permISSible form for the XML used In thiS context. •
«engl.neer > > « nam e» John Q . Doe
« /name» «task» Un iversal payroll Application <<' /task > > «task>.lnterglactic Web Site Analyzer «/task>.<.-task»
417
"a
CHAPTER 17 SORWARE DESIGN PAffiRNS
Financial For ecaster «/task» «/engineer » Our purpose is to desig n an interpreter for gra mma rs. In th e XML example, our Interpreter should ~ able to interpret the fo llowi n g expresSIO n as we ll .
• «engineer» «name» Sue W. Smith «/name» «task» Fr iendly Server Application «/task» «task» Intergalactic Web Site Analyzer «/task» «/engineer»
There are two parts relating to the Interpreter desig n pattern : pars"'9 and inlcrprcting . Parsi ng is the process of converting an input-usually a string-into a trce of objects consistent with rhc c lass model . In the XML example, this would include picking o ut individual pieces suc h as the engineer's name. Interpreting consis ts of performing useful functionality with the result of the parsing phase. The purpose and baSic technique of Interpreter are summarized in Figure 17.44.
17.7.1.2 Interpreter Interfaces for Clients Once an expression has been parsed and represented usi ng the Inltrprder class model , clients interface with an Ab.t,acIExprnsio. object that is the root of the parse tree. The client typica ll y ca lls an i."rprt'() method o n th is
Oesign Purpose Interpret expressions written
In
a fannal grammar.
Oesign Pattern Summary Represent th e grammar using a recursive design pattern fonn : Pass the: interpretatio n to
aggregated o bjects.
Fllllre '7'" Design purpose and summary of Interpreter
...----------------------------....
-
SELECTED BEHAVIORAl DESIGN PATIERNS
Client
- - ------
AbstractExpression inlerprel()
Figure 17.4S Interface to Interpreter design pattern
objecl. In the above XML example, suppo e that the twO express,o n formed by parsmg the twO 'nputs are joh.Do,XML and "" ""IJ,XML Suppose that the appitca l10 n IS Intended to co nvert XML to conversano nal pro e. When the client execute Johl1DorXA1L '"trrprd(). the fo llow m8 m' ght be output
En9'"W Joh" Q Dor IS ••o.king Oil th, joJJowI119 Ihm prowls, UI1 ..",,,J PnyroJJ AppJi "lrOl1. J"trrgnlaclle W,b Sift A"alyzer. mid Finml ial ForcctJStcr.
The class model for the clien t/deSig n pattern Interface looks like F'gure 17.45
17.7.1.3 The Interpreter Class Model The Interpreter deSig n paltern has th e Rccurs l v~ (orm because ex pressIO ns can con tain fu rth er expressions. The class model is showr. in Figure 17.46
wh ich the Interpretation function IS simple, or No" Tm"il1"IExprrssion o bjects The latter aggregate Ab, lrll IExprrsslon objects ,n turn The ,"I,rprrt() /unctio n o n a NOl1Trfmm"IExprmiol1 objec t operate by perfo mllllg required work o n the object It elf. then essentially commanding each of Its aggregated AhslraeIEx!)((ssiol1 objects to execute Its mlrrprrl() method. Th IS has much in common wit h the dynam ic viewpOint of the Composite design pattern AbstractExprcssJolI objects are ei th er TcrnliualExprrssioll objects,
0 11
17.7.1.4 The Interpreter Sequence Diagram The sequence diagram in
F,gun: 17..17 cap rure s th e Intcrprctilt ion process.
17.7.1.5 Example Interpreter Application: Network Assembly As an example of In terpreter. consider an applicat ion that handles orders from customers fcr networked computer systems, and genera tes installation ins[fuctlons Forcxali1ple,conslderthcorderrora network shown In Figure 17.48.
IClient ~-
------
AbstractExpression Inlerprel()
TerminalExpression InlorprolO
Figure 17.46 The Interpreter design pattern
1..n
Non Terminal Expression Inl.rpralO
419
420
CHAPTER 17
SOFTWARE DESIGN PAmRNS
:Client
AbstractExpresslon NonterminalExpression
:NonterminalExpression Interpretl)
... ..
create and interpretO
TerminalExpression
~
create and InterpretO
...
..l.
Figure 17.47 The Interpreter sequence diagram
It con
a 8001\ Ihz system wi th 768M B of RAM a 5001\Ihz system with 51 2MB of RAM T h ,s is Ill ustrat ed In F,gure 17.4 8. Th iS o rde r ca n be expressed usi ng the fo ll owmg ex pressio n
{ ( 700 51 2 ) } { { ( 800 76 8 ) } { ( 500 512 ) } }
assemble .. ..
800 Mhz and 768 MB
• .
-
"'-; .
700 Mhz and 512 MB
500 Mhz and 512 MB Figure 17.48 EXample of a virtual machine " program" SOCICf GraphicS reprodU(:.ed wttrl pel " ,!ss'on from Corel
twO
SELECTED BEHAVIORAL DESIGN PATTERNS
ll,e ou'pu' prod
IS
All 110 is to th e console .
as fo llow
1 The application prompts the user to enter an order
2. The appit at ion d,splay the gramma r to be u cd. 3. The apphcat, o n display, an examp le
4 . TIle user e nters an order.
5 The appit ca t, on echoes th e o rd er. Figure 17.49 speciAes th e grammar for th e orders and hows typ,ca l inpu t. The ord er exa mp le ,n Figure 17.49 is ,ndeed a legi tim ate expresSIo n in th e grammar speCIfied , as the fo llOWing veri Ae . co mpo nent -
nc r sys tem
{
-lo
} { comp o ne nt } -
component
{{ compo ne nt } {compo ne nt} } { computer { { { compo nen t} {compo ne nt} } {computer }} { (cp u ram ) { { {compute r } {computer }} { (cpu ram ) }} { (444 -1-1 ) { { { (cpu ram) } { (cpu ram ) }} { (333 33 ) }} { (44444 ) ( { { ( 11111 ) } { (22222 ) }}«33333) }}{ (44444 )
}} ~
}}->
}
The output of the interpretati on process-instructio ns on how to assemble thi S ncf\.... o rklng ord er- are
as shown in Figures 17 .50, 17.5 1, and 17 .52 In this case, th e user se lected th e exa mple prov,ded by the application. Our Arst ta k is to parse the ,nput and create the corresponding set of aggregated objects. After that, t he output is generated in respo nse to a clie nt ca ll ing aNr,workOrdtr.asscmblr(). ll,e metho d a"""blrO takes the place of ,",crpr<'O in this example , The Inte rpret at, o n of a primi,i1lc e lement alone (e.g .• a CP U In the examp le ) 15
Please deSCribe a network on one line uSing th e follOWing grammar for 'component ' Blank paces arc ignored . compo nent :; = net system I comp ut e r net system . = { component 1 { component computer = (cpu ram ) cpu-:
1 1{ compo ne nt 1
= Intcger
ram - = Integer xamp lc: { { {(400 4 111 ( 900 3)) 1 {( 600 3)1 1 { (750 10 ) 1
An '"put With a sy ntae ll
{ 1{( 11
I I I ill (222 22 ))
<"rror w,lI be iJ.:norcd With lit comment.
1 {( 333 33 )1 1 { (444
You chrxe { { {( III Il ll1 (222 22 ))
44 )
1
1 {(3 n 11 )111
Aaure 17.49 Input loe networ1< assembly example
( 44 " 44 )
1
421
422
CHAP I ER 17
SOFTWARE DESIGN PAffiRNS
Pk.se de>eribe • network on one line USI08 the (olloWIOB grammar (or 'compone nt ' Blank paces arc ,gnorod. Inputs w,th sy nt.ctic error< will be ignored withou t comment. component ::
= net system I computer
net system ;: = (component ) (component ) computer ;: = (c pu ram )1 cpu :: = Integer ram :: = integer
I (component )
Examp\c, ({{( 400 4 )){ (900 3)1) {(600 3»)) {(750 10») {{{ (400 4)11 (900 3) 11 1(600 3)11 {(750 10 ») .. . Do some work with the order . ... Assemble a network from either one or two parts as (allows,
'* F,rst Part, Assemble a network, which we will name 'component 1', as (allows, Assemble a network , which we will name 'cornponent2', from eit her one or two parts as follows ,
-
Assemble a network, which we will name 'component3', from either one or twO parts as follows ,
-
Build computer component3 , (rom th e (allowing parts, CPU with specifications . .. . .' 400 and Figure 17.50 Output for network assembly example, , of J
si mple (see the CPU class
10
the listing). What remains is to execute an i"trrprrt() function when applied to a
morc compl(x expression.
Applying the Interpreter design pattern to the netwo rk order example, we obtain the class diagram shown in Figure 17.53 . For simplicity , we assume that every network consists of just two components , so that each SyS'tmr object aggrogates two Compo"",t objects. This can be easily extended to mar< than two. The so~rce code for the implementation is contained in the accompanying textbook Web site.
17.7.2 Observer 17.7.2.1 The Design Purposes of Observer Softwaro roquiremenlS and design frequently involve a source of data, together with a number of chents that must be updated whenever the data changes. As an example, suppos< that the headquarters of Internation.1 Hamburger Corporation maintains data on its s(rvcr abour hamburger ~11es throughout thc- count-ry Distribur~d cli~nts for this data include Senior Management, Marketing, and Operations. The data c hange
,
SELECTED BEHAVIORAl DESIGN PATTERNS
RAJ\\ w,th spe ,Rcatlon< .
.4
erond part --
As cmble a network, wh, h we wdl name componenl4 , as follows. A emble a network, wh ,ch we w,lI name 'compone nt 5', from c ,the r one or IwO pans a follows , ~
Budd computer componcnl5, fro m ,he fo ll owi ng parts: CPU wllh specifica tio ns.. .. 900 and RAM w It h specIficat Ions .... 3
-Now co nnect componC'nl3 wi th componenl4 to comple te cornponent2second pan : -+ Assemble a ne lwo rk , whIc h we will name com po ne nt6 , as fo llows· Assemble a network , which we will name 'cornpo ne nl7', from eithcr o ne or two parts as follows· Budd com pUler compo ne nt7, fro m Ihe followlOg parts: CPU with speciflCat,o ns..... 600 and RAM with pecifications ..... 3 -
ow connect co rnponent2 with component6 to complete component 1-
Figure 17.51 Output for network assembly example, 2 of 3
continually , and each of headquarters' clients nee ds 10 updale li S dISpla y accord, ng to thelf various requireme",s. Lei's say , for example , Ihat Stlllor IVlaIl"gcmclIl's bar c hart muS! be lIpdated afte r a 5 percent change has takcn place, Il'tnrkclillg d, splays a new P'C c hart when a c hange of atieasl I percenl has rake n pia e , and OperatlollS reqUIres lables 10 be updaled when every c hange lake place .
~ Second part Now assem bl e a nClwo rk, which we will name 'compone nt S', as follows
Assemble a network, whIC h we wd l name 'com po ne nI9', from eilher one o r two parts a fo ll ows: Budd computer com ponent9, from Ihe fo llo wIO t! parIS' 750 PU WIth speclC. al lo n, and 10 RAM wllh speCIficati ons
• • Now con nect component I With componentS to 00 more work wllh Ihc o rder. Flcure 17.52 Output for networK assembly example, 3 of 3
gC I th e rC!l.ulting n(, (work =
---
4 23
.2.
CHAPTER 17 SOFTWARE DESIGN PATTERNS
-----------....., : 99[!1PQ'lltnl I Client r ------L---> 8ssemb/eO 1 ____ __ _ _ _ ~
0 .. 1 1
----- --- -
r -- --------
I I I
I
:
I I I I I
component 1
NetSl/stem assemble() J<
I
component2
t; ,
I I
:
cpu
Computerf: assemble()
CPU describeQ
RAM ram
describe()
,,
~
,,
•
••
Setup gelinpulFromUser() parseO
Figure 17.53 Application of Interpreter design pattern Th~ Observer design pattern is imcndcd to address these rcquirern~ nts . Irs purposes and basic techn ique
arc summarized in Figure 17 .54 .
17.7.2.2 Observer Interfaces for Clients Suppose that the abstr.lct class Sour('( IS aware of {he data source. Whenever a client want'S all observers to ,ake notice (Iypically, of a c han ge in Ihe data ), il ca lls a de sig naled melhod of So.rer . In Ihe modd below, Ih,s mClhod is named "OlifyO. The c hen, IS sh,elded from Ihe manncr in which Observer ca,,-ies oul thos process.
17.7 .2.3 The Observer Class Model The partic in the Ob!'crver design pattern requiring updating arc known as observers, and arc subclasses of a
single abstract class, which we will call Ob5
Design Purpose Arrange for a «I of objects to be affecled by a single object. DeSign Pattern Summory The single object aggregates Ihe set, calling • method wilh a fixed name On each member. FIgure 17.54 The design purpose and summary of the Obselver pattern
.. SELECTED BEHAVIORAL DESIGN PATIERNS
Server part
Client part ,-- -.
--- -- - --- - - - - -.-- .-- -- - - - ----, Observer
Source nOlily(/f:(
1.. n
updale()
Lr
2 '-
fOl all Observers 0 :
o.updateO: ConcreleObserver
ConcreteSource state
observerS tate
3
r -1:
updateO
..J
Figure 17.55 The Observer design pattern
\"lIe will follow a equencc of step to . how how
Obs~rver op~rates
Step I The lie n'! references a known '"terface object, requesti ng that the observer, be no tified For example, the client could be a process programmed to no ll ee that the data ha changed , or It could be a c1oek·dri ven ta k In the model , this is shown as a (1,<11/ object telling the SOllrer object to execute Its lIolify() functio n. Step 2 The IIoli/Y() meth od calls the II pdn l' () func tion o n eac h of Ohscro" object that It agg regate, Step 3 The Impl e me nta ll on of II pda l' O depends o n th e part icular (ollerrl,Ohs",'" to which It belongs Usually, updnl'O compares the (ollere/,Oh,,,,·,, o bjec t's sta te (variabl e va lues ) wlfh that of the cen tral dat a ouree on the serve r, then deCides whether or not to change It S va nable va lue,>
accordlOgl y It probably perform ot he r actions uch a erea lln g a new dlSpla
1ne class model tells u that evel)' Ohscro" reference, a
object. In fact , the 'ollIT",Ob,,",,, Will reference the oncrt !tSOufet obj e 1 at nm tl me H ow do the COllnclcObcn'(r objects kn ow to reference the Conc rete ou rce object] \"lIe could pas a reference to It 10 the parameters 01 IIpdnl'(), ", IS do ne In the Java PI 011 "
(sec Section 1772 .5).
17.7.2.4 Example Observer Applications
17.7,2.4.1 " Hamburgers " Observer Example ApplYing shown
In
bscrver to o ur Inte rnauo nal H ambu rger
orpora tl o n problem , we o btain. modd ,uch a, thai
Figure 1756
17.7.2.4.2 Mutual Funds Observer Example We ",'(1 Ulke., ano ther exa mple .pp(,cauon "I b,erver the updating of mutllal fllnd po nfo ll , 1\llItU. 1fu nd, mull1plc slock'} , ('0 Ih a l when it parll <..ulJr ') 10 k\ pn e t hJngco;; , It arlC_h till' "Iut., 0 1alllhc nlutual funds th at In vc') l In It orrn all y. '!ouch change, In J 1)(0 k.... pn \' j'lrc IrJ lhmlllcd t'lt:ttrootLali In o\lr t:\ \unplc
IOV(:\t "1
425
426
CHAPTER 17 SOFlWARE DESIGN PAmRNS
Cllonl
,,
,- - --
Cliont opa
Sow' part ,- --- - ------ --- - - -
-- --- - -
Source
1.. n
Observer
-)
update!!
notify()
SenlorManagement
forecast Headquarters
Marketing
update()
demand
marketinaOemand
/ If( abs( hq.demand - marketlngDemand) > 0.01 ) • ( marketing Demand = hq.getDemandO;
updale() doDisplay()
doDisptayO; )
Figure 17.56 Observer applied to International Hamburger Corporation
we will make the change to Awesome Inc.'s stock by hand. The application will then display the resulting changes in the mutual funds canying Awesome stock. We will use the OhsrrvtrlOhsrrvahlt java API to cany out this d~sig n and implc:mentation . The main usc case is as follows ; I. The application reports the status of mutual funds that invest in Awesome Inc.
2. The following repeats until the user signiAes quitting. 2. 1. The application prompts the user to supply a price for Awesome stock. 2.2. The user enters a price in decimal f.orm. 2. 3. The application reports the status of mutua) funds that invest in Awesome Inc.
Figure 17.57 shows a typical scenario. The cia" model is shown in Figure 17.58 . This cia" model uses OhStrotr classes in the java API , which arc discussed next.
17.7.2.5 ObseNer in the Java API Many of the design panerns discussed in this book are present in the java API. However, one recognizes them by their form rather than by ~ame. Observer is one of the few pattems explicitly called alit by name in the java API. The java API Ohstnltt class model is shown in Figure 17.59. The java API uses virtually the same terms as Gamma ct al. Notice that "pJa/t( . ) is a callback method in the sense that it provides Ohstrvtr objects a reference to its source, thereby enabhng them to compare their data and so on with the OhSlrvahl, object in executing "pJa/t(j . Because update is implcmc:ntcd as a callback, there is this no need for concrete Obsrrvtr classes to maintain rdcrenc('S to the ObsfflJQblt object.
SELECTED BEHAVIORAl DESIGN PAIIERNS
otc, HGrowt hMulualFund qarts w"h 3 sharcs of Awesome, assumes price of 1.0, and has non-Awesome holdings totalling 4000 'ote· kdGrowthMutualFund ,tarts wi th 2 hares of Awesome, assumes price of 1.0, and has non· Awesome holdings totalling 300.0 NOle, LoGrowthMut\JalFund lart with I share of Awesome, assumes price of 1.0, and has non -Awesome holdlnb'S totalling 200.0 Enter 'quit': Any other Input l o com inue.
go on Enter the CUrTent price of Awesome Inc. In deCimal form . 32. 1 Value of Lo Growth MUlua l Fund changed fTOm 201 .0 to 232 I Value of Med Growth MUlual Fund changed from 302 .0 to 364.2 Value of Hi Growth Mutua l Fund changed fTO m 403 .0 10 496.3 Enter 'quit': Any other Input to co nt inue.
go on Enecr lhe CUrTcnt price of Awesome Inc. in deC imal form . 21.0 Value of Lo Growth Mutual Fund changed from 232 . 1 10 221 .0 Value of Med Growth Mmual Fund changed from 36 4.2 10 342.0 Value of Hi Growlh Mutua l Fund changed fro m 496 .3 10 463 .0 Enter 'quit': Any other input to continue. Figure 17.57
va example for mutual fund application
r---::-:-
---- ---------------1 I I
r- ----------------,
Observable
Observer
I
notifyObservers()
>--
I
I
updste( Observable, Object ) :
~-------~---- ---I I
Mutua/Fund
I
value
I
numAw8someShar8S
I
I I
I I
Awesomelnc
Client
Key-
price
IJava API CI8ssi
LongTermMutualFund ------
MediumTormMutualFund HIGrowthMulualFund
IOovelOPO' Cta.ss I
Figure 17.58 ODserver example class dlagram-mutual funds example
....
updatel ... )
~7
428
CHAPTER 17
SOFTWARE DESIGN PAmRNS
Observpble
,I<
Observer
nO/ifyOirverso k - - - - - - - -- updale( Observable, Objecl)
~ MyConcreleObserver
observerS late
MyObservable subjecl
Key:
I
Java API Class
II
Developer Class
updale( .. ,)
I
Figure 17.S9 Observer in tl1e Java API
17.7.2.6 Comments on Observer • Observer also goes by the widely used name of "Model -View-ContToller" (MVC ), altho ug h there arc slight differences in emphaSIS. The "Model" in MVC is the So ure, in Figu,e 17.55 (the Obsrrvabl, in the Java API ). The 'Views" are the Ob,nv" o bjects, an d th e "Control " is client and possibly setup code. MVC emphasizes the fact that the mo del is data and the views are C Uls, whereas Observer is conceived wi th broader applica tion
• Observer aflows the additio n and removal of observers without d.sruptin g existi ng observer code. Only the loop In Obsrrvabl,.nol1jy() must be augmented. Some times th e process of adding and removi ng o bservers is co nside red part of the panern (rather than being a "setup" function ). • Observer may be di sadvantageous if very few of the observers need to rcact to changes (in w hich case the numerous nmi Rcatio ns waste resources).
• Obscrotr is di sa dvantageous when update is morc naturall y implemented ce ntrall y , or w hen update policies among observers have very little in commun .
• Obsrrvrr ca n't work if the observable cannot have a reference to all of the observers For example, we would not usc it in a clien t/server situation unless we were wi ll ing for the server to maintain references to all clients.
• In general, having the observers update themselves (as opposed to eXlerna l sohware perfo nm ing it) .s good o bject· o riented design because it keeps related fu nctionali ty together.
17.7.3 State
17.7.3.1 The Design Purposes of State Many co ntemporary applications are "covent -driven," A word processor, (or exa mple, waits (or the use r to click on an Icon or menu item, and o nly then reacts . Evc:nt·driven applicatio ns are often de igncd as STate-transi tion
systems. When a system behave by essentially transitioning among a set ofslalts , the State des.gn pattern can be helpful. For exampl e. we can descriix the Encounter vi deo game at runt ime in term s of the state it is IO- i t could transition among the StltH1g .up , WailiJ19 . StttiHg-
SELECTED BEHAVIORAL DESIGN PATIERNS
Design Purpose Cau<e an ob)c t to behave ,n a manner determined
by
IlS state
Design Pattern Summa ry Aggregate a I
hould al 0 be capab le of gracefull y absorbI ng new Slate and actIon handltng without dt
17.7.3.2 State Interfaces for Clients To use the State pattern , the lient imply makes a call o n a spe iRc method of a specik object The cl,ent" sh,elded from the various possible dfects of ca ll ing the method, whICh depend o n the object's
17.7.3.3 The State Class Model In general terms, suppose that we want to use a method doR rq"rsl() of an object 'arg" of class Ta'9" , whcre doR,qursl() can behave in different ways, according to la,g
17.7.3.4 Example State Appl ications The Encounter VIdeo game ca n typIcally be In a variety of sta tc, When you Slart to play the game, you rna have the o pportunity to sct yOllr characte ri stl s (" elllng Up" Slate ) When yo u ate III the mId" of lI11l'ra ting WIth othe r characters, your state IS dl lferent ("Engag In g"
Chenl I
,
;
/'
Target
•dcRequeslO
/
Tarqe tState
lorgetStalc
Figure 17.61 1M basic structure of the State design pattern
1
handleRequosf{)
429
430
CHAPTER 17 SOFTWARE OESIGN PA ITERNS
CHent
( l argel51al e,handleRequoslO: )
I
T
Targ et
•daRcqueslO
TsroelSlate
l.rgeI518le
,
1
handleRequesrll 71
TargelSlaleA
TargelSlaleB • • • • • •
handleRequeslO
handleRcqueslO
Figure 17.62 The Siale design pattern: doRequestO behaves according to the state of Target
play In tha·t case . If the ga me tnterface had the appearance in Figu re 17.63 , the dfect of pressing the ScI Omractcn sl/cs button would depend on th e state
or the game at the
time .
Figure 1764 shows how the Statc design pattem can be used to handle the states and actions of Encounter The cia s MyGame has an attribute called , laic of type MyGmncSlalt The type of the , Ialt o bject (I.e ., " 'hich subclass of '"lyGamtSla le It belongs to ) delCrmines what happe ns whe n stlo,araCltri, It C5(J is called o n a MyGamt obJect , The code for st lo,aracltnslt«(J In MyGamt passes contro l to Ihe handltCfick() function of slalt. Each subclass of MyGarntSlalt Im plements l,andleCfick(J in its o,,,n manne r. For example , if MyGame is in Wailing state, then the effect of clicking o n the "Sct C haracteristics" huna n is that a wi ndow appears thro ug h which the playe r ca n change hiS charactenst lcs . O n the o ther hand, if MyCa,"c is in ScltmgQutlilhcS state , then nothing happens because the user IS alread y s elling his characteri stics.
Set Characteristics
FIgure 17.63 GUI for Encounter role-playing game ~
COt.rtesy of
Tom vancoun and Cent
DESIGN PATTERN FORMS: DELEGATION AND RECURSION
MyGame
I~
stale
setCharacteristicsO _
handleClickO •
t stato.handieCIlckO.
I
Setting Up
Waiting
SettingCharacteristics
Engaging
handleClick(
handleClick~
handleChckO,
handleChckO
I, I showWindowO; •.. J/ more
I
,
I
I
I showWindOwO: ... JI more
i
,,I
I
{ /I already respondJJl9 .. /I disp{ay message
I I/ do noth'ng . ,_ /I dISplay message
I
I
I
Figure 17.64 The State design pattern applied to the Encounter role-plaYing game
17.7.3.5 Commen ts on State • The State design pattern is particularly beneficial when new states are likely
to
be needed
In
the hltu re.
• State does not hand le the question of how to set up the sUCCesSIve state (if required ) once ha"d',E"",tO has been perfonned. Although State doc no t hand le the tranSition funcllon , it can be a useful fnmework In wh ich to implement transi tion . For example , halld',E""" O ca n contain code that swaps In the new Slate A possible companion to ('he State deSign pancrn IS a state-transitIOn table whose entries indicate \~hal new state the object tranSitions into for each "current s tale~vent occurrence" pair • Whetheror not the State de ig n pattern IS applied, tate -onented arc hlte tures have been used with success for many applications (see, for example, the work of Sh laer and Mell or (2 )) Real-time apphca tions lend to benefit especially from the sta te architecture because they often rely o n a sratc/event perspective
17.8 DESIGN PATTERN FORMS: DELEGATION AND RECURSION As the exa mpl es of deSign patterns above Iliu trate , they occur ," a ),mlted number of forms We could >a y that there are patterns to the design patterns meta patterns. If yo u like . Mo,t deSign pallern are based on the dcltgahoH or ftcursiotl forms , as descnbed In thIS secti on.
17 .8.1 The Delegation Design Pattern Form ConSider a ta,k that needs do,"~ , the o bjec t thai initiates it , and an object thai doc< the actua l ",ork 0" '91111°" IS a proc"", by which the Initi ator emp loy, a th"d obJc tto get the work done by the doer. An example from re.llife IS the usc of a rcalLor In whic h th e . c ller (the InllialDr) wants to cllto a buyer (the doer, In thiS a<e) To ach ieve nex,bd,ty, the KltchenV,ewer dC
new Ant iqueWallcabinet () ; / / applies only to ant ique style
431
432
CHAPTER 17 SOFTWARE OESIGN PATTERNS
.. , c1lenIFunc;Iron{ ... )
.. InlermediaryFunctlon(
(
... inlermodla.ryFuncllon( .. ) .. ,
( .,' r&qutredFunctionO , ..
j
j
)
Client cllentFunctionO
- - - - - - - - - - - -
~
IntermedlaryFunctionO
" "
I I
!
,X ,,
I I
I
replace
"
I
,
-!t ." requlredFuncllonO
FIgure, 7.65 The idea of delegation
with
il
version that delegates construction to an intcm1e diary method
myStyle . getWallCabinet () ; / / appli es to whatever style is chosen at runtime
11,e Abstract Factory design pattern replaces several dircci m
functi onali ty to the methods of an abstract class. When we apply Abst rac t Factory in Figure 17.7, fo r example, the work of crea ting a Wal/Cahi"" object is de legated to the methods of a KilchrnSIyI, object. A common lorm of Delegation is illustrated in Figure 17.66 . where an abstract class is aggregated and acts as a base class for severa l concrete subclasses. The client calls the method ml,rjacrM"bod() of the interface class OP/"',rjacr. In turn, inltrjacrM"hod() delegates the reqUired fu nctionality to its aggregated Oorr&" object, do,rObjrcl. The functiona lity is carried out by having dorrObjecl execute a method that we have named do/l( ). At runtime do,rObjrct is an object of either the class Co"" ",OO''' , Co"crtItOom , and so o n. Since the effect of do/t() depends on runtime cond itions, so docs the effect of i"l,rjaccM,'hod(J. The class OP/III,rjfl" thus has the followi ng fonm .
class DPlnterface ( DoerBase doerObject; •
• • • •
public void interfaceMethod () { doerObject . dolt (); } }
DESIGN PA ITERN FORMS: DELEGA liON AND RECURSION
Client I I I
I
... inte~aceMethod( ... ) ! ( ... doerObject.doltO ... ~ , .,
I I I
r.-~ DPlnteriace
doerObject
DoerBase
IntertaceMethodO
ConcreteDoer1 doltO
dol/O
ConcreteDoer2 doltO
...
Figure 17.66 Basic deSign pattern form nu mber , -delegation DelegatIon . Implemented using ,he virtual functio n property. is the most common form of deSIgn patterns . Another common form is Recursion : the usc of slnK,u res '0 cffcctl\·ely reference ,hcmselve,
17.8.2 The Recursion Design Pattern Form Several deSIgn patterns require re ursion- In o,her words, part of ,he pattern essen tially uses I,self For example, recurSIon is useful for represe ntIng a linked list of objects ir. wh, h each objec, of a cia> agg rega ,e another o bjec, of the ame class. Anot her examp le IS construc'ing a graphical user In,erface tha, al low> fo r Windows within Windows withIn windows .
. and so o n. In lhl'> case, the \\'mdoIP object aggregates itself In a recur Ive patte rn fo rm , a duallnhcrnancc-aggrcgal1 o n relario nshlp eXists between 3 base class and a 5t:Jbclass. as shown In F, gure 1767 No,ice tha, the Recur
deleganon doubles back o n Itself From the dynamI C VIeWpOint , in a RecursIve form ,he ct.en, ca lls a me' hod of the Intedace, which we'll name doOptration () If the object actually belongs to ,he subclass Rcn",,,,r IllS! , ,hen execut"' g li S doOprrahon () Involves the o bjec t(s) of aggrrgalt T hese objec" may once aga ", ca ll doOprmholl(), and so on Let's take as an cxample ,he case where RccII,""on/3asr ",he la> Employer , doOprrallollO " ,he me,hod pnnrOrgan'ZIlhonO, and Rrcurs,"cC/ass i< the class SII pm",or The Idea " to produ c a prin,out f all ,hc ~mployecs of an o rga nIZatI on The d a« model IS shown In F,gure 17 68 The method pnnrOrganlZllr.onO In SuprnJlSor would be prowammed nrst pnnt ,he
'0
objects o f the clil~'" up,rVl sor. prltl l () rgaH IZtl ll otfO pnnt) th a l ) lIpcrvl,or's n a m~ Jnd the pnntln g pro (' '\ rcpt"ill' re ur!lo lveiy Thl~ rccur'iIVC pr(lce~) eve ntuall y print all or th t: nJmcs The c1J" uprn11,or Ihl! ha, the:
fQlJ owlng form
433
434
CHAPTER 17 SOFlWARE DESIGN PAmRNS
RecurslonBase
Client - - - - -
;> doo".,. r'on(j
t:;>
NonrecursiveClass
RecursiveClass
doOpe,atlon(j
doO".,.tlonq
p
aggrega.e
I
I . void doOperation( ... )
II ... aggrega •• ... } :
-
I
y
Figure 17 .67 Basic design pattern lorm number 1--<ecurslon
IClient fu_u
Employee p,lnro,ganIZlltlon(j
IndividualContrlbutor
Supervisor
pnntOrganlzalionO
prlntO'ganlzalionO ,
Gid
supervisees
•
pnntOrganlzation( ... )
I ... supervisees.printOrganizationO ...
J
~.
_____________________~t~>~'
Figure 17.68 The Recursion design pattern lonn applied to an organizational chart
class Supervisor extends Employee {
Vector supervisees;
void printOrqanization(
•.• )
SUMMARY
{
•
•
•
supervisees.printOrganization();
•
•
•
}
}
17.9 SUMMARY This chapter I ntrodu cd design pattern", which are used to ~atlsfy recurring de IS" purposes A df.:slgn partcm ,'\
a g-roup of cia ~c ( th e sIalic
VleWpOll1t )
that
tnteraClll1
a recognizable ..... ay (the d)'lwmlC
V ICWPOlnt )
Typically. a
desIgn pattern consists of an abstracl level of clas<es and a nonabSlraCl ("concrete") levd Three roles ( et of codd a", involved In the u<e of de Ign paltern<, lhe appl'
everal deSign patterns also u c a (orm o( ,tClm/OfI ,
In
whl h a class
rderences either Itself or a base class from which it inherits DeSign patterns can be rOllghly c1as ,ned as (7w llonal , sfru 11m,', o r btb,wlora'- Crw I/orlllI patterns create nonrnvlal object ensembles In a manner determll1ed at runtime. Structural pancrns are used to represent collectIons of objects. Bd,.",oral patterns deal AeXlbl y with behaVI or among a ot of objects This chapter descri bed the following crealio na l design patterns by ,yay of example The S,n gleton pattern i used to enforce classes with o nly a SIngle in tance. The Abstract Factory pattern IS used when an interreiated family of classes is required but in a vanety of "styles " A "style" In thi< sense IS a haraCtenSllc appli~ablc to every object in the family .
The
follOWing behaVioral dcc;;i gn patterns
WCft"
discussed . Facade
IS
a way to treal a group of c1a ss~s JI:; a
unit. by provIding ItS functionality only through a slOglc object Adapter IS a way to SWItch u er obJe t ty pes of given functionalIty at runtime The chapter al
of
tal C II:; used to deSign Clpphcation pilrt" bel:;t th ought
term of a SCt of stales These points are summa rized In Figure 17.69. The reader i referred to Fowler (3) and VIl<sldes (4] [or further exploratIons of dC
• DC'Slgn Pattern s are recurring designs sat lsfy mg rc urnng dec;;lgn purposes:
• Des<:nbed by Static and DynamiC Viewpoints • TypIca lly cias, models and
435
436
CHAPTER 17 SOFTWARE DESIGN PATTERNS
17.10 EXERCISES I. Which of the following arc applications of deSign pallerns) Exp lain your conclusio ns.
(a) An obJect,orlenta ted design (b ) The ab ili ty 10 vary the order
10
whi ch a
pn,,'O method
IS
app lied to the ciemen ts of a Veelor
(c) Varying the order 10 which a method is applied to the clements of a collection of objects by introduclOg a ciass who e methods IOciude a method like go ToNtxIEl""ml() (d ) Cap turing the mutual beha Vior of a pair of objects o f twO classes (e) Capturi ng the mutual behaVior of a pair o f objects of twO classes by introducing a third class aggregating the two clas es 2. Char.lctcnzc the fo llowing design purpose as , ,(aIlOMl, structllral, or btlJovioral. Explain your conclusion clearly.
We must build an application with 15 different screens involvlOg va ri ous combina tio ns of 6 us., interface contro ls (e.g .. list boxes) arranged in a si mple grid Pe rfo rm ing a mouse ac tion o r text e nt ry o n a co ntro l (e.g .. a butto n) in a screen affects other controls o n the same scree n. In all o ther respects the screens are not related and are not si milar in appearance. The compOSition of th ese
screens is very unlikely to change . 3. Characterize the fo llowing design purpose as erralronal , structural, or bthavioml. Explain your
conclusion clearl y We must build a hum.m resources application dealing with the management structure at a large co mpany . We nee d to represent the organ ization chart withi n the applicati o n. 4 . Cha ra cterize the follOWing design purpose as ertel tional , structu ral , or bthapioral. Explain your
cone/uSion clea rl y. We must build an application that allows users to build and change their stock portfolio with a various ki nds of mutual fund picks from specified subcategories. The mutual fund categories ar< ttchPlology , old mdustrits , utilities , rtal (stal(, and mining . The application allows users to pICk categories. It then milkes portfolio recommendations depending o n the user's choice. For eXilmple, the user can
ask fo r a low· risk portfolio of utilities and mining Slocks. and the application describes its recommendat ions within these constra ints.
5. Consider the followi ng two statement . (al Obstrotr consists of an object of a class that reflects a data source, togethe r with o bjects of classes that depend o n the data source. (bl When the data changes value, a method with the name "pdateO is called o n each observing object. Which of these two tatcm ents takes a static viewpoint and w hich a dynam ic' viewpoi nt
6. The following figure shows the Obstro" desig n pattern class model. Group the classes to show ab,tract and co"crete levels. Group the classes to show the three ,oles descTibed in this chapter. 7. (a) What two design pattern form. are mentioned
10
th is chapteo
BIBUOGRAPHY
(b ) ~ h,ch of the
".0 fomls IS more lIkely '0 u'c virtual functions ) Explain your answer Jnd gIve
In example
(c ) Wh,ch of ,he two form IS a I",krd
I'si of obJtCIS Ioke1y
'0
be) Explain your an wer
(d ) Wh,ch of the two forms IS the Observer pallern In Exercise 61
S. Re ('arch the Java wing soflwarc ar hltcclUre, such as Java wmg, and descnbe In a few paragraphs how It make usc of the Observer pallern Draw a cla<s dIagram a part of your an<wcr 9 Research the Java EE p ia, form and desenbe In a few paragraph, how i, makes usc of ,he Facade de Ign pattern Draw J clas<: diagra m as part o( your solullon
BIBLIOGRAPHY 1 c'mma Ench. Richard Helm . Ralph }ohn ..on and John VI''iSl dcc; D(~I!1" PQlftnt ~. El('lllmh of Rrw.wbft Ob}tcl.OnnlkJ 50//11',1'1 Wc .. lcy. 199 '2 Shlaer, Sally. and tcphcn Melio r "Ohle, Lfrrydn /\loJrlIl19 1M World.,\ lollI'S, You m o n 3 Foy,·lcr, l\'brtln Pull"" H(mhl"9 f)MI9" Pallen" AppJltJ " Acid ..:;on '«'c"lcy I?'J$ of VIISS,dc-s, John ~' . MPOII(n.~ of E"'crpnSt AI'P',collon J\rrhl lrdlm " Addlf;on· \,(/c 'iIc)' 2002
Pr~ ~
199 1
dd"on .
43 7
Software Architecture
The Software Development Ule Cycle
•
How do you classify software architectures?
•
What are data flow architectures?
•
What are three-tier architectures and their generalizations?
•
What makes database-centric systems a separate type of architecture?
•
What are service-oriented architectures?
•
What IEEE standards are there for expressing designs?
•
What do real -world architectures look
like? Figure 18.1 The context and learning goals for this chapter
Th IS p.rt of the book , oncern ed with desig n, began by dcscnbing design go.ls and principles and then described patterns of design that reCur th roughout. This chapte r describes d<sig n at the high leve l, and the chapter that foll ows at the detailed level. A sofl wtlrt archlfcch~ rt descnbes the overa ll compo nents of an apP'!ic,Hi on and how they relate 10 each oth er. Its design go. Is, as discussed," C hapter 15, include suffiCIency , understandabil Ity , modularity, hlSh cohesion, low coupl ing, robustness, fl exibi l, ty, reusability , err,clency, and reliability. For a give n softwa",
SOFlWARE ARCHITECTURE ALTERNATIVES AND THEIR CLASS MODELS
• Oatatlo,"l architecture!!. • PIpes and filters • Batch sequentIal • Independent ompon('nt
• Clicm · elVer systems • Parallel communicating proccs es: • Event systems • Servlce ·oriented (added )
• Virtual machine • Interpreters • Rule ·based systems • RepOSitory architectures • Databases • Hypertext ~ystcms • Blackboards • layered arc hitecture..,
Figure 18.2 Shaw and GarJan's categonzation of software archItectures SCUte: Shaw, M.G and 0 Gartan. " Soltware AlcMecture PefspecUves on an Eme'ging OIsctphnc," PrentICe Hall, 1996
devel opment project, lhere may be several possible app ropna te architectures, and elecllng one depends upon [he goals that ont wants to emphasize. Flexibility , to choo c one of these qualities, is a key goal of many archilectures-the ability to accommodate new features. This uc;uall y Invo lves Inrro duClng abstraction Into the praces For C"xample , we mIght want the architecture for the Encounter Video game case study to support not Just thIS partICular ga me , but any role. plaYi ng video game Attaoning one de irable deSIgn property ma y entail a trade ·off agaonst others For example , a de Igner who uses abstlactions to obtaon a fleXIble architecture may make" harder lO understand
18.1 A CATEGORIZATION OF ARCHITECTURES Shaw and Garlan [ 1] have claSSIfied software arch"ectures 111 a u cful manner Theor cia Slficallon, somewhat adapted here, is shown in Figure J 82 . Section 18.3 explaons these ",ch"ectu res There IS a WIde variety of problems requinng software solutions, and lhere is a wide va ri ety of archItectures needed to deal with them In most cases, the architecture is unique to ,he problem Sometimes, o ne of the a rch itec lures Identi fied by Shaw and Garlan matc hes the problem, in many cases they si mpl y proVIde Ideas o n whIch to base the architecrure. This is Similar to arch itecture in hOUSl' construction, In which claSSIcal and standa rd Ideas prOVide inspiration for great architecture but arc nor c;imply copied
18,2 SOFTWARE ARCHITECTURE ALTERNATIVES AND THEIR CLASS MODELS The softwa re archItect develops a mental model of how th e application I meant to \ o rk, often with nve to seven components The JrChlltCl '., mental model depends on the app li ca ti o n In qUl:.'!)l\on . of COll r~ e , but may benent from architecture< that o ther ha ve de veloped In th e p. t, JUpcn" on brodge de>!gn benents from the study of preVIously budl suspe ns Io n brodges . ThIS section e laborate< o n the arch ll ec· IUr<S claSSIfIed by h aw and Garlan They calegonze architec tures as dota flow , ondependent compo · ncnb, vlrrua l machlne'l , repository archItectures. and layered aT h,lcclllrcli. Figure: 1 2 summanz.e'" th('~e and 'heor subcate!!orocs, and the re~t of thl sec ti on cxp l"n< th e m It also add , serv l e · oroc nled
architectures.
18,2,1 Data Flow Architectures Some applIcatIons are best VIewed a, data Oc,wlng among proce'Slng unlt< DOll 1I0w dl.!;"m, (I 1'0<) IIiUstralC 5uch VI('WS Ea h pro csson~ unit of th e OFf') " de,,!
439
440
CHAPT£R 18 SOFTWARE ARCHITECTURE
member
Gel
banks
User
deposil
J". no"'"
Gel Inquiry tlccounl no
act:ovnt no. and doposlt
Validate
Validale deposil scoounl no.
Inquiry Display account
aca>unl no.
Make
Inquiry Printer
'''''depoSIt Do deposit
tJccount
balana>
dDra
query
doposll
transactlon
trat'lSBction -
.. account_
S=>
dols
Create account summary
dalabase
Figure 18.3 partial data flow diagram for an ATM application
emanates (rom sources , such as the uscr, and eve ntually flows back to uscrs, o r into sinks such as account
data bases. The c le ments of the DFD no tation were explained i n C hapter 16 . A banking application is sh own in Figu re I S.3. Data Row from the user to a "Get deposit" process, which se nds the account number and the deposi t amount to a procc,ss designed to check th ese data for consistency . If they arc consistent, the data may be sent
to a process that crcates a tran sac tion , and so on. DFD s can be nested . For example. the "Create inquiry tran sac tion" ca n itself be decomposed Into a morc detailed data flow diagram .
The functions of a data Row d iagra m may reside on morC than one physical platfo rm . Figure IS .4 shows one possible allocation.
ATM
o
Get deposit
Get Inquiry
Display account
Consortium server
Bank
server Make Inquiry
Do deposit transactIon Create account summary
Validate deposll Valldale inquiry
Figure 18,4 Platforms in data flow architectures, and an example
SOF1WARE ARCHITECTURE ALTERNATIVES AND THEIR ClASS MODELS
18.2.1 .1 Pipe and Filter One kind of data Ilow ar hltceturc.
In
Fi gure 18 6 .
the applI ca ti o n malntaln ~ ac Qunt> as tran saC ti o n, arrive at rand o m l1nH;S from co mmu nica ti o n
lines The arc hitec ture Includes;) lCP for logg in g lran,a C ll on~
In
case of system fa ilure The Withdraw
Jo lmDotAc olUltNum 11 J OAmOUPlt$3S00 00 , or Just Jobn. DoCf 2J 45 SJ 500 oo'-that IS, a character stream and bank address input such a< llallkNu"'9876 The proce ing elem ent , hown in ellipses. wai t untd alf o f the reqUIred Input has arnved before performin g function would ha ve withdrawal Input su h as
their op"ratl o n stream>
filler
hlter
filte r
IiIter
filter
pipe filter < stream
FIgure 18.5 Pipe and filter architectures
Requirement: Maintain wi red fi na ncial transactions . - - - - - - account data - - - - ,.--- account data - -
_,-- I Ba nk d a ta
L
deposit
, account data
Iransaction
r
depoSIt data
a na lyze
Comm _ _ _ bank address
transaction
transaction result
~L'---...... re cord
'--~
wllhdrawal
transaction result
withdraw
L _ _ ___ account data - -- ---'
FIgure 18.6 Example of a plpe·and·fllter architecture, to mai ntain Wired fInancial transaction
Log
441
442
CHAPTER 18 SOFTWARE ARCHITECTURE
Transaction analyzeO recordO
l..n
Bank
Account w~hdrawO
r
depositO
Figure 18.7 Obtaining a ctass model from a data flow architecture bank account example
There is no absolutel y uniform way to map data fl ow diagrams (DFDs) on to class models, however, functi o nal units of the DFD can frequently map directl y o nt o methods of classes, as shown in Figure 18.7.
n,e Incrl!asing usc of distributed computing is acccieratlng the applicatio n of stream · onented computing because rem o te function ca lling is often implemented by convening the call to a stream of characters . nlls IS do ne in Web services, for example. These use seria lization, which converts objects to XML charactersITeams. ln additio n, l/O is often implemented u ing streams, and performing 1/0 in a language such as Java often amounts to a Rltering process of the kind we have discussed .
18.2.1.2 Batch Sequential In the special case where the processing clements arc only given batches of data , the result is a blilch s
Requirement: Manage bank funds available for mortgages and unsecured lending. Architecture: Account balances
Collect mortgagelunds
-«
Mortgage pool
>--
Collect unsecured funds
Unsecured pool
Figure 18.8 Example of a batch-sequential data flow architecture creating a mortgage pool r : Accounts package : o
--- -- -- -------- -----
.-.----.... -.. -.------ - ----- - --------------~,, •
,,• • • ,•
Customer
:.-.--. -- - .------------------~
;: LA_c_c_o_u_n_t --:: ---!:
•·
.... ----.----.-.- ..
: Bank package :
:
~--.------.-.------.----
.. ,
:
-
' _..
Bank
:
getMtgPOOIO : getUnsecurePoolO : _.. _.',
----_.------- -.--...
Figure 18.9 Class madeller batch sequential data now--
SOF1WARE ARCHITECTURE ALTERNATIVES AND THEIR ClASS MODELS
For dcca dt" • data flow has been the: mos t CO rnm o n way of
be
u~c:ful
(or some lime to come EnSlAccrs nawrnlly think
cxpr~~sl n g architectures, and
ol data
It IS bou nd
to
Oowlng, from one prace Si ng "statio n" to
th~ n ~x t and of proce<slng taking place at ca h ta t Ion . The disadvantage of data fl ow d,agrams include the fact that they do not map very cleanly to code , whether obje t .onented or no t An excep lt on to thIS appites to specIfic data flow language, (,ome beIng actuall y graph ,c In nature ). wh Ich arc butlt around the very co ncept of data ilow We WIll use the data flow mo del once again when we dISCUSS detatled deSIgn In C hapter 19
18.2.2 Independent Components The i"Jcpmdnll compOHfll ts arch ,tecture consl IS of componen ts operatIng
In
parallt:1 (at least in prul Clplc )
and commUnicating wit h each ot her from time to time An obVIOUS Instance of thiS can be found on the
World W,de W eb. where milli on, of servers a nd browsers operate conttnuou Iy
In
para ll el and penod ,cally
communicate with each other.
·Components" arc portIons of software th at do no t change and that do not rcqutre kn owledge of the software usi ng them .
IT assemblies and JavaBca ns are example component technologIes
omponents
sati fy gui de l",es aImed at maktng them self·conta lned. They use other components by aggregatton, and generally Interact wi th other components throug h {'vents
The case studies tnclude a d,scussion of the Eclipse project. Ecl ,pse
IS
a development platform deSIgned
to accomm odJtc plllg-IIIS Th ese arc independent component that can be created by developers fo r vanou~
purposes. and added to the platform wit hout affec ttn g exi ting functio naitty
18.2.2.1 Tiered and Client-Server Architectures In a df(nt-S(rv(r architecture, the server componc nt serves th e needs of the chcnt upon rcque~t Clie nt -
server r~ latl o n s h ips have the advantage of low coupitng between the parti CIpating compone nt s. When morc than o ne person perfo rm s Implem entatI on It is natural to parcel out a package of clas es to each developer o r g ro up of deve lopers , and deve lo pers ty pica ll y req UIre the services of classes for wh ,ch ot hers are res po nsib le In other words , de ve lope r;' packages arc o r. e n re lated as citent and ,erver The prob lem IS that these service arc typica ll y in va ri ed sla tes of rC3dln es 3'> the app lica ti on I - In the process of being built .
A server componen t acts morc eHcclIve ly when its Interface IS narrow - arrow" m(,.-a ns that the mterface (essentially a colle tlOn of fun tion, ) co nta ins only neCCSs.1ry part>. IS coll ected ,n one pia e. and" clea rl y defined As exp laIned 10 hapte r 17. th,· Facade deSIg n pattem es tabl"hes Ju
malnfram terminal arch Itectures Olcnt/'>crver an. h,ttcturcs have c;ub ...equent l>, bee mc more ;,ophl heated J
and more va ned
orne arc now de~igncd as three· tlcf arch lt ecture~ Instl'ad of the ongmal two tlC~ (chent
and server) Tht third tl c r it t< betwee n the c1 ,cn l and the erver, prov Id,ng, Itsehtl level of II1d,rc tlon A C()mmon allocalton of (unction IS to de Ign the C UI fo r thc cl ,e nt , the database management, 'tem . or procedure management for the mIdd le layer. and »sorted app l,c, tlo n prosra ms a ncllor the dataha,e Iheli lor the thtrd la ye r The mIddl e la ye r ca n he a com mo n data "bitS" that br kef< commltnt a lto n ItcrnJtlwlv the mIddle layer can operate vIa a \l.nliard ",eh a, M ,cro,oft', ET . " (IIIMIt! FInall y the World ~ Ide \'(Ieb Un be: onlJldcred a bre d of ellcn ... rrver ar hnc(. turc In whl h "one- wrvrr/tcn ... of <..ht.""n l," .'> ft'plJ.ccd hy un krver/mdl,oo> of iten" ·
443
U.
CHAPTER 18 SOFTWARE ARCHITECTURE
18.2.2.2 The Parallel Communicating Processes Architecture Ano ther type of "Illdepe ndent o mpo nent" arch itecture idc ntlAed by Shaw anel Ca rl an" named pa,alle' (OmnHOllcnf"'9 processc . TIlls archilc lUre I characterized by scvcr;\ 1prace C". or threads. execut ing at the ~amt tIme. In h,s classIC book [2l. D'Jk,tra showed that co nceivIng a process suc h as the combIna tion of parallel parts can actuall y SImplify deSIg ns. An example of this is a SImul ation of customers In a bank Trad,t,onally, man y such simulati o ns were deSIgned withou t paral1eh m by sto ring and handlIng the events Involved . Such deSigns can sometimes be imphAc d, however, if th e movement of each customer IS a SCpM.1tc process (c 8 ., a thread o bject in Java ). uch a paralle l commun icating process dcsi.g n has the advantage that" matc hes more closely to the activitIes that it simulates A good refere nce to parallel communlca "ng processes in the Java context IS [ ]. The parallel proce ses may run o n a si ngle platfo rm o r o n separate platforms , as illustrated on Figure 18. 10. Encou nter uses th is architectural parallel eleme nt by havong the foreign c haracter Freddie move Independently from area to adjace nt area while the game progresses. This thread "communicate s" w henever
Freddie fi nds himself in the same area as the player character A UML notation that expresses parallelism was dIScussed in C hapter 16. Th is no tation, used in Figures 18. 11 and 18. 12, shows an architecture for a banking appl ication desig ned to handle multiple transactions occurri ng simultaneously o n automated teller machines (ATMs). This particular arc hitecture allows the customer to initiate tran sac ti ons without hilving to wait for completion. even w hen the transaction
,akes Significant time. The applicatio n may , for example, inform a customer that funds he deposited will not be immedIately available-that is, not wait for the completio n of that process befo re making the announcem~n[
When customer II uscs an ATM , an o bject for customer II is created (Step 1 in Figure 18. 1 1J. Customer II cr~ates SCSSIOII m (2) Sessio n m then retrieves an Accou~1t object such as customer t1 checki ng (3). The retneval.s
pcrfom1ed a ynchro no usly, and a thread , o r parallel process, is created because it may take time. Th is allows the custome r to carry out other bu si ness in the meantimc . The method call rc trievi ng the Accolmt object is de noted by • Slick arrow head indicating that the 5"';011 o bject proceeds in parallel with th is constructio n, returnin g to th e customer object. Si nce we are dealing at an archhecturallcvcl . we arc omitting details here
uc h as showing the thread objects involved and showi ng how the 5os;01l objects kn ow that thIS is its required
Platform 1
Platform 2
I
comun/catlon
e xecutJon
Figure 18.10 Platforms for communicating processors
Platform 3
SOFTWARE ARCHITECTURE AlTERNATlVES ANO THEIR CLASS MODELS
Requirement: Manage A TM traffic. Architecture beginning with first session: Customer_n
session_m
:Customer:
:Sesslon
create
customer_n_ checkJng
:Account
0:
.:
®
retrieve"
0
°
deposit·
deposlt-+j (",ore wo~
(thread detail omitted), Figure 18.11 Example of parallel communicating processor architecture diagram
managing ATM traffic. fragment of secuence
call. The Cuslom" object Immediately pcrfoml s a deposit "ansaClion by sending a me< age to t h e
5,,,,0"
object (4 ). TI,C 5",io>l object executes the d c poSit by sending a depos it message async h ronously to the
Ac oU>l 1
object. spawning a new thread ( 5 ). Other w o rk can go on-lilcluding by o th er seSSIOn s
whde the deposit IS
processed
In parallel , o[her Customt'r obj ects such as customer s are creating and operatmg on other <':;CSSlons such a seSSion
k.
This is shown
In
Fi gure 18 12 .
Figure 18. 13 shows the beginning of a class m o del that handle
thIS kind of architecture
Requirement: Manage ATM traffic.
customer_
s_saving : Account
Architecture:
6)
Customer_n
sesslon_m
:Cuslomer:
:Session create
customer 5 -Customer
I
retrieve" : create
'"
4 depoSlt+j
Withdraw
;
0:
..J
customer_n_ checking :Accounl
session_k :Sesslon
0
I
ret neve'
r_0 ::;5_
+-- - --n
d_e_P_OS_It_.
---+j
Withdraw'
f - - -- - -
U (Ihread detail omitted)" Figure 18. 12 Example of parallel communicating processor architecture
managing ATM trafOc - secuence diagram
445
446
CHAPTER 18
SOFTWARE ARCHITECTURE
,---------- .,
I
~
; Sessions : ., ,, ,
,,------.•, ,,, ,, Session , ,,
'--
Figure
18,13
•
---- ... . •
, ,
,-
, .
.
,_.-._.------. _. ___ • ____________ _______ _______ _ CuSlomers __________ J' , ,, ,• ,, ,,, ,, ~ Account ,, J" ,, depositO , ,, ,
,,,
•
.
,, ,,
withdrawO relrleveO
Customer •
-- -----.---_.-----
,
• •
Example of parallel communicating processor architecture managing ATM traffic-<:Iass model
18.2.2.3 Event Systems Architectures and the State Design Pattern Let's tum to
"""I
'Y,'mos , the third type of "independent component" architecture cla ssi~ ed by Shaw and
Carlan . Thi s architecture views apphca ti ons as a set of components, each of which wa lts until an eve nt occurs
that affects it. Many contemporary applications are event systems. A word processor, for example, waits for the user ' 0 click on an Icon or menu item. It then reacts accordingly, by stonng the fi le, enlarging fonts, and so o n. Event systems arc ofte n ful fi lled as state transition systems, which were Introduced in Chapter 11 . \,(,hen a system behaves by essentially transitioning among a set of states, the State design pattern should be conSidered fo r the design. This design pattern was explained In Chapter 17. For example, we have described the overall requirement fo r Encounter In terms of the state diagram in Figure I 1.26 of Chapter 11 . Encounter tranSit ions among the Sellin9 up. Wailin9 , Sellin9 qualilies , Reporting, and Engagln9 states, among others. Our design should capture this behavior effectively. It should also be capable of gracefully absorbing new states and action handling as the game becomes more complete, without dISrupting the existing design. For these reasons, we wdl app;)' the State design pattern described in Chapter 17 to Encounter. The State pattern solves the problem of how to use an object without having to know its state. In the CQntex't of Encounter we want to
be able
to wnte co ntrolling code that handles mouse actions but does not
reference the possible stales that the ga me can be in , or the specific effects of the mouse actions. This makes it possible to add new game situations without disrupting th is controlling code.
Figure 18.14 begi nsto show how the State design pattern can be used to handle the states and actions of Encounter. The framewo rk class RPGame ("Role· playi ng ga me") has an attribute called ,'ale , which is of rype Gam,sln'e . The subtype of slale (i.e., which subclass of GameS'ale it belongs to) determ ines what happens when handl,Ellrn'() is called on an RPGame object. The code for /,andleEv",l () in RPGam, passes contTOl to the h."dl,Ev", ,() function of state.
--
,- -I I
I I
I I I
•
: RolePiayingGame I _____1
.-------------------------------~-------
Slale
RPGame handleEventO
I I I
(
-- --- '
state.handleEvent{); )
------------ . ----- --------- . ------ -
EncounterGame 18.14
GameState handleEvenlO
I
Figure
--------,
Beginning of tl1e State design pattern applied 10 EnCOunter
I I
iI
I I I I
I I
-,
SOFTWARE ARCHITECT1.!RE ALTERNATIVES AND THEIR ClASS MODELS
------------,
lRolePlayingGam-:J -- -------
RPGame handleEvenlO
state
GameState hand/eEven'!)
( slale.handleEvonIO;)
--
EncounterGame
--- ------------
Waiting handleEvenlO
1
SettingUp handleEvenlO
f:::, ... ---- - -----
~
--1------------
~
: EncounterGam e 1l 1
Setting Qualities handleEvenlO
Reporting handleEvenlO
Engaging handleEvenlO
1 ~-------------------------------------------------
Figure 18.15 State design pallern applied
10
the Encounter video game
As shown in Figure 1815, each subclass of Gam,5Ial, implements handl,E"cnIO In its own manner. For example, if Encounler is in 5,"in90ualilirs state , and the event is the arrival of a foreign character. then the window pcrrOitting the setting of characler quality values disa ppears because th IS IS wha t the method ba.dl,E"rnIO in 5,111.90ual,Il<' is programmed to do An additional co nsequence of ,hIS particular even t/Slate comblOa tion IS that Encounter transition to rhe EII9agrng state , as required by the tate · tranSitIOn diagram This lransition is Implemenled by code
EncounterGame.setState ( newEngaging( » ;
The nexi ttme an event occurs in Ihe ga me, the I,alldI,E"oI IO funcllon of En9119in9 Will exeCUle, rcOectt ng the fac t ,h al the game IS now in Ih e En91191119 tat e
18.2.3 Virtual Machines AVlnual machmt ardulel.lurc::
trea lS an appli cation as a program written In a special-purpose language BecJuse
an Interpreter for such a language ha< lO be budt, lhl arch,tect"rc [.lays off on l If everal "program>' arc to be wmten '" the lanljUaHC, ge nerallng several appl,cal ,ons The Impl ementall on of a tO mpltlc vlftual rna h,ne requ lfe< the buddln!; of an Ifllcrprett r The lnt(:rpreLation requlrt:<; us to execute an o perall n- Iel 's JII It 1tI1trl'rt"() on a pro gram wntten In our lanllWge The 'nterpretall on of a prlmil ive clem ent alone (e g , a I'U '" the exa",ple of ~ h aplcr 17, ",here lhe part, of a " PU " are no t relevant ) " genera ll y Simple (flJr lhe ex.lIll l>lo, tim cou ld be >lmpl 10 pnnt lake
447
448
CHAPTER 18 SOFTWARE ARCHITECTURE
ho w to execute an i"'trprt'() (unct.on when ap pl. ed to a mo re complex "program ." T o do th .. , we may usc th e Interpreter de>l g n pattern. V.rtuaIOl" h". e arChllee!Ures arc advantageous .f th e application co ns"ts o f the process.ng of compit-x entit.es, and if these e nt itic , II h as th e v rders in the example , arc readi ly describable by a gramma r.
PU o ut f.t bo "l. The problem
IS
An add iti onal exa mple rcq uinng a Virtual machine is an app lica ti on th at provi des Cilmplc uscr-Jevd
prog ramming of a special purpose language. A nonprogra mmer use r, for exa mpl e, is ca pable of writlnS a "pt a s.mple program- uch a the fo 110"'111 g,
Balance checki ng / add excess to account + subt r a c t def ic it fr om sav ing; Save report / c : Reports + standard h e adings + except replace "Ed" by " Al " Pr i ntR e p o rt / sta ndard head i ngs e - mail reporttoJay n e@ xyz.net .
A virtual machine architecture parses and interprets such scripts . The idea of such architectures is dillst rated in Figure 18. 16.
18.2.4 Repository Architectures An architecture built pnmarily around data is called a rrposilory architecture. The most common of these arc ~ .. tcms deSIgned to p{'rfonn transactions against a databa se. For example, an electnc compa ny maintains a
database of custo me rs that ",eludes details about them , such as power usage eac h month , balance, payment hiStory, repa irs. and so on T ypical operations again st th is database are adding a new customer, crediting a pa ymem , rcquc tin g a payment history, reque sting a list of all customers more than three months in arrears.
and so o n. A typica l deSI gn for this kind of repository architecture is shown in Figure 18. 17 . This figure mixes the Aow of data between eMities (solid !tnes) and control (dashed lines). "Control" meJns that one of the en tities prompt th e operation of the other-for example. rurns It on and off. Other examples of applications with reposi tory architectures include interactive development environ .
me nlS (ID E ). IDEs apply processes such as ed.ting and co mpiling to a dalabase of source and object Ales. O ur Encounter exa mple in its simplest form docs not include a database.
if, however. it were to grow
Into a ga me Wilh man y ind ivi dual characters, then we might requ ire a database rather than J Aat Ale for storing t'he characters ThIS would certainly be true if we wanted to allow the user to ca ll up statIStics such as "list the characters Wilh strength under 10," and so on. Structured Query Language (SQI.) is a common way to express queries (sec, for example, [4]).
Application I
Application 2
Program I written in language understood by inte'l''''tcr
Program 2 written in language understood by intC'l'reler
I interpret~r I
I lnle'l'rc:ler I
Figure 18.16 Virtual machine archltectur~es;-lleveraging the Interpreter concept to facilitate the implementation of multiple applications
SOFTWARE ARCHITECTURE ALTERNATIVES AND THEIR CLASS MODElS
Analysis process 1
-
-~ • ••
Analysis process
Control
•••
• ••• ••
n
DBMS Key: Control flow : II Data flow: ..
~
Database
..
Figure 18 .17 A typical repository architecture
Blackboard architecture , developed for artificial intelligence applications, art reposltones that behave in accordance with posting ndes. The reader IS referred to [5] and [6] for a detailed treatment of blackboard archlt~ctures
The final ryPl" of repository architectures we
m ention
here
IS
the hypertext architecture The
m OS l
common u e of hypertext is on the Web. An application that manages the artifacts of a software engineering application is another example . The word "repoc;ilory" is often used in industry to den o te an app lication [hat provi des a und,ed view of a
collection of databases (, e., not just one). Th i relates to data wa rehouses RepositOries do not change the structure of these databases, but they allow lIn,jonn acce s to them ThIS is a peclal case of repository architectures as defined by Carlan and Shaw Repo nory architecrures occupy a significant frilctlOn of applications. Since so many architectures make
databases their core When the proces In g i negligible compared to the fonnattlng of data from the databa e, repOSitory architecture are appropriate . On the other hand , the presence of a large database can sometime mask the fact that a large amount of procesSing may dnve the architecture Ad hoc da,abase programmmB (e g., "stored procedure ") can eas ily mushroom into messy applitatlOns, wh ich perhaps should be conceived differently from the repository model.
18.2.5 layered Architectures An archltecturalltlytr I a coherent co llection of software artifacts, t)' picdlly a pa kage of classes In Its common form, a laye r u,es at mOst one other layer, and I used by at most one other layer. Budding appl, .t,on layer by layer ca n greatly <,mpl,fy the proce<s orne layers, such as framewo rks, ca n erw several applica tion> We have already seen the layered appro. h applied to the Entounter applICation , where clas«s '" the Encounter packa,!cs ",hent from cla<st' In the framework pack.ge> TI" " hown '" Figure 18 18 n,e Agure 'hows how we might orga ni ze the u'e of a 3·D graph ItS ens,"e", a laye r acce Sible from the Role· Pla 'Ing Came layer Fll!Ure 18 19 ,how, an examp le of a layered art hlle ture fran AJax bank pnntlng appil atlon n,ere arc four layers In thiS arth,tecture, and FI~urc 18 19 show, dependency 111 the reve". dire tl on ompared to Figure I ~ 18 The appli allon layer, AJax Bank P"ntlnl;, h., 10 do With prlntlnR and f rmattlnN II " olilit Upon (, e , u'>,,,) the Aunun!> and the AJax Bank ommon las> layer, The latter are blllh upon a \'endo l ~ppiled layer, which ~onlalns ~enera l utilitl su h as
449
,SO
CHAPTER 18
SOFTWARE ARCHITECTURE
3D
onglne loyer
D .. uses ...
Role-playing 9IIme Ilyer
ICharacters I
IRolePlayingGame I ILayoul I . - uses-
Application layer Encounter Characters
Encounter Environment
IEncounter Game I
Figure 18.18 Layered architectures. and example of 3D engine and video game
Requirement: Print monthly statements. Architecture: -uses" Ajax bank printing Layer I Accounts Layer I Ajax bank common IIbra.-Y' Layer Vendor-supplied Layer
+
Figure 18.19 Example of layered architecture for Ajax Bank-highest level view package of classes. For example, the Ajax com mo n library comprises classes used throughout Ajax applications, and addresses such issues as the bank's logo and its regulation s. The "using" relationship can be inheritance, aggregation , or object reference. In the example, only aggregation IS applied between layers, as shown In Figure 18.10.
18.2.6 Sen/ice-Oriented Architectures ScrvlCe-Orirnled Architectures (SOAs) arc gaining in usage. They are closely related to the idea of software as a service and cloud computing, and warrant inclusion with those discussed above. SO As arc combinations of S(flJicts: components that provide functionality according to an interf'ace speciAcation They differ from many
other application architectures in that they describe a sc t of interoperable components thilt can ~
dynamically harnessed to create functionality-rather than as a way to create a si ngle application SOAs arc in the spirit of facade objects, and include Web services as a means of Implementation. SOAs ace not necessarily obJect·oriented. In the case of Web servic« there is no assurance of globally defined classes as we have proVided for Facade In prior examples. For example, suppose that an SOA is for a businessto · busin~ss application concerning orJm. In an SO A, we would not assume that a unique Order class is known to and usable by all service suppliers and consumers. Web services in particular deals with this by dennln8 3 schema for an orderdat. structure, and referencing the schema when Web services Involve orders. Thi uses a Web service capability known as Web Seroicr D<scnption LAnguage and has the dfect of making an Order closs known to clients. This is summarized in Figures 18.21 , 18.12, and 18.23 .
SOFTWARE ARCHITECTURE ALTERNATIVES AND THEIR CLASS MODELS
Architecture
• •
t
~u s es"
Ajax bank printing Layer Acoounrs Layer Ajax bank common library Layer Vendor-supplied Layer
Class model: (relatIonships WIthin packages nol shown)
,-- - _. ,,
,,,
--_. _.. _. -----_. ---:'
IPrinter_-_._----_. I Formatter ----_ _- _ ..
------- ... : Accounts : r - - - - --. _. _------ --------., , Account Customer ,, , ,
,----====,-;'
iI
I
:'-_" Ajax bank co mmon library ,, w . ,, - - - - -- -- - - ..
----
Page
.. - - _ .. _-
_. "
,, ,, ,
Vendor·supplied layer nol shown
---- --- ----- --- . .. _- --- - -- ----- ... ,-- - ---- .... -. _- ---- ---. --- --- . ,
,, ,,
pnnting :,
Ajax bank
.._----_._- ---_ .... ---_ . . _- _. _--.,
,,,
Ajax Logo AjaxDisciaimer Regulations , , -----.----_.-._-- --------- .. ---------_ .. _-- .. ------_ .----- --.-- ------ .. __ .,
Figure 18.20 Layered architecture example uSing aggregation
Based o n compo nents th at provi de han ctio naln y accordin g to an interface spec
• Princ ipally via Web ervlces • In Ihe spiril of faca de o bjecls • NOl necessari ly 00 Example, An app lica ll o n co nce rnin g ordm • Wouldn'I assume an Ordrr class known 10 3 11 • Instead_ Defi ne an ordrr schema , refe rence when Web services involve orders Figure 1·S.21 Service-oriented architectures, 1 of 3 Servlcc -onented architecture,> e nvisage () network (mos tl y an Interne-t ) ·domlnated cnVlronml'm
which applications (and pans of app licatio ns) arc no t permanen dy wedded
10
In
each o lher Ralher SOAs
~ek to allow dy nam iC li nk ing of serviceS. For exa mple.-: , suppa e that you walll to write an appl. atlon that
orders
(The rderence for Figure 18 21 , 18 22, and 18 23 " l7] ) • ' Fire and forget"
• Stateless as much a< po-"ble • Extenslbte • Add,l",nal fun~lI o nalil Y eas il y added • Discoverable • Accou nt fo r Q ua lity o f Service
• h),
exa mpl ', security
FIgure 18.22 service-Oriented architectures, 2 of 3
In
order 10 Invoke It
451
452
CHAPTER 18 SOFTWARE ARCHITECTURE
• "Fife ,nd forget' • Sta teless 3') much as pOI:i'11 Ie • Extensible • Add,tional fun tionahty ea" ly added • Discoverable • Account for Quali ty of Service • For cXiimple. security
Figure 18.23 service-oriented architectures, 3 of 3
This defln<..'"S the components or the bu iness such as the customer data base and bu int."Ss. Credit poltcics arc cxampk--s of the latter. The s(nllCt 1t1Ier/aCt layer dennes the ser necs available that arc based upon the busincs proCl'SSCS. It specifics functionality such as listing all customers In the database and checking a transaction for conforma nce 10 buslncss rules. The laytr con iSt5 of applicat io ns buill usi ng the sCIVice internee la yer. These points are shown In Figure 18.24. crvice-onented architectures frequently uSc a bUSUltss proctss
"'Y"
.ppr.c."""
18.2.7 Using Multiple Architectures within an Application Applications typically use severa l subsidiary arc hitectures wIth in an overa ll architeclU re. Figure 18.25 shows how the fra mework for role-plaYing video games could use everal of the architecture types lIsted by Carlan and Shaw. It could make se nse, fo r example, to orga ni ze the ArtifMt, package as a database. The game characters could be VIewed as parallel communicati ng processes. We will design the overall control of the game as an event-driven sy tern .
Appplication A
Application B
Appplication C
(J
.. usesService Interface Layer
.. usesBusiness
Figure 18.24 Llyerlng for service-orlented architec1ures SOUn:f'. AQIc)ted from En. nlOfT'laS. " seMc:e
TRADING OFF ARCHITECTURE AlTERNAnVES
CharaCfers RolePlayingGame
Parallel communicatmg ___
processes
--______----
Rule-based
system
___ Event system Poslble
---------'
- -j'- architecture types used
Layoul
Database • system Layered _ _ _ _ __ system
Arlifacls
Database
system
Encounter Layout
Figure 18.25 Example of the use of multiple subsidiary archltectures-Encounter video game extension
18.3 TRADING OFF ARCHITECTURE ALTERNATIVES Since the hOler of a software archlte ture IS 0 lI11p Ortanl , It IS wi se to create more th.m one alternati ve for consideration . As an example, we will create and compare two Jrchit cctllrC'S fo r the video store applicat ion
For the nrs. candida.e, we separate .hl· applica'lOn In.o .hrce majo r pans, The "back ·end" da.abase , the middle pan , w hich cOnlains the bus lncss logic, and .he C Ul s. This IS • 1/",,·II(r archi.ecture . It IS often an appropria.e choice when some or all of .he .iers resi de on phYSically separa.e plattomlS In parllcular, If .he CUls are all on PCs, the middle la ye r on • server, and the databases controlled by a database managemen. system , then three· tier architectures map neatly to separare hardware and software unitS Note that there IS no n~ccsslty that hardware decompositions bt., the sam(.' as sofrware archltcctures, we ma y want a logical
(conceptual ) view of an applic.llon to be cnllre ly independen. of .he hardware platform, hosting " (These are the phYSlca' VICW vs .he 'oglCa' view .) App lYIl1£ three tiers to .he video Store applicallon, ,,'e cou ld ob .aln the architecture In Figure 18.26
,
VSOperalions
VSGUls
Presenta tIon
lIer
I
Figure 18,26 Three-lier architecture alternative
VSData
Dala tier
453
4S.
CHAPTER 18 SOFlWARE ARCHITECTURE
[" .......;;;;:;~~...............-..............'...........................'.................~;;;.~;~~,..~~~::::;~..............'..···...............··1 I
,
,
!I I I
I.,
: II
I
VSCuslomers
i i
I
I
1.. _ ••_ .... __ ..................... .....................
_
_
........................................... ............... ........'
1
........... .i•
Figure 18.27 Altemauve architecture for a video store application
The strength of this architecture IS that it's easy to unders tand. Anolher strength is that since the CUI part IS separate from the rental ope rati o ns it can be changed withoul di sturbin g the latter. O ne weakness is the coupling between the GUh package and the V50ptratio", package; there may be severa l CUI classes corresponding to the C. "om" class, for example. Therc is also cou pling between the classes in the V5Data package and the classes in V50p"alio", . A second architecture ca nd idate IS show n in Figure 18.27. Th is architecture g rou ps all of the classes pertaining to the vi deos in a package. The R",tal, package contains classes that relate videos and customers. The C" stomm package contains the classC"5 pertaining to customers, includi ng assoClaled CUls. A third option would be to group all d isplays in a package. Figure 18.28 summarizes onc opi nion of th ese architecture alternatives.
18,4 TOOLS FOR ARCHITECTURES Various computer·aided software engineering (CASE) tools arc used to facilitate the software engineering process. Some tools represent classes and Iheir relationships, such as Rat io nal Rose by IBM Corporation. These tools facilotate the drafting of object models, linking them with the correspo ndin g source code and sequence diagrams.
In selocting a modeli ng tool , a list of the requireme nts fo r the tool
IS
drawn up using procedures si milar
to the requirements analysis process for software application development. Here is an example of some requirements for modeling tools .
• Essential: Facilitate drawing object mo dels and sequence diagrams
• Essential , C real e classes quickly
Three-tier
Alternative
Understandable ) Flexible)
Yes Yes, CUI easy to change
Yes Yes, Basic building blocks easy to identify
Reusable)
Not very, Each layer is spocial to video store rentals Perhaps
Yes, Easy to generalize to generic rentals
Easy to construct)
Figure 18.21 A comparison of arChitectures example
Yes, Clear potential to use Facade
EFFECTS OF ARCHITECTURE SELECTION ON THE PROJECT PLAN
• Es ~ntt"
Ed,t cI,sses ea"ly
• Dcslrnble· hould cost no more than $X per user • Deslrnblc. Zoom Into part< of the model • Desirable. Possible to Ju mp direclly from the obJecl model 10 the source code • Optoonal , Reverse englneero ng available (i e., create object models from source code) • Oplional. Use color coding for tatu of class Implemental io n Tool packages frequen tl y try to span arch,teclllre, detaoled desIgn , and ImplementatIon . Varoous vendors are developong the capabi lity to hyperlink from source code to documentatoo n and VIce versa Implementati on-oriented tools uch as Javadoc can sometomes be use ful to supplement the desIgn process Javadoc is useful for navigatlllg packages because it provides an alphabeticallosting of classes and the parent hi~rarchy of each class. Interac tive development environments (IDEs) are delIvered with compolers and arc WIdely u ed as partial modeling tools. Object -Oroented IDEs ge nera ll y show inhentance In graphICal fonn , and developers are frequently auracted to these
18.5 IEEE STANDARDS FOR EXPRESSING DESIGNS The IEEE Software DeSIgn Document (SOD) slandard 10 16- 1998 provides gui delInes for Ihe documentation of deSIg n . The lable of cOntenlS is shown In F,gure 18.29 IEEE guidelones explain how the SOD could be written for various archilectural ryles, most of which are de
18_6 EFFECTS OF ARCHITECTURE SELECTION ON THE PROJECT PLAN Once: an architecture ha< bee n selecled, Ihe schedule ca n be made ma re >peclr, and more detaIled In partl ular, Ihe order in whIch part< are bUIlt can be dctennlncd For examp le , on the cas. study 11m, kes <ell," to fir" develop the (hamCler! fram ework pack.ge , followed by Ihe speCIfic EllcoulllrrCl",,,, I", appl,cat,on package S,n c thes packages w oll nOI be comple ted In Ihe ('''1 Iter.tlon f the ' llIr.I , we n.nte the
455
456
CHAPTER 18
SOFTWARE ARCHITECTURE
1. Introduction 1.1 1.2
1.3
•
4. Dependency description
Purpose Architecture Scope ..... Definitions, acronyms. ' and abbreviations IAI 5. •
2. References
4 .1 Intermodule dependencies 4 .2 Interprocess dependencies 4.3 Data dependencies Interlace description 5 . 1 Module interlace
y
5.1.1 Module 1 description 5.1.2 Module 2 descriplion 5 .2 Process interlace
3. Decomposition description 3. 1 Module decomposition 3. t. t Module 1 description 3. t . t Modute 2 descnption 3.2 Concurrent process decomposition
5.2. 1 Process 1 descriptIon 5.2.2 Process 2 description
6. Detailed design 6 .1 Module detailed design
3.2.1 Process 1 descrlpt jon 3.2.2 Process 2 descripl10n
6.1.1 Module 1 detail 6.2.2 Module 2 detail 6 .2 Data detailed design 6.2.1 Data entity t detail 6.2.2 Data entity 2 detail
3.3 Data decomposition 3.3.1 Data entry 1 descriplion 3.3.2 Data entry 2 description
Figure 18.29 Tlte architecture parts of IEEE 1016-1998-500 table of contents SOurce" IEEE Sttll016-199S.
corre ponding tasks ' Charac ters I" and "EncounterCharacters I." Arrows indicate depe ndence of packages on others. For example, "EncounterC haracters ('. cannot be completed with out th e completion of "C haracters I: as shown i n Figure 18. 30 . The sch edule sh ows th at "Integrati on and Te st I" canno t begIn until all of the other tasks In Iteration I have been completed. Month 1
---------M ilestones
Month 2
Month 3
Month 4
Month 5
--l 12341 234 1 2 341 234 1 234 Freeze
I Complete testing
~-
Iteration 1
Iteration 2
Figure 18.30 Schedule following architecture selection
CASE STUDY; PREPARING TO DESIGN ENCOUNTER (STUDENT PROJECT GUIDE CONTINUED)
18.7 CASE STUDY: PREPARING TO DESIGN ENCOUNTER (STUDENT PROJECT GUIDE CONTINUED) Thl c tlon de)cribes a '\ccnano of how the Encoun ter proJC t team may havc go ne about the creall on of the- Encounter ar hltccture
18.1.1 preparing In accordance with th,' PMI', Karen Pe ter, was the dcslgn leader, with Ed Braun backing her up and in pectlng all of the desig n work . Karen aimed to develop two thoroug hly prepared alternative archl ' tectures for the Encounter project and bnng them to the team's preliminary design re vlcw. She was deter·
-
mined to aVOId unpleasa nt haggl ing over anch ltectures that wcre devi l·d by different engineers She fe lt that ego rather than technical ISSueS predominated in such ca cs . She had even wo~e rnemanes of architecture
unclear to them what the "client" and "scrv<:= r" roles
would be, 0 they dism"scd th l alternative "Event systems," the nex t type listed, appeared to be a cand idate architecture slOce the game responded
to cnher user- In itiated
evcnt~,
such as the presSing
of an area hypcrlmk to enter an area, or to th e arnva l of th(" ( reign character \0 the sa me area as the player
c harac tc r They no tcd thIS as another cand idate JrChllC Hire.
ext ,
Ed and Karen conSidered "Virtual ma -
·compromiscs" {hal were crea ted lO reconcile com -
chines ," asking whether each game executton con -
peting architectures. These freque ntl y resulted In po r designs that everyone had to live and work with da ily for months, if no t years. On the ot her hand, Karen did
sis ted cssl"ntlall y of th e interpretation of a cnpt
not want to produce an architecrure in isolation. She
decided that she and Ed would sclCL t architecture candidates together, research them thorollghl y, and present the choices to the team
18.1.2 Selecting Architectures
-
proces os. Ea h could be run o n a \Cpa rate parallcl thread, and the c threads would commuOicate when ever th4.: c haracters encou ntered each o lhe r. They no tcd lhl s as a candidate architecture . The y onSldere d "cl lcnl .. erver" ne xt, but it was
AI Pruitt had been thinking abollt the deSIgn of the game application , and he gave Karen a sketch of an ad hoc CU I-driven anchltectu re. He pOinted Ollt that It was simple and would be qUick to Impleme nt Ed and Karen rovlc-wed Carla n a nd Shaw's 1"
Th is d id no t appear 10 them to be the ase They co nsidered whether the ga me could be thoug ht of as bu ilt arou nd a reposllory of data (a "repository system"). The data could be the va ilies of the harac ters and the statuS of the game They deCided that thiS might indeed be a po. IblillY if there were man}' characters and many artifaCtS, bccau e In th at case , rht' manipulation of large amOllnt~ of data might predominate Sin C Encounter \Va ... not to be data -cen tn c, however, they rejected (hIe;; candidate
Fin ally, they co nsidned a la yered architecture T he quesllon here was whether Encounter could be Vlc\oJcd a a c;;cncs of clac;;\ grouping wtth each groupmg: uSing o ne or two of the othcrs Karen fe lt th" t th ere wo uld indeed be at Ica t two u eflll la yers one fo r role -play ,"!; games In ge ner"l , and o ne for Encollnter They m.dt· " no te of thi S ca ndl dJle ar hltcctll re , and ended th eIr con'i.lde:ra tl ol1 of arla n and Shaw' optlo ne;;
Now the y II ted the "rChllenlire candldate< AI Prultt'< Parallel
UI -dnven ardlltc ture I11munl calln~ procC'se'
Evei'l l ... y'll' 1ll 1;"
I.ayncd
457
458
CHAPTER 18 SOFTWARE ARCHITECTURE
TI, CY dl cu"ed w hl h of th«e described the ovc",11 archltccture and whIch wcre
to commIt· to archItecture. no advan tage of the labl e (Table 18. 1) IS that It all owed th em to more ea sil y reevaluate th eir reasontng n'lCIr conclu'\loll was that layenng was the pnmary archilc tural prin iplc
Ince there was a
generic ro le·plaYIllS game layer and the Encounter laye r Itsc l f. They env lsaKcd the · cvent sysrems" architecture as ubSldiary to the layers They post· po ned a d etai led diSCUSSIon of parallel communicat· ing proccsses for th c game c h aracters. Concep tuall y .
Table 18.1 Evaluation of architecture candidates by means of design qualities
Candidates
AI Pruitt's
parallel communicating processes
Event systems
Layered
Qualit ies Sufficiency: handles the requirements
1
1
2
2
Understandability: can be understOOd by intended audience
0
2
1
2
Modularity: divided into well·defined parts
0
0
1
2
Cohesion: organized so Iike·minded elements are grouped together
1
0
2
2
Coupling: organized to minimize dependence between elements
0
1
0
1
Robustness: can deal with wide variety of input
1
0
2
1
Flexibility: can be readily modified to handle changes in requirements
1
0
1
1
Reusability: can use parts of the design and Implementation in other applications
0
0
1
2
Information hiding: module Internals are hidden from others
1
1
2
2
EffiCiency: executes within acceptable time and space limits
1
2
0
1
Reliability:
0
1
1
2
TOTAlS
6
8
13
18
CASE STUDY: PREPARING TO DESIGN ENCOUNTER (STUDEN1 PROJECT GUIDE CDN1INUEDI
lhdr mam archw::,cture sele
tlOn
is reAeeted
In
ngun!IS. 35 Th~y
decIded to ~XP"'ss the "evcr.t ystems" arch,tecnon! by m~ans of tates and transitIons. Then they debated whNher to use the State deSIgn pattern or a tatelaction table to describe the eventltransl' ttons, and deCIded to apply metrics to assist in choosing from the architecnores under consIderation, Including AI Pruitt's. They used e-mail to try to get agreement on the ""(:Ightlng of critena for architectures (extension,
change, etc ,-see Table IS I i.e., "Evaluation of arch,tecnore candidate by means of design qualities,") ,
-
-
10
advance of the meeting, without mentioning
the architecture candidates themselves. They then e· maIled AI a draft of the comparison table in advance of the meeting to make ure that they had not missed any aspects of his proposal Al pointed out that the choice of architecture was heavoly depende;]t on the weIghting, but was willing to accept the team's weighring. Karen and Ed drew up the spread sheet Table IS. I, comparing Al Pruitt's architecture (a her· natIve 2) and two others they had developed , and maikd It to the team members so that they would be prepared for the meeting.
18.7.3 Team Meeting (Preliminary Design Review) At the meeting, Karen and Ed first confirmed agree · ment on the weighting of croleria Because of their use of c-mail pro o r to the meetIng , th e team did no t take long to Iron out the: few remaining Inconsisten ·
v
cies No mentio n was made ye t of the arch Itectures themsel ves They presented the arch ,ttcnore altcrnatives to the team , shOWI ng the pread heet result< Aiter some d,SCUSSIon and mod,ncati o n of theor assessments, the team conRrmed thtor selec tion of the laye red arch ,tecture and the u« o f th e tate desIgn pattern Karen and Ed', thought process and preSontallon had been thorough The tcam's dISCUS· SIan focused on how to Improve the arch,tcctu,c Ihe wanled to thInk thrOuRh the
18.7.4 Refining the Architecture Karen and Ed wen! now faced with the task of decomposing each layer. They performed this by plaCIng the two additional archllecnoral elements in se parate packages. In the role-playong game laye r they formed a package for the state machine called RolePlaYlngGmh'. To handle the game characters, which move around in parallel , they created a Cha racttrs package They also created a Gam,f".iro"",,,,t package to contain classes describing the places on which the charac ters would move . Finally, they envisaged an Artifact. package for the funore to describe the miscellaneous Items such a shields a~d swords th.t would be involved. This package, postponed for future releases, would have a Repo.itory architecnore. Their decompositoon of the Encounter applicatIon layer was analogo us since man y of its classes had to inherot from the generic game level They decided to create narrow access paths to the packages of this layer to prevent a sinoation In wh,ch any class could reference any other class. They felt that such un restricted references would soon become impossIble to manage durong development and m.intenance. To accomplish this narrow access they used the Facade design pattern fo r each applicatIon package . Ed had some reserva tions abom doing (his because it 10 · creased th e amount of code the team would have to create .nd manage. Methods would not be called directly, he poonted out, but only through speCIal methods of the facade o bjects , thereby increaSIng the total number of methods It also Introduced compl ,cations in that internal classes could not even be mentioned by objects external to the package (although theor generic base classes could be), but Karen convinced h im that the price was worth the beneRt of havong a lea r onte rfa e for each package. They obta Ined approval for their archotecture at a ubscquc nt team meeting .
18.7.5 Documenting the Architecture Ed and Karen used etlan I through 5 of the IEEE standard IOl6 toexpre s thear hotcc ture lna oftware DeSIgn Document ( DO) Ince the h.d dIVided the app lo a tl On Into two layers, one of wh, h wa slated for reu e, the y de Ided to do lIment the framework "ro l c- play",~ I/a me' 10 er In •
459
460
CHAPTER 18
SOFTWARE ARCHITECTURE
18 .8 CASE STUDY: SOFTWARE DESIGN DOCUMENT FOR THE ROLE-PLA YING VIDEO GAME FRAMEWORK
We have two designs to describe The Rrst I that of the Role-PlaYIH9 Video Gn IMe framework ; the second is that of the Encounter role -plaYing game . The DD, for both de Igns are split into twO parts_ The first parts, DD ectlons I through 5, shown below, consist of the architectural aspects of the design . The second part, SDD ection six, appeanng at the end of Chapter 19, con IstS of the detailed designs. n,e dependence of Encounter on the framework IS spccd,ed
10
the Encounter case tudy ,
HIstory of versions of thI S document;
yylzzz K. Peters: Initial draft x/yy/zzz K_Peters: revised, incorporating comments by R. Bostwick x/yylzzz K. Peters: moved details of c1asse to Section 3
1. Introduction
2. References SojlUln" EII9",ccrill9 An
b)",-O"e,,'ed Pcrsprc"oe, by
E. J Braude (Wiley. 200 I). UML The UHtfied Moaef"'9 u"'9""ge Guide, by C Booch, J. Rumbaugh , and I. Jacobson (Addison Wesley IEEE standard 10 16-1987 (reaffirmed 1993) !,'Uldcli nes for genera"ng a Sofrware DeSign Document.
u,"
3. DeComposition Description
Note to the Student: This s
3.1 Module Decomposition
1.1 Purpose
ThIS section shows the decomposition then
This document describes the packages and classes of a framework for role -playing Video games.
explai!1s each part in a subsection.
games si nce ItS size is kept small to facilitate learning.
n,e framework consists of the RofePlayiH9Game, CiJllraricrs. Ar"jael" and LAyo,,' packages_ These are decomposed into the classes shown in Figure 18_31 _ The classes in these packages are explained below. Unless otherwise stated, all c1asso in the c packages are public. As indicated by the (UML) italiCS notatio n, all of the framework c1asse are abstract.
1.3 Definitions, Acronyms, and Abbreviations
3.1. 1 RolePlayingGame Package
1.2 Scope This framework covers essentials of role -playing game classes. Its main intention is to provide an
example of a framework for educational purposes. It is not Intended as a framework for commerCial
This package framework : a collectton of interrelated classes used, via inheritance or aggregation, to produce families of applications
RPG, Role-playi ng game: a video game
In
which cha~cters Interact in a manner that depends on their characteristics and their environment
IS
deSigned as a
state - tranSition
rna.
chine. The concept is that a role -playing game
IS
always in one of severa l states. This package makes it
pOSSIble to describe the pos ible sta te of the game and the actions thai can take pl~ce in response to
event>. It implements the State deSign pattern (sec [8]) The Sta te of the game I< en ap ulated
CASE STUDY: SOFlWARE DESIGN DOCUMENT FOR THE ROLE·PIA YING VIDEO GAME FRAMEWORK
RolePlayingGame
RPGame
Characters state
GameCharacter
handleEvenlO
..J
O.. n ( Slale.handleEvenl(): )
IRPGEvent r-
., GameState handleEvenl O
GameEnvironment
GameLayout
2
GameArea ~ Artifacts
For future releases
GameAreaConnection
Figure 18.31 RPG fra mework for role·playing video games (represented) by Ihc part Icu lar Gam,Sla l, obJe tag · gregated by the (s Ing le) RPGam, object Th is ag!."e · gated object i named statc. In other words, state is an attribu te of RPCam, of type Gam,SI,"'. The functIo n ha>ldl,E""'I() of RPCam, I ca ll ed to ha ndle each event occurnng on the monItor (mouse c"cks, etc ). It executes by ca ll ing the hmldl,E"",:() functIo n of state The app licab le versIon of handl,· Evtrll() depends on the particu lar ubclass of Gm.,Slal, that state be longs 10
3.1.3 GameEnvironment package T his package de cnbcs th e phYSIca l envIronm en t of the ga me . T he class GntllC'Llyolll aggregates co nnl'C tion obj t:ct" Each connecti o n obJc 1 aggrcgatc~ the pai r o( Gam rA,m objects that Il connect<.. Tlw. arc hl .
lectu re allows for multiple connections between twO areas . Eac h GamrAr(Q object aggregates t11t~ game
characters that
ontalAS (If any ) and can detect
encounters among chara tl;'r~
3.1.4 Artifacts package (Not Implementedfor Future Releases)
3.1.2 Characters package
TIl\'; packagc IS Intended to store e l c m c nl~ to be;.' 10CCllCd
It may seem strange to have a package co n· tai nlng JUSt oAe class, but most arll faclS In software desIgn have a te ndency to grow Even if the pacakge docs not grow, this d~ not dISqua lify it< usefu lness. For anot her example of a package with just one class, sce jaua appl'l, whose only class IS Applrl (but 11 . 150 contains a few '"tertaces)
TIm package containS the
It
Cdrn,r/wdCItr'
whIch dC>CTlbes the charoet rs of the ij3me
la"
In areas, slich as tree or tables. and
Cnt ltl C
posse< ed by character , such as , hIe Ids and bncka es
3.2 Concurrent Process Decomposition
nl(' framework dOl's not II1volvl" conClIJT(:nl pro
~'C'
4. Dependency Description
ThIS 'c lIon dc< "be all the way' In ".hl h the modules depend on cach other
461
462
CHAPTER 18 SOFTWARE ARCHITECTURE
Tl,e only dependency among the framework module, I the Jggregation by Cam,Arra of
UML Th, UH ifi,d Modrl"'g UlHgung, U>
5. Interface Description
Booch, J. Rumbau g h, and I Jacobson (Addison Wesley. IEEE standard 10 16· 1987 (rcafflrmed 1993) gUide· lines for generating a oftwar. Desig n Document
All classes in these packages arc public, and thus thc Internces conSi t of all of the methods in thei r classes.
3. DeComposition Description
Gamr ham fer
18.9 CASE STUDY: SOFTWARE DESIGN DOCUMENT FOR ENCOUNTER (USES THE FRAMEWORK) HIStory of versions of this document,
The Encountcr architecture is deSCribed usi ng three mode ls· lise casc, cia s (object) model , and state. In addition, the relationship bet,,'een the domain packa8es of Encoun ter and the framework described '" thc SDD enti tl ed "Ro le · PlaYinS Came Arc hitecture Framework" will be sho wn .
x/yylzzz K Peters, initial draft •
•
•
x/yy/zzz K. Peters, addcd decomposition by usc casc model and state model
1 . Introduction
1.1 Purpose Th is docu me nt describes the desig n of th e Encounter rolc· playing game.
1.2 Scope This deSign is fo r the prototype version of En· counter, which is a demonstration of architecrure ,
detailed design , an d docume ntation techniques. The architecture is inte nded as the basis for in teresting versions in the future . This descrip tio n excludes the framewo rk classes, whose design is provided In the SOD cnlitled "Ro le· Playing Came Architecture Framework."
1.3 Defi nitions, Acronyms, and Abbreviations None
The IEEE standard is extended usi ng Sections 3.4 and 3.5 in o rder to descri be th ese models. Recall th at the other possi ble model is data flo w, whic h we have no t co nside red useful in this case. In the particular case of this video ga me , we chose to use th e statc descri ption as part of th c requirement as we ll as the design.
3.1 Module Decomposition (Object Model) This section sho uld no t dupl icate the "detailed design" secti o n described in the next chapter. We do roOt go i ~to dotail here regarding the con tents of th e packages.
T he package architecture for Encollntl!r is
show n in Figure 18.32. T he th ree packages arc E'1C'OUl1tlrGamc , El1co ,mttrCha rac1trs , and fl1C"o"nttrEH OtrOtfmrnl. These have: facade c1as cs El1 counfc:-Gamc, El1couPltcrCasf, an d fn co uPi ttrEl1lJiroPlmtnt respectively . The facade class of each package has exactly onc instantiation , and
2. References
is an interface through whic h all
dea lings wit h the package lake place . Th e re main. ing classes are not accessible from outSide the
"Role· Playi ng Came Arc hilecture Framework: sec· tion in Software £.9i."n.9 A. O'J
package (Sec Section 17.7. 1 In Chap ler 17 and [ I ] fo r a complele deSCri ption of the Facade deSign pattern .)
CASE STUDY: SOFTWARE DESIGN DOCUMENT FOR ENCOUNTER (USES THE FRAMEWORK)
EncounlorGamo
EncounterGame .. facaC16,.
EncounterCharacters
EncounterCast .. fscade,.
Encoun18rEnvironmeni
EncounterEnvironment .. facade ..
Figure 18.32 Architecture and modulanzatlOn of Encounter game
3. 1. 1 EncounterGame Package The EncoIHl,crCmt1( package consi ts of the classes can· rrolling the progress of the ga me as a whole 11,(, package
IS
dl"signcd to react to
lIsc r
The data stnl ru res Aowing among lhe pack· ages arc: defined by the Area , EncoIH1!rrChnrtJc frr, and Ellco lI~llrrAr(Q Dill/teflon clclSSC.,
actions (eve nt,).
3.4 State Model Decomposition
3.1.2 EncounterCharacters package The E'1C'ouHttrChamc frr5 packa ge cncompas
lOS
th e
characters invo lved In the game. These Include
EnCOUnl('r co nSIst,
of the slate, <;hown In FIg.
ure 18.3 .
character(s) under the co ntro l of the playe r toge ther with the foreign chllra lers ,
3.1.3 EncounterEnvironment package
This state diagram was provided in the SRS , Section 2 . 1.1 , where it was used to des nbe
The EnCOUHltrE,wiroH,"oll package dcc;cnbcs the phys -
the rcq uirements fo r En ounrer Tht, remaIn ·
icallayout of Encounter, oncluding the areas and the
ing stares mentioned in the reqUtremenb WIll
connecti ons between them
be implemented in ubsequent relea<es
moveable Items,
It doce; not Include
Ir any
3.2 Concurrent Process Decomposition
3.5 Use Case Model Decomposition
There are two concurrent proccc;c;cs In Encou nter Th e
fir<;! IS the maon VISIble a tion of the game, m whIch the player manually moves the maon chara ter from ,rea to adjacent area The second con<"t< of the moveml'nt of the foreign character (rom area
10 ildJilCC lll area.,
Thl section IS added to the IEEE 'pcclflca tl on, whICh doc not address the use case concept It has been added at the end of thIS section 0 a, not to dl>turb the st;;ndard order
3.3 Data Decomposition
EncounH.' r
Trfwrl
Descflbc, the
10
AdprtCtlI
~nH.' St' u,(,
onS I ~ t s
f thrl'"
u .. e
JIi;Co;; IPlllwl,:r
Artll , Jnd EtltOIHlltr FortHl11
Chili"
Il't
('xplJlI"lcd In del;)!! In thc R "cellOn 2 2, Jlld Jr(' clt·tollled In ,cellon ... kllcr III till' dot-um
' fll
()'c<;: :lrc
463
464
CHAPTER 18
SOFTWARE ARCHITECTURE
Player
Setting up
_ -1 Reporting Setting qualities
dismisses report
Player compleles setup
window Player dismisses set qualities
Player requests
widow
Player requests to __-- , qualities
status
Waiting I---<: Foreign character
Playel
Foreign character enters SleB
enters area
moves to adjacent area Player quits
\
Encounter
campleted --l
Engaging
presenl] absenl]
Figure 18.33 State·transition diagram for Encounter video game architecture
Details .,.., given in the "detailed desigr." section.
There are no significant dependencies among the usc cases,
4. Dependency Description
4.1 Intermodule Dependencies (Class Model)
This section describes the dependencies for the
The: dependencies among package interfaces arc:
various decompositions describe d in Sec tion 3.
shown in Figure 18.34. EncounterGame
EncounterGame EncounterCharacters
Encoun1erEnvironment
FIgure 18.:W
Architecture (rnodularization) of Encounter \/ideo game
CASE STUDY' SOFTWARE DESIGN DOCUMENT FOR ENCOUNTER (USES THE FRAMEWORKl
Th~ Ell OIm,rrCnmr pa kage depend o n all of the other En ounter p() ckage~ The En oJmlrrEmmotllnnst
4.4 State Dependencies
po kago I d Igned to depend On the E"co""lrrebara,'ers pa kage ThIS IS becau c the game'. charac · ter Int~rnc tl o n takes place o nl y on the context of rhe
Each State I related to rhe
4.5 Layer Dependencies
~nvl ronm ~n t. I n part icular, Arm objec t arc re po nsi ·
ble for detcmllning the presence of the player's char.ctcr together with the fo reign charncter O,'pendenclcs among no nln terface classes arc expJalnl.'d late r i n th i.; docume nt.
Such dependencie specIficatio ns.
arc
detailed
The Encounter app location depend. on the Ro/rP/IIYJIl9 Gllmr fra mewo rk a , hown on F,gure 18 .35 Each applICa tion package u'c< exa t1y one framework package
5. Interface Description
deSIg n
TIll<; section descnbes the InlC-nan.· .. lor the obJcct model o te thaI ,eve ral of the cla',cs descrobed arc dehned In the de
4.2 Interprocess Dependencies When an engagement rakes place, the pmcess of moving the mai n charac tt: r about and the pro c;,; s contro lling the movement of the fo reig n charac ters Interac t.
5.1 Module Interfaces
4.3 Data Dependencies
5.1. 1 Interface
Descrobes the interaction among the packages
to the EncounterGame
package The data tructures OO'oJ '" B among the pac kages arc defi ned by the classes, whose mut ual dependencIes are descro bed on ccto o n 6 of thIS docume nt.
Th e Inter face to t h c Et1 colwfcrGnmr package IS pro ·
by th e the GII,"r racade cia
v lded
obJ e 1 of the E" colmttr It conso" of the follOWIng
Etl COlwtrrGm11c
j._---_..._ .._--;::-=..-:::..:::-.=-=:::-=:::-:::._:: ;...... _ _--:::.-:::-::.=._=:::.==:::.: ._: ;._._.
~
i
I
Characters
GameEnvlronment
AolePlayingGame
l
I
• •
•
.. uses ..
, Role-playing game layer (framework)
........ ... . . . . . .. . .,...: :': '::'
:.. .•.......-.....--·1-..... ,.._ ..•- .... .
..
=
I•
,,
,
I
•
, j , \ I
IEncounterCast I
~
===~:;-
IEncounterGame I I EncounterGame
--'---------
I EncounterEnvironment I
EncounterCharacters
• by member classes Imp/emen· ring framework Interlaces
.- -- -- --.Agure 18.35 FramewOrk·i-applica tlon depend ncles
-.
,,
EncounlorEnvlronment
- - - .--
_.
-
-
, ,
465
466
CHAPTER 18 SOFlWARE ARCHITECTURE
1 Encounler "mc ~e lTh cE n oll nlcrCamcOllgcl\
the ani , 2
InS tJIl
and areas one or two connc.:(ll() n~ dlstilnt
e
arn e laIc uC I la lc OIl urre nl ~ EtlcoutllrrGmttt In sta nce
6. InMHe HeINclghborhoodArc.s(Arc.;llgct\ II,,.
sta le
of
Ihe
f 5.2 Process Inter ace
3 VOId SCI lale(CJl11eSlatc)lI- of th e Ell ol!ll lrrGamc In StanCe
4. IIAny even t aHec lmg th e . ingk- Ell ou,lll'r ,ame In stance:
5. voi d handlcEvc nt (AWfEve nt )
5.1.2 Interface to the EncounterCharacters package The intcrfJce to the Encol/lflcreharnel,n pack age is provided by the tbrEncolmlrrCnst object or the E"colwltr-
Ca,' f.. cade class It consist of th e fo llowing. 1 Encou nlcrC3st gelTheEncounterCast()//gc ts the single lO~ta nCt:
W e stated on Sectio n 3.2 th at there a rc twO processes In volved in Encoun ter. Th ere is a SIg ni fica nt design decisIo n to be made in re· gard to the interface to th e fo re ig n c harac ler movement process, and we describe th e result here . O ne o ptio n is to have the fo re Ig n c h.r· ac ter a thread, contro lling itself. This has advantages, but requ ires this c harac te r e ither to know the enviro nment- a disadvanta ge in te rms of c han gi ng and expanding the gameo r to be able to fi nd out about the e nvi ronm ent dynam icall y, whic h wo uld be an elegant de· sig n but too ambitio us lo r the scope of this case study. The architect'ure o pts for another alternati ve, wh ich is tated here.
2. CameCharacler getTh ePl aye rC harac ter()//i e ., the uniqtJc character
3. C ameCharacle r ge tTh eFo cclg nC haracter()/lthc un ique ch arac ter
4. IIExchange q ualI ty values specific to th e game area
5. VO Id engagePlayc rW ithFo reignC harac ter (CameArea)
5.2. 1 Player Character Movement Process 11,e interfaces to the process that moves the player's charac ter aboul th e game consist o f the g raph ical user interfaces specified in Ihe SRS. TI,e process reacts 10 events descri bed in Section 3 4, whI ch are handled by th e El1colw lrrCmnr package in accordance with its spcctfk~H jo n s , described later In th is document.
5.1.3 Interface to EncounterEnvironment package The interface to the: Etlcotm frrEHv;rollmrnl package is provided by the EncouttlcrEnvirottmt'Ht object o( bfCounttr EPllJlfomnrnt Facadt class. It con ists of th e fo llowi ng:
t . EncounterEnvi ronment gc tTh eEn.counter Envi ro nmentO//gers th e Facade o bjec t 2. CameArea getArea(Stri ng )
5.2.2 Foreign Character Movement Process The process or moving th e forc lgn chara cter is a separatc process associa ted wi th and co ntro lled
the Etlco14 ntrrCamt si ngleto n object. Th is process IS contro lled by th e me th ods inherot ed fro m Jalln lang Thread
18.10 CASE STUDY: ARCHITECTURE OF ECLIPSE
3. CamcAr<:aConncction getAr<:aConncction(StTing) 4. void movePlayc rTo(Area ) 5. VO Id mo veFo reig nCharac terTo(Area) AreaNolAdjacentExceptio n
thro w<
by
No te to the Student, The description that follo ws describes the anchitecture of Eclipse in a top·down fas hion.
CASE STUDY: ARCHITECTURE OF ECUPSE
18. 10. 1 Scope (1111' p~,.,graph makes PCCIr.C Ihe , ope o( thIS
• The PI"g-l" Drotlop",'''1 EII""o","rnl altows develop ers 10 crcatc and add plug-inS It uses the Java development tools.
documenl (the tide "ArchItecture of Ecl,pse" seems clear enough untd we rcad In th" paragra ph that ;t " quailfied) 1 . 01 Apnl 2004 . thcre werc three Eclip.e ",kases \'lie wdl pro Ide an veralt descriptIon of the architecture of rciea,e 3.
18.10.3 Platform Module The platform decomposes", shown In FIgure 18 37 The modult< ,n Figure 18.37 are as foltows . • Rutllime handles the avallahle plug -ins at runtime
• Wor po, manages proJects. which con",t of files
18.10.2 Overview
and folders
The Eclipse ar hitecture has been de
• SIU/IJorJ W,dgrl Toolsrl (SWT) prOVIde< graph,cs Cieml."nlS
• JF
Rgure 18.36 has just three part>-a manage· able number to comprehend Eclipse" a large and very complex pro duct, however. T oge the r with the brIef explanatIons below, this decompoSition IS helpful. One has to searc h for a whde to find a de
co mmon UI
• \Vo,kb,,,c/, "defines the Ecl,pse UI paradIgm Th" Involv('<; editors, Views, iln d perspectives
18.10.4 Java Development Tools The deSIgn phdo
Pilltform
The
Java Development T ool UDT) module" the Java cnv,ronm(,; nt It on I Sb of [he Jm}tI (orr module ThiS
• The Plaifonn IS the InfTastn.lclllre of Ec J.p<e a nd is Independen t of languages with which Eclipse ca n be used and Independent o( all plug· in<
is shown
In
Figure 18 38 .
We won't pursue thIS module or further par" o( the Eclipse architecture In till ca,e study
• The Jm", O",tlop,",,,t Tools utiJ.ze the Plalform and IS class model (or a Ja va In«'raWVe development environment
I
Plug-In Development Environment
I
Java Development Tools
Jj. depends on
I I
Jj. Platform Rgure 18.36 very high level architecture 01 Eclipse St:Iuru MiC-UtO from Ct.tmn"Ia
"I
(net'!. and 8«k ~''f'Il "CMlflovung 10 Ecllp~ PnnclO'~. P,'tter~. Plug Ins. I\O(llson W{W;1ey 2OOJ, P 5
467
468
CI1APTER 18
SOFTWARE ARCHITECTURE
I
UI
I
I I
I I I I
Plug-In Developrnent Environment '-
I
Java Development Tools
I
1/
I
JFace
Slandard Widget Toolsel ~ depends on
Pla~orm
",,
Core
,
I I
\ \ \
, \
Key: Figure
18.37
0
@
I I
Workbench
I I
Workspace Runtime
A depends on B.
Architecture of Eclipse platform
source ' AOapted hom G3mma. Erkh, and Back., Kent " contrIbUting to Eclipse Principles, Patterns, Plug-InS," Addlson·wesley. 2003, p 283
The architecture of the OprnOfficr or!! sui te is designed to be platfo rm·independent. It consists of four layers, as described 10 Figurc 18.39.
18.11 CASE STUDY: OPENOFFICE ARCHITECTURE
NOle to the Student, It is not straightforward to locate the description of the OpcnOffice .rchitecture in a single, iden· tiAable place.
We will no t discuss the StarOfficc API here. As indicated in Figure t 8 39, however, three lay· ers depend on it. The author has made local improveme nts in the writi ng of the origi nal. This architecture description is at a very high level.
The following is a useful white p.pcr th.t cts ou t the design methodology used for OpenOfRce, and nluch of thi s section is .d.pted or quoted from ( IOj UI
I I I
Workbench JFace
SWT
I I I
Java Development Tools
I
Java Core
I
Core: Workspace Core: Runtime
Figure
18.38
Architecture of Eclipse the Java development tools mOdule
Source Adap{eO 'rom Gamma. Erld\ and e ....1(, Kenl " contributing to Ectip$e: Pnnc:~l r5,
p"ttcms. ano Plug-InS," AdcfISOn-'''ltSI~. 200J. P 282
CASE STUDY: OPENOFFICE ARCHITECTURE
.-~
Application Dependent
80:: -'" en
Framework
~«
IU· "
l.1Jyers
Infrastructure System Abstraction
-L
Operation System / GUI
OpenOffice Architecture
-0..
SW
SD
SC
« .-u
Application Layer
SM
= ,_._ ......
Framework Layer
Q)
~
o
~
e-'"n
UNO
UCB
SO l::===-:::;-;::===~-;::==; r VOS TOOLS .- ---- -- -------- ._--- --------_ ... -------
Infrastructure Layer
-- -- -_ ..System -----
STL RTL OSL Abstraction Layer ------- ------- --- _... -.----------_._.--.---- ----------OS / GUI [
I
Figure 18.39 The architecture of OpenOffice ~ Edited from Qpe:/OfflCe. hltpJ IWwW openoffice OI'glWhiteJ)aJ)ers/l ec.h. overview/ tech3wervlew I'ltmJ,J
The System Absttilct.o n laye r "e ncapsu lates all system spec.fic APls and prov.de a cons. ten t o b· Ject·oriented AP I to .cce« sy tern resources in a platfonn mdependent manner · It provides a k.nd of single, v.rtu.1 opctilt .ng system on wh.ch to build OpenOff,ce The In frastructure layer . a platfornHndcpen. dent environment for bUilding app lica tio ns, compo ncnt~ Clnd <;crvlces
The Framework laye r· To al low reu<e, tI", laye r prov.d('S the envlto nm ent for appi1ca llo ns. It al prQv.des all shared funcllon.l.ty ,ueh "' com mon d.alogs, (.Ie ac(css, and eonfigur.l1on mana gem nt n'e Appl.c.at.on layer "All OprnOffic< 0'9 appl •. cat1<Jns are part of thIS layer T he way the. appl. · cat.ons .nt·rou I~ b., d on the lower layer> .. Th next ~CC llOn\ dc\Cnoe ,hesC' bytr~ In mort
°
18. 11.1 System Abstraction Layer Th is sec tio n is reproduced from [ 1 I) It references Figure 18 39 Platfonn ·dcpe nded implementation take pia e below the ys tem Ab. tractlon Layer ( ALl or arc part of 0 pl1o nal modules "In an ideal world an .m ple mentat. on of the SAL·,peciRe [unctlo mhty and recompi ling the upper I. er module will all ow you to nm the appl.catlons To prov.de the whole se t of fun ctio nality, the opti onal platform spee dic mod · ule" I.ke telephony suppon or speech recog n.t.o n, have to be ported , too " To reduce portin g cfforts. the AL fun ctio nality I ) reduced to a 011111",,,1 " . ." t, avallJblc o n every pladom, " (or ~Omc ,v,tcnh th e laye r Inc1udc'i ~o m (" Impl Clll cntallO lh to emulate
"'ul11 e runCtlO Il i.1 hl y or bt' havlor. F r example on "'y, lc.:m, whe re n nilllVc nudtllhn:ild ,ng I ,,,pportcd
the layer ca n su pp rt <0 ailed ·u<e. land' thrc:ad, •
469
470
CHAPT
This d~>crlpllon IS not very lear, In (act, It is difOc\l!t to wnte meaningfully and clearly at a high level. What follows nc"" however, IS Indeed clear and meaningful.
Asshown in Figure 18 40, the AlconsIStsof the Operating ystem layer (0 l ) the Runtime Library (RTL), the Standard Template lIbrary (STU , and the platform -independent pan of the Visual Class Library (VCl) Thesc are descri bed neXL
The last <entence is useful and appropnate at this level. The meanlnS o( "semi platform Independen t" is unclear, second se ntence IS not clear but is presumably explaIned in the more detailed sections
n,e
18.11 .1.3 Standard Template Library "As age· neric co ntaine r library the standard template library is used . It supplies imp lemcnlcllio ns for list, queues, stacks, maps, etc."
1B-11 _1.1 Operating System Layer 'The operallng system layer (OSl) encapsu lates .11 the o perating sy tern speciflc functi onality for using and accessing system speCific re ources like Rles, memory, sockelS, pipes, etc. The OSl is a very thin layer with an object-orien ted API. In co ntrast to the upper layer this object-oriented API is • CAPI." The reaso n for this IS to allow easy porting to
The relationship with the Standard Template library that comes with C+ + should be c1arifittl
18_11 .1.4 Visual Class Library 'The VCl encap su lates all acce
5
to the different underlying CUI
sys tem s. The implementation is separated into fWD
various platform s using different Implementation
major parts. One is platform · independent and In cludes an object -oriented 20 g",ph ics API with
languages _"For embedded systems or Internet app li -
metafile-s, ron~s , raster operatio ns and the Widget
ances, for example, an assemblc:r language can be use d to realize th e Inlplcmentation ."
set use by the OpenOffice .org sUIte. ThIS approach virtually gua",nt.es that all widgets have the same behavior independentl y of the CUI system used. As a result , the look-and·feel and the functionaliry of the widgets on all platforms arc the same."
18.11 .1_2 Runtime Library "The runtime library provides all semi platfonn independent functionality . There i
an implementation for string cia scs pro -
vided. Routines (or conversion of ~tnngs to diHcrent character sets are implemented . The memory man agement functionality resides in this modu le ,"
This explains the squiggly lines in Figure 18.39 that separate the rwo parts of the VCL
Infrastructure Layer System Abstraction layer
I Operatjng
j
Runtime
I Standard
Ubrary
System
Template
(RTL)
(OSL)
I
I
LlbJ1lry
Layer
,
(STL)
I
I
Visual I Class ! Library (VCL)
I
Operation System I GUI Ftgure 18.'0 OpenOffice architecture
system abstract!on layer
.soc.n. Edlted from ~I!nolnce, httP.JIWWW.OOCnofflcO. OI..B/WNto~O\Ic;..oicwItec.h-.M.••\Iiew.html.l.
I
CASE STUDY: OPENOFFICE ARCHITECTURE
The platfoml .dependent pan Implements a JD·gr.lph,c drawing anva, that IS u
mentation of "lru lUred storage) , a generic registry . l ypc~af(' managcmc.' nt , and pcrsl",tcnCc of property
Currently, there CXI"-l
data "
Hllpk'mcnlallon"
for the
Win32, X· Window , 0 /2, and Mac The a e < to the prlnllng functionality , clipboard and drag. and·drop IS also reali zed In"de the V L. "
hbraru,:s Thl~ Includes a co mmon Implementation
for handlinS date and time re lated data , an Implc ·
18.11 .2.3 Universal Netwo rk Objects Un lUmal Ntlwork Obit Is "the o mponent tt-chnology used wllhln ptliOlficr or9 "It . IS heaVily bascd o n multi · threading and n(:( ..... ork communlCJtlon ca pabilities
18.11.2 Infrastructure Layer
It
The Infra
"The system con"stS 01 several p,ee An IDL· Compiler, whi(h generate, out of the ,pecd,ed def" nitlon of an Interface a binary n:prcs(.'n13110n and
tht· associated C.Header o r Java tcc hn o logy Iii", The binary repre entatIOn" platform and language
18.11 .2.1 Virtual Operating system Layer The purpose of thiS layer L "to make the usage of 'Y tem rc
the: virtual opera ting system laYlor en apsulates all
the functionality of the operallng system laye r Into + .. classes. The CH classes here offer an easy to use acces to all sy tern resources in an obJect. oriented way ·
mdependent and is at runllnH.:.' lIsed to marshal argllment ror rem ott' n.m lion call..: or to ge nera le code on
[he fly for a specific language to acCeSS the Imple · mentation provided by the Interface TIll> tec hnique reduced the amount of generated codt' for the dl . krent language b,ndllig tremcndously The draw · bJck i that not only for every language binding a
speclA backend for the code ge neratio n" needed It
18.11 .2.2 Tools Libraries "The tool functional ·
IS lhJl for every speclhc
Ity of Open Office conSists of vanou
IS needed a t nll1limc "
sma ll 1001
o mpd er a bndging n1 0 dulc
Framework Layer Infrastructure Layer ~
Vlnual Ope ra1lO 9 System Layer
I
,
•
Tools Llbranes
(TOOLS)
UnIversal Content Broker
Compound ObJecls
I
I (UCS)
(VOS)
•
ScriptIng and BaSIC Library
(SSL)
I System AbstractIon Layer
FIgure 18,41 OpenOllice archl tectur
Infrastructure layer
5oLw(# l
0V\'fVi('W
htm!.3
471
472
CHAPTER 18 SOFTWARE ARCHITECTURE
prov.des a platform ·.ndepe nde nt .mpleme ntat.on of till S functionality for ompo und documents and for embedding v. ual controls
This paragraph is no t ea~y to undcrsra nd but it Is at a high levd and becomes clearer as o ne reads more details. It m ixes a description of the arch.tecture with • ration.le for il. Requirements documents frequently include piece of
w.th the OLE structure slOragc format. Th.s allows accts to OLE compound documents on t-very plat · fom, whe re OpenOmce.org is ava .l.ble. O n Win ·
rationale .
dows the implementa tion interacts with OLE services
players ano vJnOU~ v l ewc r~ Storage IS compatible
and so .1I0ws a ti g ht .ntegratlon of OLE·ca pable "Many parts of the UNO technology . re impie -
mented ClS UNO components. This (acl lat alcs Ac xl' bility and runtim e exte nsions: c.g., providing new bridges or communication protocols. U NO provides
appli alion s"
18.11 .2.6 OpenOffice.org Scripting and Basic Library
l~n spare nt access to components locally or over the
network. 1I0P ca n be used fo r network commun icatio n. J( components arc realized as shared libraries ,
they ca n be loaded by UNO in to process memory of the app lication accessed by fu nction calls. Th is does no t require mars halling of arguments as requi red (or
remote function calls."
Th is paragraph seems to be hera lding an am bitious design , consisti ng of objects available o n the network.
"Scrip ting" refers to the ability to write proce · dures that cause the application to execute application functions in a dG'Si red sequence.
For example, .ba l Ales in Windows and .,b files in Uni x arc scripting files. Design documents inevitably rel y o n jargon that the reader must be f"miliar with .
"Th e scripting functiona lity that comes with
the Ope nOfAce.o rg suite is a BASIC dialect featuring an interpreter that parses the source sta teme nts and
18.11 .2.4 Universal Content Broker "The Unl' vcrsal Co ntent Broker allows all upper layers to access dirf~re nt ki nds of structure content tran spar-
e ntl y. The U CB consists of a core and severa l Universal Content Providers, which arc used to in tegrate different access pro tocols. Th e current
implementations provides content providers
for
the HlTP protocol, FrP protocol, WebDAV pro · toco l, and access to the local fi le system . The U CB docs not o nl y provide access to the co ntent, it also provi des the associated meta information to the content. Actua ll y there is synchronous and asynchronous mode for opera tions
supported."
ge nerates meta instructions. These instructions ca n
be executed direc tl y by the supplied meta ·i nstruc· tions processor o r can be made persi stent i n modules
o r libraries fo r later access. All fun ctio nality supplied by the upper level application compo ne nts is acces· sible via a scripti ng i:1tcrfacc i n the component
tec hnology . Thi s wi ll help to ensure that new com· po nent · usi ng the OpenOffice.org compo ne nt tech · nology can be fu ll y scriptable without spending a huge amo unt of dfort. The scripti ng interfaces are also implemented as compo nent's ('hat will allow an easy in tcgrCltion of
other scripllng languages." They provide fu nctional. ity . such as core reflection and introspection , Similar
to Java platfo rm functionaliry .
18.11.2.5 OpenOffice.org Compound Objects "The Compound Object implementatio n provide the functionality to build compound documents, where fo r example a spreadsheet is being embedded in a word -processor document." Inc implementation
18. 11.3 FrameworkLayer The Framework Layer has the parts shown in FI!,'Ure 18.42 . These parts arc descri bed next.
SUMMARY
Il.. « Q) u :s:::
0
~
-'"
rn
Figure 18.42 OpenOffice architecture
Application Layer Framework Layer Applicallon Framewo rk library
SVX
I
Library
I !
Infrastructure Layer framework layer
~ Opttr.ofRce. nup I/WWIY openolhce orgIWh1le..Papefsltech overvieWl1ech
-
18.11 .3.1 The Application Framework Library ee Figure I 42 "Functionality shored by all applicat io n ond no' provided by any ot her laye r is realized here. For ,he fram ~work , every v l~ual applica ti on ha s to provIde a
shell and can provide several views The library prOVide all basIC func"onal,ty so on ly ,he appli a· tlon speCific fearu re have to be added ." "The Frame'"ork is also responSible fo r co n'ent detection ond aggregation " The AFL prOVides 'em ·
-oveMew hlml_3
18. 11.4 Application Layer
Th IS layer conS ists of ,h e acnoa l appllCatlo n< such as the word proce sor, spread!)hcCl pn: entation , hart -
°
Ing, and on All ,he<e are rea lized a sha red libror,,·s , loaded by the app llCatoon framework at runtlme _ Th e framework prov ldt's th e environment
for these appl,ca " o ns and prOVide ,he functionailly for InterilClion am o ng them
platc management and co nflguratto n mclnagcment It
-is in some areas rela ted to the compound docu-
ments. because of the fun tio nolity for merging or swltchong menu and 'oo lbors It olso prOVides the capabdlty for cust omizatlon of appioca too n "
18.11 .3.2 SVX Library 'The SVX library proVides shared funct ionali ty for all appl,co ,ion< whICh is not related to a fT3mework a pan of ,he library IS a complete obJec"orlen,ed draWing loyer that is used by several applica " on< for grap hIC editing and ou'pu,. also a complete 3D-rl."ndcnng sy,tcmc;; 10;; part of the drawong funct iona li ty The common doaloS' fo r fan, selcctlon, color chooser, e'c . are all pan of thos library AI~ the whole
Software architecture de cnpllons I nform
the reader, but in a oeneral manner Th ey arc necessaril y impreci c: abollt the meaning
of the part
Arc hi, ecture of nontnval softha ve to be learned over
ware appli ca ti on
time JUSt as It [akc
tim e to learn any Com -
plex subject Tho< proce 'IS helped by delv Ing in,o el ected dNad s as needed . p(-rhaps even to ,h e code level , and ,hen rc·readln g needed", hll ec ,ure and detaded de"!:,, de ·
18.12 SUMMARY A software arthltCClUrC dcc;c.n l c th e components of a ... oftware ~y'-lem and th e WIth each olher Ther il rc many ddft'rcnl way ... a "YSlcm ca n be archllccled
\\I JV
III whic h th e
Jrl an and
II1tCr.\U
hon\" h;)\I(, dJ ...... dH.~d
\Qhware arch lt ·Cturcc; Into <'JtCJ,(O (ll-'''U h a<; dJlanow, IIHJ c pcndc nl cUlllpOncnh , Virtual 111 3 hl nc ,
fl"'
0"
tory, and lay "red ')CrvKC -OfI Cnlcd arch lte lure I ;'InotiH.' r type.: uf Jrc.h lt c llIrt' In w h lL h VJ llUU \ C mpOl"wnh art' (.omb lncd to provld ~
~()ftware
a ., 'rvlCt
d -"11m arc dotumen,ed In J urpo<e TIl(' 1)1) lor ,he I nwuntcr to>e <1lI
473
474
CHAPTER 18 SOFlWARE ARCHITECTURE
For large ' oitw;lrC project I ll " Impo rtant lO modulafl zc th e 'OrlwOlrc dc., lJi(n. Modu lafl zlIllon facilItate!.
dlfferenl wo up' of devcio pe,", work lnll o n Ihe d,fferenl parI, sHllullancously T o make Ihi' work as efficlen ll y a, po"iblc, Ihe Facade desIgn pallern an be u cd 10 provide a clean inlN!ace for each module. n,e Facade pillh..'rn I typ i all y appropria te when developers arc colloca led. In di stributed enVironments, Web service!.
a n often be u cd. Once an archOlcclure I <e lecled, Ihe proJeCI « hedule IS updaled 10 reRec llhe order In which Ihe p.rt< are 10 be developed.
18.13 EXERCISES I. In a paragraph . ex plain the purpose o f a software arc hOleclurc and how il relales 10 design.
2 Suppose Ih.1 yo u arc deSIg ning a batch imulatio n of cus tomers in a bank. BCln8 a batch si mul atio n. the charactcnstlc~ of the si mulation are Arst sct, then the si mulation IS execu ted wit hout Intervennon H ow could you describe this as a data Aow applicano n) U sc a simple skele ton
co nsisl1ng of fo ur parts 10 Ihe dia gram . (Identify you r four parts . and Ihe n look at how yo u cou ld descnbc this applical'ion as a state-tran si ti o n dillgram .) Which perspective offers more va lue in de scnbang the architecture] 3. Wh en desig ning a client -se rver architecture, th erc arc generall y two altern ati ves: Ibm an d Ihick clients. A thin clien t implie that client hmctionality is kept to a minimum; most of th(O processi ng is performed via th e server. A th ick cl ient implies that much of the functio nality is con tained in the
diem; the functional ity o n the server is kept to a miniml.!m. D iscuss the o ne o r two major
adva ntage and disadvanlages
10
each of these approaches.
4 Operating system are frequently desig ned usi ng a layered archItec ture. Resea rc h the linux o pe~tlOg sys tem o n th e Internet, and explain how it utili zes J laye red arch itecture. What arc the
benefit of such an architecture,
5. Conside r a word proce SI ng appl,cat ion with which you arc lamil,ar. Sketch the software architecture of th at program using one of th e architectures descri bed th e purpose of each of the components of your architecture.
In
this chapter. DeSCribe
6 . Selec t an alternative software architecture:." for the wo rd processing appltcallon of Exercise 5. Compare bot h architectures you selected and desc ribe their relative merits.
7. Some design patlern are particularly relevant at the architectural level. Na me two of these and explain their r('levancc.
8. Which software arehitec ture is the best ca ndida le fo r each of the fo llowIOg app l,cations a. An applicallo n for reordcnn g auto parts from hundreds of stores b. A roal-time appl icatio n Ihal shows the heallh of an automobile
c. An appitcJtion that provides advice to stock CUStomers. It uses a multi·platform design consisting of several Web sites O ne si te conti nually collects and stores pnces and o ther In(orma tion about stocks; a second site conti nuall y collects stock advice from anaiysts; a third recommends pon(o lio suggestions to users d. A sclenti(ic instrum ent com pliny builds equipment (or analyzing molccu lilr tnlctures. The
application you are 10 design analyzes .he structure 01 DNA mo lecule , which arc very large.
BIBUOGRAPHY
TEAM EXERCISE
Architecture Develop the architectLire for your proJect. Dcscrlbe YOLir ar hltcctLire u;tng the IEEE tandard, as tn the JSC srud a compa nYing thn. chapter (vlakc It clea r what type of archrtccrurc and cit! rgn paltern arc bemg applied how at lea (one other architecture that you considered , and explain ,,,,·hy you choc;:;e the altematlve descnbed Include the u e of metncs It IS not reqUIred that YOLI automatically chao e the architectures via metn ~ alone: .
Track the [arne YOli pend dorng this exerCi Se In increment of nvc: mInute , and Include a lime: heet haWI ng the time pent by IndIVIdual and by the team U,e or Improved upo n the loml tn Table 182 that reco rds the time pen t per person o n
Cil
h modu le Give your opinion on whether your (!(Icklng of
tIme paid off, and whether YOLir time cOLild have been better managed Table 18.2 Form showing tIme spent per module Module
Team member
Smith
1
2
10
4
Jones Brown
S
2
3
4
12 14
BIBLIOGRAPHY I ha ..... i\1 C and 0 Carlan Sol,w.Hf A"b,'rdlotrr PmPtdlt'f"> 0" an Elflctl/llfl) 1)'«('llllIl( Pn:nlr c Hall 19C-16 1 DIJL.stra E A DISCIpline of P' 09ra"'," I",/ Prentl(.(' Hal' , 1976 3 ua D CDrlCW'rt:t'I' P'Oljr.JPI4"IIHtlIH IlUll1 D~'9 " Pflfl( lrtt1IHtJ Pall(t'?u ( /"JI'O Slnf') Add,,>,)n ' \'(' <:"olcy I tno .. Kaluznlolcky, E K , and V Kanah;H X~., ~ P,ol}fa,../PI'"9 /or '/,( True lkl,I"H" All IIII,~u dlo" Ii) Inr Xb.lSt Llff~W.19 ( ,II Iht C(m 'ex l ~f JH.I\( tilT. I", i Fox",o. aYlJ (lIPW, "'lcC r:.w Hill l)rofc"u,mJl 1996 S )ap3nn;:uhan, V KaJcndra I odhlil"",ab and l...Jwrcncc: lbum editors. lIIa.k~o.u .1 A,.b,ln.lutn .,lId "f'"lnoJllclI\ A(oldcn),<. ll r " 1999 6 rnf'clmofc. Robrrt Jnd Amhon y MnrJNn (Ed ,to,... J. DlDclcJlO.lrJ Sy~ltm S (n" In 'fIJIJI 'tnt'i '" ArlIPC I . l lllllr"l~rnl( i'J,J""", \\,,,!ry 1<)88 7 Erl Th om ii~ . £ '1" (( Onf"ll lfJ Ilrd"'fdillf ronH/lIS, T nhflotogy IInJ l)f"SuJ" P(cnt,,-c Ii all 200(\ 8 C.lmm.l Er.<.h , Richard t Idm Ralph John,on , ilndJohn VI"'>ldC"'> /)«ollill P.lllff"' EI,mOl" 0/ Rt\4\abk Ob/I'\ I·()nrJI,tJ 1 1 ~ ,Jrt Add,'>on W ~1C'f , JlJtJtJ 9 Gamma l,.,h , and Ikc.k . KC"m ( on,,,bwlrll!/ In Fdtp\( Prlll0l'lt , PlIflrm> UI1J PIWII ·'"t: Add, ..o n Wcdcy 20<.P I(} CJpc:nOflK:C' ProJect, htlp www vf')t'nl)(hce nrw", h'le. PJpcr>. Icc h OV('rvl('W Ic;<.h _ ovcrvlcw html ll ~ (,I(.(.c: ..,cd 0' C'mht-r 2'. lUt)") I
475
Detailed Design
Planolng
/
TesUng
Maintenance
The Software Development Ufe Cycfe
Requirements
•
How do tJse cases and architectures relate to detailed designs?
•
What are useful object-oriented design principles?
•
Why design against interfaces?
•
What IS detailed design ror agile processes?
•
How do you SpeCify classes. functions, and algorithms. panicularly
analysis
Impls" .entation
-.:::::
in UML?
Dnlgn
•
How do you plan for component
reuse?
•
How does one use standards for expressing detailed design?
•
How is detailed design performed for
large. real-world projects? Figure 19.1 The context and learning goals for this chapter O(;{:;lIlcd design is the technicill activity that follows architectural selection and Covers all remJinlng
aspeCIS of Icch/llc.1 crealion shorl of aClUal code. It addros es major goa ls of software deSign (from Chapler 17 ). sufi1C!cncy. understandab il ity, modularity , cohesion, coupling . robustnes , fleX ibility, ,""us' abi h ty , In formaiion hiding , dficiency, and rchabdllY· Th is hapter start> by relating lhe detailed design
RELAnNG USE CASES, ARCHITECTURE, AND DETAILED DESIGN
pro<.""" to the artlf. ts that have already been dcvdopcd by ,he tIme we get to this point , especIally the usc ases of the requirement, analys" pro c" and the hIgh -level de Ign-the arch,te ture ( e tlon 19 I) With regard to suffi lency , detailed des Ign provides enough partIculars for developers to implement the ",quorement of the appll atoon As for unde"tandab,llty and modulanty, obJect-onented desIgn specIfy classes, theor attnbutt-s, and the or meth ~ i'nncipb of de,alled object-onented designs arc Introduced on Section 19 3 This fom1 of the applicatoon allows u to Inspec, deSIgn for strong coheSIon among grouped components and weak ouplonK with others FleXIbil,ty, ,he reu e of component , and informatIon hidonll are d,scu ed on SectIons 19 4 and 19.6. Detailed deSIgn cntails the developmen , of sequen e d ,agram from usc cases (Secllon 197), whIch are pnncipal SOUrcL-S for the pec,(, Olion of classes and me,hods The chap,er ends wIth case srudies The agde method, d"cussed In haptcr 4, hegIns codIng without a full detaded deSIgn , and pcrhaps wIthout any detaded de Ign at ali ThIS means that ,he detaded de Ign essentIall y lorms in the monds of the programmers and IS gencrally documented wlthon the code Neverthcles<, dctaded deSIgn contonueS '0 exi t for agde developer . We d,sc uss this further In eCllon 19 .
19_1 RELATING USE CASES, ARCHITECTURE, AND DETAILED DESIGN The rclationship between lise cases, architecture, and detailed de 'sn ca n be understood by analogy with the process of deSIgning a bndge . U,c cases would be part of the requirement> for th e bridge (see ,he use case example in Figure 192 ). Based on the r('qulrC~mcn(s, cnginloci would then selec t an archllcClurc
by stcpplng
back, as it were , and looking at the big picture U sua ll y, more: than one architecture ufnccs In this case , a sU5IXnslon architecture wa~ selected . ThiS process is diu trat-cd
by FI8ure 192 .
Once the architecture ha been elected , engineers ma y develop the detailed deSIgn ' 0 enable ,he reqUired use cases with the architecture selected This is suggested by F'gure 19 3. In the software analogy to the bndge example. each corre pondong stage accumulate, additIonal c1a«es, wh,ch arc shown to F,gure 19.2 and 193 In Step I, lise cases are spe lfied as part of the requirements. In tep 2, these, together with other sources, are used to Identify the domaIn classes. In tep 3, we develop the software .rchitecrure, as described 1
1. Use case (part of requirements)
' Cars should be able 10 Iravel from Ihe lap of Green's HIli al 65 mph , In a straight hne, and amve at
Jones Hollow within 3 minutes,"
2. Domain
classes
-+l
IAuto I
t-
Road ~
3. Architecture
Pylon Cable
Figure 19.2 The relationship among use cases, architeClure, and delalled design an analogy from bridge bUilding. 1 of 2
477
.78
CHArTER 19 DETAILED DESIGN
1. Usc case (pan
2 Domain
01 requirements)
dasses
-Cars should be
B
ablo to ltavel l rom
3, Architecture
Road
the lOp 01 Grecn's
HIli a t 65 mph, In
r------------------------------------, r::::l I
a Str81gh 11108 .
(addecllor I dll.OIlledck ) gn) :
and amv.!) at
SuPPOrt use case
~ Guardrail
Jones Hollow
4. Detailed
within 3 minutes:
Design
I
~
:
Road
1 :, ,
Cab~
,,
,, ,
I
,
Green's H ill '--- -
Pylon
- -----------
Figure 19.3 The relationship among use cases, architecture, and detailed design-an analogy from bridge building, 2 of 2
Hdl to Jones H o ll o w a< specified Fo r software de .gn, we verify that Ihe classes and methods specified by Ihe detailed dC~ l g n are capable of executing the required lI'i;{" cases .
19.2 A TYPICAL ROAD MAP FOR THE " DETAILED DESIGN" PROCESS Deta.led des 'll n 51arts wilh the resliits of the .rch ilecture phase and ends with a complete blueprinl for the prog rammin g phase. Figurl' 19.4 haws a typica l sequence of steps taken to perfo rm dctaded deSign . There is rcally no universa l
• dass model: domain & architectural classes
• overaJl stale model' • overall daLa
now model '
• use case model 2. Introduce classes & design patterns' that connect the architecture classes with the domain classes • concentrate on riskjesl parts first; try aJtemallves
For C!Kh 01$"
4. Specify class Invariants'
FOI' e • •" mell':od _
=
5 . Speedy methods with pro- and post·
conditions. acttvity diagrams.' & pseudocode" FOI' os:l.!IIIt
6. Sketch unit lest plans 7. Inspeci lest plans and design
• 4 ••.J" h'o
I s.Release lor implementatIOn
Figure 19.4 A typical road map for creating detailed designs
I
OBJECT·ORIENTED DESIGN PRINCIPI ES
tep 2 of F'b'llrc 194 rcates the cia scs that associate the architecture on one hand with the doma", c1asse on the o ther hJnd , a, .!Iu tTOted ,n the prev,ous seCllon. J)c"gn pattern may help in doi ng th, < for software designs. We oft n begin the dcta.!ed dcs'gn process wlIh tho e aspec ts of the deSIg n that must be Implemented, come what mJY, or that presentthc m ost n ,k Forcxample, in dCSlllfl1nl! En o unterwe m,ght conSIder risky the way In whIch the c1as
19.3 OBJECT-ORIENTED DESIGN PRINCIPLES Marton [ I , 2) Identified five prinCIples fo r class desig n of o bject ,o rl e nted sof twa re that also go hand" n· hand W1\h ag,le development These are
• Sing1.e . Responsibility PrinCIple • "A clas. sho uld have o nl y o ne reason to change." • _ cohesion • Open-Closed Princ ipl e ' • "An art Ifact should be o pe n for ex te nSIo n but losed for ma diRcat io n on way< that affect 1\, cI,e nh." • especially modules, cia <es , a nd fun tlo ns • -a modu le ca n be extended wlthollt chang ing It S code • Liskov Substitution Princ lple l • ' Subclasses shou ld be
Bot h should de pe nd o n abstra ctIo n, • AbstractIons
l
Intcrfllc...es are better th an one ge nera l purpo,c Interfa ce '
Figure 19.5 SOme obJect-onenled design pnnciples
-
. I
I~nr.lnd Meyer, "OhJ ec. t O nclHc::d
,...(IWJrt
on,tru( li o n," . c(.on d Felltlon, Pn.' IHII..t:' Iiall , 2007
1 l1arb.HOI 1.... .. kl)V Jnd j qhn ClllI ~ ~ . "Ab<.tril(.tlon ;'Ind C;pc..'<"lflu tI VIl
• Ro~n Martin, "I\~II • Ib,d
111
PlOgl~111 D cvt.'i opn1l'nl
j\ tlT Pn."' .. 19$0
oit w.u c f)c vclnpmc: m PIIIlc..IPIc: .. PJlu:rn ... ,"nd Pr~(tl'C""" Pn.: nl ltC' 11311 2
1
479
480
CHAPTER 19 DETAILED DESIGN
bro.d tOpiCS such as "all there i< to know aboutlustolllers and their habits"~ or "campinS prefere nces." In other wo rd<, I.>ses should ex hibit. hlsh level of cohe Ion When classes have only onc re pon"b d,ty. they arc ea.slcr to 1ll311lQln
and
reuse .
The pClI .(J.
Ustlng 19.1:
drawAIIShapesO--ildding functionality causes erasures
void drawAllShapes ( Vector<Shape>someShapes ) { for ( i=O ; i <someShapes . length ( ) ; ++ i ) { i f (someShapes.get(i) .type() == "circle" drawCircle ( someShapes.get (i» ; else if ( ( someShapes. get ( i) . type () == "square" drawSquare(someShapes.get(i»; }
}
A common way to avoi d modification and conform to the OCP is
by
lItil izi ng inheritance and
polymorphism . liSling 19.2 shows how thIS is accomplished in a new ve rsion of drawAIIShap"O. In this new version . shapes such as Circles and Squares inherit from the base class Shape. A a Shape is extracted from the vector, its polymorphiC drawO meth od is called to draw that shape . This mea ns that each type of shape i respo nSible for knOWing how to draw itself. If Rew shapes need to be suppo rted. drawAlISI,up<> O does not need to be modified-It au to maticall y calls the drawO meth od of that new shape when it is removed from the vector.
Ustlng 192: drawAllShapeSJ -lmprOOJed we sion now open for addition
void drawAllShapes ( Vector<Shape> someShapes ) { for ( i=O; i < someShapes .length () ; ++ i ) someShapes.get(i).draw() ; }
Th~ U".u S"bsl;,"tio" Pri"ciplt states that any code referenCing an instance of a base class must also work co""ctly if, instead. it is p.ssed an instance of a derived class. In o ther words, a d~rived cia", must honor the
semantics of. base class. If this principle were to be violated. then every time a new derived class is cre.ted, cod~ would have to be modiR~d to rd~rence the n~w class. Violating the OCP.
DESIGNING AGAINST INTERFACES
Copy ,,,
~
••
........... --.-.. --... -... .,
••
Read Keyboard
Wnte
Pnnter
Figure 19.6 Dependency InverSion
Copy
Reader
Writer
Read Keyboard
Write Printer
Figure 19.7 Avoiding dependency Inversion uSing abstractIOn
The Drp",d",ty IH"""OII Prill iplr (DIP) IS concerned with hiding detatl" It ask us to deSIgn hI g h-level module In such a way that th ey do nOl depe nd o n low- level mo dule , Instead. eac h sho uld depend on absrracti o ns Th,s makes the modules undcr< tandab le and usable In lhemselves o n
19_4 DESIGNING AGAINST INTERFACES The Id a of dcslllnll1g allaln,' Inll'rlacc< " lIke emplOYIng a contrac t The program e lement ,uppl II1g lun llonaJlly (c g the (IHlomcr c.liJ", } ~lIilrantc('s 10 prOVide ,nt cdi) e ftln tltm ... wllh ~pcL dH.:d name parJnlc:lcr l"yp<: •• and return type, (e K , VOId h,Il("OId) an d /,oo/ra" prllll/\ 0 .. ", . ( ' Irlllq nCtv IIIIITypr)) The pr gr.lm cle mem, USIOII the (unctlonalll Ycan lhen be d ,,~n d wllh ollt havlnlt 10 ~n ()w how th e ILIIKtlo nal, ty" 100plemen tcdall they need to know" how l() ",e the Ill te riate We have d"tu,wd Ih" CO ll tcp l In the o nte", 01 de,' gn
411
.82
CHAPTER 19 DETAILED DESIGN
Client code
Used code
Bili ingClient
Customer
IISICuSlomersO blliCuslomersO
-- -- -
.. wntten in lerms 01 Customer (not specific Iypes ot Customer)
--
bil/{) printAccounts()
Abstract la yer RegularCustomer biliO printAccounts()
Concrete (non-abstract) layer Figure 19_8 Designing against Interfaces-an example of designing against Customer rather than RegulanCustomer
Also , the Facade de Ig" pattern is a way of providing a clean interface to
patterns \\,herc patterns have client
a package o( cia es. Designmg against interfaces takes man y forms . One is the usc of ab traction . For example,
be written about l\ltnmmai objects, then
if code is
to
we try to write it so as to mention on ly AJlimnl objects. In other words.
we try to usc: only the Animnl lntcrface . ThiS allows gn:ater applicability and grea ter flexibihry for our design As a hlrth.:r example, suppose that we arc writing code about eu tamers . Thi s ca n be understood as writing against the ( usfomtr interface. We ca n actuall y consider uSlOg an abstract class Clcstomtr, which may
have nonabslraet subclasses such as Rr9u/arC,,' to",cr, as hown in Figure 19.8. This desig n is mo re nexible than writing again 1 a concrete (nonabstract) class Rtgu/arCustomrr because we ca n easily add other types o( customers, such as Sn v"'9,C,,' to",cr objects, with 'pecia lized verSions of hillO, without haVing to change the code that uses ( us/orner objects. The diVision into an abs tra ct and a concre te la ye r is characte risti c o( many deSign pattC'rns.
For Java
In
partICular, one tries to use Java ·speCific "Interfaces" (or the interface role descnbed ilbove.
These specify method signatures (name, return type, and parameters types ) o nl y. Unlike Java inheritance, classes can Implement any number
or interfaces
and a dOlled line triangle is used
In
The
UtvtL notat ion (or an interface is a dotted-line rec tangle,
tead of a o ild one.
19.5 SPECIFYING CLASSES, FUNCTIONS, AND ALGORITHMS The goal of complete detaoled design is to prOVide a complete blueprint from which a prog ram can be constructed A good house blueprint leaves Ihe builder with as (ew doubt as po sible about the .ntentions of the designer, and the same is true (or detailed software design . Figure 19.9 describes typica l steps in carrying out detailed deSign for each class, and the succeeding te" explains the Slep in delail. A fully detailed class diagram includes all allribute and operatio n names, signatures, visibol,ty, .-.,mm types, and so on. Accessor methods arc commonly omilled . It IS customary 10 omit accessor function (e g , 9rtSiuO and srtSizt()), since th«c can be inferred from the presence o( the corresponding attribules (e.g ., 'izd. UML tools have the benefit of allowing designers to suppress (I.c., to not show ) cortaln clemonts of the Rgu~-for exa mple, the "responsibilities" section or the variable types. Many tools allow designers to view only the class« and their relationships, in order to get Ihe big picture.
SPECIFYING ClASSES. FUNCTIONS. AND ALGORITHMS
1.
2. 3 4 5
6
alher Ihe attrlbule< l"Icd In Ihe R . • If the R J< or~an.zed by class Add addll.on.1 .trnbules required (or Ihe des.gn ame a mel hod orrespondlng to each o( Ihe reqUlrement< (or th. clas . • ea,y the ~ RS Ie; organized hy c1a<;, '.me .odll.onal method, reqUlrl'd (or Ihe des.gn . how the attnbute, and methods o n Ihe o b,e I model tatc c1as ,nvanants.
,r
Figure 19.9 Fully spec.fy.ng a class One language.lndepende nl manner III wh.ch 10 speedy classe IS Ihrough Ihe OREA Interf.ee Oefinillon Language ( lO ll Th" " a slandard. teXlual (ormal (or ,peedYlll& Ihe .ntcrface, prov.ded by collect.ons of las es their a"nb"Ies . and Iheir funcllons Fo r Ihe spec .f.ca l.on o( IDL. sec [4 ] In some organi za ll n . detatlod dcs. g ns arc spec.fied by prov.d.ng code w.thout fun I. o n bod.e, ralher than UI'"IL. Th" IS somcllm.s Ime of agtlc de velopers Th e advantage o( Ih" procedure" that there" no need 10 rranslale del.tled speedicatlons 1111 0 code A d. advanlage IS thai a code fo nn IS somew hat less rcadab le than ordma!)t pro c The funcllOns In the code form arc then filled Ollt at Impltmcntat lon lime by programrne~
19.5.1 preconditions, Postconditions, and Invariants An effective way to specify functions is by means of prrC'oud,floI15 and p05tcotldlllO tlS Precond itions specify th e
relationships among vanablc') and constants that arc assumed to ('Xlst pnor to the runctlon' cxeclitio n. postcondltions speedy the req Uired relallon shlp~ after the funcnon 's ext ution For example , the func ti on w.,bd,.w(.1l1 UJill>drnw"IAlno" .. IP) of an "cco" .. 1 cia < could be spectiicd as ho \" n In F. 'ure 19 10 Anolher
Invariant of withdra w{): balancel >= -OVERDRAFT-MAX AND availableFundsl = balancel + OVERDRAFT_MAX Conventions used xl denotes an
Precondition" : withdrawalAmountP >= 0 AND
aUnbute: xP denotes a
balancel- withdrawalAmountP
function parameter; X'IS the value 01
-
>= OVERDRAFT MAX
x
alter execution:
X denotes a class constant
Postcondition" : balance/' = balancel- withdrawalAmountP
'The lunctlon Invariant Is an addillonal pre- and postcondlilon
Figure 19.10 Example of speclfyln!! (unct.ons preclsely- specify.ng wlthdrawo .n Account
483
484
CHAPTER 19 DETAILED DESIGN
cx.,mplc of a preconditiOn
IS
an tlgr parame ter that
J
method
J4I!'oumcS"
I ~ greater than zero The dfects of a
method arc ,t, poo l 0111"" 011, . ll,ey are the very reason for the method, and mu
mall,lall' ,nlelle lual control over the behavior of functions They specify relalionsh,ps Ihal do nOI change, which IS wei orne in the envi ronme nt of an application, where complex change IS so ohen difficult to manage. An exa mple fro m Encounter" the fo llowll1g possible ,nvaria nt for the "dju" Q,w'"y() method. Invariant - th e- sum of the va-lues of the qualities.
In other words, when the value of one quality,s changed with nd)u" Qun'"y(), the values of the remaining quahtles change )n a way thtH Ie'aves their sum unchanged.
19 .5.2 Expressing Algorithms with Activity Diagrams and Pseudocode It is helpfu l to specify nontrivial algorithms at detaded desig n time. The adva ntage of doing this is that engineers can Inspect the algonthm separatel y without lhe intrusion of programming com plexities , the-reby trapp,ng man y ,mport.or defects before they magni fy into code defect . The more critica l the method, the more Important thIS activity
Methods wi th complicated branching art: candidates fo r actwity diagram s
("advanced flowcharts") . Activity diagrams were described in Chapter 16. PsrodocoJe is a means of expressing an algorithm textuall y without having to specify programming language detads. As an example, pseudocode 'or a hypo thetica l autOmated X·ray controller is shown ,n Figure 19. 11 An adva ntage of pseudocode is that it is easy to understand but ca n also be made precise enough to express algorithms. Anot her advantage is that algorithms can be: inspected for correct ne ss independently
of the clutter of a programming language. A third adva nta ge is that defect rates in pseudocode can be collected and used as a predictor for ddect rates in the product. usi ng histonca l defect data. Some orga ni zat Ions use inspected pseudocode a annotated comments in the source code listin g. Tool s
are then able to extract the p eudocode from the source. For example. using "lip" to preface pseudocode statements, the code could impleme nt the pseudocode cited above-see F'gure 19 . 12 ActlVIry diagrams and pseudocode each have the advantages listed In Figures 19 . 13 and 19 . 14 . The decision whether to use them or not depends on (aclOrs particular to th e ap-plication Some devel opers shun
act,vity d,agrams as old· fas hio ned, but activity d'agrams and pseudocode can be worth the trouble for selected parts of applrc.tions, where they help to produce better quality products. FOR number of microseconds supplied by operator IF number of mICroseconds exceeds critical va lue T ry lO gel upend oris approval
IF no supervisors approval abort with "no supervi sor approval
for unusual duration" me sage ENDIF ENDIF IF power level excee ds Critical value abor! w,th "power level exceeded" mes age ENDIF IF (patient properly al,gned .I< shield properly placed .I< machine self· test passed) Apply X·ray at power level p ENDIF . . ENDFOR
Figure 19.11 Specifying algorithms with pseudocode a critical X.ray example
-
REUSING COMPONENTS
II p FOR numb e r of microsec o nds supplied by operator for ( int i = 0; i numMicrosecs; ++1 ) { II p IF number of microseconds e xce eds cr itical value if ( numMicros ecs > XRayPolicies . CRITICAL- NUM - MI CROS ECS ) IIp Try to get supervisor ' s approval int supervisorMicrosecsApproval = getApprovalOfSuperForL o ngExp osure{) ; II p IF no supervisor approval if ( supervisorMicrosecsApproval < = 0 ) throw ( n ew SupervisorMicrosecsApprovalException{) ) ; •
•
•
•
•
•
•
•
•
Figure 19.12 Pseudocode as extractable comments In source code
• Clanfy algonthms in man y cases • Impose Increased disc lphnc o n the r> roc~ . . s
or do
umcnllng detailed deSi gn
• Provide additional level at which inspec tio n ca n be perfom,ed • Help to trap defects before they become code • Increase product re liabi hty • May decrease overall co,(> Figure 19.13 Some advantages of pseudocode and activity diagrams
• C reates an addll ional level of documentation to maintain • Introduces error POSSlb,hucs In tran slat ing to code • May requ ire too l to ext ract p cudoco dc and facilitate drawing;) lI vity dlagrJm~
Figure 19.14 Some disadvantages of pseudocode and activity diagrams
19.6 REUSING COMPONENTS Most e nHlnee nng dlSclphncs (elec tnca l, mec hanl ai, c tc ) rel y o n th e u·. r of compo nents that ca n be procured s<paratciy Bndge deS igner" for exa mrle, try to u,e standalu I-bea ms The wlde,pread adop tio n of ob)e tonented, ob)cct -hke, and ot he r co mpo ne nt paradigm, ha, helped to promo te oftwarc reu'e Ikea,,'e of the large numbe r of methods pack'Bcd with each ci a", ftlf' l1 0 naht y that we need " ofte n In ludcd and i< r<:lallvely conven ient to 10 ate The usc of MKro,oft I, brane' , V"u . 1 ila,ic Lontro l" '1IGro,oft A"embhe$ Java Bans, and Java App ilca u in Prowamm ll'!; Interface Lia"c, arc exam ple\ of w de reu,e hap tc r o n Jrc..l lllt'C lu rc . Ire pJc ka gc\ of ompo nellh dC"d,.;ncd r(Jr r ·U\C We d ~c1t) p {rMl1ework ... to ~U ppOrl ilPp1K<111 0 11 Jr tHl el- lUrc, . il nd '0 the Jrt" clf('ulv(' ly n.'u'Jble FfilffiCW()rks. dl scllc;
d
In
th e:
prCV IO U \
The Java co re Al'l "anr,lher exa lllpic of a Widely
u,cd framework lava ilea n, prov ide ret" .b lc tu mp nent' for }ava applKatlOm They In Iud grap hl , II al" and "c nlc rrnsc" bean;, wh ic h e nca psula te COl 1'01'. te ta'~<
485
486
CHAPTER 19 DETAILED DESIGN
>u h J> datJbJ,e a e <. In additio n to th. advanlaj(cs afforded by bClng da"c" beans obey sta nd ards that make them cJ pable o f mallipulalio n within devel op ment e nv ironment ' Web · ba cd programs (i.e , nOt o mpo nc nt< ) '" h a Java c npt and C I sen pt> art o ften reused At • dirrerent level , the tandard Templal c Library ( TL) prOVides m ,. · a nd · matc h ca pabili ty of ,t.ndard ,' lgo rithms suc h as >orllng and scarc h ing . STL IS applicable to a va"ety of data struc tures a nd to objech o f virtually any clac;s. In summary, a omponcnl marketplace ha~ emerged and IS g rowing co nlilluall y n,e Encounter video ga me case stud y prese nted at the end of this c hapter CO nlalll cxamples o f reuse with in an cnterpr.isc: in this case, a Ham," de .... elopment business T o he cO~ l - dfcctlvC'-and thus compelltlvethe company leverages its software as Illuch as possible among projec ts. For example, rathrr than invest the resources to develop a class for the c harac ter in Encoun ter alo ne, It Inc!> to scpaf"il tc the develo pme nt Into a ga me c ha", ter class, and usc a subclass for Encou nter's c ha",cter. The ga me cha",cter cia .. ca n be rcu<ed for o ther ga mes. Th is Idea is extcndcd in the case study to a game framework con'S lsli ng o f several related classes, which IS the commo n context for reuse. HaVing found an exist ing compo nent Ihat cou ld possibly be used in an applicallo n, should It be used ) The follOW ing factors arc ty pical in making this decision, and t.hcy sugges t fact o rs tha t shou ld be acco unted for III creating o ne's own components slated for reuse • Is the component docllmented as th oro ug hly as the rcst of the application) If not, ca n it be)
• H ow much customizatlon of the component and/or the application is reqUired, • Has the component been tested to the same icvelas, or more extcnsively than. the nest of th e application If not, can it be]
T o deCide on reuse of components with sig nifica nt size, a [able comparing the costs can be devel oped, si milar to the o n~ in C hapter 8 where a make vs. buy example was shown .
19.7 SEQUENCE AND DATA FLOW DIAGRAMS FOR DETAILED DESIGN Some detailed designs are best commu ni ca ted via deta ded sequence dia grams o r deta iled data flow diagrams. Figures 19. 15 and 19 . 16 provide guidance on ",hat needs to be done with sequen,e diagram and data Aow diagram to complete the correspo nd ing detailed design . The te xt that fo ll ows provide detail. and examples.
1. Begin With the seq uence d iagrams constructed fo r detailed requirements and/or architecture (i f any) corresponding to th~ usc cases. 2. Introduce additional use cases, if necessary, to descri be how part o f the design typica ll y mtcract with the rest of the applic
SEQUENCE AND DATA FLOW DIAGRAMS FOR DETAILED DESIGN
I. Gather data flow diagrams (DFD<) co n
19.7.1 Detailed Sequence Diagrams Recall that use cases ca n be utili zed to exprc,>s reqLllfcmcms, and that \\Ie also usc them to determine t he key domaIn cia se for the apphcation. For th e dt·tailed design phase, \ve proVIde cla'>es WIth the methods referen ced i n the sc:qucncc d iagrams. As an exa mple, the sequence dli:lgram fo r the: "Encounter Foreign Character" IS ~ h own In Figure 19 . 18, hawing th e message between obje ts on the software design. The reaso non g beh ond the h",ctl ons chosen IS as follows . 1. Forro9110Itlrael" is to have a d,