Software Engineering: Modern Approaches

  • 14 258 8
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up

Software Engineering: Modern Approaches

Brief Contents Prefa C X IV Acknowledgmen ls Part I Part II •• XVII Introduction to Software Engineering Software P

5,960 2,959 147MB

Pages 775 Page size 1536 x 2048 pts Year 2011

Report DMCA / Copyright

DOWNLOAD FILE

Recommend Papers

File loading please wait...
Citation preview

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, ex pla in, how to produce requirements that speedy what the product " ""e nded to be Part V explaI ns how to 'fleci(y so ftware designs. hapter 20 de,crlbe, software architectures C hapter 2 1 de,crlbes how to specl(y the detaded de,igns. Design patterns, a standard means of com municatI ng Intelligently with each other about desIgn , arc described In haptcr 19. Part VI di cusses Implementation (progra mming), Cmph3>IZII11! standards and precIsIon . A major goal IS to help devel opers to wnte program that arc much easier to verify (or correctness Part VII describes how to test the part~ o( an app lication, a well as the whole. It includes test procedures that specify how te ts are onduc ted and the test cases that specIfy the input data for tests. Part VII also describe. the types o( customer documentaroon artiFacts that are produced and their purpose

1.4.3 Project A software project deRnes the activities and associated results needed to produce a software product. Every project involves a SIm ilar set of activities: planning , determining what's required, determining how the software hould be built to meet the requirements, implementing the softwa re, testing the software, and maintaining it once delivt·r 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 .... ,.,.,.

· ",.-1\ _' 1'.'_. l"'.

I,.

2 _ ""''':' ....... h'>rpo.f"~U'''

: - rl l _ . U . .. 1 OCu~p ... LO'" . rl leV. .. u. l . . ooroce , 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 answers the questions posed .n F.gure 5.5 The rest of this section addro 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 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-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. &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 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 ,bl

nut. W ould have to te,t under , 11 IrcumStJIl CS, mJny nOt intended , incurnng unn c:tessary ex pense and produ Ing a wrong re,ult all

Better vers ion .

