Brief Contents
Prefa C X IV Acknowledgmen ls Part I
Part II
••
XVII
Introduction to Software Engineering Software Process
I TI, e Coa ls and T e rm ino logy o f Software Eng ineering
I
2 Inlroduclio n lO Q uality and Metrics in Software Engi nee ring 21
3 4 5 6
So ftware Process 32 Ag il e Software Processes 63 Q ualilY in the So ftwa re Process 80 So ftware Co nfig uratio n Manageme nt
120
Part 111
Project Management
7 Princi pl es o f So ftware Project Management I 140 8 Princ iples o f Software Projec t Management II 168 9 Q uality and M e trics in Projec t Manageme nt 21 3
Part IV
Requirement Analysis
10 Principles of Require me nts Anal ysis 2 30 I I Analyzing Hi gh -Level Requ irements 245 12 Analyzi ng De tail ed Requirements 278 13 Q uality and Metrics in Require me nts Analysis 331 14 Formal and Eme rg ing Me thod in Requireme nts AnalysiS (O nline chapte r) 349
Part V
Software Design
15 16 17 18 19 20 21
PaTt VI
Implementation
Part VII
Testing and Maintenance
22 Pri ncip les of Im p leme ntallo n 539 23 Q uality and Metrics in Imple me ntation 58 4 24 Rcfacloring 60 I ~--~----------------25 Inlroduc tl o n lO oftware T esting 62 1 26 Unit T e ting 630 27 Mo dule and Integratio n T esting 666 28 T e' omplex. Development efforts like AnaH' ca ll for extensive edu ca tI on and coordinati on w lthon project manage men t, quality as~rancc, conAguration management, architccture, detai led de i8 n, programmins, and te ling organizations. Dependmg on how th e project was organized an d designed , anyone of these organizat Io ns could have been partly responSIble for ,;eem!! to It that the code on qu(,,,ion wa< not called after Ilftofr.
1.2.3 Radiation Overdose As software co ntrol~ an ever-In rca~inu numher of devi (,S, It, rclmh llily " cominJ.( undt"r in rt:ali;lflgly tOt t-nsc scrutIny. I" the prOject manaflernent maUaz lnc 13..,lm" DebbIe ,.ge, Jo hn M om1lck, ~ nd Bcna Ramon. wro te
3
4
CHAPTER 1 THE GOALS ANO TEI1MINOLOGY OF SOFlWARE ENGINEERING
of a la,,,su1I allqjlng "nta,sive overdo,e, 01 gamnt. ray' partly due 10 Ilntitallons of lhe computer program lhat gUIded l>se or a panicu lar radiallolHherapy machine. TI,ey reponeclth ... following . "The International Atomte Energy genc saId In May 100 I lhal alleaSl flve of lhe dealhs were probably (rom rodiatlon pO"Ontng (from the rna hine) "nd al leasl 15 more pallenlS ri,ked devcioping 'serious compltca ltons' from rodial lon • [4 JThe defecl dId nOl show up unt il a ,ignificanl lIme afler rd ease, and o nl y after cenain scquenCL'S of operator action,. The fo ll owing des ribes the software defect , and IS quoted (rom [5]. etting the bending magnet tak,:s aboul 8 seco nds Mtl9n" ca lls a ubroutinc called Plim, to introduce a tIme delay . ince several magnels need to be ,et, Plim, is entered and exited several time A nag to indicate that bendi ng magnets arc being se t is initia lized upon e ntry to the Mti9n,' subrOlltlne and cleared at the end of Plim,. Furthe nnore, Plim, c hecks a hared variab le, set by the ke yboard handler, that indicates the presence of any edi ting requests. If there arc edits, then Plim, clears th e bending magnet variab le and exits to Mti9"" , whic h the n exits to Dattlll. But lhe edit change va riabl e IS c hecked by Plim, o nl y if lhe bending magnet flag is set. Since Pllm, clears it during its first execulion , any edlls performed during each succeeding pass lhro ugh Ptim, will not be recogntzed. T hus, an edit c hange of th e mode or energy, althoug h reflected on the operator's scree n and the mode/ energy offset variable, wi ll not be se nsed by Da I", I so il can index the app ropriate ca libration lables for the mac hine parameters. I This is a fairly involved explanatio n but no t al all beyond the complexity of man y software systems in existe nce today . When should th is type of e rror have been fo und] If sound ohware e ngi neering d iscipline h ad been employed during all phases of the project, there would have been several opportunities in the development process to detect it.
1.2.4 More Software Disasters
r
Readers who wish to know about more software disasters, big and small , are referred to Neumann 6), who discusses risks. problems, defects, and disaslers relati ng to reliability, safety, security vulnerabilities, integrity, and threats to privacy and well ·bei ng. Another source is the ACM publication Softwar, Engin,rring Nolrs and its Risks Forum [7].
1.3 WHY SOFTWARE FAilS OR SUCCEEDS Thankfully , nOl all software projects e nd in the rypcs of disasters described above, but fa r tOO many end in failure . What docs il mea n for a software project lO be unsuccessful] Simpl y put, an unsuccessful projcct is one thaI fails to meel expeclations. Mo re specincally, the undesi rable outcomes ma y include the followi ng , • Over budget • Exceeds schedule andlor misses market wi ndow • Doesn't meet staled customer requirements
• Lower quality than expected • Pcrfonna nce doesn't meet expectations
• Too difAcult to use Lc:v(nson . N.ncy , .nd Turner C.S., "An Inve of how softwarc e ngi neers can be co nfro nted wit h ethica l dilemmas. H avi ng a se t of guidelines grea tl y as 1st. the e ng ineer in making the ri g ht decision .
1.7 CASE STUDIES Read ing about softwa re engineering concepts alone is insufficient for gai ning a thorough understanding of the ubjec!. The best way to unify and reinforce the man y topics presen ted in th is boo k is to ( I ) learn how they are applied to the development of real software ap plicatio ns and (2) gain hands-on experi· ence devel opi ng a software application as part of a team To mee t the Rrs t objective , case studies have been developed o r described and are presented thro ugho ut the book . They serve as concrete exam ples of software appl icatio ns, a nd include appropriate artifacts as they are discussed and presented in the text. The case studies arc intro duced in the next few sections. T o meet the seco nd o bjective, students working in teams arc provided guidance as the y apply so ftware engineering concepts to the
develo pment of a g roup proJect. As they progress, students will ge nerate project artifacts and working co de. Artifac ts gene rated as part of the case studies can also be used as guidance in developing artifacts for the group project. There are three cases studies used in the text, as illustrated in Figure 1.9 . The Eneo."/tr Did,o gam , is a si ng le·p laye r, stand-alone video game application that is completely implemented through the course of this book in conjunction with online components. In addition , two open source projects are used to illustrate h ow open source prOjects are devel o ped: the Eclipse integrated development envi ro nm ent and the Op",Offic, office productivity suite . Open source projects arc developed differently from traditional software in that many
Encounter (created for this book)
1 Case Studies
Eclipse (open source)
Fllure
1.9 The main case studies used in this bOOk
OpenOlfice (open source)
CASE STUDIES
difkrent !> orga nIza tIons, de . vc\op featun..'S and fun tions and thcn co ntribute them b. I:. to the ba e ·oftware applicatIon . In this wa
an open sourc
appli cation grow in fun l ion.
ality and all ne," fea tu res arc free ly avai lab le for o thers to use and budd o n. Variou o ther examples arc used in this book , includIng a vidco store app \'ca tlo n.
Ihe Jo"i9" character. C haracter> engage each other when they arc in Ihe same arca atlhe arne time. The rc ult of an engagement depe nds o n thc values of the haracters' qualilie and on the locatio n where It occurs. O nce an engagement is complete, the play· er's c haracter is moved 10 a random area . Players can se t the va lues of the lf qual ili es except while engaglOg a Joreig n character. The new quality values take cffect o nly aflc r a delay. •
1.7.1 Encounter Video Game The En o unter video game is a si ngle.p layer, sta nd . alone VIdeo game applicatIOn A player is assigned a main chara ter, and Encounter si mulates all o r part of the lifetime of that character Success in playing the game is measured by attaining a points goa l for the playe r or by the ability of the playe r to survI ve fo r a give n time limit. Figure 1.10 shows a ty pical scree n shot: the courtyard area co ntaining a playe r· contro lled charac ter, Elena. Came characters beg in wit h a nxed number o f points allocated equally amo ng qualities including coneal tration, stamina, inltlligftKt. pali(Jlct. and strnlgtb . The game co nsists of movement among a set of areas. The main characte r moves between them , encountering a game · generated character ca lled
'1,
1.7.2 Eclipse Open Source Project The seco nd case ludy is Eclipse . Ecl ipse [ 14] is an extensible, highly co nfigurabl e o pen ,ounce IDE (integrated develo pm ent e nviron ment). An IDE pro· vide an enviro nment and sct of lools fo r the devel · op me nl of softwa re app lications. II provides loo ls to build , run . and debug app \'cati ons, the abili lY 10 share arllfacts such a code and object WIth a tcam, and suppo rt for and intcgral10 n wi th vcrsion contro l. lkcallse Eclipse is o pe n source, ILS source code and des ign arc fTeely available and readi ly extensible by th ird parties thro ugh the use of plug · in s. In fa ct, Eclipse is co nsidered a plaifo,," . It isn'l a '·flni shed" product, and is intcnded fo r contin o uo us and indefi nite exten io n [ 15]. Numerous open
Figure 1.10 SnapShot (rom the Encounter case StuCly video game: Flena In the courtyard
15
16
CHAPTER 1 THE GOALS AND TERMINOLOGY OF SOFTWARE ENGINEERING
,"cr Interfa e a nd fe atUre set s lInllar to o ther ol~ce ,u ll e> suc h a, M lc roso fl II,ce OpcnOlflce org also wo rk, lran'pa re nti y With a Va rtCIY of Ale formats, Including those o f MI ro solt OlRcc' [ 16 ] A tYPical O[lc n fr, c' >c reen, hot IS s hown In hgurc I 12 The Orc n frlCc proJc 1 encou rages partlcipa lio n by d eve lopers, as ,he tYPical developer-o rie nted Web page ,ho ws in Fig ure 1. 13. We w tll dt<cu,s the management of the O penOfRcc projec t In rart II I. H ere i a summary, quoted fro m a n Opc nOm c Web si te .
fOllnd JI lhe home of lhe
, o ur .... ,.,.,.
· ",.-1\ _' 1'.'_. l"'.
I,.
2 _ ""''':' ....... h'>rpo.f"~U'''
: - rl l _ . U . .. 1 OCu~p ... LO'" . rl leV. .. u. l . . ooment procesS is camcd out correctly ValidallD" I omparab lc to balanein!! yo ur he kbook when the bank's statement amves. You match all the tr," ". lion in thc monthly ,tatcment wuh those In your rC!!'ster, ensuring that nonc have been omitted or entered in orre tl y and that the tran action amounts In your regi ster mat h those in the s tatement. In addition, you vahdate that the ending balance in your regl ter matches that in the statcment. Even thoogh you kept your balan c up-to -date, ml~takcs may have been made. Validallon cat hes those mIStakes a nd ensureS the correCtness of yo ur balance. This IS analogous to testi ng of a software system . The twO l11alO activities invo lved durin g V & V are inspection a·nd software testing. Inspections, and
1:..
also review"' . arc verification actlvitic and involve peer examination
or projc
t artifacts ( requirement s. deSIgn ,
code, etc.) to discover clefc ts. The idea is to And as man y defects as pOSSible as ea rl y as possible. Inspections arc covered in greater detail In C hapter 5. Testing is the principal part of validation . oftware testing IS primarily a validation actiVity, occumng at the e nd of a development cycle to ensure that sofrware satisnes its user requ ireme nts. Testing involves providing the system with a sct of inputs, and validating that the system behavior and output matc h what is expected. Any deviation from an expected outcome i, considered a defect. Te ting is covered in detail in Part VII. ote that it is a combination of verinca tio n-primarily in the form of inspections and validationprimarily," the form of testing-that consistently produces high-quality software. Testing alone is not ufncient. No matter how talented software engineers are at fixing defects, if the quality level is low entering validation , as measured by latent defects (tho e present but not necessarily known ), there IS a high probability that va lidati o n will take sig nificantly longer than expected and the quality level will remain lower than desired . As many defects as possi ble must be removed from the artifacts before validation begins. V&V and quality practices, as they relate to each major software phase and activity , is included in the quality chapter ncar the e nd of each part of this book . Figure 2.5 summarizes these V&V concepts. To reinforce the verlncatio n/ validation distinction , let us perform V&V on a simple example. Suppose that the customer wants an application that "solves linea r equations of the form ox + b = c: We translate this into user requirements such as ;
1. The user shall be able to input numbers a,
b, and c up to
10 digits each, with up to four places following
the deC imal point. 2. The application shall produce a soluti o n to the eq uation ax mathematically exact answer.
+ b= c
that is within 1/ 1000 of the
The n we implement a program to satisfy these requirements .
• Verincalion: Ensuring that each artifact is built in accordance with it specincations - "Are we bUilding the product righd' - Mostly inspections and rev iews .
• Validation:
hecki ng that each completed artifact satisfies Its pccincations.
- "Arc we bUilding the right product)" - Mostly t""', ng.
Agure 2.5 Verification vs. validation
PlANNING FOR QUALITY
It i our respon ibtiity to ensure that we have butit the application correctly by checkinll that we proceeded appropriately (rom the begInning of the process to the end , Th,s is the IJtriji,alio" process. For convenience, we will number the development ph ..es as follows . I, ~t the customer's req,,,rements. 2. \X/Ole down the requirements in detail. 3. Obtain the customer' approval o( the requirements statement. 4.
Code the application . (For Simp licity , we have omitted a desIgn phase .)
5. Test the application . Verincation checks the following questions, I. Do the requirements express what the customer really wants and needs, Some verification issues here arc as follows , Is ax + b = , the correct torml What are the precision requirements] What i( 0 is entered for al 2. Are we carrying out the process o( obtaini ng the customer's approval in an appropriate manner) Some verification issues here arc as (ollows, Are we allowing the customer adequate time] Are we exp laining all needed terms to the customer) 3. Does the code implement the written requirements in every respect ] Thi s requires an inspection o( the code itself, in which the requirements are considered o ne at a time and the matching code is perused. This could include a mathematica l proof. (Strictly speaking, verincation does not cal l for executing the code.) 4. Do the proposed tests adequate ly cover the application ] For an application o( realistic Ize, this would include an inspection of the test plans, test cases, and te t procedures . Th,s is se parate from te ting itself, a validation Slep discussed below . Val idatio n of, this product consists of obtaining the customer's approval o( the wrillen , completed requirements and executing a set of tests on the comp leted code . For example, we enter a = I , b = I, and c = I , and validate that the program produces x = O. To summarize our diSCUSSIOn of the VII< V process , at any given mom(:t.ll a oftware engllletr is eIther creating an artifact , verifying it as he does so, or va lidating a completed artifact . nlis is illustrated in Flsure 2.6.
2.4 PLANNING FOR QUALITY SlIlee quality practices arc implemented throug hout the software life cycle , it " Important to expre s qualit app ro. he~ and goa ls in writing ea rl y in a project- in other words , w~ 1I hdore thc goals arc used in tracklll!! the prOJect's quality. Agile projec ts emphasize the allalllme nt of qualtty through o nt inual intcra tl o n wllh tlw ell,t omer III person, -arly ImplementatIon , and conllnual , cumulattve te tlng. Tlte IEEE has published several , i~ th at the tC\ling phase DC ur~ at the end of the development c de th e f,rs t time the ,y,te m is tes ted a a w ho le. Maj or Issue< , plan , o bjective , and tnea~urablc eva luation Crlterl. , The ' re lea<e" is a workln~ vCrlilo n of cd internall y by the project team or externa lly by stakeholders and cu,t merli. Type of rel eases an be [2J • A proof of Oil 'p I, or f,lISibi lily ' IIIdy, that Is used to demonstra te or invest igate feasibi lity of a particular aspect of the software . Thi includes producing software or simulations These are covered in Section 3.2.32 • A prolotyp, that is a workmg verliion of software demo n trating a parti cular capabi lity that is deemed high risk . Prototypes are covered in Section 3 2 3, t , • An "internal" release that is o nl y used by the devel o pment tea m and is used to ensure tha t develo pment is on track, elicit feedback, and provide a basis fo r further devcio pment and addi tiona l capabili ties. • An "external" release that IS shipped to customCrli fo r evaluation . Trea ting each iterati o n as a self·contained project allows clear and manageable objectives to be set, and reduces overall projec t complexity by breaking it down into small er pieces. By produci ng working software at the end of each Iteratio n, project progress can mo re easily be mOnito red and planned, and feedback can be ci ici ted to ensure that its capabi lities arc meeting stakeho lder requireme nts. Typically, early iterations ge nerate softwa re releases that address aspects of the project with the highest risk . In this way, as the project progresse the overall proJec t risk level is reduced. An example o f an iterative and incremental process that is used within parts of Microso ft is reported by Cusumano and Selby [4]. to wh ic h the y give the name "synch·and·stabilize: Product features are defined at a high level during the initial phase of a project, with the idea that many Will evolve as product development proceeds. The product is divided into parts, each co nsisting of a set of features , with small teams aSSigned to each part. The project is also diVided into parts, o r iteratio ns. each with its own completion milestone. Each iteration includes several features . Feature teams employ incremental synchronizati o n by combining their work and stabili zi ng the resulting system o n a daily or weekly basis In this way the evolving software application is continually kept in a "working" state .
3.2.3 Prototyping, Feasibility Studies, and Proofs of concept Prototypes and feasibility studies are impo rtant techniques in software development, and are explicitly included as formal steps, o r phases, in several process models. We discuss them now in more detail.
3.2.3.1 Prototyping On begi nning a software projec t, we are usuall y faced with factorli that we do no t yet fully underlitand . The look and feel o f gra phical user interfaces (CU ls) that will sati fy the custo mer is o ne common example. T iming is ano ther. For example, suppose that we plan to build a Java application to control an airplane. A critical issue to pm down very early would be; Will the Java Virtu.1 Machine be fast e noughl Each unknown factor o r risk is best confronted as oon as possible so that its severity can be assessed and a plan developed to deal with it. Risk management is dealt with in detail in C hapter 8. ProlotyPi"9 is an important risk management tec hnique. It is a partial implementation o f the target appl ication useful in identi fyi ng and retiring ri ky p.lrtS of a project. Prototyping can also be a way to obtain ideas abollt the customer's requirements. An inc,. a,e in o nc's underlitanding of what is to come can save expensive rework and remove future roadblocks before they occur. Agile processes contain some of the beneAts of proto typi ng because they deal at all times with worlt,ng code, However, they do not have all of the beneAts, since prototypes proceed in parallel with the main threod of the project, whether agile o r not.
SOFlWARE PROCESS MODELS •• , •••••
••••••••••••••••••
.. Prototype Implements
Prototype
Project beginning
,:~-
risky parts of this activity lirsl
·0_ •°
~,
Main project timeline
Key:G= end of a unit 01 time
0
....
•
•• •• •
time = Activity wilh risk
Figure 3.6 An illustration of prototyping in the context of a development project
As Figure 3.6 hows , work on a prototype typically progresses in parallel with regular work o n the project. The risks are prioritized and the prototype is geared towa rd as many of the mosi imporrant ones as time allows. In the example shown in Figure 3.6, the prototype ignores the large risk near Ihe beginning of the project because it will be dealt with early in the ordinary course of the project in any c ase. Large programs, such as billion dollar defense projects, utilize extenSive prototyping to retire risks and to guide the requirements and design of the real thing . For example , before the U.s. Navy built the Aegis generation of shipboard systems, it built an entire scaled -back version , complete with software and hardware , installed o n a s hip for the purpose. Thi s prototype served to indicate to the Navy what the main problems might be with the eventual systems . It also helped the Navy to deve lop the requireme nts and design of the eventual system. Simple gra phics showing curs usi ng paint · type too ls may be s uf~cient if the prototype's goa l i to envision the interfaces. The more extensive the prototype, the mo re risks can be retired with it and the more easily a customer's requirements can be understood . O n the o ther hand, protorypes are themselves software applications , so extensive prototypes arc expensive . A rou gh assessment as to whether or nOt to build a prototype is shown in Figure 3.7. Th e table in the figure illustrates, for example , that a re latively inexpensive prototype with high va lue s hould probably be built. "High value" means that building the protorype helps th e
Calculate payoff In detail
no
Calculate payoff In detail
Figure 3.7 A rough calculation of whether developing a prototype would be wo rth It
.1
CHAPTER 3 SOFTWARE PROCESS
t Payoff from building prototype ($'s saved per $1 spent)
optlllUll expenditure on prototype
full
project expenditure
0/0 expenditure on prototype
0%
1000/0
GUI
only Figure 3.8 Concept of when It is worthwhile to build a prototype (near the beginning)
cu tomer understand better what kind of product is likely to emerge , helps the e ngi neers understand better what kind of product shou ld emerge, andlo r retires a development risk . Many cases fa ll into the "maybe" ca tegory of the table in Figure 3.7, and more detailed analysis is required to assess the value of protorypi ng. \'l/e are seekin g an optimal level of effort to be spent on a prototype, as sugge ted by Figure 3 8. As the expe nditure o n a protorype increases, its usefu lness increases, but so docs Its drain on the project's budget As a resuil , there is a point at which the payoff is optimal (the maxImum point for the curve ), and some point beyond which funds are ac tually being squandered (w here the curve drops be low the horizo ntal axis). As an exa mple, consider an e -commerce application in which a clothing company wants to sell goods on line, retain customer pronles, and allow customers to obtai n pictures of themselves wearing clothing from the ca tolog . A typical calculati o n about prototypes factors the cos t of protoryping features and the potenti.1 for using prototype code in th e nnal product . Figure 3.9 gives nnancial estIma tes fo r prototyping four parts of the clothing ve ndo r application ,
I . CUI screenshots 2. T ransaclioll security 3. Complete transaction 4 . Customer tri es o n clothing
For each of the fo ur app licat io n features consi de red fo r the prototype, severa l estimates can made, the cost of building the feature , the percentage of the feature's implementation that will be reused in the applicatIOn itself (i.e., not di scarded ), and the "gross benefit" from the effort. The gro benefit here estimates the gain from prototypin g the feature , excludin g reuse of th e code and excluding all e · ~nses . For example, as show n in Figure 3.9, we have estimated that if the "Customer trie on clothing" feature were to be prototypcd, it would save a minimum $20,000 in development co fS Thi estimate I based on factors suc h as the fo llow ing,
SOFTWARE PROCESS MODELS
Cross IkneRI
ProlOlyP
3.2.4 Spiral Model One of the earliest and best known iterative proces es is Barry Boehm's Spiral Model [5). It is called a spiral because Boehm concept1Jalized development iterating as an outward spIral, as shown in Figure 3. 10. Boehm's spiral model is a risk· driven process in which iterations have the specified goals shown in Figure 3. 10. (Recall that risks are potential events or situations that can adversely affect the success of a projcct.) A project starts at the cenler, as it were , and each cycle of the spiral represents one iteration. The goal of each cycle is to increase the degree of system definition and implementation , while decreaSing the deglee of risk. Risk management is built into the process in that very early in each iteration , project risks are identified and analyzed and a plan for the iteration is created that includes mitigati ng some or all of the risks. As an example, suppose that at the beginning of a cycle a risk is identified with the screen layout of a portion of the user interface. Software could be developed to implement pan of the user interface so feedback can be eliCIted from takeholders. Doing this mitigates risk early in a project and leaves ample time to implement necessary changes. Thu the ov...11 project risk reduces the funher along you arc in the process. After the major risks arc addressed and mitigated, the project transitions to a waterfall model , as shown in the outer spiral of Figure 3. 10 Each iteration in Boehm's spiral model consists of the follOWing steps, 1. IdentificatIOn of critical objectives and constraints of the product. 2. Evaluation of project and process alternatIves for achievlll8 the objectives.
SOFTWARE PROCESS MODELS
COST
Dele,uutE
ntROUCH
EVALUATE AL i EJdU.l1VEI
8108
oe,Ec11V£l. A1.. ftRNATIV£S, CONsntAJNTI
1DE>m'Y, RE SOLVE R.tSKS
RISK ANALYSIS
,
RISK NtAl. Y&lS
RISK ANAL YSIS
",
OP EllA naHAl: PROTOTYPE
.,
COMM'iiriEHT PAR Ii flOtt
RJSK
'.,
-'
ROTOiTP £,
AHAI,., PROTOTY PE., ~ ~R:OTO· TYPE 1
,,
"EVIEW ROTS PlAH Uf'E CYCLE PLAN
- -- -
_ COHCEPTOF OPERA nON
EKlLATlOHS
SOflWARE
"an: DEVELOP· MEHT PLAN
INTECRATION
"HOttST PLAN NEXT
PLAN
MOOELS
-- - --
BEHCHMAR KS
OETA.D.. ED DESlCN
SOFlWARE PRODUCT OESI CH
ReQUIREMENTS VALIDATION
... ... ...
"
CODE '" UNIT "-
OESK;H VALIDAnON AND VER'FICAl1OH
PHAS£S ,
\ ACCEPT. ' IMPLEMEH. \ ANtE TEST
TAllON
" INTECRA·' nONAHO
TEST
,
lEST
D£VELOP. VER IFY NEXT LEVEL PRODUCT
Figure 3.10 Boehm's spiral model for software development Source: Boehm, B. w.o"A Splral MOClel of SOftware Development and Enhancement." IEEE COrnputtf. Vol, 21 , NO
5. May 1988, pp
61-n
3. Ide ntification of risks . 4. Cost·effec tive resolutio n of a sub et of ri sks uSi ng analysis, emulation , benchma rks, models, and prototypes.
5. Developmen t of projec t deliverables including requ ireme nts, deS ig n. impl ementa tion , a nd testi ng. 6. Pla nni ng for next an d fu ture cycles-the overa ll project plan is updated , including sc hedul e, cost, and numbe r of remaini ng iterations. 7. Stakeholder review of iteration de hve rables and their commitme nt' to proceed based o n thei r objective
being mel. Each traversa l o f the spira l resu lts in in remental deliverableprnCOl shol.dd str ive ~ even greater cooe RlIlntAtnotlilaty " ~dons of tn..t Ae M. Vol 47. NO, 10. OCtober 2004, copyrlgh l (" 2004 ASsocIaOOn lor computing MachInery. Inc. Rop'Ii"Ued by pbll'rtsOO
53
5'
CHAPTER 3 SOFTWARE PROCESS
Figure 3.20 Maintaina bility Index comparing OSS and CSS for the same application. 2 of 2 Source SamoLadas. monls. I Stametos. L Angel.S. and A. Qlkonomou. "open source SOftware oevelopment ShOUld strive for even greater code rnamtalnabIJty .. CommunlCatloos 01 the ACM, VOl 47, NO 10, October 2004, copyright, 2004 , As.soclallon for COmputIng MaChinery. Inc Reprtnted by PeHI''ViM.
Various tools and e nviro nments are available to faci litate open -source development. Figure 3.22 shows a sche matic diagram of o ne sllc h tool. Collabnet. "Subversion" is an o pen -source version control system used for many open·source prOjec ts
Key adva ntages and disadvantages of o pen -source processes are summarized below. Advantages of open source
• TI" work oj mauy moy b, obloiudj"" For projects that mo tivate o thers. work can be o btained from motivated o utSiders.
• Dn"lopm I",d
10
b, mort moliva l,d. because they choose to work o n it.
• Op",-sollrcr applieoliolls art v'ry w,lI ltSl,d, because they arc continuall y exercised by many and usually have efficient testin g processes .
Release I
I
Sales. service. /
productivity ....
I I
Cumulative
revenue
I I
I I
Time
CumulaUve expense " "
I
Open ~ource :
development : maintenance I I
Proprielary • I
Fllllr. 3.21 Hybrid open-source/ proprietary processes
CASE STUDY: STUDENT TEAM GUIDANCE
•
ColiabNet TeamForge: Structure & Features My Workspace
Community & Projects
'-*"' • ..,.. ' '''melt ' _
.. .. -=..:I
'we&. AI'IJI' ICb
,
I
...-
t
+
u...-.p.'I O'.
i
Pp'e;rtt
_rapEl.
... " ' . . . . . .
""
$
: ...
Oft.4., ' .... _ .,. ~
,:.elk 1M' ,","". do · dl ,.., 'tI 1'Ot-u.
...
\.Mit" Uk_40 _~..ub,no
lAc ....... .,.,
.,.~'-
we"e", ' 1'Oj«U
M. 'I' "tOl'I/to.w
..,tfkU MId t ooh
(,,,"",.0-0_
b, p la~
eo • 'i
•
prw.
,
--
•
,--
•
2,
,.,,' ..., 7,="
•
--
v, ..., ' 'ns
-
"
•
...
•
-
-
."' __ .0.111 C
La
I.
lOCI .. ~1101 In •
Figure 3.22 ColiabNet TeamForge: Structure and Features Source" CollabNet. httpJ/WWWopencoll8bnevproductslsleetc.apabllltles html
Disadvantages of open source
• Tbry art flIlflilablt
10 Oil'
m.d all : Th. is part of the barga.n
• DOCunlrntlliio Pl 15 qucstio"ablr: Developers are not cont;islc m
• DtSi9" dorum(1,'alioll '(lids
In
what they produ e
'0 b, poor. It seems that the ope n·source proce"
has espcc .ally great trouble keep.ng designs and code sy nc h ronized, a nd so dcsign docum e nts are ofte n poor or even no nex.sten t To ,einfo rce th e concepts o n pro esses de> ribed '" thl< chapter, we continue w.th ca e stud.c
3.3 CASE STUDY: STUDENT TEAM GUIDANCE T o re",force the many softwa re c ng",cen ng o ncepts and practice 'n trodu cd in th" book , .t's best,f ou are develop.ng a oftwan: project .n parallel You will ga lll the mo,t If the prOject .s a tea m dfort a< th.s I> ho\, most real . world ,oft ware project arc exc lItcd At the e nd of most major parl< of the book a 'C lion ( lIch a' th. s one) enti tl ed Ttam Gu.da" (ca n be found . gu .d .ng 'o u throllg h th e different pha,,,, of o llr group proJe t
55
56
CHAPTER 3
SOFlWARE PROCESS
u will he a,ked to ~c nera te speciO artd actroce , lIIodel. inco rpo rale prolo lypes ,n o ne or more o f Ihelr Iterallons omC lImes, it " unclear whe lh er certa,n requiremenls ca n be ,mplemenled In pract,ce, plac,ng the enl.re prOject at " k. In su h cases, !((I"bd, ly " lIdits may hc advisable, wh.c h are partIal Im plementations or si mula lions of the app hCJ lio n. In o pen· ource proces <s, so ftw are is developed and malnlained by peo ple o n a volunteer basis. Sou rce code 's open 10 all , and th ere Is a process for virtua lly anyolle to susgest and Impl eme nt e nhancements and . ubmil and repalfddccts This process is re pea ted and the app hcat .o n grows in ca pabili ty and stabIli ty. In thIs wa , ope n· source proje ts are developed ,n an iterat,ve manner. In addit,o n, by exercising an application many tim es, th e ope n-course community rtlnctlons as a huge test ing process.
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 Manifees 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
,
'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. Kcee,sed November S. 2009}. 2. HicMlilllh, Jim , -H131ory Agik /\It4_iftsJd," 2001. httpJlwww ~&II~miln.fC:Slo.orglhlsIOry. htmllaccC\scd Novcmha S, 2009] 1 HQJh~nlth. JIm.. ~nd A Cock.bum, -Agile Sortware Dcvclopnlcnt~ 11" Uusjn~s of Innovallon: IEEE C~,..ftr, Vol. 34, No 9, $q>'<mber 2001 , pp. nO-ll2 . • . Cohn. M.rt. -Usn IOn" AppIJ,J For Agik Sol'..." Dnoe 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 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" -
"
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, an orilanlzation where everyone is a peer bllmaHagtr. 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
"
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 nk 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 (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 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. 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 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
[email protected] .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
[email protected] .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 mu
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 *
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, 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
-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 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 .
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 en" 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 Obje 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.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 'ClJy each detailed requirement by mean of a test
AGILE METHODS FOR DElAll ED REQUIReMENTS
T est input for Requir! 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 "modecus,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) IXI11 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 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 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- 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 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 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 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 rc, o nmaxNumChsrs/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 dettr. "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 lumic, sequence or state diagram (operation)
• wls-- : 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 " 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 Adapl
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!pvck· 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 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 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 ~'
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
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. 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 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 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 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
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 sldl,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 connectCTlbes 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>turb the st;;ndard order
3.3 Data Decomposition
EncounH.' r
Trfwrl
Descflbc, the .. 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 e 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. Icc h OV('rvl('W Ic; by relating lhe detailed design
RELAnNG USE CASES, ARCHITECTURE, AND DETAILED DESIGN
pro 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 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 ndrnw"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 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< rorllng 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 of Ell olwlcrGflmr
SRS.
EncounterGame encounterGameS :
11" s .s thl.: ",nglcton Th is cia." co nlrol~ the movc:men l of the fon: lg n
o n ' lrlJ C l or~
character
Methods of (haradrrMov,""H I
obJc
t
of E"loll"lcrGtlmc
pr ivate EncounterGame () :
Inheritance
Th is cia'> Inhent< from Java 1""9 Thread
EtlCOlltllrrGmnc
Precondition.:; none
Post ndillon...
Mcthod"
rcJ t (~ I n EII(Olmtcr(,(lrtlc In,l"J,nte
of E",outllcr(,mnr
publi c static EncounterGame run ( ) ; public static EncounterGame
Slart, the foreign ~ h .ract"r ,n th" dung""n Muve, the f",elgn haractor Irom arCJ to area
getTheEncounterGame() :
Via area ('onnC('II()n = 0.5. oth e rwi$~ sets oal",P to Zero TI,l" method 'aw.he, r~qll1n:n1t.·nt 3 2 2 (lower Im1lt t) llll onZt>ro qUiJhlV value, )
.r
SOl
502
CHAPTER 19 DElAILED DESIGN
6.1.6. ES
The
EncounterCast
Class n e me thod ,pe ,A Jt,o ns for thos inglcton . interfa e
cia ... , af(' given
In
Section 5 of dll s document
6.1.8. AR Area Class This clas< encapsu late< the place in wh ,c h the chJractcrs eXISt , and corresponds to reqUIrement 3 2.AR Inhent ance
6.1.7. FC The ForeignCharacter Class n is
Thi S d.,o;s Inhents (rom
clas. i analogou to Plnycr(l",raclrr. described nex t, and ,s designed to sa tisfy the SR 3.2.FC
GnmtA rra
Attributes,
6.1.8. PC The PlayerCharacter Class This class
pri vate St ring nam eI ; I I corresponding to requirement
,s desig ned to satISfy the requirements 3.2.PC
3 . 2 . AR. 1. 1
Inhcrirance Thl c1asc; Inherits fro m Attnb utes,
private Image i mageI ; II cor r espo nd i ng t o requirement 3 . 2 . AR . 1.2
E'ICOlilllt rCha ra clcr.
private Stri ng [ J qu alitiesI ; II co rr es pond ing to requireme nt
private static final Play e r Cha racter playerCharacterS ;
3 . 2 . AR . 1. 3
pr ivate Vector co nn ect io n HyperlinksI;
This is the si ngkton object representing the player's charac te r.
Metho ds
Methods,
pub lic v o id display ( ) I I shows the area objec t's image on the mo nitor.
public static final Player Characte r getPlayerCharacter( ) ;
public static Area geUrea (String areaNameP )
nis me thod returns play,rCharaclcrS.
return s the area correspondin g to MtaNamtP
according to requirement 3.2 AR.2.2.
6.1.7 The EncounterEnvironment package The classes of thiS package describe th e environment
public static AreaConnection getAreaConnection ( St ring area ConnectionNameP )
In which the game takes place. It is shown in F,gure 19.37.
GameEnvlronment
-..f GameCharacler
GameArea
~
GameAreaConnection
Area
EfiOO' mterErMn.",·. fLe,lI
rC
I EncounterAreaConnectlon ConnectlonHypeftlnk oJ
EncountetEnvlron,icent
FIgure 1'.37 EncounterEnllironment package
CASE STUDY DETAILED DESIGN OF ECUPSE
rerum~ the areJ
object co rTcspo ndlng to ,lrc.1CO""KhoPiNIll1ttP ZI ordr l1g to reqUIrement ' 2 AR 2 2 0,,"((11011
6.1.9. CO EncounterAreaConnection Class This la cncap ulatc.:; the way~ to get rrorn areas to adjacent a~as. It Inh erits (rom ArWCOtltl(( tJOIi and COrTe pond. to requirement 3.2 0
Inhentance This cia" Inhents rTom Gmll(A,rn Co.l ~ "crholl I n the framework package Aunbulc); pr .lv ate Ar ea f irst Areal :
/ I con esp ond lng tor equ l r erne-ot 3 . . CO . 1 . 1
Atlnbutcs:
private Connection connectionI ; 11 the corresponding connection Methods·
The only mean~ngful method is mou s eC li ck ( ) "
6.2 Data Detai led Design There arc no data structures beSides lhoc;c mentioned as part of the ela ~e) 111 e tlon 6 1
19.13 CASE STUDY: DETAILED DESIGN OF ECLIPSE
pr l va t e Ar ea seco ndAreaI ;
//co rr espondLnq t o requirI
No te to the tudent· Eclipse i a large project, and this ca e study docs not attempt to dcscnbe its des.gn in detai l-merely to provide excerpt from a small example of how detailed de ign IS some times speCified in the ca l' of Eclipse. The co mplete document would be based on the archltect\lrc decomposi tion describ ed preViously It would have a section on ca h of the Plaifo,," , the Java DWc/Ol'm,"1 Ellvlrollmrnl, and ,he Pluglll Dn",'o"m",' EHVlrOHmrnl. \'(Ilthln the Plaifo,," <eClion , It would have a Workspllrr and a Corr ,cClion \'(Iltll1n the Corr "cellon , It would have a RlUllmt( t:C1lOn Part of lilt, lauc.:r IS shovm next.
Platform. Core. Runtime
th" dowment
6,1.11 CH ConnectionHyperlink C lass 11", cia., encapsulate. the wa y ' to Het fWIll area' to adJac..cnt areas It Although the re~der 'he Eclip'c documentation C~ n undcraan I the tm e In gencr~ 1 h:nn .. , It ,\ not \rr.llt-;hLl f\\fard (0 IOC~' tc.- lilt"
r
eXilet r feren
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 Jer look at th e ar h,tccture a nd slic h IS needed.
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-ldabdily . Design pa tterns often Inlroduce add iliona l cia <e supplied With pre
Ircntu..e H411 1981 S -I[EE Id ~k2 1.2005 IFFF lolndard Dlctiona I)' of l Col"Urt,·, of ,he: ft~';,rt.' A,pt.'(..'\ of I epcndabdtty · lEa Id 9~1 I 200 (j Shl3Cr Sa lly ;,nd Slephan Mellor, Ob/fd Lfcrydt1 t\ICklrlln9 "" Wo,/J III '"lIn Pr(,llIlce 1-1311 It,
Preconditlo n s : a nOorX = ' Q ' ORa nOorX= ' X '; 1< = aRowO(:;;3 ; 10 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 ) { • ""'rt 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 = 'a' ) && ( 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 •
Invariants: The values of q ua lVal ueI(J are >= 0 * @author Er ic Braude , Tom VanCour t • @ve rsion 0 . 2
*/
575
576
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
publ i c cla!!. Encounte rChara cta r e xte nds Gam. Cha r a cte r
{
/ ** Total quality point s at initialization . * / private static final float QUAL_TOTAL_ INIT= lOO . Of ; / / Symbols used when other classes ref er to specif ic qualit ies . / ** Symbol for o n e of a character ' s qu al i ties * / public stat ic final String QUAL_CONCENTRATION = " concentrati on" ; / ** Symbol for o ne of a character ' s quali ties * / public static final Stri ng QUAL_ INTELLIGENCE = "intelligence " ; / ** Symbol for o ne of a character ' s qualities * / public static final String QUAL_ PATIENCE = "patience" ; / ** Symbol for o ne of a character ' s qualiti es * / public static final String QUAL_STAMINA = "stamjna ', ; / ** Symbol for one of a character ' S qualities * / publi c st at ic final String QUAL_STRENGTH = "strength ' , ; / * * Quali ties that each enc ounter character posesses < p > Req : 3 . 2 . EC . 1 . 2 * / pr ivate static final String[J qualityTypeS = ( QUAL_CONCENTRATION , QUAL_STAMINA , QUAL_INTELLIGENCE , QUAL_PATIENCE, QUAL_STRENGTH )
/*
INSTANCE VARIABLES
*/
/ ** Values of the qualities < p > Requirement 3 . 2 . EC . 1.2 */ private float [1 qualValuaI = new lloat[ qualityTypeS . length J;
/ ** Name o f the GIF file containing the character ' s image .
* The
* *
*
character i n this image is assumed to be facing left . Select this character ' s height , relative to heights of other charac ter s , by padding the top and bot tom wi th t r anspar en t pixe Is . No padding gives the tallest possible character .
*/ pr ivate Strinq imageFileNa-eI
= null ;
/ * CONSTRUCTORS * / / * * Allocate ini tial total quality po ints equally among the qualit ie s.
*
Requirement : 3 . 2 . EC .1. 2 (quality value initialization) */ protected EncounterCharacter () ( super() ; for ( int i = 0; i < qualityTyp4lS.1ength; ++1 ) qualValueI [lJ QUAL_TOTAL_INIT / qualityTneS . len'lth : &
)
CODE USnNGS REFERRED TO IN THIS CHAPTER
/** Construct a new character using the given name and *
Requirement: 3.2.EC.l.l (character naming ) * @param nameP Printable name for t h e character . *@param imageFilep * character image.
image f i le.
Filename, relative to document base, .... for
*/ protected EncounterCharacter ( Str ing nameP, Str ing imageFileP ) {
tIlia () ; •• tNama ( na=eP ) ;
ip'g8Fi.leNam er = im,qeFileP;
}
/ ** Construct a new character using the given name. *
Requ ireme nt: 3 . 2 . EC . 1 . 1 (character naming ) * @param nameP Pr intable name for the character . */ protected Encount erC hara cter ( Str ing nam eP ) { this ( oaceP , null ) ; }
/ * METHODS */ / *. Requir eme nt 3.2.EC.3.2: " Configurability of £ncounterc haracter * quality va lues. ' , * Synchron i zati on holds qualit yVal u eI constant even wi th o ther threads * running. *
SDDreference: 6.1.2.1.1 * < p > Invar iants: see the class invar i ants *
Preconditions: qualityP is in qualityTypesS(}
* * *
AND qualityValueP> =O AND qualityValueP < = the sum o f the quality values
Postconditions: qual i typ has the value qualityValueP
*
AND the remaining quality values are in the same pr oport ionas pr ior * to invocation, except that val u es less than some tolerance are * zero. • @param qual ityP Quality whose value is to be adjusted . * @paramqualityValuePThe value t o set this quality to . * / public synchr onized voi d adjustQuality (String qualityP, Iloat qualityValueP) (
/ / Value of the quality to be changed float qualityValuaM = qualValuaI[ indexOf( qualityP) 1 ; / / Save the sum of the values float originalSnmM = ."mOfQualitiu () ; / / pc Set the stated quality to the desired amount , adjusted to the // threshold value . HtQuality( qualityP , qualityValuaP) ;
// pc If the caller adj u sts the only n o n-zero quali ty value , / / divid e the adjustment a mo unt e qually among all other qualit ies .
S77
578
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
if ( originalS"mH == qu a lityValue H ) {
float qualityDiffEa ch = (origi nalSumH - quali tyValue P) / (qua li tyTyp e S . length - 1) ; for ( int i = 0 ; i < qualityType S . length ; ++ i ) if ( ! qualityTyp e S[ i ] . equal s IgnonC. . e ( qud i tyP ) ) se tQuality ( qu a lityType S t i l , qua lityDiffEacb ) ;
}
else ( / * Co mpute factor ( "pr oport i onM" ) by which all other qualities mu st * change . * Example : ifthevalueswere 1 , 3 , 5 (i . e . sum9) , and the first quality * is ch anged * fro m 1 to 2 , th en "" 3 " and " 5 " chang e from 8 / 9 of the t otal to 7 / 9 * of the total , so each should be mult ip l ied by 7/ 8 , i. e . , by (9 - 2 ) /
*
(9 - 1) .
*/ float proporti on)( = (originalS"mH - qualityValueP) / (original.S"mMquali tyVal.ueM) ;
l /pcAdjusttheremaining q ualities , retainingtheirmutualproportion for ( int i = 0 ; i < qualityTypaS . l.ength; ++i ) if ( ! qualityTypaS[i] . equalslqnoreCase( qualityp) ) setQuaHty ( qualityTypeS [i] , qualValueI til • proportion)() ; }
}
/ ** Get a copy of the list o f names of qual ity values . * @retu rn working copies of name strings representing qualities . */ public static String[] getQuaHtyType. () (
String [] returnListH = new String [ qualityTypeS . length ] ;
string array . for ( int i= 0 ; i < qualityTypeS.length ; i ++ )
/1 Copy the //
Copy each strin g .
returnLiatM(i] :: new Stri.nq( qualityTypeS[i] ) ;
return returnListM ;
// Return the copy .
}
/ * * Returns the value of the specified qua lity . * < p>Precondition : qualityp is a valid membe r of * @param qua lityp
* @ret urn
The quality we want the value for . The value of the specified quality .
*/ pub 1 ic float getQual.ityValue ( String qualityP ) { ret urn qual.Valuer ( inMxOf ( quali tyP ) ]; }
quali tyTypeS (]
CODE USTINGS REFERRED TO IN THIS CHAP I ER
1** Quality va l u e s below th i s threshold are set to zero to avoid having
*
the game go on f or an indetermi n ate a mo·unt of time . *
Requ i r e me n t : e . g . 3 . 2 . EC . 1.2 (lower limit on n on - zero quality * values ) * @return Toleran ce value
*1 ataUc!ina! float g8tTolerance () { return O.5f ; )
1** Retu r ns t h e ind ex of the specified quality . * < p > Precondi tio n: q ual1tyP is in qua 1ltyTypeS[J , give or take • c api t aliz a t ion . • @param * @re t urn
q u alityp The quality we are searching for . The quality index .
*1
private stati c i n t i n dexOf( Stri n g qualityP ) {
int returnlndexM= -1; II Default to "missing " value . f o r ( int i = 0; i < qualityTypeS . length ; ++ i ) I I Sear ch qual i ty name table . if ( qualityTypeS [ i 1 . equals IgnoreCase ( qualityp» I I Quali ty name match? { returnlndexM = i ;
I I Note the i ndex value .
break; )
return returnlndexM; )
1** Set d ef a ult ma x imum allowable number of characters in names of
* char acters .
*
Re q ui r ement : * @r eturn
3 . 2 . EC . l . l (limit on character name length ) Maximum number of characters allowed in a char acter name
*1 protected int m'xNumCharslnName ()
{ )
return IS;
I H Set a quality value without regard to the values of other qualities .
* Tru n cate
• • • ' •
any value below the threshold value down to zero . Synchronization prevents cha n ges to qualityValueI while other threads are using it . < p>Requirements : 3 . 2 . EC . 2 (lower limit on no n- zero quality values) ,
Precondition : qUillHYP is a valid me mb e r of qualieyTYP"sll
579
580
CHAPTER 22
PRINCIPLES OF IMPLEMENTATION
* < p > Postcondition:
* *
* @pa ram * @param */
Quality values are greater than tolerance orareD .
qualityP The quali ty to set the value of . valueP The value to set the quality to .
public synchronized void
setQuality( String qualityP , float value P )
{ i f ( valueP < gatTolerance () )
qualValueI( indexOf( qualityP) 1 = O. Of ; e lse qualValueI( i ndexOf( qualityP) 1 =value P ;
}
/ ** Display the char acter * < p > Requirements : 2 . 1 . 2 . 1 (character displayed in game Area ) , * 3 . 2 . PC.1 (c haracter image selection ) , * 3 . 2 . PQ . l (c haracter image in quality update window) * @p aram compP UI component in which to draw the character * @param drawP Graphics co n text for doing the drawi n g . * @par am posP Pixel coo r dinates within compP for the center of * the image . * @pa ram he ightP ixP Desired image height , in pixels . * @par am faceLeftP true if character faces left , < tt> f alse if faces right . *
*/
public void showCharacter (Component compP , Graphics drawP , Point posP , int beightPixP , boolean faceLeftP) { if ( ;m " geFileN"meI == nu 11)
{
/ / No image file name . Pr int the character name instead . dravP . aetColor (Color . .... genta) ; / / Normally a visible color .
=
FontMetrica fm drawP. qatFontMetrics () ; dr • .,P . drawString ( qa tNeme () ,
pos P . x - fIR . otrin<J1fidth (getNne () ) poo P . Y - fIR. g e taeigbt () / 2 ) ;
/ / Pr int the name , centered /2 , / / at the character location .
)
e lae {
/ / File name was provided . Draw the image file . Image chImeg.
int int int
= CompP . q _ tToolki t
() . q_ tlmaq. ( jm. qaFile Nep.I ) ;
Im"ge"idth = cblmoge. getWi dth ( ChUpP) ; / / ;m" g e Be igbt = cbI_ge.ge taeigbt( compP) ;
Raw size of the image .
acale dWidth ~ I m"ge"idth· b e igbtPixP / ;m"ge Beigbt ; / /
Scale width same as height . / / Assume that the normal image faces left . De'c ide whether to reverse the image .
EXERCISES
if (
fac:eIAftP )
Draw the image a s g i v e n , h eightPixP/2 , / / scaled a nd ce nt e r e d .
dravP . dravImaqe ( chImaga ,
//
po.P . x - acaledWidth/2 , po o P . y pooP . x + ocaledWidth/2 , po s P . y + heightPixP/2 , 0,0, i·.ge Width-l , i mage Re ight-l , compP) ;
el s e dr ••P.drawlm.aqe( chI.aage ,
1/ Draw the image revers ed ,
pooP.x + acaladNidth/2 , pos P . y - heightPixP/2 , / / pooP . x - scaledWidth/2 , posP . y + heightP i xP/2 ,
scaled and cente r e d .
0 , 0 , im e qeWidth-l, jmage Re i ght - l , compP) ;
}
}
// End o f showCharacter . / ** Computes the sum of the quali ty values . * Syn chr o niza tio n ma k es sure that another thread won ' t change * qual ityValu e I * whi le t h is th read i s p art - way through computing the total . *
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
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 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 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 underurc 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 the inspecto r shou ld be loo king for as he or she reads the code. The following is .n example list of .tems found .n a code review check!'st. Code In5pection Checklist I Vanables ,
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' 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")
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 would usuall y be ,nappropnatc, and tx, ul,Ord,,{) ca n be moved with th IS refactOnn g to the more appro priate cla< O,drr ,\Iout F"Id . 'lin d" to Mou, ,\ ,Itlbod. These refactonngs arc especially nceded when we ,"troduce n~
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
•••
•
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 OduCeon·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
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 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" 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'"!)' 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 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
= 5)
If we were to
uSe
&& (numDaysLate
o nl y a value of 6
10
= 0 .. AND qua lityValueP > > GetChorocler T est I: nom,nol vo lue ««< querry < - - Obtained querry < - - Required > > > > GetCharactcr Test 2: Outside porame· ler values « « < ddoultNamc < - - Obrarned ddaultName < - - Required > > > > EncounlerChoractcr Test 3: limil po· rametcr values
> 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), which" ,ubqanlla l en u~h 10 ~tr,,'ie Item I but IS otherwt>e as mode't as po" ,hlc. If Our goa l IS top· down Int wa tlon (dC'Lrtbed In detad ,n ctl ,on 27 3 4) then we fiN reate ,Illb, "' Step' TD .• and TD-b These ar ,ubs"tut", (or the Ite.m th at arc ,ul"t. nl,,1 l'nollllh ( r Item I to he lested (,te" Ti). C) but ot hcrw,, ' req",'e as lilt! . dfort ;" pr",, !>lc
..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 of methods, because every met hod con be repeated any number of times. A procedure must be employed to make the number feaSible . For example, a tnage approach can be usefu l 10 identifyi ng common sequences. A given sequence of methods ca·n be C1ForeignCharaeter 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 L!( . ...
1
~ I
GameEnvironment
(J'!CO 'IW C
Pip" I A
•
,.
GameAreaConnection
•
;1111'/7 ofDf6
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'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 ,
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, existing, and clcxed issues Over lime. Table 29.7 is an example of the statistics available using IssueZ,lIa [ 15] during an exomple time penod. It tracks the number 01 dderts in each state (e.g., rrop