Wb",w" all /orei911 playm Olll(1j'II"19

rh( play,,)

cballg, Ib, q"al,ly

ItWit I

are

ab,,"1 fro", II" arM

Iwrt,

"til,,,, 0/ 'h"

lu, flu

pfaYfr may

ham ''', kuPlll9 Ih,

s'Wn tolal oj 11)( qUf,lily vailllS Iwd){ltIgtd n Jr Playe rQualityWindow , ( " 5«11011 tbd ) is

""d

for Ihis purpo". Chall9" Ink, ,//rel /o14r "collds afl" II" "OK" b,,/loll is press"l. Figure 13.6 An example of ambiguity ,n requ irements

A metric (range: 0 to I 00) 100. 2:: lunambiguity 01 each detailed requirement (0- 2))

2.lnumber 01 detailed ,.quirement.)

o=

could have man y meanings, 2 = clearl y cne meaning

Figure 13.7 A metric for unambiguity

13.6 CONSISTENCY OF REQUIREMENTS A set 01 detailed requirements is cOIISllI",1 if there arc no contradictions among them . As the number of detailed require ments grows, inconsistency tends to become difRcult to detect. Inconsistency is illustrated by the three requirements in Figure 13.8.

Requirement 14. Oilly basic food slapl« sball b,

carri,d by gam, char.elm •

• •

•••

Requirement 223 . f",ry 9am, charael" shall carry wdlu.

. . .,. Requirement 497. Flour, bull". mill!. and sali shall b, co.sid",d ,''' only basic food slapl«.

Fl&Ure 13.'

Example Of Inconsistency In reqoirements

PRIORITlZAnON OF REQUIREMENTS

Means: No contradiction , in whole or in part Example: .,

...

..... The DVD

~

classificatlon order shall be the order of preference of the customer. ...

OVOS shall be classified alphabetically as drama.

comedy, ho"or .....

Metric: Percentage of contradicted requirements Figure 13.9 Consistency in requirements

The object·oriented style of organization of requirements helps to avoid inconsislenCle by classifying detailed requirements by class and by decomposing the m in,o a si mpl e form This IS not a guarantee of consistency, however, and so requirement inspections include a c heck for consi ,ency. H ere I a checkli , for improving the consistency of requirements, • For each requ iremen" are there olher requirements that could lea d

'0 co ntradicting or annulhng i,)

• For each requirement , are there other requ irements that arc very similar and so can reate Inconsislencles?

• Does each requirement avoid a chair. of conseque nces tha, ca n', be readily fo ll owed )

A consistency metric is Ih, prrc,"lag, oj d,lail,d rrq llir",,,,lIs partly or wholly cOlllmd,clcd r/5 In the \o ftwar{' engineerin g communlly begJn to poo l :lnd rd i1tc th eir ,dcJ\ for notJtlon Jnci

gra phical reprc ~c nt a tl o n of oftwa re deS ign, la that we do cover, however are adequate for m ost of o ur needs . UML is an excell ent ste p in the direction of imp roving software engi neering, but wi ll probably be improved upo n as the d isc ipltne evolves. The c hapter describes class relatio nships in UML, includin g inherita nce (Class Models, Section t 6.2 ) a wa y to represent control among fu nc tio ns (Seque nce Diagrams, Sectio n 16 .5 ), diagrams of state , events, and transitions (Section 16.6), its moderni zatio n o f fl ow c harts (Ac tiv ity Diagrams , Sec tion 16 .7 ), a nd finally data flow diagrams (Sectio n 16 .8 ). Section 16 .9 shows an exampl e that combines these.

16.1 CLASSES IN UMl Classes in UML are represented by rectangles o ntain ing the class name at a minimum . The detailed version includes attribute and operatio n names, signii Nres, visibility, return types, and so o n. Figure 16.2 shows a clas from the detailed design of an application that controls the Aow in a chip man ufactu nn g plant of canisters holding wafers Not all of the attributes need be specified in the class model. Wle show as much detai l as nceded, neither more nor less. Showing more deta il clutters a diagram and can make It h arde r to understand. Some required attributes may be left 10 the discretio n of the implementers. It is also commo n to o m it accessor hrnctions from class model (e .g ., gelSiu() and sctSize()) si nce these can be inferred from the pre ence of the corresponding attributes (,m). As an example of a class , co nsi de r an application tha t as ists the u er in drawing a Simple figure of a person using geo metric shapes. We'd probably want a Rectangle class for this with attributes such as 'm9th and h".dlh. Since the app licatio n is supposed to be smart, we'd want it to use the concept of a foot (e.g., to kno'" where feet bel o ng), so we'd probably want a Foot class. By int rodUC ing these c1asse , we arc improVing the cohesion of related parts, such as the attributes of a foot , the understandability of the dl" Ign , and ,ts mo dularity . W e are also hiding information until it's needed . Thi example will be explored a \~e go through this c hapter, and will be described as a whole in cetion 169

16.2 CLASS RELATIONSHIPS IN UMl This sectio n discusses the way In whIch UML collec t< cla«es and such rel.tionships call ed associations.

In

packages It .lso inllod" es

CLASS RELAnONSHIPS IN UMl

and

" ,

pllClulge of classes

-"

.. -

myPackage

mySubPackage

.

" '-

-

class MyFIrstClass ( ... )

'w,, _ •

1

MyClass

.I·

....,_ . .

_..

-•

package myPackage.mySubPackage; class MyClass ( ... )

subpackage / - hidden-

MyFlrslClass -'

./

Bcccess/blllty of classes from outside package -'---

IC visible »



public package myPackage; class MySecondClass ( .. . )

-,

MySecondClass

/

~

Figure 16.3 UMl notation for packages and Java implementation

16.2.1 packages The U nified Modeling La nguage uses the te rm Pllckng, for collecting desig n elements suc h as classes. UML packages can contain subpac ka ges , or an y material s associated with an applicatio n, Includ ing source code, designs, documentati o n , and so o n. Figure 16.3 shows the UML nota ti o n for packages a nd sub packages. Classes within a package can be speCified as access ible o r as inaccessi ble fro m code external to the package. "Package" also happens to be the nam e of collectio ns of Java classes. Java packages trans late into file directories; thei r subpac kages decompose into subd irectories, and so o n. The Java implementation of this is shown in Figure 16.3.

16.2.2 Associations Attri butes arc o ne way of sh owi ng the properties of a class, and arc ge nerall y used to de no te si mple types such as integers o r Boolean s. Msocia lioll is an additi o nal method of indi ca tin g clas properties, and is commonly used to denote that objects of two classes de pend on each other in a strucnlra l way . ASSOCIations are drawn with a solid line belween two classes. We ca n a nnota le th e relati o nsh ip, which may be o ne- o r two·way . Twoway associa tions are problematical because we nee d to be sure lhat bo th e nds of the implied info rmat io n are kept consistent. This is illus trated in Figu re 164 . Consider a n application that a Sl tS the use r In drawin g a Sim ple fig ure of a person . We ma y want a FooISb.", class if the sh ape of a foo t needs to be described (promoting the "sufflclc ncy" of the design ). There wouJd be an association between FoorShap, a nd FOOl , indicat ing coupl ing be tween the two Th is example i described as a whole in eClio n 16 9

363

364

CHAPTER 16 niE UNIFIED MODEUNG LANGUAGE

employs

~

Employer •

IS

employed by

,---il

Employee

class Employer ( Employee! J employees; •

• • • •

) class Employee ( Employer! J employers; •



• • •

)

Figure 16.4 UML notation for associations

/

16.3 MULTIPLICITY The ends of an association line can be annotated wirh "lI/hipliClty, which describes the numerical relationship. or the number of instances, of each class. For example , consi der the Employ"IEmploy" relationship as shown in

Employ" indicates that each insta nce (object) of an Employ« can be assoCiated w ith 1-3 Instances of an Employ". Conversely , the " I. .• " next to E"p/oy" mean that each instance of an Employer can be associated with a minimum of one Employtr (with no maximum ), In ocher words, the Fi gure 165. The "1..3" next to

I

multiplicity next to a class indicates how many instances of th;n class are associated with one instance of the class at the other end of the association line. A single value ca n be used to indicate an exact number of objects,

If a multiplicity is not present neXl to a class, the assumed value is I . This is also illustrated in Figure 16.5 , which shows that one Employee

IS

associated with exactly one PcnoPlalInfo instance , and vice versa.

16.4 INHERITANCE In UML, illbmlancc desCribes a relationship between classes in ..... hich o ne class assumes the attributes and operations 01 another It is often thought of as an "is·a" rdation ship. Forcxamplc, since an

Employ" "i.-;," Pm"" , we can express their relationship with inheritance by saying thal an Employee inherits from a Person . U"I,L

Employer

employs

1..3



~

is employed by

1..•

Employee

, Personallnfo Figure 16.5 Multiplicity of associations In UML •

INHERITANCE

... and

"'-

MyPack8ge package MyPackage: abstract I MyAbstractClass . . . . MyAbslraclClass ---I-~Inheritance

package MyPackage: class MyDerivedClass

MyAbstractClass

r l---. int atl; •

• • • •

void myFunctlon( ReferencedClass r ) (



00

)

}

MyDerivedClass an: Int

- - attrllwte

Lm2yF:..u:::n.::c:.:ti::o:.:n~()_....::.°cperatlon

""':::===:::'_-"'/

Figure 16.6 Inheritance in UML and Java implementation

indicates inheritance with an open rriangle. We refer to the class being Inherited from (e.g . PmoH ) as a basc class, the class dOing the inheriting (e.g .• Em ployu ) is a d"ivd class. Figure 16.6 shows an example of a package consistin g of two class. ; MyAhstractClass and MyOmv,dCla ss . with MyO,rivcdClass inheriting from MyAh,tractClass . Abstract classtS-that is, those classes that ca nnot be instantiated into objects are denoted with ital ic . [H !!ifacts are collections of method prototypes (name, parameter ty pes. retum types, and exceptions thrown ) Classes rraliu interfaces by implementing the methods that the interface promises. The UML notatio n IS shown 111 Figure 16.7 It is customary to arrange class models 0 that base classes are physicall y above derived cia se H oweverl this positioning is not necessary in any technical sense .

UML Notation ......

Interiace MyAbstractClass . ...

Interiace

,~ --- - -- - - - -------~, : Mylnterlace :, : myMethod()

.

i

'------7\..------' --------

rsallzsllon I

class MyClass imple,ents Mylnteriace

,,

(

-----------------.. • • • • •

)

I I MyClass myMethod()

Fllllr. 14.7 Interfaces In UML and Java Implementation

365

366

CHAPTER t 6

THE UNIFIED M ODELING LANGUAGE

onmaxNumChsrs/nNameO ) name = new Stnng ( aNarne.fJ6tBytesO, 0, maxNumCharslnNamoO ) : else II assign the pammeter name name = new Strlng(aName };

}

Figure 16.22 Activity diagram example

The pro blem is to build a program that, given the fo llow in g,

B, 0 , and • a ilst of fact s, such as -A, -

.

• a list of rules such as A..R=:-L, - AkB=:-C, - and B.. C=:- -R det > «task>.lnterglactic Web Site Analyzer «/task>. 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. 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 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 .. 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 art o ften reused At • dirrerent level , the tandard Templal c Library ( TL) prOVides m ,. · a nd · matc h ca pabili ty of ,t.ndard ,' lgo rithms suc h as >orllng and scarc h ing . STL IS applicable to a va"ety of data struc tures a nd to objech o f virtually any clac;s. In summary, a omponcnl marketplace ha~ emerged and IS g rowing co nlilluall y n,e Encounter video ga me case stud y prese nted at the end of this c hapter CO nlalll cxamples o f reuse with in an cnterpr.isc: in this case, a Ham," de .... elopment business T o he cO~ l - dfcctlvC'-and thus compelltlvethe company leverages its software as Illuch as possible among projec ts. For example, rathrr than invest the resources to develop a class for the c harac ter in Encoun ter alo ne, It Inc!> to scpaf"il tc the develo pme nt Into a ga me c ha", ter class, and usc a subclass for Encou nter's c ha",cter. The ga me cha",cter cia .. ca n be rcues WIth the methods referen ced i n the sc:qucncc d iagrams. As an exa mple, the sequence dli:lgram fo r the: "Encounter Foreign Character" IS ~ h own In Figure 19 . 18, hawing th e message between obje ts on the software design. The reaso non g beh ond the h",ctl ons chosen IS as follows . 1. Forro9110Itlrael" is to have a d,

(a local log of lransa lIons, a lISt of problem users, and a templale for lon proce" " con ·

tlnlled unt" the 10\ c-.t ·lcvel pro C"'~ '" 8 clements Jre rca hed 11,c IJuer Me tYPICall y Indi vidual (unction,»,

ro"ibl of d,fleren, cla"e For example . Ihe gr,D,pos, l() lun I,on ,s expanded ,n lO [hree lun lion' II(CltinK 'he p.,sword, venlyong i', and making a display ) Two 01 the: Th e valul"'S of th e characters'

qualitlcs are as reqUIred by SRS requirement 3.2.EN .3 Ii the player's character and the for·

TI,e deSIgn of the tllcoun l,rCharaclm package is shown in Figure 1936. It is implemented by the Facade desig n pattern , with EllcounltrCn" as the fa · cade object .

cign character arc in random but different areas.

6.1.4. ll. The Engaging, Waiting, preparing, and Reporting Classes The '7:z." numbering is used to collect classes that arc not specified individually.

6.1 .5. EC The EncounterCharacter Class This class encapsulates the requirements for El1coul1ttr

charac ters that arc not covered by R.PGam,Characlm . It satisfies requirements SRS 3.2.EC. Class invariant, The va lues of qlla/lla/ur/ arc nonnegative (see lfattnbulcS" below (or the deAni ·

tions of qua/lla/",n . Inheritance

Inheritance

The e classcs inherit from Gam,Slal, in the framework package.

This class mherits from GameCharacter in the framework package.

Characters . Iramework package"

GameCharacter

EncounterCharacters ..application package-

EncounterCharacter

.·facade-

PlayerCharacter

EncounterCast ForeignCharacter FIpIre 19.36 Detailed design of Encountercharacters package

CASE STUDY: DETAILED DESIGN OF ENCOUNTER

Attnbutc of

EI1C'Olmltr

These att~.f

requ irement

Set Ihe stated q uality to the destred amount

baraclcr

32ECI

private static final String[ J qualityTypeS

IF the caller adjusts the on ly nonzero qual · ity value , divide the adjustment amount

equally among all other qualtttes

This represem the qualities that EnCouHlu char-

EL E change the remalOlng qualttic., re o

acters pas ess. These arc conCe ntrati o n, sta·

tainlng their murual proportiOn,

mlna , Inlclhgcnce, patience, and strength .

private float [J qualvalueI 11u IS an array qualtttcs.

COnt3 1nlflg

the valuec; of the

Constructors of EnC"ounlrrCI){zracrrr

These satisfy reqUIrement' 3.2 EC3 of the SRS Null constructor Po tconditton The qualit lc arc all equa l fracttons of 100

Sct each quality whose va lue is now less than 0.5 to zero.

public float qetQualityVillue ( Str ing qualityP ) Preco nditions qua lt tyP IS a val,d q"altty string Returns the va lue of qua lt tyP

pub 1 ic f loa t qetToleranc e ( ) Return , thc value below whIch quality values cannOl go

protected EncounterCharacter ( St ring nameP )

protected int maxNumCharsInName ()

Pos tcond l Lions ·

Rerurns: t'he max imum number of charJcter In

( I) the qualities arc all equa l fnct ions of 100.

th e names

(2) the character's name

public float sumOfQualities ()

IS

ameP

Methods of EncolI" I"Charact"

public synchronized void adjustQuali ty

( String qualityP , float qualityValueP ) TIll method ,.ttsfle< requirement 3.2 E .3 2 Invananls none

Precond,tIons, qualltyP I< In qualttyT ypc =0 AND quahtyV. lueP < = the sum of the quality values Pcxlcondl t lon\

quahtyP has the value qualtty Value P AND the remaining quality values arc tn the qmc proportion 3\ prt()r to Invocallon , exc.ep t th at va lue:, I c,,~

than 0.5 arc zero The followIng" the p

·:J)I • .45 1 I,

c ~

--

» z 0







;:

~

'"n-

VI

' 500 «OJ Jt 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 ue 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 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 = 0 *(2)width > =O

*

* Postcondi t ions:

* (1 ) area == length * width

*1 public void setAr ea ( ) / ************************************** / {

area = length * width; } }

Note I , The first question is whether the preconditions are complete. In view of the stated desire not to restrict the values of 1'''9th and Ividth , the preconditions appear to be adequate. (One is not always com:ct in onc's intentions. bur the point is thal the y are documented and so ca n be revisited . Undocumented intentions,

o n the other hand, lead to confusion and greater errors.) Note 2, Next, we assess whether the method allows a reaso nable recovery if the precondition fails . Since there I no provision for this in the code, the method's robustness is compromised. A check on 1"'9th and width that leaves a'ta unchanged, and that generates reasonable notices, would elevate the method's robustness. listing 23 .2 is a more robust version of RtctaH9l,. It restricts the values of fields to what is intended, a practice that usually makes computing more robust. The objectIon In Note 2 above is also addressed. Nevenheless, listing 2 is still subject to critICisms, which arc discussed below

Ustlng 23.2: A more robust Rectangle class

---------------------- -------------------1* *--------------------------------------------

* Rectangle

*

class, including safeguards for limits on area

* Known Issues: * (1) Limits dimensions to floats, not double.

QUAUTY OF IMPlEMENTATION

• (2) See known issue (s) for indiv idual method (s) •

*1 public cla . .

MoreRobustRectangle

{

----- -- ----- --------------------------------------------II VARIABLES --------------

I I Class invar iant (i ntent: the corresponding area is limited) : I 1 0 When constants arc named rather than being stated explicitly, the code becomes morc eisily targeted to new u~s . There arc several places in the MorrRobu"Rcc"'"9k code where constants would have improved its flexibility- for example , naming Floar MAX_VALUE as J\W...ALLOWABLE...AREA. As another example, instead of the statements

pr ivate float length = 0; pr ivate float width = 0; we could state the (ollowing,

private static final float DEFAULT_LE NGTH = 0 ; private static final float DEFAULT _WIDTH = 0 ; private float length = DEFAULT _LENGTH; pr ivate float width = DEFAULT _W IDTH;

3. Hid, Wlmt Possiblr. In software engineering, o ur ma in adversary is compleXIty. O nc useful tech nique (or combating complexity is to hide from view the parts that are no t relevant at the time. "Hiding" applies ro code that is not available to other code that should not need it. Class membe rs that are not to be accessed by methods of other classes are thus made l>rioart (or prorrcr,d if inhentance is required ). Cia ses that are not to be accessed by methods of classes outside their package are not made p"hltc.

Cod,. When common code is collected into a meth od, the result is grea ter flexibility ; otherwise the common code would have to be changed in multiple places. Robu,rRtcrml91, doe a good job

4. Collter Commo"

of this by collecting the checking o( the invariant in one place, classlnvaria nrHold50. In this respect, then, the code is flexible. S. R,d." D,p",d",cy 0" Clohal Variahh This means that each method and each class sho uld be self·contained so that they can be mixed and matched . Perusing the methods o( Roh.,rR,c"'ngl" we sec that the o nly method referrin g to an attribute of the class is "fAr,aO, which refers to arta . In pnnciple, we can eliminato arm as a variable, elImInating "tArtoO and introdUCing 9,rArraO that returns the area . This is an improve ment in Rexibility , but it could coll ide with another quality, efAciency . lf the applicatio n requires very (reque nt use ot arta , II may be preferable to compute it once and refer to II often .

6. Program C""rically Here we ask whether the code is at a suffiCiently abstract level to be usable for additional or changed reqUIrements. It is possible to approach thi S at the de Ign level by u ing abstract classes, but our focus here IS o n impl,,",n rafion flex ibility Flexibility depends o n the directron that an application is taking. For example, if this class is to be part o( a 3D appli alion, we ma y want armO to compute the area on the mo nitor o( a rectan gle m space , een at an an!;le-that is, taking perspective into account. Thi s is a rar more generi c computJlI on.

7. U" U"d",,,,"dahl, Varlahl, and Funcrio" Nom" In d,scu sing Rexlbilrty , we indl atcd that vanables and methods must be understandable (or the code to be Aexlble. In f. t, the very name 01 a va nab le or method is an Imporlant way of makIng it underarnpk.. 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

Figure 24.7 Big refactorings"-Extract Hierarchy Soutce Fowter el ai , Refactorlng' (mOfcMng the Design 01 EX'tSMg COde. COpyright , 19991Jy Pearson Educ.auon. Inc. ReoroduGeClIJy pelTT\fSSlOl"l of Pearson Education. Inc.

simphcity (ConsIder how comphcated it would be to change just the CUI parts or to allow several displays for the same account data .) Figure 24 .6 shows how the o ri gina l des ign can be decomposed into the core part of

A CCOIUlt ,

se parated from classes describing varioLis ways to display the account.

Our Rnal example of a "big" refactoring, Exlmel Hicrarc/,y , applie, when il has become clear that a new or extended hierarch y of classes IS nceded-in particular, when the classes in the existing hiera rchy are not refined enough for the task at hand. For example, as shown in Figure 24.7, a designer may use a class such as PrO)tcl to implement a project management application . We'll presume that the application has become too soph isti cated fo r a generic project. So, for example, quite different functionality IS needed by software engineering proj ects vs . entertainme nt projects. As shown in Figure 24 .7 , cXl.Tacting a hierarchy of classes

fro m the original beco mes a needed rdac torin g

24,2 COMPOSING METHODS The "composing methods" category of rcfactorin gs concerns the process of creating , removing , and combinm8 methods to SUIt an evolving Clpplication . The various rypcs of mcrhod composition examined

by Fowler are shown in Figure 24 .B. They are e.plalOed bel ow. • Extract method • Inllne method

• • • •

Inline temp (re move a temporary vanable ) Replace temp with query (i,e , a function ) Introduce cxplainlOS variable (to replace complicated expressIon) Split temporary vanable (I.e., used more than once)

• Remove assignment to paramel'ers

• Replace method ","h method object Figurl! 24.8 " Compose methods" refactorings Sourw Fowter et at . Rotoctot .!IO Improol!l"l8 the OF r,gn 01 RepOCluc:td I7f ~6ttmssron Of Pearson Educltion.. InC.

ExlStlna ~. COgyr'igtlt

I

1999 by Pearson Eclucation. InC..

COMPOSING METHOOS

Exrracr M,rboJ refers to the process of identifying a block of code and creating a method that serves its purpose . The block of code can then be replaced with a call to that method. One perfo rms such a ,eplacement when the beneRt of redUCing clutter outweighs the penalty of having to look elsewhere for code details. This depends on the sense of purpose of the code extracted, its relative complexity, Its "ze, and how fr"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 unlldatlo 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 proctcen in hapter 211, on unIt testlllg , 00 t SIO c they often overlap a nd a lso leave va n ou' ki nds of gaps An examp le of p. t research is dc, nhed by Rapp' and E J. W "yuke r [ I J. '" which paths are selec ted on Ih ba40

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=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



; •





There is no additio nal begi nning o r e nding text.

2.2.1.5 Build 1 Test Item Transmittal 2.2.1.4 Build 1 Test Procedures

Report

... . ..

2.2.1.4.1 Test Procedure Specification

2.2.1.6.3 Activity and Event Entries

Identifier

The ' defect rderence" is the number used by the defect tracking system for Ihis defect

This identines the class/method from wh ich Ihe test is executed.

2.2.1.7 Build 1 Test Incident Report Inregration_ Tests/Build I_T est in package T ests

2.2.1.7.1 Test Incident Report Identifier

2.2.1.4.2 Purpose T o sct up a tesl of build I wilh

Bu ild U cst3

a minimum o f o ther parts of the appl icati o n

2.2.1.7.2 Summary see Figure 28.22 .

2.2.1.4.3 Special Requirements The test hal"

2.2.1.7.3 Incident Description Ed Blake wa d is-

ness in Integrati on TestslBuildl _T esl, m nsisting of a class with a si ngle method, mainO, is to be co n· structed . and tests 1, 2, 3, . . arc to be executed and the results compared.

tracted during the execulion of tesl 3 by an alann in the building, and could no t record the re ui ts It was decided no t to inte rrupl or repeat the test seq uence, and to conducl test 3 as part of Ihe tesling for bui ld 2.

Defect reference

Result

Test

*

Build I Te

t

Log

I

Passed

N/A

2

Fa il ed

1823

3

Dala 10,1 - T o be repca led

N/A

Lost 01prec Isio n in re lu rned value

2872

s

• ••

••

Figure 28.22 Build 1 lest log (summary)





••

719

720

CHAPTER 28 TESTING AT THE SYSTEM LEVEl

repe t, tlon of lh b lest.

d "played th roug h the Enco"n ltrEnviro",mml object, an d Ih ,1' the o nncctlon< among them arc con ,sLent wi th the SR .

2.2.1.8 Build 1 Test Summary Report

2.2.2.2 Build 2 Test Design T hese teSts first will

2.2.1.7.4 Impact It \ ,s d~c ldcd th, t the Irl IdcnL(s) repo n ed above were n Ot serl ou enough to rcqum.: a

ve rify th at the correc t Etlfo lHllrrEnvironmCJ1 t object ca n

2.2.1.8.1 Test Summary Report

be obtai ned, and the n wdl show that the Arca o bJeclS

Identifier

and Art'(/ COPlllrclioll objec t ca n be re tn eved as req uired.

... I t~Sl passed wi th

2.2.2.3 Build 2 Test Case The func tio nality to

the exceptIon of the defec ts noted . TI, i wi ll be h,ndled by the regula r defect repair process.

be tested is co ntai ned in the fo ll owi ng publ ic fun c·

2.2.1.8.2 summary TI,e bud d

2.2.1.8.3 variances

tio ns of

GnmcArm 9c1TI"DrmillgRoomO

co build I teq incident re port.

2.2.1.8.4 Comprehensive Assessment

Ellcolm f(rEIIVffOtHlltn l .

GnmcArm gCIThcO""9tO" O •

• • •







Enco ll PlltrEnvi rOl' ,"ril l 9(1 ThrEt'ICO UH IrrEllvi r(l",molr()

Add itional remarks supplyi ng details c an be placed here.

2.2.2.4 Build 2 Test Procedures: To be 2.2.1.8.5 Summary of Results

supplied •













2.2.2 Build 2 STD

2.3 System Test STD This (annat is similar La the fo rmat in Lhe build I S I D.

2.3. 1 System Test Plan Th ese lc t5 arc pcrfo m1 cd agai nst lhe arc hitec ture, as

2.2.2.1 Build 2 Test Plan These tests will ve rify

described in Figure 28.23 . TI,e tests verify that the effects of game actio ns

that th e areas of the game can be re trieved and

in

Eu oUl1ttrCa mr

corrt"ctl y manifes t them selves as

EncounterGame

EncounterGame EncounlerCharacters

-'.c.de·

EncounterCast -'8PcM _

EncounterEnvironmenl

EncounterEnvlroniicent ott.c •••

Figure 28.23 ArChitecture and modularization for Encounter video game

CASE STUDY: ENCOUNTER SOFTWARE TEST DOCUMENTATION

nlO~nl~nts of EH

O".t"

chara ters

wllhin

the The integralion leslS verify that the require· ments of Encounter, as stated in the SRS, have been satisAed.

~nvlron",ent .

2.3.2 System Test Design ~ syslem lests are designed to verify the

The acceptance te IS arc slored in the Accept· package, and include the usc cases. The Initialize usc case IS sh own In Figure 28 .24 and is executed by the mai"O method of the class Initia lize in the Acctpt."erTts' package.

architecrure by executi"g and verifying se. quences of "'Ierface methods

."crT",

2.3.3 System Test Cases Syst~m T est I

The E"rounltr Fortig., CJJarn

use case is shown in Figure 28 .25 and is executed by the ",.i"O metho d o f the class Acctpta"ctTts t l"itia/izt .

I. Move player character into dllngeon .

Itr

2. Move foreign character into courtyard. 3. Move foreign character into dungeon .

2.4.2 Acceptance Test Design

4. Execute an encOllnter in the dungeon .

The use cases indicated in Section 2 4. 1 are to be executed in sequence severa l times, in accordance wilh the lest case in Section 2.4 .3.

System Test 2 •





2.4.3 Acceptance Test Cases

2.3.4 System Test Procedures

2.4.3.1 Test Cases for Initialize Use Case

• • • •

2.4 Acceptance Test STD

The lests are instances of the Initialize use

case, also known as "sct"narios."

2.4.1 Acceptance Test Plan

:Encounter· Game

main player character: Pia er Character

User

1a· .

:Player quality window .. create"

dress ing room:

Area

I

1 b. -create .. ~

2. -create-

'y

I la . onter quality valuo

Jb. • etOuolityO 4. select exit tor character

,

5. moveO

• Numberlng key ed to uH case

Fleur. 28.2.4

Sequence diagram for Initialize use case In Encounter

.,.,

721

722

CHAPTER 28 TESn NG ATTHE SYSTEM LEVEL

:Encounter arne

:Encounter Cast

freddie: Foreign Character

1. 1 displayForolgnCharO

:Player's main character

1.2 d,splayO

~

engagement: En a ement

1.3 .. create ..

2 execuleO

I

2. 1 S.IP~ye.aua ll1yO

I

2.3 selForolgnOualityO

2.2 seIQua/l1yO

2.4 selQuall1yO I

:Engagement Di~a

3. 1 .. create ..

r 3.2 dispiayAesul10

Figure 28.25 Sequence diagram for Encounter Foreign Character use case in Encounter

2.4.3.1.1 Initialize Acceptance Test 1 1. S1~n up game

2. Supply main characte r wi1h 1he fo ll owi ng qual. ity values ,

In

2.4.3.1.4 Initialize Acceptance Test 4 . .. 2.4.3.2 Test Cases for Encounter Foreign Character Use Case

the order show n:

Strength , 30, then Conce ntratio n, 20. 3. Move the main character to the counya rei

2.4.3.1.2 Initialize Acceptance Test 2

2.4.3.2.1 Encounter Foreign Character Acceptance Test 1 I. Set the main chara cter's "patience" va lue to 30.

2. Set the foreig n c haracter's "patience" value to 20. 1. Start up game.

3. Move the main c haracter to the draWing room. 2. Supply main character with the foll owing qual· ity values.

10

the order shown:

Strength , 30, Concentrati on, 20, and Patience, 30. 3. Move the main c haracter to the courtyard.

2.4.3.1.3 Initialize Acceptance Test 3

4. Cause the fo reign characte r to enter the drawi ng room.

5. Ve rify that an e ngageme nt has taken place 6. Observe the e ngageme nt window showing the results .

1. Start up game.

(The players patience value should be 40. and the foreign c haracter's 10.)

2. Supply main character with the following qual · ity values, in the order shown, Strength, 30 and Concentration, 20

2.4.3.2,2 Encounter Foreign Character Acceptance Test 2

3. Move the main character to the dungeon .

I. Set the main character's ' stren arc req,"rcd O n c th c>c modificati o ns arc matie, it al'pe . .... that

7.3

744

CHAPTER 29 SOFlWARE MAINTENANCE Table 29 • 3 IEEE 1219 • 1998- Maintenance phase 2'• problem analysis a. Input

b. Process

• Original project documentation • validated MR from the Identiflcation phase • Study feas ibility of Ihe MR • Investigate Impact of the MR • Perform detailed analysis of the work required • Refine the MR descripllon

• Conduct technical review • Verify ... c. Control

d. Output

. .. test strategy appropriate . .. documentation updated • Identify safety and security issues

• Feasibility report • Detailed analysis report. including impact • Updated requirements • Preliminary modification list • Implementation plan • Test strategy

e. Selected quaJlty factors

• Comprehensibility of the analysis

f . Selected metrlcs

• Number of requirem£:flts that must be changed • Effort (required to analyze the MR) • Elapsed time

SOurce IEEE std 1219-1998 Reproduced with perrrusslon

we will need o nl y to replace all Area and Are.Connectl o n references in th e client code (the code usi ng the new configuration ) such as

· . . = new Ar ea ( ) ; a nd · •• = new Co nne ct io n ( ) ;

with calls of the form · . . = Le velNBuilder . getArea () ; and · . • = LevelNBuilder . getConnect ion ( ) ;

and so on IEEE metrics that quantify these modiRcations arc as fo ll ows .

• Number 01 requirements changes for MR ~ 162: between 140 and 450 as fo llows. Since we have organized the require menrs

by

class, we

COU nt

• The number of new classes that must be described: 60 to 90 (there are 20 to 30 levels let' d1 S .lY. an or ' f each of thes., Abstract Factory requires a .. ctory class . a ;ubcla s of Are. 'nd a bel f A • u u ass 0 rea. Connection) plus

• The number of new methods: (2 to 5) per cia s • (60 to 90) classes ", 120 to 450

IEEE MAINTENANCE STANDARDS

• Estlmat~ of effort for MR # 162: 2.4 to 9 person -month as follows : The effort ca n be estimated in tc nllS of the number of person -days per require me nt , based o n these data for the project 0 r..r, For example, If the original project has 300 detailed reqUirements and was completed with 0 person -months, we ca n USe 0 ,02 person -months per requirement, so that MR # 162 should be taken care of \~ith ( 120 • 0 .02 ) to (450 • 0 ,02 ) = 2.4 to 9 person -months. The highly repetitive narure of the classes uggests a lower number in this range , perhaps three person-months . • Elapsed time os!'imate for MR # 162 The elapsed time estimate can be computed from historical data in a si milar manner to the Effort compulation . To improve on these mNric , apply the following . a. Use linear regression, in which a set of past data is used to derive a straight-line approximation , and th is straight line is used to approximate the result. For example, instead of usi ng simply "300 detailed requirements were completed with 6 person -mo nth s = 0 .02 person -mo nths per requirement ," we ca n use a graph of several different past projects and fit a traight -Iine relation ship to these, as shown in Figure 29 . 14_ This gives a more reliable resuIt : • range of 2 .5 to 9 .3 person · mo nths. It should be noted that regression methods are also available that fit curved lines. b. Account for factors such as the nature of the application and the composition of staffing For example , if the data are available, one can create graphs that use o nl y projects of the sa me rype , or projects whose staff had equivalent experience levels. c . Include variances with the measures described . (It is useful to know averages , but we are also interested in the extent to which measurements have differed from the averages in the past.)

9

300 detailed requirements compleled w~h 6 person-mon1hs

-o

-

.8



g3









z

200

300

400

Number of detailed requl