100% found this document useful (1 vote)
3K views775 pages

Software Engineering Modern Approaches

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
3K views775 pages

Software Engineering Modern Approaches

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 775

Brief Contents

Prefa C X IV
••
Acknowledgmen ls XVII

Part I Introduction to Software I TI, e Coa ls and T e rm ino logy o f Software Eng ineering I
Engineering 2 Inlroduclio n lO Q uality and Metrics in Software
Engi nee ring 21
Part II Software Process 3 So ftware Process 32
4 Ag il e Software Processes 63
5 Q ualilY in the So ftwa re Process 80
6 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 Princ iples of So ftware Desig n 350
16 The Uni fie d Model ing Language 36 1
17 Softwa re Desig n Patterns 383
18 Softwa re Arch itecture 438
19 Detai led Design 476
20 Design Q uality a nd Metrics 508
21 Adva nced and Eme rgi ng Me tho ds in Software Design
(O nline c ha pler) 538
PaTt VI Implementation 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
~--~-----------------
Part VII Testing and 25 Inlroduc tl o n lO oftware T esting 62 1
Maintenance 26 Unit T e ting 630
27 Mo dule and Integratio n T esting 666
28 T e<llOg a t the y< te m Le vel 694
29 Software Mai nte na nce 730
C lossary 759
Index 767
Contents

Preface . ... . . . . .. .. . . - .. .. ... .. . - . ........ ... .. .. . . .... .... . . • • • • . . . . . •


XIV

The Issue of Scale . . • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • XIV

This Edition Compared with the First . .. . . .• . . .. ... . . . . . . . . . . . . . . . . . . . XIV

How Instructors Can Use This Book . . . . . . . . . . . .• . . . . . . . . . . . . . . . . .. ' " . xv

..
Acknowledgments . ... _ . _ .. . • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • XVlI

PART I Introduction to Software Engineering

I The Coals and Terminology of Software Engineering . . ... _ _ . . . . . .. .. . . .. . . _ .. I


1. 1 What is Software Engineering ... .. . . . . . . . . . . _ . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Why Software Engineering Is Critical, So ftware Disaster ..... . . . ... ....•. . .. 3
1.3 Why Software Fails or Succeeds .. . . .. .. . . . . . . . . . .. . . . . . . . . . _ . .. . ..•... 4
1.4 Software Engineering Activities . . . . . . . . . . . . . .. .. . . . .... • • • • • • • • • • • 5
1.5 Software Engineering Principles . . .. ... .. . . . . . . . . . . .' - . • • • • • • • • • • • 10
1.6 Ethics In Software Engineering . ... . . . . . . . . .. ... . .. . • • • • • • • • • • • • • • • 12
1.7 Case Studies ..... . ..... . ... . . . . . . . . . . .. . • • • • • • • • • • • • 14
1.8 Sun'lmary . ... . . . .. ... . . . . . . . - . . . . . . . . . . . . . . . . . . . .. . ..... . • • ••• 19
1.9 Exercises . . . . . . . . . . . . . ......... . . . . . . . . . . . . . . .. . ..... ,. • • 19
Bibliography . . ... . . . . . . . . . . .. ,.. .. .... . . . . . . . . . . . . . . . . . • • •• • 20

2 Introduction to Quality and Metrics in Software Engineering . . . . . .. .. .. • . . .. - 21


2. 1 The Meaning of Software Quality . .. . . . . . . . . . . .. . . . . . . . . . .•. • • • • 12
2.2 Defec ts in Softwa re . . . .... . .. . ... .. . . . . . . . . .. .. • • • • • 23
2.3 Ve n~call o n and Validati o n . . . .. . ......... . . . . . .. ....... . • • 25
24 Planning for Qua lity . . . . . . . . . . . •. .. ..... . . . . . . ...... . 27
25 Metrics .... , ................ . . . . . . . . . . . . . . • • • • 28
26 lImm ary ., • •• • ., ...... .. • •• ••••• •• ••• •••••• •• • • 30
27 Exercises . . • • • • • • • • • • •• •••• • • . . .. , • • •
, 1

Bibl iogra phy . • • •• •• • •• • • • • • • • • •• •• • • •1

PART II Software Process


• • • • • • 32
3 So!twar~ Process
3. I n,e
• • •

Ac tl vltl c' o f o(twar I'rocc~, •



• • •

• • • • • • • • • • • •
, ,
,;-
32
33
o(twarc: Pro css Models
a,>~

tud y S tud nt Team CUldanLc •


• •

• •

• •



• • •
,-
CONTENTS

.4 llfll lll o1f)f ....... . ..•........ . ., . • • •• • ••• ••• •••••••••• • •••• 59


E~Crc I 5c.:S •.. , •. . •• .., . • • • • • • • • • • • • • • • • • • • • • • •• •• •••••••• 60
BIbliography . . ............. . ' . ......... .... ,'. , . ........ .. . 62

4 Agile Software Processes . . . . . . . . . . . . . . . • . . . . . .. ..•. .. .. ... .. . ., 63


4. 1 Agil e H i>tory and Agi le Manifesto , . . . • . . . . . • . . . , . . . . . . . . . . . . . . . . . .•. . 64
4.2 Agile Princi ples .... , . . . . . . . . . . . . . . " . . . . . . .. . .. , . . . . . . . . . . . . . . . 65
4.3 Agi le j\~clh o ds . . . . . .. .... .. . .......... . . .. . ......... ........... . 66
4 .4 Agi le Proces c:s .. , . .. . . . . . . . . . . . . . . ,.. . . . . . . . . . . . . . . . . . . . . . . . 68
4.5 Integrating Ag ile with No n.Agil e Proce es ., . . . . . . . . . . . . . . . . . . . . . . . . . . . . ,' 74
4.6 umnlary . . . . . . .. . . . . . . . . . . . . . ............................... . n
4 .7 Exerci ses . . . . . . . . . . . . . . . . . .. . ........ . ...... . ................. . 78
Bibliograph y ..... .. . . . . . . . . . . . .... . . . . . . . . . . , . . . . . . . . . . . . . . . . . . . 79

5 Quality in th.e Software Process ..... . . . . . . . . . . . . . . , .. , . .... , . .. . . . . . . . . . . . . 80


5. 1 Principles o f Managing Quelity ... . .. , .. , ..•.... .. . . . . . . • . . • . . . . . . • . . • . . 81
5 ,2 Managin g Qua lity in Agile Processes .. . ..•. . . , . , , .. , ... , .. , .•.. , . . . . .. .. 82
5.3 Quality Planning . . . . . . . . . .. .. . . . . • . . . . . . . . .•.. . . .. . . . • . . . . . . . . .. . . . 83
54 Inspecti o ns .... .. . • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 87
5.5 QA Reviews and Audits . . . . . . . . . . . . . . . .. . . . . . ... . . . . . . .. . ... . . . . . . . . . 92
5.6 Defect j\1\anagenlent . . . . . .. ., .. . .... ... . . . . . •... , ...•.•. .. . . . . . . . . . . 93
5.7 Process Improvement and Process Metrics . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . 96
5.8 O rga nizati o n. Level Q uality and the CMMI . . . . . . . . . . . . . . . . . . . , . . . • . . . . . . . 100
5.9 ease S tudy, Software Quality Assurance Plan for Encounter .. . . , .. . . • . ... . ..... 103
5. I 0 Summary . . . . . . , . . . . . . . . . . . . ... . . . . . . . . . . . . . .. . . . . . .......... . . . . 1 18
5. I I Exercises . . . . . . . . . . . . . . . . . . . . . .. .. . . ... . . . . . . .. . . . . . . . . ' ... . . . . . . I 18
Bibliograph y . . . . . . . ... , . . . . . . .. . . . . . , . .. ... . . . . . . . . . ... ... . .. . ' .. 11 9

6 Software Configuration Management . . . . . . . . . . . . . . . . . . .• .... . , ... .... ,...... 120


6, I Software Co nfiguration Management Goa ls . . . . . . . , ... . ...• . . . ,... . .. ... .. 121
6.2 SCM Activi ti es .. . . . . . . . . . . . . .. . ...... . . . .... . .. .. . . . . . . . ,.. . .... 121
6. 3 Co nfigu ra tio n Managemen t Pla ns ....• .... ... .. . . . . . . . . . . • . • . . . . . . . . . . . 128
6.4 Configura tion Management Systems ..... . .. . . . . , .... . •. , . ...•... . . . •. , . . 128
6.5 Case S tud y, Encounter Video Game ... , . . ... " .. . . ,. . . .. .. . .... ... .... 129
6 .6 Case Study : Eclipse . . . . . . .. . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . ... . ... 134
6.7 Stude nt Team Guidance , Configu ration Management ...... .. , .... . . . . . . . . , . . . 136
6 .8 S ummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ... . . . . . . . . . . .. ... . , 137
6.9 Exercises ...... . . . .. ........ . .. ....... . . . . .,.......... . .... . ... 138
Bibliography .. . • • • • • • • • • • • • • •• • • • • • • • • • • • • •• • • • •• •••••• ••••• 139

PART III Project Management


7 Principles of Software Project Management I, Organization. Tools. and Risk Man.g~ment , . 140
7. l oft-ware Project Orga nozatio n , . .. .. , . . , . . . . . . . , . . . . . . . . . . . . . . . . . ... 141
7 .2 Team S ize . ... . . . . .. ...... . . . . . . . . . . .. . . . . . . . . . . .. .... . . . . . . . . 14-4
7.3 Geographically Distributed Development ... , . . • . . . . . . . . . . . . , .. , . . . . . . . . . , 146
7.4 The Team Software Process . ,., ...... , " . . . . . .....• ',. ., .. , ...... I I
7.5 o ftware Project Too ls and T ec hn ique, ., ... . •.•. , .,.,.. . . . . . . . . . . . . . . . . 153
CONTENTS vi

7 .6 Risk Management . . . . ... . . . ... ... . . . . . . . . . . . . . .... . . . . . . .. . .. ... . 159


7 .7 Student Team Cuidance, Organizing the Software Project's Management . . . . . . . _ . . . 162
7.8 Summary . . . . . . . . . . . . . .. ..... . . . . . . . . . . . . .... . .... . . . . . ... . .... 165
7.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Bibliography . . . ,. . .. . . . . . . ............... _. . . . . . . . . . . . . . . . . . . . . . 167

8 Principles of Software Project Management It Estimation, Scheduling, and Planning . . . . . . 168


8. 1 Cost Estimation . .. . . . .... , . . . . . . . . . . . ,... . ... . . . . . . . . . . .. ... . ... . 169
8 .2 Scheduling .. .... . .. . .. . .. . , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 182
S. 3 The Software Project Management Plan . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . . . . 185
8.4 Case Study, Encounter Project Management Plan . . . . . . . . . _ .. _ .. . . . . . . . . . . . 187
8.5 Case Study, Project Management in Eclipse .. ... . . ... _ .... _ . . . . . . . . . . . . . . 196
8 .6 Case Study, Project Management [or OpcnO[-fice . .. .. .. _ .. . . . . . . . _ . . .. _ . . . . 205
8.7 Case Study, Student Team Cuidance .. . . . . . . . .. .... . .. . _ . . . . . . . . . _ . . . 208
8.8 Summar)' . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . ..... . .... ..... . . . . . . . . 210
8.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . .. . 21 1
Bibliogr.Jphy . . . . . . . . . . . . . . _ .... ... . . .. _ . . . . . . . . . . . . . . . . . . . . . . . . . . 2 J2

9 Quality and Metrics in Project Management .. .. _ . . . . . . . . . _ . _ . • . . . . . . . . . . . . .. 213


9.1 Cultivating and Planning Internal Quality .. . . . _ ... . _ .. _ . _ . . . . . . . . . _ . _ . . . . 214
9 .2 Project Metrics . . . . . . . . . . . . . . . . . . . . . . . . _ . . . . . . . . .... ... . .... _ . . . . . 215
9.3 Using Metrics for Improvement . . . . . . . . . . . . . .. . . . . . . . . . . . . _ . . . . . . . . . .. 219
9.4 Software Verification and Validation Plan . . . . . . . .. . . . . . . . . _ . . . . . . . . . . . . . . 223
9.5 Case Study , Software Verification and Validatio n Plan for Encounter . . . . . . . . . . . . . 225
9.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 228
9.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Bibliography . ... . . . .. . . . . . . . . . . . . . . . . . . . . . . . .... . . . . . . . ... ... . .. 229

PART IV Requirement Analysis

10 Principles of Requirements Analysis . . . . . . . . . . . . . . . . . . . . . . - ... - . . . . . . . . . . . . . 230


10. 1 The Value of Requirements Analysis . . .. . . . . . . . . . . . . . . . . . . . . - . . .. . 231
10.2 Sources of Requirements . . - . . . . . .. . . . . . . . . .. . . . . . . . . . . . . . . . . - ... . 231
10.3 High-/tvtl vs. Dctai/,J Requirements .... .. . ... - . . . . . . . . . . . . - - . . . . . . . . . . . 232
10.4 Types of Requirements . . .. . ....... . . . . . . . • . . . . . . . . . . . . . . . . . . . . . . . . . 233
10.5 Nonfunctional Requirements . . . . . . .. . .. . ... - .. - . . . . . . . . . . . . ..... . .. 233
Documenting Requirement s . . . . . . . . . . . . . . .. . . . .. ....•... , . . . . . . . . . . . 238
10.6
10.7 Traceabi lity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Agile Methods and Requirem e nts ... .... . . . . . . . . . . . . . . .. . . . . . . .... . 239
10.8
Updating the Project to ReAec t Reqll1rements AnalYSIS . - ... - . . . . . . . . - . . . . . . . 241
10 .9
Summary . . . . . . . . . . . .... .. .. . . . . . . . . . . . , . . . . . . . . . . . . . . . . . 243
10. 10
244
10. I I Ex•.... rei'ses . . . . . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . . .. . . . . . .•.. .
., ... • 244
Blbll'oorapl,y . . . .. .... . .....
.. . • • • • • • • • • • • • • • • • • • • • • •

I I Analyzing High -Level Requirements . .... . .. .. .. . . . . . . . .. . • • • • • • • 245


II I Examples of Cu'tomer Wants . , .. . . . . . .. . .. - . - . - .. • • 246
I 1.2 Sta ke ho lder V"l on . . . . . ., . . . . ... . • • , . . . ., ., . 247
I I 3 The Interview and Documentation Pro e s . . . . . .• ..•.•. .. • • • • 24
1\ CONTENTS

I 1.4 \'(/nl ing an ve"'iew .... . . . . . . . . . . . . . . . . . . . • . . . . . . . . . . .... . . .. .. 249


I 1.5 Des ribing Main Funclion and U e Ca.es ...... •. ...... .. ... •. . . . . . . . . 249
II. Agile Methods for Hi gh · Level Req uirement s . . . . . . . . . . . . . . . . . . . • . . . . . . . . . .. 252
11.7 pecifying User Inlerfaces: Hi gh Level . . . . . . . . . • . . . . . . . . . . . . . . . .. .. ..... 254
I I .S e urily Requireme nts .. . . . . .. . .. .... . .. . . . . . . . . . . . . . . . . . . . . .. . . . . 258
I 1.9 Using Diagrams for Hi gh · Level Requiremenl ..... . .. .. .... ... .. ... . ....• 260
11.1 0 ase Study: High-Level Software Requiremen ts Specihcatlon
( RS) for the Encounter Video Came . .... . . . . . . . . . . . . . . _ ..... . .... . . _ . . 264
11 . 1 I Case Study: High -Level Requirements fo r Eclipse .. . .... • . . . . . . . . . .... .. ... _ 268
11.12 Eclipse Platfonn Subproject (First of three) _ . . ... . . .. . ... . . . . . . . . . . . _ ... _ .. 269
I 1. 13 ease Study: Hi gh -Level Requirements for OpenOfAce . . . . . . . . . . . . . . . . . . . . . . .. 273
11 . 14 Sunlmary . . . . . . . . . . . . .. . . . . . . . . . . . ,.. .. . . . . . . . . . . . . . . . . . . . . . . . . . 275
1 1. 15 Exercises ..... . . ... .. .. . . ...... . .. ... , . . . . . . . . . . . . . . . . . . . . . . . . . .. 275
Bibliography .. . . . _ . .. ... .. .. .. . . . . . .. . . . .• ... .. . . ....... _ . . . . . . . 276

12 Analyzing Detailed Requirements ........ . . _ .... . . . . . . . . . . . . . . . . . _ ....... . _ 278


12 . 1 The Meaning of Detailed Requirements .. _ ..... _ . _ .. .... . _ . . .. . . .. . . _ . . .. 279
12.2 O rganizing Detailed Requirements .... .. _ .. . ....... . ...... . _ . . . . . . . . . . . . 280
12.3 User Interfaces: Detailed Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 291
12 .4 Detailed Security Requi rements . . . . . . . . . . . . . . . . • . . . . . . . . . . . . . . . . . . . . . .. 296
12.5 Error Conditions .... .. . ... . . . . . . . . . . . . . .... . .. . ... . . . . . . . . . . . . . . . . 296
12.6 Traceability of Detailed Req uirements ... .... .... . . . . . . . . . . . . ... _ ... __ . .. 297
12 .7 Using Detailed Require ments to Manage Projects .. _ •. _ ....... . .... _ .... _ . .. 300
12.8 Prioritizing Requireme nts . .. . .. . .... . . .. .. . . . . _ . . ... . .. . .. . .... _ . _ . .. 301
12 .9 Associating Req uirements with Tests . .. _ . _ ... . .... __ .. . ..... _ . . . . . . . . . .. 302
12. 10 Agile Methods for Detailed Requirements .... . .. ... _ . ......... . . . . ..... _ _ _ 303
12 . 11 Usi ng T ools and the Web for Requirements Analysis ..... _ ....... . . . .... . _ . .. 305
12 . 12 The Effects on Projects of the Detailed Requirements Process . .. . . . . .. . . __ • . . . .. 308
12. 13 Student Project Cui de: Requirements for the Encounter ease Study _ .. . _ . .. _ . . . .. 309
12. 14 ease Snldy: Detailed Req Uirements for the Encounter Video Came ......•... _ . _ .. 315
12. 15 Summary . ... . ... , . . . . . . .... . .. . . . . . . . . . ,... .... . . . . . . . . . . . . . . . . 328
12. 16 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Bibli obrraphy . . . . . . . . . . . . . . . . . ....... ...... ... . . ,. . . . .... . . ....... 330

1 3 Quality and Metrics in Requirements Analysis ..... ..... _ . _ . • . . . . . . • . . . . • . . . . .. 331


13_1 Quality of Requirements for Agile Projects ..... _ .. _ . ... . _ . . .. . .. • . . _ . . ... ' 332
13.2 Accessibility of Requirements . . _ . _ ....... ..... •... _ .... _ ....• _ . . _ _ . . .. 332
13.3 Comprehensiveness of Requirem ents . _ . .. . . . _ .. ... ... . .. . .... . ......... _ 333
13.4 Understandability of Requirements .. . •...... _ . . _ .• _ . . _ . . .. ......... . . _. 335
13.5 Unambiguity of Requirements . .. . . ... .. . ........ . .... . _ •. .. ..... . .. _ .. 335
13 .6 Consistency of Requirements ... .. ........ . . .. . ..... . _ . . . . . . . . . . . • . . . 336
13.7 Prioritization of Requirements ....... _ . _ .. . ........ .. .. . _ ... _ .. . . _ .. . . , 337
13 .8 Security and High .Level Requirements ...... . ...... • . . . . . . . . . . . . . . . . . • _ . ' 338
13 .9 Self·Completeness of Requirements __ .. . ... _ .... . .• . .... . ..• . . . ...... _ _ _ 339
13_10 Testability of Rt:quifcments . . . . . . . . . . . . . . . . . . . . . . . • . . . . . . . . . . • . • . . . . . . 340
13. 11 Traceability of Requirement . ... . ... .. .• __ . _ .. .. •......... _ ..• _ . . . . . .. 342
13. 12 Metrics for Requirements AnalysiS .... _ ... . •...... .. • . . . . . .. _ ..•.. _ •.. _ 3~3
CONTENTS

13. I 3 In pc tlng DetaIled Requi~ments , 344


• • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • •
13 . 14 ummary . . . . . . . , , • • • • • 347
Exerc.ises • • • • • • • • . ... ... ..... . . ........ . . ... ... .
I . 15 • • • • • • • • •
• • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 348

14 Formal and Emerging Methods in Requirements Analysis : An Introduction


(Online Chapter) .... ' . , , . , . , . , , .. . • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 349
14. I Provable Requ irements Method
14.2 Introduction to Formal Methods
14.3 Mathematical Preliminaries
14.4 The Z ·Spec ificalion Language
14.5 The B Language System
14.6 T rade·offs for Usi ng a B· like system
14 ,7 Summary
14,8 Exercises
Bibliography

PART V Software Design

15 Principles of Software Design .,' ,.,' .... . ... . , . . , .... , " " , . ,.' , . . .., .. ,. 350
15. 1 The Goals of Software Design ,.,., •. " .. ', . .. ' , .. " ... ," , ., .• ', ... ,. 35 1
15.2 Integrating Design Models ... , ... , . .. . . . . . . . . . • . . . . . . . . . . . . . . ' . . ' .•. ' 354
15. 3 Framework.s ... . . . .. . . . . .. .. . . . . . . . . . . . . . . . . . . . . . . . . ........... . .. 357
15.4 IEEE Standards for Expressing Designs . , .. . . ... ' . . , ... . ' .... . ' , . . . . . . . , .. 359
15.5 Summary . ..... , ' . , .... , . .. ' ,. , . , ' . , . , ' , ... , . ' , . , . , .. , . . . . . . . . . , 359
15.6 Exercises ....... __ ... . .. . .. . . . . . ....... . ..... . . . . ... . . . . . . . . . . . " 360

16 The Unified Modeling Language , . . •. ,., . , .. ,., . . , . . ' , ' .. , , .. ' , , , • ' , .. . ... . 36 1
16. 1 Classes in UML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . ....... , ...... . . 362
16 ,2 Class Relation hips in UML , .. " . , . " . , .... , . .• , .•...... . . . •. ' .... , .. ,' 6 1-
16.3 Multiplicity ..... ... ... . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ... . .. 364
16.4 Inheritance . . . . . . . . . ....... .... . . ..... .. . . . . . . . . . . . . . . . . . . . . .. . 364
16.5 Seque nce Diagrams ... ......... . . ............. ..... .. . • • • • • • • • • • • • 368
16,6 State Diagrams ..... .. ..... .. ..... . ... . ............. . ........... . 372
16.7 Activity DiaglClm ....... ..... . . . . . . . . . . . . . . . . . . . . .. . .. . . ... ... . 374
16,8 Data Flow Models . . . . . . . . . . . ... .. . ..... . . . . . . . . . . . . . . . . . .. ..,. 376
16.9 A DeSIg n Example with UML . , , , . , ' , . , " .... , .... ' ,., .. , . . . . . . . . . . . 377
16. 10 Summary . . . . . . . . . ,. . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . .. ... ... . 380
16. I I ExerCises . . • • • • • • • • • • • • • • • • • • • • • • • • ••
• •• •••••••••••••••••
• 38 1
BIbliography • •• .
.. ....... . ........,. ....... . , , . . , . . " . .. 382

17 Software Design Patterns , . '


. .. . .........,...... .... ............... . 383
17 . I Exam ples of a RecurrIng Dc"sn Purpose .. , ' , . ' .. , . " ' , . " .. ,,, ..... ... , 84
~86
17 2 An Introduct Ion to Design Patterns . . , . . , .. , .. , . ,,. ,•, .. , •...
17 3 ummary of D es ign Pallerns by Type ' rea tio nal ,
Slru IlJral , and Ilehavlora l , .. , ' " ,." , . ,. . , .. • •••• 3'10
174 ' h a raCLcri s [l c~ of I CSls n Pallern s: VI Cw pO lnt ~, Ro le. , and Level< " , • •• • .' 3<)6

17.5 Sci c.tcd reall o nal De<ij(n Pa ll ern ~ , , ' " . . .. , , , , , , , '. 400
de ted truclUral J)c,i~n Pall e,"' . . , . .• ... .' . . .•. , , 408
176
CONTENTS

17.7 de ted Beh, vlOra l D , '/(n Patterns . .. . • • • • •• • •• •••• • • 417


17 8 De<igll Pattern Forms: Delega tion and Recur ion . . . , . • • • • • • •• •• . • • • • .. 43 1
17.9 ummary . • • •• ••••••• • • • •• • 4 35
• •• • • • • • • •• •
17. 10 Exer ises ... • • • • •• ••••• • • • • • • • • • • • • • • • • • • • • • •• • • • • • • • • • •• 4 36
Bibliography • • • • • • • • • • • • • • • • • • • • • • • • • • • • ..
• " . • • . . • 437

18 Software Architecture . . . . .. .. .... .. . . . .. . . . . . . . . . . . . ....••..... 438


18. 1 A Categorization of Arc hitectures ... . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . 439
18.2 Software Architecture AlternatIves .nd T hei r Class Mode ls ... .. .. . . . . .... 439
18. 3 Trading orr Architecture Alterna tives . . . . . . . . . . ..... .... ....... . . . . . . . . 453
1804 T ool for Arch itecnlres .. . . . . . . . . . . . . . . . . . . . . . . .. . . ...•.. . ..... ... 454
18.5 IEEE Standard for Expre sing Designs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . 455
18.6 Effects of Arch itecture Se lection on the Project Plan . ..... . .. .. .. ...... . 455
1S.7 Case Study: Prep.nng to Desig n Encou nter (Stude nt Project Guide conti nued ) ..... 457
18.8 Case Snldy : Software Design Docume nt for the Rol,.PlayiH9 ViJ<o Gam, Framework . . .. 460
18.9 Case tudy: Software Design Document fo r Encou nter ( Uses the Framework) .. . .... 462
18. 10 Ca c Study: Architecture of Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . 466
18. 1 I Case Study · OpenOffice Arch itecture ....•.. . ...... . . .. .. . . . . . . . . . . . . . . . 468
18. 12 Summ ary . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . ........... 473
18. 13 Exercises . • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 474
Bibliography ... .. • . . . . . . . . . . . . . . . . . . . . . . . , .... .... . . .. _ . . . . . . . . . . 475

19 Detailed Design . . . . . . . . . . . . . . . . . . . . . . . . .. ...... . .... ... .. . . . . . . . . . . . . . 476


19. 1 Relating Use Cases, Architecture, and Detailed Design . . . . . . . . . . .... ..... . .. . 477
19.2 A Typica l Road Map fo r the "Detailed Design" Process . . . . . . . . . . . . . . . ....... . 478
19 .3 Object. Oriented Design Principles . . .... . .. . . . . . . . . . • . . . . . . . ... .... .. .. 479
19.4 DeSig ning agai nst Interfaces ....... .. ...... . ... . . . . •.... .. ...• . ....... 481
19.5 Specifying Classes. Fu nctio ns, and Algorit hm s . . . . . . . . . . . • . . . . . . . . . . . . . . . ... 482
19.6 Reusi ng Componen ts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . .. 485
19.7 Sequence and Da ta Flow Diagrams for Detailed Design . . . . . . . . . . . . . . . . . . .. .. ' 486
19.8 Detailed Design and Agile Processes . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . ...... 490
19.9 Design in the Unified Development Process . . . . . . . . . . . ..•...... ... ... . .. . 490
19 . 10 IEEE Standard 890 for Detailed De ign .... ..... . . . ... . . . . . . . . .... .• .. . . 491
19. 11 Updating a Project \~it h Detailed Design . . . . . . . . . .. . . . . . . . . . . ... . . .•. . .. 491
19 . 12 Case Study: Detailed Design of Encounter . . . . . . . . . . . . . . • . . . . • . . . . .. • . . . . . 494
19. 13 Case Study: Detailed Design of Eclipse .... .... . . . . . . . . . . .. . • .. .. . . . . . . . . 503
19. 14 Sumnlary . . . . . . . .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ... .• . •. .. 505
19 . 15 Excrc·ises . . . . . . . .. .. . ... . . . . . . . .. . .. .. . . . . . . . . . . . . . . . . . . . . ... ... . 505
Bibliography . . . . . . . . . . . . . . .... .. .. . . . .... .. . .. ..... . . . ... . . . . . . . . 507

20 Design Quality and MetriCS . . . . . . . . . . ... . . . . . . . . . . . . . . . . . . . . . .. . . . •. .... S08


20. 1 Degree of Understandability. Cohesion. and Coup ling . . . • . . . . • . • . . . . . . • . . . . .. 510
20.2 Degree of SufAciency as a Quality Goal . . . . . . . . . . . . . . . . . . . . • . . .. ..••.... 510
20.3 Degree of Robustness as a Quality Goal . . . . . . . . . . .. . . . ......• . ... . • • . ... 11
20.4 Degree of FlexibIlity as a Design Quality Goal .. . .. . . . . . . . . . . . . • . . . . . • . •. . 512
20.5 Degree of Reusability .. a Design Quali ty Coal . .. . . . . . . . . . . . . . . . .....••... 13
20.6 Degree of Time EffiCie ncy as a Design QualifY Mu ure ...•. ..•. .. . . . . . . . . ..• 517
CONIENTS •

20.7 Degree of pace EfficIency as a Design Quality Measure . . . . . . . . • . . . . . . ... .... 519
20.8 Degree 01 Reliability as a Design Quality Measure . . ... . ... ... ... • . . ....•... 521
20.9 Deg ree 01 Secun' ty as a D eSlg"
' Q ua I'tty M c,asurc .... ... . . ... . . ............... . 523
10. 10 A essing Quality in Architec rurc Selection ... ... •......•.... .. • . .. . . . •. .. 525
10. 1 I As essing the Quality of Detailed Designs . . . . . . . . . . . . . . ..... . . ... . . .... . . 531
20. 12 Sunlmary . . . . . . . .. .. .. .. .. ... . .. . .. . . . . . . . . . ... .... . .... . . . . . . . . . 536
20. 13 Exercises . . . . .... . . ..... . . . . . . . . .. .. . . . . . . . . . . . . . . . . . . . . . .. .... . . 536
Biblio~paphy . . . ...•..... ... ... . . . .. . .. . .. . ..... . ... . ..•... . ...... 537

:2 t Advanced and Emerging Methods in Software Design (Online Chapter) • • • • • • • • • • • • • • 538


21 . 1 Designing in a Distributed Environme nt
21 .2 Introduction to Aspect· Orie nted Programm ing
11.3 Designing for Security with UMLsec
21.4 Model · Driven Architecrures
21 .5 The Formal Design Process in B
21 .6 Summary
2 I. 7 Ex" rc isc
Bibliography

PART VI Implementation

22 Principles of Implcmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539


22 . 1 Agil e and N o n.Agile Approaches to Implementati o n .... . . . .... . ... ..•.. . . 540
22 .2 C hoosi ng a Programm ing Language . . . . . . . .. . . . . . . . . . . . . . . . . . . . . .... 540
22 .3 Ident ifyi ng C lasses . . _ . . .. . . . . . . . . . ... . . . . . . . . .. ... . . . . . . . . . . ... . . . 540
22 .4 D efin ing M e tho ds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 t
22.5 Imple me ntati o n Prac tices .. . . . . . . . . . . . . . . . '. .. . . .... . . . . . . . . . . . . . . . 544
22 .6 Defe nsive Programming . . . . . . . . . . . . ... . .. . . ... . . . . .. . . . . . . .. .. . . . . . . 548
22 .7 Cod ing Standards .. . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . , . . . . . . . - .. . 552
228 Comme nts • • • • • • • • • • •• ' . . . . . . . . . . . . . . . . .. ..•.. .. ..•. • ..... . 554
22.9 T ools and EnViro nments (o r Programm ing . .. ..... . . . . . . . . . . . . . . .. . 555
22 . 10 Case Srud y: Encounter Impl ementation . . .... . . . . . . . . . . . . . .. .. ... . . .. . 556
22. I I Case Stud y: Ec lipse .. . ,. . . . .... . .. .... . ..... ,... . . , . . . . . , .... . 559
22. 12 Case Stud y: O pcnO fAcc . . . .. . .. .. ... . . ....... .....• . . .. . ... . •. .. 559
22 . 13 Student T ea m G uidance (o r Impleme ntatio n . . . . . . . . .. , . . . . . . . . . .... . . 565
22. 14 Summary . . . . .... ,.. ,. . . ' . ,. ...... . .... . .. .. • • • • 566
66
22. 15 Code Listings Referred to in th is haptc r ., . . . . . , . . . . . . . . . . ... . . .. . •

22. 16 ExerCises . • • •• • ••
.,.,. • • • • • • • • • •••• •• • • • • • 8t
BiblI ograp hy ., , . • • • , ... . .. .
. , ... •• •••• • • •• • • • • •• • 58

2, Quality and Me trl s in Implementatio n ., ...... . , . , . . . . . . .. .. .. . . • 58 4


23 . 1 Quality of Impleme ntatio n . .' . . . ....,. .... .... . M
232 de In'pect lon, and Relatcd Q uali ty Pro edure, • .' ... . •••• • •
,7
• •• • •• •••• • • • 599
23 .3 Summary . . .., . .. . 1)(
23.4 Exer ,.CS • • • • • • • ., .,.". . • •••
24 Rf!facloring . . ................................ ... . . . . . . . . . . . . . . ..... . 60 1
24 . 1 Big Refactori ngs . . . . . . . .. . . ....... .. ..... ... .. . . ........ ...... . 604
24 .2 o mposlng Methods ... . ..... . . . . . . . . . . .. .. . .. .. .. . .. .. .. . . . . . . . . . . 606
24 .3 Moving Fea tures between Object ......•. . . . . . . . . . . . . . . . • • . . . . . . • . . . . . . 608
24 .4 Organizi ng Data .... . .. ....... .... . ........ . .. .... . .... . . . . . . . . . . . . . 609
24 5 Generalization . ... .. ...... ....... . ..... . .. . . . .... .. . . . . . .......... 612
24 .6 IntroducIng Modules ...... . . . . . . . . . . . . . . . • . . . . . . • . . . . . . . . . . . . . . .. . 616
24.7 RefaclOri ng in Projects . . . .. . . . . . . . . . . . . .• . . . . . . • . . . . . . . . . . . . . . • . . . . 617
24 .8 Summary .... . . . . . . . . . . . . . . . .. . . . . . . . . . .... ... . . . . . . . . . . . . . . . . . . 619
24 .9 Exercises . . . ... .... ..... . ............... .... ... . . .... . .. .... . . .. .. 619
Bibliography .. .. .... ... .... . .. ... ..... . .... ..... . . . ........ .. .... 620

PART VII Testing and Maintenance


25 Introduction to Software Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . . . . . . • . . • .. 621
25 . 1 Testing Early and Ollen ; and the Agile Connection .... . •...... . .... . .. .. •.. 622
25 .2 Retesting: RegreSSIon Testi ng . . . . . . . . . . . .. . . . . . . . . . . .. • . .. .•..... .. •. . 622
25 3 Black Box and White Box Testing . . . . . . . . . • . • . . . . . . . . ..... •. . ..•....•.. 623
25,4 Unit Testin g vs. Post· Un it TC5ling ... . ... ... ..• ... .. .... . ... . ... .. . . ... 624
25 .5 Testing Object·Oriented Implementations . . . . . • . . . . . . . . • . . . . . . . . . . . . . . ... 625
25 .6 Documenting Tests . ...... .... . . ... .•..... . . . . . . . . . .. . . . . . . . . .. 626
25 .7 Te t Planning .... ... . . . . . . . . . . . . . . ........ . .............. . ... .. ... 626
25 .8 Testing Test Suite by Fault Injection . . . . . . . . . . . . ...... . .. .. . . . . . . .. .... 628
25 .9 Su mm ary . . . .... . . . . . . . . . . . . . . . . .... .. . . . . . • . . . . . . . . . . . .. .. 628
25 . 10 ExercIses . . . . . . . . . . . . . . . .... .... ........... ~ . . . . . . . . . . . . . . . . . . . . . . .. 629

26 Unit Testing ... ... . . . . . . . . .... . . .. . . ............ . .. . . . . . . . . . . .. .. . . .. . 630


26. 1 The Sources of U nIts for UnI t Testi ng . . ... . ...... . .....•......•. .. .. . . . 631
26.2 Un it Test Methods .
. .. .. .. . . . . . . .. .. . . . . . . ... . . . . . ... .
... .... . . . . 631
26.3 Testing Methods . . . . .. .. . . . . . . . . . . . . . . . . .. . .......... . ... . . .... . ... 642
26.4 T est·Dro ve n Development . .. ... . .. ... ..... .. ..... . .• . ... . ... . .... .. 647
26.5 Case Study: Encou nte r Video Game .. . •.. .. . . ...... .. . . . . . . . . . . . • .. . ... 652
26.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . .. . • . . . . . . . . . . . . . . . . . .. . . . . . . 662
26.7 Exercises . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. ..... . . . . . . . . . ... ... .. 663
BibliogTilphy ... .... . ....... ... . .... . ... . . . . . . . . . . . ... . .. ... ... 665

27 Module and Integration Testing . .....•. . . . . . . . . . . . . . . . . . . . . . ... . • ... • .. ... 666


27. 1 Stubs and Drivers . ... . . . . . . . . . . . . . . ..... . ... . . . . . . . . . . . . . . . .. ..... 667
27.2 Testing a Oass ..... . ...... ... .... .. . .......... . ... . ... . . . . . . . ..... 668
27.3 Integration . . ................... .. . . . . . . . . . . . .. ....... ...... . . .... 672
27.4 Daily Bu.ilds ............... .. ....... ... ... . . . . . ........ . . . . . . . . . . .. 679
27.5 Interface: Testing ... .. .. .... .. ... . . . . . . . . . . . . . . . . . . . . . . . ... .. . .. . . . 680
27.6 Module Integration .. . . .... . . . .... . . ... . ........ . . . .... .... . . . . . ... 682
27.7 Case Study: Class Test for Encounter . . . . . . . . . . . . . . . . . • . • . . . • . . . . . . . . . . .. 683
27.8 Case Study: Encounter Integration Plan .... .... . . . . .•. ....... .... . ... ... . 688
27.9 Su:mmary .... . . . ..... .... . . ...... ...... .. . .... . . . •.. .... .. . ..... 692
27. 10 Exercises . .............. . .................. . .. _ .. . . .. ...... . ...... , 692
Bibliography .. . . .. . .......... .......... . ............ . ..... . 10- • • • • •• 693
CONTENTS

28 T ~tinll at th~ S)'$t~m Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 69.


28 .1 Functional Testing . ..... .. .. . .. ..... . .. . . .. . •. . .................. " 696
28.2 Nonfunctional Testing . ...... .... . .... .... . ........ ... ... ........ . .. 698
28 .3 Testing with Lightweight Requirements .............. ............... . . . . . 708
28.4 T~tin8 hortly Before Release ...... . ...... . .. . .. . ...... . ............. 713
28.5 Ca e Srudy: Encounter Software Test Documentation .. . . .... . .. ... ........ . . 714
28 .6 Case Study: Eclipse . . ..... . . ... ... .. . ............. . ... . ..... . ... . .. 723
28 .7 Case Study: OpenOffice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 726
28 .8 Sunlnla.ry ..... .. . . . . . .. . . ....... . ...... .. . .. ... . .. . . . . . . . . . . . . . . 728
28.9 Exercises .. ... .. . ... . .. .. . . . . ... . ... . . ... . .. ... .. . .. . .. . . ..... . .. . 728
Bibliography . .... . . . . .. . .. .. .... , . . . . . . . . . . . . .... ..... . . . .. . . .. . . 729

29 Software Maintenance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 730


29. 1 T ypes of Software Maintenance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 1
29 .2 Issues of Software Maintenance . . . . . . . . . . . . . . . . . . . . . . . . . .... . . . ...... 734
29.3 Maintenance Process .. . ......... .. .. ...... . .. . . ... . _ . . . . . . . . . . . . . .. 736
29.4 IEEE Maintenance Standards . ..... .... . . .. .. .. . . . ........ . . . ..... . ... . 74 1
29.5 Software Evolution . . . ... . . , . . .... . .. . . ... . .... .. . . . . .......... .. . . . 749
29.6 Maintenance Metrics ..... . . . . ... . ... . . . . . . . . . . . . . ..... . ... , . . . . . . . . 751
29.7 Case Study • •• • • •
• • • • •
• • •• • • • • • •
• • • . • • • • •••• • • • • .. . . . ... . ..... . 754
29.8 Summary • • • • •• •• • •• •• • • • • • •
• • •
• • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 756
. 757
29.9 Excrcises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • ••••••• •• ••• • • ••••

Bibliography . ... .. . .. .. . . . . . . . . . .. . . ... . . . . .... . ..... .... ... . . . . 758

Glossary . • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 759
Ind~x ... .. • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 767
preface

Mu h of the mod"rn world nln ' n software As a result , ,oftware e ngineers arc e ntnl ted with signincant
rc<po n<lbd,ty Although It is. biomedical engi neer, for examp lc, who deSig ns hea lth mOnito ring systems, it is
a sohware engi neer who creatc' its a tual contro l functions . A marke ting profess io nal deve lops ways to reach
u, tomcr> o nlme but It IS a software e ngineer who makes the system a reality .
T oday's . oftware eng.netr must be able to partl Ipate In mo rc than o ne kind of software process , work in
agile tea ms, deal with custo mers , expres requirements clearly , crea te modul ar deSigns, utilize legacy and
o pen <ouree projec ts, mo nitor quality , incorpo rate security, and apply many ty pes of tests.

THE ISSUE OF SCALE

A software application consists of tens, "undreds, even thousa nds of classes. This is very different from
managi ng three o r rou r of them , and resu lts in the dragon of complexity suggested by this book's cover. As
al 0 ugge ted there, however. thiS dragon ca n be subdued. Indeed, to deal with numerous and complex
c1asse , softwa re engi neers ha ve at their di sposal a wide variety of too ls and techniques. These range from the
waterfall process to agile methodologie . from hig hly Integ rated too l suites to refac toring and loosely coupled
rool se ts. Underl ying this variety IS co ntinumg resea rch into reliable approaches, and an acknowledgment of
the fac t that o ne Size docs 110t fit all projects.

THIS EDITION COMPARED WITH THE FIRST

The ~rst edition or this book emphasized the object-oriented approach, which ha subsequently
become widespread. It was also designed to help tudent teams cany out hands-on tenn projects through
theory, exampb. case studies, and practical steps O bject-orientation and hands-on continue to be major fearunes
or this edilio n. However, we hav~ widened the scope of the first editio n, especially by including extensive
coverage of aglie methods .nd refactonng, together with deeper coverage of quality and SOrlWare design.
Readers of the first edi tion made extensive usc of the complete video ga me case srud Y-d n example that
they could follow "from soup to nu ts" but which was signiRca ntl y mo re comprehensive than a toy This edition
retains and updates that case study, but it adds the exploration of a simpler example o n one hand (a DVD rental
lore) and large, real, o pen source case stud ies o n the o ther. In parti cular, to provide students a feeling for the
scope and complexity of real -world applicatio n , this book leads them through elected requirements, design,
Implementati on, and mall1tenance or the Ecli pse and Ope nOfAee open souree projects. The ize, complexity,
and transparency o r these projects provide s rude nt~ a wll1dow into <oftware en!!lI1eeri ng o n • reali Ii scale.
Every book o n software engineeri ng races a dilemma, how to reconcile the organ iza tion of the fopi
with the o rga ni zatio n of actu.1 software prOject phas,s An orga l1l zatlo n of chapters into procc project
management/requirements anal ysisldcSlgn/ lmplernentation/te,t/maintenancc i straightfo rward but IS ".ble
(0 be mlSi nterpretl'd as pro motll1!! the waterfall development pro e" at the expense o thel'<. ur approa h has
been to ,,'e th" org. nlzatlo n In the <even part< of the book but to demo n<trate throughout that e. h phase
PREFACE •

lYl.'ica ll y belongs to a cycle rather than t'o a si ngle waterfall sequence, In particular, our approach integrates
agtle methodo lOgies co nsistently.
This e dition also introduces somewhat advance d inAuentia l ideas, including model-driven arc hi.
!ectu~s and aspect ·oriented programmmg . Nowadays, formal methods are mandated by government
agenCies for the hig hest level s of security, and this book aims to educate readers in their possibilities. Due
to print space limitations, some of thiS material is to be found in the online extension of thi s book.
In summary, specifk features of thi s edit ion compared with the first arc as follows :

• A sharpe n ing and standardizatio n of the material from the first edition

• A strong agi le thread throughout, including a chapter o n agility alone and one devoted to refactonng.
• A separate chapter on quality in six of the book's seven pans

• Real -world case studies, taken from the Eclipse and OpenOffice o pen source projects
• Greatly expanded coverage of software desig n and design patterns

• New chapters on advanced, inAuential software engineering ideas

• An o rganizati o n of many of the book's seve n parts as follows :


• PrinCiples

• Detail s

• Quality

• Advanced Methods

HOW INSTRUCTORS CAN USE THIS BOOK

This book has been designed to accommodate multipl e approaches to the learnin g and teaching of software
engineering . M ost instructors teach the fundamental s of soft,vare process. project management, requirements
analysis, design . testing . implementation , and maintenance Beyond th is comm o n ground, however.
instructors empl oy a wide va riety of styles a nd e mphases. The follOWing are majo r approaches. together
with the sequence of c hapters that support each of them.

A. Proass emphasis, con e ntrating o n how applications are develo ped


All o f Parts I through IV; and C hapte rs 15, 22 , and 25 (th e remaining principles and intro ductio n
ch apte rs)
B Desi9" emphaSIS, whic h tca ches softwa re engi neeri ng primaril y as a design activity
Princi pl es and introductio n· C hapters 1, 3, 7, and 10, all of Part Vi and haptcrs 22 and 25 (prln Iples
and Introduc tion )
C. Programmln9 a"d a9il, (mphaSlS , whic h emphasizes so ftware engi nee ring as a code -o riented a II vi ty that
satisAes rcquircment~, emphaSizi ng agi le app roache
Prin Iples and Introduction · hapl crs I , 3, 7. 10, and 15, all of Part VI I and C hap ters 25 and 26

D. TlDo-sm,sl" coursr, whi h enables th e in~tructor to cover mo t top I s and a ' I ~n a lib tant lal hand, -o n
project
PREFACE

Df, All of the chapte ~ 111 the book, either in sequence "ro m beginning to e nd
or

D2 In twO pa ses as follows :


(i) Principles and i",rodu tion hapters in the Arst semeste r: C hapters 1, 3,7, 15,22 , and 25
(ii) The remaining chapters in the second semester

E. EmplJa,i, on II I" md,-on projecis " Old caSt ,'udies, which relics mos tly on an active team or individual project as
the vehicle for learning theory and principles
Principles and introduction c hapters : C hapters I, 3, 7, IS, 22, 25 , and 26, and all case study sections in
the remaining chapters

F. Tbtory and principles e,"ph"sis, conce ntrating o n what one can learn about software engineering and its
underpinnings
Principles and introduc tion chapters : Chapters I, 2, 3, 7 , 15, 22 , and 25, followed , as time allows, by
C hapters 14 and 21 (emerging topics)

C. Qualily a,mmna and leslin9 rmpha,i,


Principles and introduction: Chapters 1,3 , 7, and 10; Chapters 2, 5, 9 , 13, 20, 23 (quality ); and Chapters
25, 26, 27, and 28 (testing),

The web site for this book , including review questions and the Encounter game case study, is
www.wiley.com!coll egeJbraude.

Eric Braude
Michael Bernstein
Boston , MA
January 20 I 0
owl ments

We owe a debt of gratirude to o ur srudents at Bosto n UniversIty's Metropohtan Coll ege. Working in myriad
industries and busi nesses, they have give n us invaluable feedback . The Coll ege itself has provided a model place
fonhe teaching and learning software engi nee ring . Ounha nks go to Dick Bostwick a nd T o m VanCourt, much
of whose work in the first edition carries over to this o ne. We are grateful to the peo ple of Wiley fo r workin g with
us through the painstaking process of writing and publishing th is book. We are particularly appreciative of the
help from our editOrs, Dan Say re and Jonatha n Shipley; from Ceorgia King, Yee Lyn Song, and the indefatigable
staff. We thank the reviewers of o ur manuscript, whose feedback has bee n invaluable :
Arvin Agah , Un iversity of Kansas
Steven C. Sha Her, Pennsylvania State University
Stephen M . Thebaut , University of Florida
Aravinda P. Sistla, Un iversity of Illinois, C hi cago
James P. Purtilo, Unive rsity of Maryland
linda M . O tt, Michigan T echnolog ical Un iverSity
Jianwei Niu, Un iverSity of Texas, San Anto nio
W illiam livel y, Texas A&M University
Chung Lee , Ca li fornia State Un iversity, Pomona
SudiptO Chosh , Colora do State Uni versity
Max I. Fomitc hev, Pennsylvania State Un iversity
Lawrencl" Bernstein, Steve ns Institute of T echnology
John Dalbey, California Poly tec hn iC Un iversity
Len Fisk , C alifornia State Un iversity, C h ico
Ahmed M . Sa le m, Ca lifo rni a Sta te Un ive rSity , Sacramento
Fred Strauss, New York Un iver ity
Kai H . C hang, Auburn Unive rSIty
Andre van de r H ock, UnI versity of Ca lifo rn ia , Irvine
Saeed Monemi , Ca hfo rni a Po ly techn ic Unlver ity
Robert M . C ubert, Un ivers Ity of Florida
Chris T seng, San Jose State UniverSity
Michael Jame Payne, Purdue Un ive rsity
Ca ro l A. Wel lington , h ippensburg Un iversity
¥ifel Dong, UOIvcrSlty o f Ok laho ma
Peter Blanc hfIeld , Nottingham Un iversity
Desmond Creer, Queen'< UnIversi ty Belfast
We IQ , Yan , Que!:n's University Belfa st
bigham Mahmood, Derby Uni vers Ity
~rcl P,cterSo n, H OKcsc hool Van Amsterdam
. book
IS wou
Id
not
h
ave
~ - po'<lblc
""en ,
WlthOllt the onstant lovc, patlen e. and encouragement of Ollr fan"l,c
Th
The Goals and Terminol

o So ware En ..• neenn

• Why is software engineenng


important?

• Who and what does is consist of?

The Software
• What are its main actMtles?
Development
Ufecycle • What ale the principles of software
engineering?

• What ethics are Involved ?

• What sorts of case studies Will be


used to illustrate the subject?

Figure 1.1 The context and learntng goals for this chapter

Th e goal o f o ftw arc eng ln ee nng , and the theme of thi S book, I th e creati o n of oftware sy tern th at
meet the needs o f cu t o m e r and arc reliable, d fic lent , and ma i ntainable. In addition , the 'y tern h ou l d be
pro duced 10 an eco no mica l fa sh io n, meeting prOject sc hedul es and budge t . ThIS I no ca y task, espeCiali
(o r large , complex applicatio n TIllS c hapt cr Introduces th e fi eld o f oftwarc c ng ln ee fln g and e, pl. IO " h ow
.t addresses th e<e goa ls. We hrst ex pl ., n the term "so ft ware c ngincenn g," sho " ' IOg th at.t on" h of man\'
pan s.
2 CHAPTER 1 THE GOALS AND TERMINOLOGY OF SOFTWARE ENGIN EERING

1.1 WHAT IS SOFTWARE ENGINEERING?

OJIoI'." ",gln",;n!! b on englOeering dl scip hn~ thot lOvo lves all ospects of deve loplOg ond maintalOlO!! a
software prodo t Enginee nng discl pline< suc h os lvii , I11cchonlca l. and clectricollnvolvc the deSIg n . analysIs,
and con tm tlon of an "tibct for some prac tIca l purpose ' o ftwarc e nginee rin g IS no exce ptI o n to thiss--
>oftware produc ts certainly hav~ pra tica l purposes.
Th~ IEEE deRnes Software Engineering [ I ) as follows ,

I. The app lication of a systematIc. disciplined , quanti Rab ie approach to the development, oper.lt lon and
mainte nance of soft wore, that is, the application of englOeenng to so ftware .

2. The study of approac hes as in ( I)

As this deRnition sugge ts, it's not on ly what is produ cd that's important but a lso II011J it is produced
Eng,"eenng disciplines employ an established set of sysln.alic, dis iplin,d, and qlUmlifiab[, approaches to the
development o f anifacts. By thoroughl y applyi ng an analogous set of approaches to the development of software,
we can expect the production of software that is h ighly reliable, is maintainable, and meets speclRed
requirements. A dISciplined approach is panlcularly imponant as the size of a software project grows. With
increased size comes greatl y increased complexity, and applying a systematic and disciplined approach is criticaL
One of the first uses of the phrase "software engi neeri ng" wa in 1968, by a NATO Study Group on
Computer Science [2]. A conference was o rganIzed at that time, motivated by the "rapidly increasing imponance
of computer systems in many actiVIties of society ." The Study Group focused their attention on the problems
with software, and held a working conferen ce o n Software Engineering that turned out to see far into the future.
The foll owing are some quo tes fro m the conference that summarize the cause for their concern:

The basic pro blem IS that ccnain classes of systems arc placing demands o n us which are beyond
our capabilities and o ur theori es and methods of design and production al this time .. It is large
systems that arc encounteri ng great difficulties. We shou ld not expect the production of such
systems to be easy.

Panicularly alarming is the seemingly unavoidable fallibility of large software, since a mal .
function in an advanced hardware-software system can be a matter of life and death .

Programming management will continue to dt-scrve its current poor reputation for cost and schedule
dfectiveness until such time as a more complete understanding of the program desIgn process is achieved.

O ne of the problems that is central to the so ftware produc tion process is to identify the nature of
progress and to find some way of measuring It.

Today we tend to go o n for years. with tremendous investment to And that the sy tem, which wa
not well understood to stan with, docs not work as anticipated. We build system like the Wright
brothers built airplanes build the whole thing . push It off the cliff, le t it crash, and sIan over again.

The Study G roup discussed possible tec hniqucs and me tho ds that mIght lead to solving these problems.
They deliberately and provocatively used the term "software engineering," with an emphasis on engineering,
as they wanted to "i mply the need for software manufacture to be based on the type of theoretICal
foundations and practical disciplines that arc traditto nal in the establi hed branches of englOcering: The
believed that If these foundations ond diSCIpline were applied to bUIlding software s stems, the qualtt of the
resulting systems would be vastly improved.
Today, many of the issues they identified are addre<sed by evolvlllS software engineering techniques
and practices even as the ,cope of applications has incrcosed dramatically . Throughout this book we examIne
these practices and explalll how they con tribute to prodUCing high. qunlity software. 8efor.. doing that,
WHY SOFTWARE ENGINEERING IS CRITICAl ' SOFTWARE DISASI ERS 3

however, it IS instructive to begin cxanllning why softwa re fails in th e first place, and how some fai lures can
tv"" le.d to ca tastrophic results.

1.2 WHY SOFTWARE ENGINEERING IS CRITICAL: SOFTWARE DISASTERS

Even WIth the best of intentions, a large number of software projects tod.y are unsuccessful, wit h a large
percentage never completed . Worse , quite a few software projects still end in d,saste r, causing a loss of
money, rimc , and tragically , cvc nl ives. \Y/c review some reprcscnta[ivc samples here as cau ti onary ta les. In all
cases, the method employed were inadequate for th e complexi ty of the required application . Failures such as
these motivate us to conti nually ask: How can we: apply softv.1are engi neeri ng methodologies to ensure the
appropriate level of qualoty in software applications)

1.2.1 The Virtual Case File Project

The FBI's Virtu.11 Case File system was intended to automate the FBI's cumbersome paper· based case system, allow
agents to share invtstigative onfo rmati o n, and replace obsolete systems. Instead, after an expenditure of $ 170
millIon, the result did not accomplish these objectives

at all . 111e effect ha been to inhibit the FB I from growing its
crime-fighting mission despite the growth in terrorism and the increased sophistication of many criminal
organizations. All of7oo,ooo lines of code, costing $ 100 million, had to be ahandoned. Poorly defined requirements,
networking plans, and software development plans were cited by investigators as causes for thi disaster.

1.2.2 The Ariane project

' O n 4 June 1996, the maiden flight of the Ari..O( 5 launcher e nded in failure . O nl y about 40 seconds after in itiation of
the flight sequence, at an altitude of .bout 3700 m, the launcher veered off its flig ht path, broke up and exploded: [3)
The cost of develo ping Ari..O( during the preceding decade has been estimated at $7 bi llIo n. A significant fraction of
this was wasted on June 4, 1996. Anlm, 5 itself. oneluding its speCific develo pment, has been va lued at $500 million .
The source of the problem was desc ribed in the ofnc ial repo rt [3) as follows (italics added ),

The internal Inertia l Referen ce System software exception was caused during execution of a data
conversion from 64·bit flo. ting point to 16 -bit Signed intege r va lue. The floatong , point number
which was converted had a value !o'Teater t han what could be represented by a 16·bit signed
integer. This resulted in an Operand Erro r. T he data co nversion instru cti o ns (in Ad. code) were
not protected (rom causi ng an Operand Error.. . Tht (rror occurrrd in a pari oj Ibt 5o!fwart that only
performs a lignment of th e strap· down inertial platfo m1 . This software module computes mean·
ingful resu lts on ly before lift ·off. As soo n as the launcher lifts off, this fu nction serves no purpose.

In other words, the data conversIon code itself was ' correct" but was called upo n 10 execute when it should
not have been . The defect lay wit hin controlling code. This ki nd of problem is easy to desc ribe but not ea y to
aVOId because many people ore involved in large projects. Large projects become extraordin.nl>' 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
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

I Lc:v(nson . N.ncy , .nd Turner C.S., "An Inve<llg3tion of lhe ne,. · 25 ACCident.: IEEE Comput.r, Vol 26, 0 7,
July 1993 , pp. I~l , co pyrig hl 1993 IEEE
SOFlWARE ENGINEERING AcnvmES 5

Falling to meet j ust one of these objectives can cause a project to be deemed unsuccessful. For example,
if a project is completed under budget, meets all requirements and functionality, has high quality, good
performance and is easy to use , it still may not be successful If the schedule was missed and no customers are
willing to purcha e it as a result .
Charette [8 ) notes that there are many underl yi ng reasons software projects are unsuccessful , including,

• Unrealistic or unar!ic ulated project goals

• Poor project manage ment

• Inaccurate estimates of needed resources

• Badly defined system requirem e nts

• Poor reporting of the project's sta tllS

• Unmanaged risks

• Poor communication among customers, developers. and users

• Inability to handle the project's complexity

Other contributing factors are,

• Poor software design methodology

• Wrong or inefficient set of development tools

• Poor testing met'hodology

• Inadequate test coverage

• Inappropriate (or lack of) software process'

Unsuccessful software projects usually fall victim to several of these . T o reiterate , the goa l of software
engineering, and the theme of this book, is the creation of software systems that are relidble, effiCient,
maintainable, and meet the needs of cuSlOmers. Software engineering provides the tools and metho dologies
necessary to accomplish these goals, resulting in the development of successful softwa re systems.
We'll end this section on a positive note. The authors feel that software engineering has improved greatly,
when measured fairly . Projects of equal ambition can typ icall y get done far more successfully now than 10 years
ago. The issue really is that the ambition and scope of, applications have grown enomlOusly. The Eclipse software
development platform , which this book uses as a ca e study, is an excellent example of a successful application .
This is largely due to its Aexible design , inclusive requirements process, and thoro ugh testing.

1.4 SOFTWARE ENGINEERING ACTIVITIES

The production of software systems can be extremely complex and present many challenges. Sy tltms, especially
large ones, require the coordi nation of many plOpl" ca lled s takeho lders, who mus t be organized into t~am s and
whose primary objective is to build a produ I that meets de ancd requireme nt The entire effort must be org,mud

, C h.",,, , Rober!, ' Why oftwar< Fa ds: IEEE pcc,rum, Vol. 42, No. 9, epl<ll1b.r 2005, pp 42-49, opyright I
2005 IEEE
6 CHAPTER 1 THE GOALS AND TERMINOLOGY OF SOFTWARE ENGINEERING

• People

• ProlCLl .takcholders

• Product
• TI,e software product plu$ a socia ted document>.

• Project
• The J tlville amed Ollt to produce the product.

• Process
• Framework wIthin which the tcam carries o ut the aClivilie necessary to build the product.

Figure 1.2 The four "P's" that constitute software engineering

into a cohesive proj<c/, WIth a solid plan for success. Finally , to successfully develop the product, the activities of
the people must be organized through u e of an orderly and well ·defined proass. Collectively, these activitIes are
known a the 4 P's of software engineering, people , product , project, and process. Successful software projects
mllst adequately plan for and address all of them . Sometimes, the needs of each of the P's conflict with each other,
and a proper balancc must be achieved for a prOject to be successful. Concentrating on one P without the others
can lead to a project's failure . For example , if people are organized into efncientteams and given the resources
they need to perform their roles, a project can stil l be unsucc~"Ssful if there's no den ned software process to follow,
as chaos an ensue. The 4 P's are summanzed in Figure 1.2 and are discussed in the sections that follow .

1.4.1 People

People are the most Impo nant resource on a software project. It is through their effons that software is
successfully constnlcted and delivered . Competent people must be recmitcd, trained, motivated, and
provided with a growt h path , which is no easy task . They are the lifeblood of any successful project.
Software development is often dictated by tight, market·driven deadlines and demanding lists of required
product features . Because of th is, only well -o rganized groups of engineers, educated and experienced in the
methods of software engineering, are capable of consistently carrying out these activities to everyone's
satisfaction . The alternative is often chaos and, all too fTequently , disaster.
Typicall y, severa l groups of people arc involved with and have a stake in a project's outcome. These are
called its sliJk,hold,rs . TI,ey include business management , project management , the development team,
customers, and end u ers. Although each group is motivated to see the project succeed, given their diverse
roles each has a different pe~pective o n the process. This is discussed next, for each of the gToups cited.

Business Management
These are people responsible for the busi ness side of the company developing the software. They include senior
management (e.g., V.P. Finance), marketing (e.g" Product Manager), and development managers. Their primary
focus is on business issues including pront, cost effectiveness, market competitiveness, and customer satisfaction.
They are typically not panicularly knowledgeable abollt or involved in the technical aspecrs of the project.

Project Management
Project managers are responsible for planning and tracking a project. They arc involved throughout,
managing the people, proce>s, and activities . They continuously monitor progress and proactively implement
necessary changes and improvements to keep the prOject on schedule and within budget.
SOFTWARE ENGINEERING ACTMTlES 7

Development Team
Software engineers are re~ponsible for developing and maintaining the software. Software developme nt
in lud~ many t~ks such as requirement gathering , software architecture and desig n, implementation ,
t~tlng, con Aguration management, and docume ntation . This book will have much to ay about each of these
topi .. oft",are engineers arc motIvated by man y factors including technical innovation, low overhead (e .g.,
a minimum of business· type meetings), and having the time and support to stay involved in technology .

Customers
C ustomers arc responsible for purchasing the software. They may o r may not actually use the software.
Customers may be purchasing it for use by others in their organization . They are primarily interested in
software that is cost-effective, meets speCific busi ness needs, and is of high quality . They are typically
involved in some aspect of specifying requirem enrs, and si nce they arc paying for the project, they have the
ultimate say in defining the requirements.

EndUsers
End users are people who interact with and use software after it is Anished bei ng developed . End users are
motivated by software that's easy to use and helps them pcrfo nn thei r jobs as efficientl y as poss.ible. For
example, once they become accustomed to and are effective using a particular user interface, they are
typically reluctant to accept major changes to it.

1.4.2 Product

The products of a software development effon consist of much more than the source and object code. They
also include project documentation (e.g., requirements d ocument, design spec ification ), test plans and results,
customer documentation (e.g., installation guide, command reference ), and productivity measu rements.
These products are o ften called artifacts, and arc summarized in Figure 1.3. Th is book describes the comp lete
set of ani facts.
Pan 111, o n software manage ment, describes project metrics and how they arc collected and used to
measure productivity.

• Project documentation
Documents produced during software dcR niti o n and deve lo pm e nt.

·Code
Source and object.

• Test doc uments


Plans, cases, and r"sults.

• Customer doc uments


Documents explainln8 how to use and operate produ L

• Productivity measure me nts


Analyze project produ~tivity .

figure 1.3 TIle main prQduct art facts of a software project


8 CHAPTER 1 THE GOALS AND TERMINOLOGY OF SOFTWARE ENGINEERING

I art IV , o n requirement' ,na ly,i>, 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<·d to customers. These major project activities are summarized in Figure J A .
In addition to these activities, va ri ous development paradigms , techniques, and tools exist and arc
employed on different projec ts. A development paradigm is a way of thinking about the process of producing
software .
An example of a development paradigm , and one that is in wide use today, is the obj,cI-orirnt,d paradigm . It
was invented to make designs and code match the real world . That is, an object as represented in a software
de ign is patterned after a real · world object. For example, suppose that a banking application is to be bu.ilt
that includes support for customers, bank accounts, and transactions on the accounts. In an object·oriented
paradIgm , these real ·word concepts are represented in the desig n and implementation by corresponding

• Planning
• Plan , mo nitor, and control the software project.
• Requ.irements analysis
• Denne what to build.
• Design
• Describe how to build the software.
• Implementation
• Program the software.
• Testing
• Validate that software meets the requirements.
• Maintenance
• Resolve problems, adapt software to meet new requirements.

F"",. 1.4 Major actMtles of a software project


SOFTWARE ENGINEERING ACTMTlES 9

· I~ '
~-.- II'
\ ' ,.

D/rect correspondence

Customer Transaction Account


object object object

Software design and imp/ementaoon artilacts

Figure 1.5 A key role of the object-oriented paradigm


St:Jurce" GJaptucs reproduced WIth pe'lltlsslon from COlel,

clas es. This greatly faci litates identifying and applying modi fica li o ns to a d esig n necessi tated by change to
real-world requirements. Fo r exa mple , if the steps executed durin g a particular lra",aclio" need to c hange. the
design can more ea ily accommodate this since there's a corresponding lra",aclio" object in the d eS ign. The
design representation fo r transactio ns is encap ulated within the transacti o n object, and mo di fica tio ns ca n be
applied mo re easily. Th is is illu trated in Figure 1.5. In no n-o bject· oriented langua gcs . the representation of a
real-wo rld concept such as a customer may be spread across man y d isconnccted pieces of source code .

1.4.4 Process

A ,oJlrDare process is a framework for carrying out the activities of a project in an o rga nIZed and di sc iplined
manne r. It imposes structure and hel ps guide the man y people and aCllv llies in a co bere nt manner A software
prOject progresses through differe nt ph.,,; , each interrelated and bo unded by tim e. A softwa re process
expresses the interrelationship among the phases by defining their o rder and frequency , as well as defining the
deliverables of th e project. Figure I names the majo r pbases and indicate the o rder ,n which they arc usua lly
perfonTlcd.
SpeCific software process implementatio n are ca ll ed ,oJlwo" prom, mod,i,. The re arc severa l suc h model ,
but most are based on either the u>a'tryall o r il". I,., d,,,riopmCII' models. Each of thcsc IS brieA descn bed below
Part 11 covers the evolutio n of software processes and de tails these plus several o the r of the most Importa nt
process models.
The lDaltrfall proem IS t he simp lest .oftwa rc process mo de l, and fonllS the basis fo r most ot hers. A pure
",atcrfall process dictates tha t phases arc impl emented in seque nce, with nO phasl' starting before the prev Io us
one ha~ almost omp lctcd T hat is , phases arc execu ted In a tri ti y sequential order, uSliall y With mall
overlaps Once a wa te rfall phase is fini shed It'S deemed co mpl ete for the projc t and there IS no need to return
to It. Vanallons of waterfa ll eXist where already <.omple tcd pha. es may be reVISited and min or updates
applied , as a result o f ",ork done o n subseq ue nt pha,cs . Waterfall begi ns with an in "ptl o n phase, wherl' tiw
product is co nceived and buslI1c', objec ti ves de fmed . Next is th e spe Iheation of the rcquiIX'Il1ent , foll o wed
by the d.c:s,sn pha,>c, the Imrl eme ntallon pha,c, thc tt" tln g phase, and Rnally the ma in tc nan (. ph.'e. FI/: ure
, 6 "Iustrates the main pha ses and the ir se'lucnee T hi S mea n, that th e I)fOCes, goes aro und the Ir Ie of
Figure 1. ' Just o nce.
Software development ra rely nce u" In th e ' lriU wa terfall seq uence . I,,,t ead, It SKIp, ba ~ and lort h
somewhat among rcq Ulr(' mcnl ~1 deS ign , Imp lcm nt alw l\ , llnd lC!rIling In praLltL C, lheo, we oflt:n U!JC' drratwt'
10 CHAPTLR 1 THE GOALS AND TERMINOLOGY OF SOFTWARE ENGINEERING

Tlmo
,

Requlremenls

Design

Implemenlation
Phases (ac/lvities)
)...Testing

Maintenance

Figure 1.6 The waterfall software development process

processes for software deve lopment , in whic h all or some of the waterfa ll process is repeated several times.
Some processes dictate that activities may be carried out in parallel. In the agilt process, programmers
typically view implementation as part of desig n rat he r th an an entirely separate phase . Here. most phases in
the Circle of Figure I. I arc repeated frequently-as often as every two weeks . This book makes frequent
reference to agile methods.
When performed in a di scip lined manner, iterative styles can be highly beneficial. They are especial'ly
u eful when the requirements arc only sketchily known at the start of a project. A subset of the system is
constructed from a partial list of requirements, customer feedback is obtained , and additiona l requirements
are generated . This cycle repea ts until the complete system is built .
Since policy decisions about software process take place at a n organ izational level (company,
department , group , etc.), there is a need to assess the software development capabilities of organizations_
The Capability Maturity Model" (CMM ) is suc h a measu re . T he CMM and its successor, the CMMI ,
were developed by the Software Engineering Institute. The software engineering capability of individual
engineers can be developed and measured by th e Persona l Software Process SM (PSP) created by
Humphrey (9 ). The hi g hli g hts of CMM I and PSP are woven through some chapters of this book. A
third level of softwa re organization is Humphrey' Team Software Process" (TSP) [ 10], which describes
the process by which team s of software engineers get their work done . The Internationa l Standards
Organization (ISO) de~nes quality standards against which many organizations assess their softwa,..,
development processes.
Well thought·out documentation standards make it much easier to produce useho! , ,..,toable artifacts.
Several standards are available. Many companies provide in-house standards. For the most part , this book
applies the IEEE (Institute of Electrical and Electronics Engineers) software engIneering standard~, man of
which arc also sanctioned by ANSI (American National Standards Institute). Standard focu the process by
providing a baseline for engineer, instructor, and students. In pr"ctice, they are modified and tailored to
speciRc projects.
Software process is the subject of Part II of th is book

1.5 SOFTWARE ENGINEERING PRINCIPLES

The Acid of software engineenng has matured greatly since it began ov~r 40 years ago. Throughout thIS tin,e
practitioners have learned valuable le.son that contribute to the best practices of today. Sonte have become
outdated, but many are still very relevant and widely implemented today. In hI< book [ II j, AI.n DaVIS
SOFTWARE ENGINEERING PRINCIPLES 11

I . A'laly QuaLty Numb" f

2. High-QualIty oft.,mr I. Po sibl,


. Gin, Pru.INrts to C.-'om,,, EMly
4. Ust an Approp';<I't Sof'.'a" P,acl'Ss
5. M,ni,.izt In t,lI, '.al Dj~'a"c<

6 . '"SpiC' oJ,
. Ptopl, Art ,Ix Kry '0SU CCI'SS
figure 1.7 Major principles of software engineering

gathe red 20 I principles that form th e foundation o f software e ngi nee rin g . Figure 1.7 hig hli g hts some of the
most imponant , and we exp lore eac h of the m .

Make Quality Number 1


There is nothing more important than d e li ve ring a quality product to custOmers- they simply will not
tOlerate any thing less. H owever, different people have different ideas of what quality means, and it th erefore
must be specified and measured. Prime examples of quality are how closel y softwa re meets the customer's
requirements, h ow man y (o r few ) defects it has, and how much it costs to produce . Q ual ity measures nee d to
be speCified in advance to ensure the correct targe ts are being pursued and m et. Thi s book contains several
chapters devoted to quality but , m o re important, the notio n of quality is behind m ost of its conten t.

High-Quality Software Is Possible


Although it may be difficult to produce hi g h -quality softwa re , following mo dem softwa re e ngi neering
me thods and techniques has proven to meet reasonable quality goals. Exa mples include invo lving the
customer, protOtyping , cond uc ting inspections, and employing incremental so ftware processes.

Give Products to Customers Early


Many software projec ts fail because customers are g ive n th eir first look at so ltware too late in the developme nt
cycle This was a maj o r m o tivation fo r the Introd uc tion of agi le methods It's virtuall y Impossible to know all the
,equi rement ~ in advance, and invo lvi ng c ustomers as early as possi ble is critica l to ge tting th e req uirements right .
Thei r ea rl y invo lve me nt in h e lping to s pecify requirements is very important, but giving th e m wo rking software
and having them use it is c ntica l to und erstand ing what th ey rca ll y need. C us to mers ma y think they want a
particularfeature, or think th ey want a user inte rface to look a ce rtain way , but un til they ge t a versIO n of software
to work with you ca n never be ure . Employ ing l ec hn ique~ suc h a ag ile processes, pro totyping, or incremental
processes a llow c ustomers to ge t softwa re into th eir hands early in th e devel o pment cycle

Use an Appropriate Software Process


There arc many 50ftware process models, and no si ng le o ne IS appropriate for every ty pe of project . For
example, th e waterfall process work, wel l fO I' rrojcct~ w he re a ll o f th e req UIre ment arc well kn o wn up front.
Conver.e ly , aHil" and ot her ,tera tive pmcc,sc< arC a il ed lo r w he n fe w req uire m e nts are kn o wn In advan e .
Good sofrwar engInee rs and projec t I 'a d c r~ take th e tim e to und c~ t"nd th e type of projec t bei ng unde rtaken
and u ~ an aprrop n 3tC model
'2 CHAPn:R 1 TtlE GOALS AND TERMINOLOGY OF SOFTWARE ENGINEERING

Minimize Intellectual Distance


Th" pnn ,pic say' that (or an software <olution to a rcal ·world problem , Ihe structures of both the ~oftwarc
, lul, on and r~al . world prob lem should b~ a ,i milar a' pOSSible . nlls was Illustrated In Figure 5, show ing how
ob)e t·onen t3110n can 0 hi eve this objective The closer Ihc S lru~ lurc< arc 10 each olher, Ihe ea,'er it " to
develop and Illalntalll thc so flware

Inspect Code
nm should be extended 10 read "In pect All Artifacts," where artdacis arc defined as any product of
the software development process including technica l specificati ons , test plans, documentation , and
code. Inspecti ons have been proven 10 Ind errors as early.< possible, increase quality , and decrease overall
prOject co t.

people Are the Key to Success


H ighly ski ll ed , motivated people arc probab ly Ihe most important factor contributing to the ucees, of a
software project . Good people can make up for a variety of obstacles including poor tools, insufficient
processes, and unforesee n problems. Good peopie will figure out a way to overcome these obstacles and make
Ihe project a success. Poor performers without any of these obstacles will probably still fail. Hiring and
retaining the best people is critical to prodUCing high·quality and successful software.

So far, we have discussed the parts, principics, and activities of software engineering . Assuming that thesc
are understood and assembled, we need 10 understand the socielal responsibilities of software engineers.

1,6 ETHICS IN SOFTWARE ENGINEERING

Reliance o n the ethics of software engineers has become an essentia l part of contemporary culture. To take an
example, it is simply nOI possible for a car driver to verify and validate the code for his car's cruise control or
for a patienl or rad,ologi sl 10 verify the correctness of the code controlling the X·ray machine pOinting at his
head. At some poinl, there is no choice but to assume that Ihe software crealed and installed in these and
other systems has been implemented correctly, and in a manner consistent with the public interest. This is a
matter of ,)hies.
The Mrrri.rn- W,h,'rr [ 12J online dictionary defines ethics as,

I the discipline dealing with what is good and bad and with moral duty and obligation
2_ a set of moral prinCiples

Most disciplines operale under a Hrict set of ethical standards, as published in a cOllcsponding code of
ethics, and software engineering is no exception . The ACM and IEEE have joinlly developed a o/flDarr
E"9i"rffln9 Cod, oj Elhies and ProJ",ion.' Prac)i" [ 131. The ACMIIEEE·CS Joint Task Force on oftware
Engineering Ethics and Professional Practices has recommended the document , and the ACNt and
the IEEE·CS have jointly approved Ihc standard for leaching and practicing oftw.,.., engineerins_ The
code includes a short and long version , with the shon version listed in Figure I.S. The shon versIOn descnbcs
Ihe code at a high level of abstraction . The long version cont.ins a number of clause corresponding to Nch
of the e.ght principles in Ihe short version, wilh each clause providing mo,.., details and examples. 80th
versions arc conlained In [ 131.
ETHICS IN SOFTWARE ENGINEERING 13

PREAMBLE
The short version of the code summari zes aspirations at a high level of the abstraction, the clauses that arc
included in the full version give examples and detail of how these aspirations change the way we act as
software engineerirlg professionals. Widl0U! the aspirations, the details ca n become legalistic and tedious,
without the details, the aspirations can become high sounding but empty; together. the aspirations and the
detatls form a cohesive code.

Som..'are engi neers shall commit them elves to making the analysis , specification, design , development,
testing and maintenance of software a beneficial and respected profession. In accordance with their
commitment to the health , safety and welfare of the public, software engineers shall adhere to the
following Eight PrinCiples,

I. PUBLIC· Software engineers shall act consistently with the public interest.
2. CLIENT AND EMPLOYER· Software engineers shall act in a manner that is in the best interests of
their client and employer consistent with the public interest.
3. PRODUCT· Software engineers shall ensure that their products and related modifications meet the
hig hest professional standards possible.
4. JUDGMENT . Software engineers shall maintain integrity and independence in their professional judgment.
5. MANAGEMENT· Software engineering managers and leaders shall subscribe to and promote an
ethical approach to the management of software development and maintenance .
6. PROFESSION · Software engineers shall advance the integrity and reputation of the profession
consistent with the public interest.
7. COLLEAGUES · Software engineers shall be fair to and supportive of their co lleagues.
8. SELF · Software engineers shall participate in lifelong learning regarding the practice of their profession
and shall promote an ethical approach to the practice of the professio n.

Figure 1.8 Software Engineering Code of Ethics and Professional Practice


SOUrce: ACMIlEEE-CS. Software Engtneerlng COde of Elhlcs and Prolesslonal Practlc~. copyrIght j"l IEEE.

These precepts have practical conseq uence~ and ca n help guide a software e n gi n ~er toward a course of
action when confronted with a difficult si tuation . A few exa mples follow ,
Example I. Suppose Ihat your manager asks you to joi n a tcam at work and assumes you arc suf~ iently
skillcd in J~va . However, you don't know Java , but really want to work o n the project and think you'll be
able to learn it quick ly and learn a valuable ski ll. Do you mention your lock of Java knowledge to your
manager and risk berng pulled from thc project, or do you say nothing, evc n though your inexperience
cou ld Jeopardize the success of the project? Clause 6.05 provides guicance, "Not promote their own
rntcrest at the expense of the profession , clrent or empl oyer." Knowing th is , you could inform your
manager that you do not currently have the necessaty Java knowledge , but present a case at the ame
time for how you will lea rn enough in trnle .
Example 2 . A software engineer workillll on ~cvcra l Rovernme nt contracts is "e n ouraged" b
management w charge time aga "' ~ 1 the onlraCI wrth I'he h il< h e~t number of available h u", ~ hat
do you do? Gurdane (or th rs is provided ny clause 4 04 "Not eng"He rn de cptl"c ~nanc lal Pr.l ti es
such as bribety, doub le billinll, or olher inlproper Anancla l pm tl e< "
14 CHAPTER 1 THE GOALS AND TERMINOLOGY OF SOFlWARE ENGINEERING

Exomple 3 . You are asked to develop a complex, c ritl 31 pie c of softwa re for a commercial product
you're working o n. You di s ove r a publ i do mai n version o f the ' ou ree cod e. You're tempted to use the
source code as It will save mu h ti me and effon and allow you to move o nto the developme nt of another
Important part of the sys tem soone r th.n expc ted However, It's not li censed to be used fo r commercia l
purpo cs . What do you d o] Clause 2.02 provides gu idance: "Not knowingly usc so ftware that IS
o bta ined o r retained ei the r illega lly or unethica ll y."

These arc just a few exa m pic> 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 develo pment of a g roup proJect. As they progress,
is insufficient for gai ning a thorough understanding students will ge nerate project artifacts and working
of the ubjec!. The best way to unify and reinforce co de. Artifac ts gene rated as part of the case studies
the man y topics presen ted in th is boo k is to ( I ) learn can also be used as guidance in developing artifacts
how they are applied to the development of real for the group project.
software ap plicatio ns and (2) gain hands-on experi· There are three cases studies used in the text,
ence devel opi ng a software application as part of a as illustrated in Figure 1.9 . The Eneo."/tr Did,o gam , is
team To mee t the Rrs t objective , case studies have a si ng le·p laye r, stand-alone video game application
been developed o r described and are presented that is completely implemented through the course
thro ugho ut the book . They serve as concrete exam - of this book in conjunction with online compo-
ples of software appl icatio ns, a nd include appropri- nents. In addition , two open source projects are
ate artifacts as they are discussed and presented in used to illustrate h ow open source prOjects are
the text. The case studies arc intro duced in the next devel o ped: the Eclipse integrated development envi -
few sections. T o meet the seco nd o bjective, students ro nm ent and the Op",Offic, office productivity
working in teams arc provided guidance as the y suite . Open source projects arc developed differ-
apply so ftware engineering concepts to the ently from traditional software in that many

Encounter
(created for this book)

1
Case Studies

Eclipse OpenOlfice
(open source) (open source)

Fllure 1.9 The main case studies used in this bOOk


CASE STUDIES 15

difkrent !><,ople, from ariou> orga nIza tIons, de . Ihe Jo"i9" character. C haracter> engage each other
vc\op featun..'S and fun tions and thcn co ntribute when they arc in Ihe same arca atlhe arne time. The
them b. I:. to the ba e ·oftware applicatIon . In this rc ult of an engagement depe nds o n thc values of the
wa an open sourc appli cation grow in fun l ion. haracters' qualilie and on the locatio n where It
ality and all ne," fea tu res arc free ly avai lab le for occurs. O nce an engagement is complete, the play·
o thers to use and budd o n. er's c haracter is moved 10 a random area . Players can
Variou o ther examples arc used in this book , se t the va lues of the lf qual ili es except while engaglOg
includIng a vidco store app \'ca tlo n. 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 . 1.7.2 Eclipse Open Source Project
alone VIdeo game applicatIOn A player is assigned a The seco nd case ludy is Eclipse . Ecl ipse [ 14] is an
main chara ter, and Encounter si mulates all o r part of extensible, highly co nfigurabl e o pen ,ounce IDE
the lifetime of that character Success in playing the (integrated develo pm ent e nviron ment). An IDE pro·
game is measured by attaining a '1, points goa l for the vide an enviro nment and sct of lools fo r the devel ·
playe r or by the ability of the playe r to survI ve fo r a op me nl of softwa re app lications. II provides loo ls to
give n time limit. Figure 1.10 shows a ty pical scree n build , run . and debug app \'cati ons, the abili lY 10
shot: the courtyard area co ntaining a playe r· share arllfacts such a code and object WIth a
contro lled charac ter, Elena. tcam, and suppo rt for and intcgral10 n wi th vcrsion
Came characters beg in wit h a nxed number o f contro l. lkcallse Eclipse is o pe n source, ILS source
points allocated equally amo ng qualities including code and des ign arc fTeely available and readi ly
coneal tration, stamina, inltlligftKt. pali(Jlct. and strnlgtb . extensible by th ird parties thro ugh the use of
The game co nsists of movement among a set of plug · in s. In fa ct, Eclipse is co nsidered a plaifo,," . It
areas. The main characte r moves between them , isn'l a '·flni shed" product, and is intcnded fo r contin o
encountering a game · generated character ca lled 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
16 CHAPTER 1 THE GOALS AND TERMINOLOGY OF SOFTWARE ENGINEERING

, o ur<:c cx tcn'lons c..a n b fOllnd JI lhe home of lhe ,"cr Interfa e a nd fe atUre set s lInllar to o ther ol~ce
E lip,e ProlC t, www .ceilp ·c org. ,u ll e> suc h a, M lc roso fl II,ce OpcnOlflce org also
Eclipse ha, bee n ,ue (",full y used ~, ~ tool for wo rk, lran'pa re nti y With a Va rtCIY of Ale formats,
wide -ra ng ing app lic ation t pc, ,uch ", J~v~ d evd o[l- Including those o f MI ro solt OlRcc' [ 16 ] A tYPical
Illent, 'I cb services, embedded d cv lcl' programming, O[lc n fr, c' >c reen, hot IS s hown In hgurc I 12
and ga me program ming CO il tes ts. T h e Ecli pse plat - The Orc n frlCc proJc 1 encou rages partlcipa -
(o ml itself provides a programming languagc-agnot\ti lio n by d eve lopers, as ,he tYPical developer-o rie nted
lofTastnlc turc. uppOr! fo r specific lan guages IS pro - Web page ,ho ws in Fig ure 1. 13.
Vided b plug · in s, and ea h plug -In must ad he rt· to th e We w tll dt<cu,s the management of the O pen-
<a me niles as a ll th e o th er plug-ins that u,c th c OfRcc projec t In rart II I. H ere i a summary, quoted
platfo rm [ 15 ]. Su pport fo r the Java prowa mming fro m a n Opc nOm c Web si te .
langua ge IS p rOVided by ,he Java Developme nt T ools
UI T ), w hic h is bui lt on th e Ec ltp e pl. , fo ml a nd There a re three categories 01 ac ti ve proj -
provlde< • fu ll -featured Java IDE. ects in O pe nOlfice.o rg : Acap"d, which
A typ ica l Eclipse scree n hot is s ho wn in IS whe re most tl'chni ca l project art:
Figure I I I loca ted , [ncubalor. w h ic h hou es ex pe ri-
me nta l projects and e nd eavors, a nd
1.7.3 Open Office Project Nalia, -u"'9 , whic h includes proje c ts pro-
Th e third case stud y that we Will u<e in th is book is vi d ing info rmari o n, resources, builds/
Ope nOfRce (ope nofRcc.o rg ), "a multi -p lat form of- and forums in a user's nat ive language.
fice produc ti vity suite . It incl ud es the ke y d es kt o p
applications, such as a wo rd proce sor, spreadsheet, The Accep te d Projects at a POlOt . arc
- .In [fme
presentation manager, and dr2wing program , with a sh o wn in Figures 1.14 and 1.15.

,
• CD hd'1"" ,"01 II I' o:'>'>rpo.f"~U''' ? tar....
'l'!_." " 'A
fe"
• .,. 'I~III~ ~ ""-('YO'\l ,",'I' ", _ 2 _ ""''':' _ '.rla'.
• ..... _ _ _ ,,_,.- ' ''1'' Uo. l _ .. , ~. . ( ....... h<: ~I ..... " " 1. 0
· ",.-1\ _' 1'.'_. l"'. I,.
7 •

ct •• n ...... k> .... ,.,.,. _' . ~J . 'O r


.. an " U;". ~ I o.unl • nUI/I ..... "II_.o.cWl _o- V.., ,_eO. Tlu.1
5J f'''_ ~~

• 4 " L .. ..... - :
• c.. .... ,~ ..· ~ t •
.,. '" """ . Iln.~'-
""_
r; •,, •-c-,
'L-""_
..,.......z" _ or'\OI.Q ... .
• It' Co .~r.~\cc I~ I \ ' .I "I ..a I~I~ · .~ I ••
• •• •• • ••••• ••• ••••• •••••• •• ••• •• ••• •• •• ••• ••• ••••• ••••• •• • ••••• •• • •• ••••••••• ••

· -.
..., . ~

- "
. ".
•• q
, _
q u . ... oJ
rt d o,
.
..........

: - rl l _ . U . .. 1 OCu~p ... LO'"

..
• .

...._ ' , '''''''' ••• d " .....
' " '.II: ~ ... _
. rl leV. .. u. l . . oo<.J\. ... _ .

••
• . .,
• C<"'!JI . ~'"

,,·"at _ .
. . - . . . .': 7 " ~ ...
= ..vfI ....".
·
.
• ( .... ~ •• _f , - , , _
·,
..-
. 'L
..
-~
.-s,. _Ib-..., ~. 1 .~...al l .
~
,.... , - . . _ I .......

.
• ~ .....u ../0> .. - 11I..u
,-_ c.. • CI'm ..... , . P - • I

• »~ - -
.


..... ~!)

L I'* . ~
;Jl....ul
· _ . 1(-'''''-
• ~UN r 0

.. -""'"
• . . . .:.:0 . .. ""->
"
,..
• Rr+ .,rtf .....

·.-,"
8 ,," ' ,, _ 1' " ....
• 5' , , t ab ' o. "




~ .. "'Io ....... 11 ~'..... .
1M If'~ ''a,d,o. ~ .If ~· ' Tr*'
,t. IIfId.I". ,I,.. , ~~ . .... ~ ...... ~. .. 11. ~

FIgure 1.11 A typical screenshot of the Eclipse Interactive development environment


CASE STUDIES 17

" iii
• • le 31 .... . 1

I nu s u· an OpenOfI1C c Tal documer.t -

•If

Figure 1.12 A typical screenshot of the OpenOffice word processor


- d

-
SurnnHomc
Ruourc.~ Mit 1'1 0 LIII,I OOCIIIMMill -1Jn I S!)VfU CCdt

list' SUM, (en)


Consul't01nlS SuMY
Thank you!
Opcnom ce.ofg :
An Inlmdurtfon
Ab(!1It tb
Qotvm~nU! IOf! Wher. to 10 from h' f.
QP':nQ!!i( r Otg W. M, yOtJ 10 ""'Mt wit.c 1 ~' Q ;:,nOma Qrg"""DSJI"O gfn acquaonled WUI 0lJf c~ ,. OIJI
rn J NU!,h• • ptOflCl' and our way of brng You should Coro.llMI m411'19.At !rIISIM'?'!, to 0pen0l'IIc.. 01]. Iht
/!kmA Us P'gt . 1M DorWDfnli1'2n. lht Op"nO!!}!;' gIg ID' NysH,,' pllge. W lhe P'Sart, ~
Then you mighl consllife, 'Inldpdn!)
Our cOtJ\lTIlJnlly If open for atlJor;e 10 pMJaolhf No matstf If you II1t fIG( • i»Uv"rntnet 01 a
Itchn,cal orieratd person, ttlilt lJ II pitH fOf you In Oft. Of I\"\Of't of OUi PJOJKfS 10 htlp the
d .... lopmtnl. mpro..lI'Ilrd Of p1orTIollOfl 0111'1, OpenC)!F,ct 0" " . . . . . . 'l.IIIf

By VI, 1111 of t~, Tho W ~'P IniO 11'1, p.nlClp.ahon IS by tvbscntll1'l910 ont Ot mol' dour nwting ~1t1 !PI''''' !1'I_
Webt"' , tOY :agrtl piCj.Cl(t) ~ fHI you I;iln h.M • cOl'llnbuJ lon 10
10 ~ bound by
Ihn. Po tNt:

IT)(I 8t1ow otl. 5OfI'\f of our m*'9 1m. that nvgl'll bt fA V'dtfHl F 01 • MI ~lI\g plU M -cit the MI,t'"'
firm' Qf Un US" pag. on OpnQk. R'q "b ...

I. 1

" p rlC ?, t nt . . . .

-
....... . .. ; LIl . . . . . . 01 2 oOIl1ee org ..... (rd art i)1
9' ' ytJI" 'om,... yG,I,.... ,...,., ...... ......,

Figure 1.13 Typical OpenOffice communication with development


18 CHAPTER 1 THE GOALS AND TERMINOLOGY OF SOFTWARE ENGIN EERING

...
~ '5 "em (ramewcrt Mllbecs "",,[, ".arne.crt
,ml'O
Dotsn.r
Atrir!tgg!sand M@!l" tOOls
fnylRM\tO l HoBmICbcl

frW db,
Scboenhft!!.
DO. RPbll!;[

Dos:ument,uQD scopn Ctq documt,.,tttion End·UHr docu.... "t.t"'" (fK t~ V¥IOVS c:onlpOittnu ~
Up ap.nOfficu"V·
k lrml! MiOia 'ICtemal This pr'CIJ.ct will ho,t .. lh. __ tem. C:(IIM aIow~
Honms,hr!
(K Il09)

11'11 Ahrrn, .
Chosl,.!)

\jrM!ht, SYit'm I tytr ChaSSQf


prof MIt •. ••
H,DOH Pgbfng
PO Y09l;t.

Figure 1.14 Accepted OpenOffice projects at a point in time. 1 of 2


SOUrce: OpenOfflc.e. http://projects.openofficeorgtaccepted html

! 'Y"/lfS'P' Pitt. liOn


- -

MartetllQ ,Nwhtng The POJKt I\.nt. '''0 ow 9uwth -.d use 01 0) lilCimc. oPt
tK~" . errc.u iI'K'tudIt: dItv,' ,.- .. eol'teroll. ':If1I,
pot'r: outt...ch.
PonWig to ,..... ~t1'oii'iS .

C),IIity AmI..ce: t . .mt and Q',"fwlC'l9" tIuiIdI of


801Ml.r. SCRtt o;.:nO....OI9
CIII. Cgn:Ion
Sh!.!m

Sr..skbg' lM'1a Nlbtl , ~ The",,!' '.,.t ... ' ertlan.


fih Rithi.

"'*" ;sal'tlya:c-.. ce,'j It tltlo


YoX'D" CgntBl'
. .. ,.
MtUn u
.,·"Sb,
.".,

I.U: 10'''''0 .
-- LAII.JiWIIIM:
uti
••• ...
.. $ 12 • ~.
-: ... _-_ ...
or 1M PIrIIjICt.
i TIl.

Pet!',
- .. 11= wad ... C~

Figure 1.15 Accepted OpenOffice projects at a point in time. 2 of 2


1.8 SUMMARY

Developing complex software systems in a successful mann~ r has historically been very difficuh. The goal of
software engineering IS to define a fra mework for creating software systems that are reliable, efficient, and
maintainable, and meet the needs of customers. As illustrated in Section 1.2 on software disasters, producing
software that is unrel iable ca n have catastrophic consequences Although most software does not end in
disaster, care mu t be take n to avoid the many commo n pitfa lls and mistakes that can plague a software project .
The 4 P's of software engi neeri ng-people, product , project, and process encompass the different
aspects of defining, building, and mana gi ng software. The people arc the mo t important part , as they not
only create the software but also are the customer for who the work is bei ng do ne. The work products
include not only source and object code , but also a complete set of artifacts descri bing the system. A software
process model dennes a framework for ca rrying ou t the di ffe rent phases of a software project. It imposes order
and stnlCNrc to a project.
Underlying software engi neering is a set of time- tested principies. KnOWing these prinCiples helps to
understand the mo tiva tio n for the softwa re engineering methodology presen ted in this book
Software engineering is a profession that carries with it certain ethical respon ibilitles. The ACM and
IEEE have jointly publi hed a code of ethics to he lp gUide software prolessionals in their work .
This book uses three main case studi es throughou t as realistic examples of software project

1_9 EXERCISES

1. Besides those listed in this chapter, what additionai expectations do you think oft-ware products
may fail to meet?
2. Research a rece nt real-world "software di aster." In you r own words, describe the underlYing cause
of the problem . What could have been done to avoid itl
3. What ar~ the four P's of software engineenngl (Reca ll them without consulting the book .) BneAy
describe each .
4. In a paragraph , name at least two of the most impo rtant deficiencies you can think of In the rrporil"g
of project progress that co ntribute to an unsuccessfu l projec t outcome.
5. Expla in myour own words why people arc invariabl y the most important resource o n a project.

6. For the stakeh older groups listed in the text, give an example of a project mOllvatio n fo r each_
7. You arc developing a second-generation custom order entry application fo r a particular customer
Explain and give examples of at least two types of problems that can arise if the customer is nOt
involved in defi ning the new applicati on, and their first use of the application i after it i com pleted
8. Why does the use of standards make it eaSier to ge nera te usefu l, re liable docum entsl Wh y isn't
their use a gua,".'t< that hi gh-qual ity docume nts "ill be produc<:dl
9. Expla in the di ffe re nce between a oftware process and a so ftware process model.
10 . Figure 8 lists the ACMlIEEE Sojlwart E"gi"rrri"g oJ, oj Elhics .IId P,ojtS5IoII.1 P,ac';Ct. Drawing eit her
fro m your own expe ricn c~ or from a hypothetica l Si tuati on , aescribe a sce nano that adhere to one
of the e ight pnnclples. Now describe a sce naroo th at Violates o ne of the pnnClple<>
Metrics in Software
Engineering

• What does ·sohware quality" mean?


PlaMlng
• What are ·defecls· In applications?

• What IS the difference between


verifica tion and validation in software
The Software development?
Development
Ule Cycle
• How do you measure software
quality?

o.Ign

Figure 2.1 The context and learning goals for this chapter

Budding sofTwa re that ex hlblt< a lu gh level of qua li ty" one of the majo r themes of till book and !< J
c rll lea I faClor in the produ t,on of ,"cce"fu l <oftwarc,y tem s However, a h,cvlIlg a 11I gh qllallty level I< no
easy task Qua lity must be Int c~ra ted '"to project' fro m the bell lnn lll"; and dunng every pha. c f produ t
develOJlmenl This IS why qua lllY!< d"clMed throllgholltthe hoo k and" be ing Intrud uced at Ih" carl <lage
Throughout the Ide of a software proJe I, data o r mcaSllrcmcnt<- are o ll eLlcd t aseen,," the
elf cllven s. of the: processes emp loyed and the , oftwarc helng CO " 1/11 tcd S" h lat. arc ailed '""n"
22 HAPTER 2 INTRODUCTION TO QUAUTY AND METRICS IN SOFTWARE ENGINEERING

Planning Maintenance

Integration and
Phaaes Requiring -
System Testing
Quality and Metrics
Requirements /
Anal is J
IDesign I Implementation
and Unn TesUng

Figure 2.2 Software development phases requiring the application of metrics

These mea<urc various a pects of a prOject sllch a the qua lity level of the software itself, and also the degree
of the proJect's adherence to its schedule and o ther measurables suc h as the productiVIty of e ngi neers. This
c hapter provides an overvIew of software metrics and an explanation of how they relate to software quality
Each of the major parts of thIS book contains a c hapter relating how quality is practIced and metrics
collected and applied to the development phase covered in that part. Figure 2.2 depicts the d ifferent pha~s
reqUiring quality practices and metrics collection.
So fa r, we have used the teml "software quality" quite freely _ Now we'll provide a concrete definition.

2.1 THE MEANING OF SOFTWARE QUALITY

Everyone wants "qua lity," but what exactl y does software quality mean] There are varying views o n this. Some
measure qua lity in terms of categories such as reliability, portability, and so o n. H owever, if one of these-
portability, for exampl e-is not a requireme nt o f the product in any fOffil , then it is not releva n t. Some feel
that the mo re an application c han ges the wo rld for the better, the mo re quality it possesses. Others defi ne
oftware quality in temlS of how well a development process is followed , or how ex:ensively the emerging
product is tested . Ultimately, it is hest for a n o rganization to defi ne fo r itself and its cu.stomers what it means
by "quality ." Above all, it is importa nt that "software quality" has a consistent mea ning within the project's
stakeholders. A definition fo llows that will be used throug hout th is book.
To give some background, let us first co nsider a "quality" plain old -fashioned lead ~ n ci l (frequently
yellow). All would agree that such a pencil mu t first sa tisfy its requirements, typically including that it ·shall
be solid wood; shall have a lead core with designated hardness; shall have an era er that can erase most of
what the lead has deposited o n plain pape r, shall have the required leng th; etc." To be a 4uality o ld-style
penci l, however, we expect additional attributes suc h as that it is "harder than usual to break, lasts twice as
lo ng as average pencils, has a very cf/cctive eraser, etc." To summarize, a quality co"vrnlio"al item has attriootes
beyond its requirements. In software engi neeri ng , however, this is "01 the typical definition of quality.
What is different about software appli cations is that they inevitably contain defects. Every defect is a
deviation fTo m requi re ments, regardless of whether the requirements are carefully written down . Hence we
cannot think about the quality of software the same way we think about the quality of a lead pencil. Instead, a
good deR nition of software quality IS the follOWing:

The more closely a software product meets Its requII'ements, the hig her its quality .

Figure 2.3 illustrates thIS view of quality .


DEFECTS IN SOFTWARE 23

Requlr •. ".nte 100%


(."4 ren. Ind ~)

0%
\
~
,
\
I
I
I
Typical quality focus I

Figure 2.3 The meaning of software quality: the degree to which the actual requirements are met
.$Otft'e. Q~ucs reoroctuced Wtth Dell 'us.s.'on from COfel

We have not yet di cussed how requirement are gathered and generated . For now, let us as ume that
requirements arc generated with the be t kno wledge available during requirements analysis . Even in this case,
after the software has been developed and the product has been shipped to custome rs. it may be discovered
that some requirements are in fact incorrect or missing . In these cases the software is co nstructed usi ng the
requirements as documented, and we would say the software meets all its ncplicirly specified requireme ntS but .t
may not fully satisfy its customers. There are a number o f di ffe rent ways thi s can happen .
As an example, if customers are not consulted during requirements den nit. o n the system i constructed
without their input. When they eventually usc the so ftware they may nnd it does no t function as they wish and
are dissati fleet Even if customers are consulted and provide input, it is possible they will sti ll be di ssatisfied o n
using the software. For example, suppose that a software system implements a user interface, with scree n
layouts and menus specified in a requirements document . If customers are not given an o pportuni ty to use the
interface before the product is released , they may nnd that what appears to work well o n paper is actually
cumbersome to use. In these scenarios and others, we would say the product docs nOt exhibit high quality
because it does not satisfy the customer. Therefore a mo re compl"te definition of quality \~ould be,

The mo re closely a software product mee ts its specined requirem ents, and those reql11rcments mee t the
wants and needs of its customers, the higher its quality .

T echni ques for gathering requirements and ensuring customer . atisfaction arc covered in Part IV an
requirements ana lys.s.
Besides the benent of custome r satisfaction, producing high.quality software provide · other adva ntages It
has often been shown that a correlation exist betwee n products with the least number of defects and the honest
schedules. There .s also a corrclaiion between poor quality and chedulc overruns, and hetwee n poor quality and
increa<cd project costs. The mo re defects there arc in software, the mo re tllne cngineers spend fiXing them,
taklll8 time from other imponant project tasks. Also, the more defects that exist, the more likely that software
changes necessitated by fI.lIlg these defects wi ll themselves result in mo re defe tS For all these reasons and more,
quaJ.ty .s one 0(- the most .mportant atlnbutcs .n <oft ware and a key co ntrihutor to it, uccess.

2.2 DEFECTS IN SOFTWARE


A dt/a:l1Il a pha,., of software appl.ca tion .s defined a< a dev.at .o n from what'< reqUIred for that plu e. In pr.1 l1 ~e ,
most software system~ Lo ntaln def· t, and therefore do not ent.rely meet their rcqlll rc meOl\ TI,e software
d.S3stc...., described.n hapt r I i1lu<tratc the co t of dd ctS III the ten and cw o hundred,- of mill. o ns of
dollars f)dect~ can be introdu d at any Skill" .n the development proces<. A m"J'" I(oa l of , ofrwarc en!:",een ng .
24 CHAPTER 2 INTRODUCnON TO QUALITY AND METRICS IN SOFTWARE ENGINEERING

Idellllf InR and remov ln ~ a, malty ddc t<as I>o\<;blc, a. ea rl y as pos"ble, throughout produc t development, eithcr
b ' ,nspccho n 0 1art lfa ts or te,'lng of the system For examp le, II ,oftware 15 ,n the ImplementatIon phase, the code
Illa d viatc fro mthe>ofiW'lre de,,!!n f> roduced In the preVlou deSIgn phase, o rot may be coded in soc h a way as to
produ c an incorrect out put n,e Ie<ult o f either a<c ISco ns.dered a defec t In thIS partl cular casc, an.n pec llo n of
the ode prior to testing 1< conducted, wIth. go. 1o f .dent, fy ,ng as many defects.s posSIble O nce the software IS
full y lI11cgra ted into a sy\tcm, testing is co ndu ted to e nsure that It conforms to the specIfied requIre me nts.
Defec ts arc the cleare t man ifestatio n o f a qua lity . ho nf.11. The latcr in the deve lo pment cycle they are
d i. overed the morc they cost 10 rcp ai r. n,erefo re two qualoty goa ls of software devciopme nt processes arc as
fo llow ( 11:

I. T o remove a< man y dcfe ts as is reasonabl y possi ble before the produc t is de love red to the c usto mcr.

2. To remove as many of these defects a ea rl y In the development process as posSIble.

T o the A,,; t pOint , defec ts discovered and «'paired durin g softwa re development will no t be found by
custome,,;, of cou,,;c. The more defec ts that ca n be removed , the higher the quality of software is likely to be,
and the mo re the cu tomer will be sati sAed .
T o the seco nd pOllll , as softwa re is developed a nd defects are introduced (which is, in practice,
Inev.table ). the earlier they arc discovered the less they cost to repair.
Acco rd.n g to Boehm [2J and o the,,;, the cost of defect repair after software is released to custome,,; can be
100 times greate r as compared to Axing the same defect early in the devciopment cycle. Various studies show
various cost esca lat.o n factO";, but they all rep ort a dramatic rise in the cost of detection and repair. Figure 2.4
shows o ne est. mate of the relative cost of defect repair during each stage of development . Fo rc xample, if a defect
is Int roduced dUring the require ments phase, assume that itcosts $1 to detect and repair if done during that same
phase. If it slips through to the implementation phase, the same defect will cost $20 to rcpair. If it falls all the way
throu gh to mai nte nance, which is when custo m",,; arc using the software, the cost can be $100 to repair.
The reason for this .nc rease in repai r cost in subsequent phases can be illustrated with an example ( I ].
Suppose you have an application that perform s a large number of Alc reads and writes . As part of your
devclo pment process, at the e nd of the design phase you conduct an inspection of the design and discov"r
two defects: o ne in the algorithm that performs file reads and writes; the other in the allocation of memory to
ho ld the file records. Assume that the work required to fix these defects after the inspection takes two days to
complete, and the steps take n arc as fo llows:

I . Mo dify the algo rithm to fix the defect.


2. Conduc t an inspec tion o f the reworked design to verify its correctness.

Requirements ~ ~ Malnr-nee

O••lgn 1-- Implementallon _ T..t

filii" 2.4 Cost of detecting and repairing a defect during maintenance, depending on the phase in 1/1ieCled
VERIFICATION AND VAliDATION 25

Suppose, ,"stead, that the defects went undetected and pas~ed through to the implementation phase.
The dcf«ts would be: harder to detect and could now affect several hundred lines of code. If the defect5 are
detected during a code inspection, the work required to Ax them could take a week to complete. The step
required would be: as follows :

I. Modify the algorithm to Ax the defect.

2. Conduct an inspec tion of the reworked design to verify its COrr«tness.


3. Recode the affected portion of the code .

4. Conduct an inspection of the reworked code to verify it is correct and co nform s to the re wo rked design.

Suppose now that the defects went undetected and pas cd through to the te n ng phase. The defects
would be even harder to detect and now take more time to fix . In addition to the o nc week reqUired If found
during code inspection , the following additional work would be requ ired :

5. Assistance from the tester to recreate the defects.


6. Discovery of the exact cause of the defect within the software.
7. Dedicated machine time to support debugging .
8. Retesting the fix to enSure it works correctly.

These activities can take an additional week to a month , dependin g o n ho \" dlrflcult it is to isolate and
repair the defect. This example Illustrates the cost of not detecting and re pairing defects as close to thei r
injection as possible and wh y every eHort must be made to detect and repair defects as earl y as possible .

2.3 VERIFICATION AND VALIDATION

Software verification and validation (V&V) is a process implemented througho ut the software li fe cycle to
ensure rhe 101i0wlOg.

I. Each step in the development process is carried o ut co rrectly . Thi s is ailed v"ijica lio .. .

2. Each artifact produced meets its requirements as speci fi ed in pri o r phases. Th is IS ca ll ed va/ldalion .

The IEEE Glossary [3) defines these terms as lo llows.

Verification: 'The process 0 1 evaluanng a system o r co mpo nent to detennll1e whe ther the
produc ts o f a give n devel o pme nt phase allS fy th e conditio ns impo cd at Ihe start of th at phase."
Forc xampl e, is the soltware design sufficient 10 impl ement Ihe preVIO usly speCifi ed requirements
Does the code full y and correc tl y Imple ment the d esi g n ~
Validation : "T'he process o f evaluating a sys tem o r compo nent durms o r at the end of the
develo pme nt process to determine whether It sa ti fi e pecifi ed reqUirements." In o ther wo rds,
does the Imple me nted system meel the spe Ined user requ ireml'l\lsl

Vcr;fira llon .. om parable to keeping your balance current 111 your he kbook based o n vour dall actl It '
As you Wrtlc c hecks and make deposit , you c nt erthe amount In the c heckbook register MI d upda te the balan c
26 CHAPTER 2 INTRODUCTION TO QUAUTY AND METRICS IN SOFTWARE ENGINEERINQ

1:..
h time u make an entry you heck that your anthmetlc " correct and your new balance I~ right Thi, IS
anJlogou to e n,uring that each phase ,n the ,ofiwarc devclol>ment 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
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 validation-
primarily," 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 + b= c that is within 1/ 1000 of the
mathematically exact answer.

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 <tandards t
help meet thIS objective. These, and <l.ndard, lIke thClIl , tend to be emp loyed In larller project< that are not
"gile or that emp loy a~ilc m~lhod s on ly partIa ll y
The Software ualtly A"uran Plan ( QAI' ) (lEE td 73 0· 2002 ) i. a do um enl for c, press Ill!; an
overall approa~n to qualtty Ihat IS ~ondu t -d tnrnuu it oul the en ttre ,oftw.r. Itl. cy Ie Major top I ,
28 CHAPTER 2 INTRODUCTION TO QUAUTY AND METRICS IN SOFiWAR ENGINEERING

k l
Artllect PartiAlly
Compleled
undor comploled
artifact
construction arlilaci
Process Process
'1 ,,
A, , " ,, , ,
,, ,, I
I ,
,
,,
,
, , I /
Creation Venfication Validation
• ,, ,
,, ,, /

,, ,,
,
"
Software engineer

Figure 2.6 verification and vahdation of an artifact: before completion vs. after
SOUrc" Graphics reproduced with permission from Corel

included ,n th e pla n arc listed below . Details of the SQAP are covered in Chapter 5. The plan includes the
following ,

• The organizati onal stnlcture of the quality team

• A list of documentation to be crea ted governing the development , verification and validation , usc and
maintenance of the software (e.g., software requirements speCificatio n, verification and validation plan,
so ftwa re deSign pecification, etc.)
• The defi nit ion and schedule of inspections to be conducted and how they are to be conducted
• The metrics to be coll ected, monitored, and analyzed
• Reference to software test plans
• H ow problem reporting is to be managed and conducted

The V&V Plan is t he manner in which the So ftware Quality A'5urance Plan is supported by verification
and validation . The IEEE has published a Software Verification and Validation Plan (SWP) framework (IEEE
Std 10 12- 2004 ) to assist in documenting the speCific V&V practices to be implemented. The contents and
application of the SVVP are covered in C hapter 9.

2.5 METRICS

Metrics arc numerical measures that quantify the degree to which oftware or a proces possesses a given
attribute Examples of metries are "defects pcr thousand lines of code" and "average software module sizl':
Metrics are collec ted and anal yzed throughout the software life cycle, and help with the following ,

• Detemlliling software quality level


• Estimating project schedules
• Tracking schedule progress
• Determining software size and compleXity
METRICS 29

• o.,teml1ning proJecl co I
Improvemen l

When gools such as software qualily level and project cost are not expressed specifically enough, they
m. be subje t to differing interprelalions . The,e difference can ause confusion and conAiet . For example, a
goal stated as 'The application should crash vcry seldom" is not specific. How do you measure "very seldom"? Is
it once per day? Per week? Per year? A more preci e goal would be 'l1,e application should crash no more
than 3 time per year: Stated this way, the goal is not open to interpretation and is measurable.
Without quantifiable, objective measures to provide visibility into a project it is difficult to measure a
project's progress in terms of wh"'ther it is on schedule, whether it is meeting its quality goals, and whether it
is ready to ship to customers. In addition, "you can't improve what you don't measure." Continuous
improvement of an organization's processes and software is predicated on collecting metrics and selling
quantitative improvement goals for future project .
To be uccessfully utilized , metric collection commences at the onset of J project and continues
throughout the entire hfe cycle , through maintenance . Metnc collection and analysis can take a significant
amount of managerial and engineering effort , but the payoff is well worth it.
Software metrics can be classified into two broad categories, prodlici metrics and proms metrics. Product
metrics measure characteristics of the software product , o r system , including its size, complexlry, perform.
ance, and qualiry level For example, size can be expre sed in the number of lines of code, p"jormancc as the
number of transaction per second , and qua lily I,vel as number of defects per thousand lines of code, which is
commonly referred to as defect density .
Process merrics measure attributes of the software processes, methods, and tools employed during
software development and maintenance of a software sy tem . Process metrics include project effort, schedu le
adherence, defe I repair rate, and productivity . For example, proj,el 4Jorl can be expressed as the number of
person months of development , and d,Jrcl "pair ral' as the number of defects repaired per week. Many other
metrics can be collected, and they arc di scussed in grea ter detail in the quality and metrics chaplers later in
the book . Chapter 9 describes metrics collection and utilization in more detail. The next section discusses
metrics and their use in measuring quality

2.5.1 Quality Metrics


Since quality is the degree to which oftwarc satisfies its requirements, we must be able to measure thi s degree
of compliance It.s useful to identify a set of software quality mEtrics, whic h arc a subset of the total metric
collected for a project, These metrics are peclAcally focused on the quality characteri<tics of software and of
the processes employed during the so ftware life cycle .
As described by Kan [4 ), impo rtant quality mctri c, include the following ,

• Defect den i ty
• Mean time to failure

• CuslOmer problems

• CuslOmer satlsfa tion

D4,,' 4tHsily IS Ihe number of defects relative to the so ftware ,izc _ 12 C is tYllicall y "xpre <cd ill Ihou<Gnds
of lines of code IKL ), so d Ie I den\lty i, expressed as defcc tslKL , Remember that a defe t IS defined
as a rlt.'Vlatlon from u,er reqUirements, 50 ddc t dcn\lly " une of the most ha, 1 metl'iL, u<cd IC measure
30 CHAPTER 2 INTRODUCTION TO QUAUTY AND METRICS IN SOFTWARE ENGINEERING

qu~ill . III gcncral. lhe hill her lhc defe I den-Ily , lhe lower lhe qual,lY OrgnnizallcJI" tYPIc.,lIy characterize
defe "h I ' pc or hy ,everily, 10 distlnl(liish lhelr relative Importance n,c followlnK I< an example of how a
11IgIl-<eveni defc t would be dcllned and of a quailty goa l based on the definition.

A la,< I ddc I IS deRned as a reqUireme nl lisled in seCl lo n 3 of the oftwarc ReqUirements


peCll alion lhallhe appilcatlon fails to sat"fy The app l ic~ lion <hall have no more lhan 5 class I
defc IS reported pl' r 1.000 uscrs dunng lhe Arst mo nlh of operatio n.

NOle lhat lhi< deRilltion and goa l arc very specinc and measurable. Again , when goa ls are not expressed
in a quanliRable foml , they ma y be subjecl to differing inlerpretalions. For exa mple, consider an alternative
defi nillon to lh(' o ne above· "lhere should be very fcw class I defec ls reported in the first few months of
opera ll o n " n,ere is no way 10 measure "V(' ry few" and lhcrdore 10 va lidate compilance .
A commo n indica lo r of oftware quallry i lhe reliability of a system , as measured by its availability or
lhe froquen y of <ySlem crashes over a period of time. The lypica l metric used is mu," lim, 10 fai'u" (M I I F) and
is lhe amounl of elapsed time between SYSlem crashes. n,e MTTF metric is often used wilh safety . related
ySlem< such as the ai rline trafRc conlrol syslems, avionics, and weapons. For instance, the U .S. government
mandates lhat ItS air traffic co ntrol SYSlcm ca nnol be unavailable for more than lhree seconds per year [4 J.
Another example an be seen in many telecommunicalions switches, such as those used in cellular networks.
Large network proViders mandate that lhis equipment must have "five 9's" availability, which is an uptime of
99 .999% per yea r, This lranslates to a tOlal yea rly downlime of 5 minutes, 15 seconds . The reader may well
ask. 'Why nOI make the required MTTF 100%1" The answer is thai lhis is generally not allainable. and so no
developmenl o rganizatio n would sign up to do the job.
GIS/om" prahl"", are classified as the lotal number of problems encountered by customers while using the
product. Some of the problems may be caused by valid defects in the softwa re. Others may be caused by non ·
dde ts, such as a confUSing user interface, poorly written documentation, or duplicate defects (i.e ., defects that
were already reponed andlnxed bUI not known by lhe reponing party). Duplicates can be an imponant indica lor
as to how widespread a defect is, based on the number of times lhe same defect is reponed by different users. In
all these cases, whether a problem is cau cd by a defect or not, customers arc encountering perceived "sability
problems and as a resull ma y not be salisfied wilh lhe software . This makes the OI,'omtr prohltms metric an
important indicalor of quality. This metric IS typically expressed as problems/user/ month . It and olher metries
collected after a software product IS released are discussed in Pan VII on testing, rdea e. and maintenance.
Cuslom" Stlli,faclio" metrics arc com mo nl y collecled lhrough the administration of customer satisfactlOn
surveys. Companies such as Cisco Systems (5) collect feedback from lheir customers, with satisfaction
measured o n a 5,polOt scale (5 = Very Satisfied; I = Very Dissatisfied ). IBM includes the CUPRJMDSO
calegories (Capabi lity/functionality . Usability, Performance, Reliability, Insta llabiilty, Maintainability,
Documentation/informati o n. Service, and Overall ). Hewlett· Packard uses the FURPS categories (Function.
alilY . Usabi lity, Reliability . Performance, and Service) [41 . Results of these surveys are used to dnve
Improvem ent initiatives in their respective organizations.

2.6 SUMMARY

Quality o;oftware is a major theme of lhis book . Quality can be defined as "the more closely a software product
meets the wants and needs of liS cuslomers." There are many advanta/!es to produong quality software ",ciud",g
Increased customer satisfaction, reduced developmenl hedules, and reduced project OSL Quality practttt< are
implemented at the beginn",!! of the software life cycle and last through product release into maintenance.
Defects in software a.re deviatIOns from requirements As many defects as possible hould be removed
during product dL"Veiopmcnt, so these defect will not be delivered to C\I tomers. The earlier in lh" life
BIBUOGRAPHY 31

cycl~ dckcrs are d~tc tcd, the casler they are to repair and the less they cost to flx . Studies have shown that
ddc:crs d ll'Cted and n:paln,"d after software IS released to customers can cost up to I 00 times as much as if the
same defects were repaired shortly after they were introduced.
Verin ation and valldallon (V&V) is a process lor verilying that artifacts produced dunng the life cycle
contain a few defec ts.s po sible and validating that software satisAes its requirements. Verincation answers
the question. "Are we build,ng the product righo" Validation answers the questIon , "Arc we bUilding the
right product ·
Metrics are numerical measures collected throughout the software lile cycle, and quantify the degt'ec to
which software and processe possess certain allributes. They help with determining quality level , estimating
schedules, tracking chedu le progress, detcmlining software size and complexity , determining project cost,
and improving processes. Metrics related to quality include defect denSity, mean time to failure , customer
problems, and customer sa tislaction.

2.7 EXERCISES

I. In addition to the reasons stated in this chapter, name at least two other advantages to producing
quality software.

2. It has been noted that the later in the lile cycle defects go undetected, the harder they are to
discover and repair. In your own words, describe two reasons why this is true.
3. (a) Describe in your own words the difference between verificntion and validation .
(b ) What are the advantages and disadva ntages 01 speCifyi ng a V&V plan before a plan for
conducting your specific project?
4. (a) What are metTics?
(b) Give a reason why you understand metrics to be important.
5. (a) In your own words, describe the difference between product and procm mCtncs.
(b ) For each of the following objectives, state a mctric you would use to help in achieving Ihe
objective, state whether it is a product or process metric, and exp lain how it would be applied.
i. Avoid project schedule delays.
ii . Measure continuous quality improvement from one project to the next.
iii . Identify software parts that are exhibiting quality problems.
iv. Establish a baseline for improvi ng schedule accuracy .

BIBUOGRAPHY
J WhJllcn, NC.iI, "Mu""~1119 SoJllDUrt DCOf/oPMOlI ProJteb," John Wiley b ons, p 195 , 1995
1 Both-m. Barry, '"S4Iwart EI191n''''"9 EC01101f1IC1," PrenllcC'·I-bll, 198 1
1 "JE.EE S~ndatd lo,,~ry of So(IW'tuC' E"f'(InCCnnH TcrmlnoloK)'." IEEF. td 6 10 12· 1990, D ece mber 1990, pp 80·S1
4 K.in, Stephen N . 2003, "Mtlfln "rId MoJtls '" fllmlfr Ouo/rly EI19""rrrtfg, $ccond Edi llon, Acld,\.on.W C'... IC'y, Pt"Jl"'Son Edu .)1101'1 In .
pp 86- 100
S GiGO SylU:nIS, G.u:tomer S,un.f"cllon Metric", hllp IIwwlII f.. 1~() com/wC'blibouva 501<1 208laoou l.ISCO_ClpproJ l\..to_ Quilhtv_
CU)Wmcf,Jal_ wrvcy html l .. <xclIi\oCd Noy 4, 200C>J
Software Process

• What are the main activities of


....nlng software processes?

• What are the main software


process types?

The Software • How would a learn such as a student


Development team go about setecting a process?
Ufecycle

Figure 3.1 The context and learning goals for this chapter

A software project progresses through a se ries of activities, sta rti ng at it conception and con tinuifl8
even beyo nd its reicllsc to customers. There are numerous ways (or individual and team s to organize these
activities. T ypically, a prOject is organized into pba,es, each wllh a prescribed se t of activities conducted
during that phase. A ",flu/art proces, prescribes the interrelatio nship among the phase byexpre sing their order
and frequency , a well as defi ning the deliverables of th" project. It also speciRes criteria for moving from one
phase to the next. Specific software processes, called software process ",odd, or life cycle modds are
described. Th is chapter is o rga nized to first des ribe the individual activitie of ofrware proce ses, and thcn
to describe process modds the variou ways in which these aCtl vi lieS can be pursued
In addition to the activities prescribed by proce s models, there is a et of ge neri actiVities, called
"mbrdla acIIV";es , that are implemen ted throughout the life of a proJect. For instance, projec ts contain certain
THE ACTIVITIES OF SOFTWARE PROCESS 33

risks th at if the cume 10 pass ca n affec t the uccessful outcome o f the so ftware. Risks need to be identiAed ,
mo Ol tored , and ma naged thro ugh out the life of a project. Th is is an umbrella ac tivity known as risk
management Ot her umbrella activities include projc t man age me nt, con Agu ratio n ma nageme nt, and quality
manage me nt. Project ma nageme n t is covered in Part III , con Rgu rat ion ma nageme nt in C h apter 6, and quality
man.geme nt t h ro ug ho ut, but especia ll y in Pa rt VI1.
People someti mes associa te process with overhead, unnecessary pape rwork, lo nge r schedul es, and so
on. In other words , they fee l that process d oesn't add v.lue, o r wor e, tha t it adversely affects the success of a
projec t. Whe n imp le me nted incorrectl y, sofrware processes ca n indeed lead to undesirable results. H owever,
as " 'e explain in th is c hapte r, if p rocesses are applied with a degree of flexi bil ity and ada ptab ili ty , they are o f
grea t be ncAt a nd invaluabl e to the successful o utcome o f projects.
In certai n situat ions, a versio n 01 working softw are contain ing a subset of th e overall pro duc t
func tio nal ity is req uired earl y in the overall schedule. This versio n of the emerg in g pro duc t, called a
prototypt, typ ica lly impl eme.nts fu nc ti o nal ity th at is deemed a risk to the project. T y pica l rcaso ns to bu ild
prototypes include provi ng tec hnical feas ibil ity and validating the usab ili ty of a user interface. Pro totypes are
covered III de tail in Secti o n 3.2.3. I.
T o rei n fo rce the contents of th is c hapte r a nd to provi de gui dance to snlde nts at the sa me ti me, thi s
c hapler e nds with a sectio n devo ted to getting stude nt teams started with a te ml projec t.

3.1 THE ACTIVITIES OF SOFTWARE PROCESS

Most software process mo dels prescribe a similar set 01 phases and ac tiv ities. The differe nce between models
is the orde r and freque ncy o f the phases. Some process models, suc h as the wate rfa ll , exec ute each ph ase o nl y
o nce. O the rs, suc h as ite rative mod els, cycl e throug h multiple times . This section desc ribes th e phases that
are prevale nt in most softwa re process model s, and is summarized in Figure 3.2. Th e ph ases in Fi gure 3. 1 and
Figure 3.2 are ide ntical , except that Fi gure 3. 1 co mbines ince pti o n and planning . The partS are explained
bel ow. SpeCific process mo dels a nd h ow they impleme nt the phases are covered In Section 3.2.

1. Inception
Software produc t is co nceived a nd d eA ned.

2. Planning
In itia l schedule, resources a nd cost arc dete rmined .

3. Requirements Analysis
Spcc ify w h a t the ap pl ica ti o n must do , answcrs "what7"

4. Desig n
Specify th e parts and how they fi t; a nswer< "how7"

5. Imple me ntation
Wri te the code .

6 T esting
Exe.::ute the app il atio n with In put test data

7 . Mainte na nce
Re palf d feets and add capabi lity.

Figure 3.2 The main phases of a software project, showing Inception as a separate phase
CHAPTER 3 SOFTWARE PROCESS

Inception ( . d Wh h
Th, Is the phase where illlti31produ t Idca, arc formulat ed and a Vl<lo n o f the <0 tware , o ncclve . et er
it is il brand new produ lor an .lI11pr vcrn c nt to cx'~tm
. g so (tWlJrc, every PrOlcct start, wilh an ,dea of what ,s to
be built. Malor hlllctio naloty and project cope is deAned . Target customers and market segm~nts are
idcntlAed . Customers and takeholders may be con,ulted (o r hl gh . level Input Into software functlonaloty.
However, stakeholder involvement at LillS stage ,s doffere nl from that during the subsequent requirements
analy is phase. Dunng Inception, the goal i to galher very high level feedback. As an example, suppose a
company is considering budd ing a video store applicatio n. A market ana lysis may be conducted to determIne
the existe nce of competing video store applications. A summary of their features and an analysIS of their
tre ngths and weaknessc is compi led. The commercia l uceess o( the propo cd application is determined by
identifying potential new customers and contacting them for Info rmation concemlng,

• Their satisfaction with their current application


• Ideas for needed fun ctionality and feature
• Their likelihood of adopti ng a new product

As an example , suppose that a currenrly deployed ystem requires custom hardware, but potential
customers would prefer using standard Windows PCs. Based on this analysis and feedback , the need for and
Viability of the proposed applocation is determined. If· it is deemed prom iSing, high . level functionality for the
application is deAned based on the feedback received, and the project proceeds to the planning phase.

Planning
Once a high . level idea for the application is developed , a plan is formulated to produce it. Since this is still
very early in the overall life cycle and detailed infom,ation is not yet available, the plan will be a rough
estimale. However, some plan must be in place to understaAd the scope and cost of the project . A project plan
that ide ntifies the high.level activities, work ilems, schedule, and resources IS developed. From this
informatio n a cost estimate can be developed. This ste p is very important to determine the feasibility of
a project . For example, if the cost is deemed to be too high , a reduction in features may necessaty. If the
product release date is too late, more resources may be added It is critica l that the e types of problems be
identified as early as possib le so corrective action can be taken .
The results of this phase arc typically captured in a oftware Project Management Plan (SPMP). The
SPMP and project management are covered in Part IV. Because the plan is only a rough one at thi stage, it is
necessary to modify and adapt it throughout the lofe of the project. For example, suppose that during
subsequent requirements analysis potential new customers arc identiAed and additional functionality is
requested. Using the video store application as an example , suppose a request is received to add additional
workstations to stores so customers can retrieve detailed movie information, such as release date, movie
studio, cast, director, producer, genre, and so on. This new fun ctionality may require additional proj«t
resources and changes to the schedule. The SPMP would be updated as a result . Some life cycle models, such
as the spiral model described below, prescribe speciAc points in Ihe process where planning information is
revisited and updated when required . Agile projects, as will be seen , keep planning to a minimum.
In addition to the activities described above , a plan is developed for managing project artifact such as
technical specifica tions and source code . This is known as to.HfiouCQtlOH ""'""Q(D!",t, and mcludes tasks such as
tracking changes to artifacts and handling multiple versions. Configuration man.gement is pl.nned .t th.l
early project stage, before the first project artifacts are generated. Configuration management is cove~d .n
detail in Chapter 6.
THE ACTIVITIES OF SOFTWARE PROCESS 35

Requirements Analysis
During this phase . detail~d infolmation regarding customer wants and needs. and problems the software is
Intended to solve are gathered . Info mlatlo n ga thered and documented is in much greater d~tail than it was in
the inception phase. During inceptio n. only e nough information is required to start planning the project.
During ~quiremcnts analysis, speciAc product functions and features are denned along with requirements
such as performance, reliability. and u ability. Requirements are ge nerated in a form that is completely
readable and understa ndable by customers. Hi gh-level requirements in particular are typically expressed in
ordinary English (or the loca l language) . Various techOlques arc used to o btain this information, including
customer interviews and brainstorming sessIo ns. Requirements describe what the application is intended to
accomplish . They are specified in sumcient detail 50 they can be used as input for the subseq uent design
phase, which defines how the software will be buill. The resul ts of the analysis arc typically captured in a
formal Software Requirements Specification (SRS ), which serves as input to the next phase.

Software Design
The purpose of software design is to deAne how the software will be constructed to sa tisfy the requirements.
That is. the internal struCture of the so ftware is deAned . The two main levels of software design are software
architecture and detailed design . Software architecture is analogous to the overall blueprints of a hou e as a
whole. Blueprints specify the number of rooms and their layo ut . door and window locations, number of Aoors,
and so on. Software architecture speCifics how the software is broken into subsystems o r modules and the
software interfaces between them . For example. the architecture for a video store application may consist of
components such as a user interface module, a problem domain module. and a database module . Agile
projects general1y perform design . implementation , and much testing in an intcrweaved fashion rather than
cal1ing OUt design as a separate phase.
The detailed design is analogous to the details contained in a house blueprint. In house plans. details
such electrical wiring and plumbing are specified . In software . details such as al gorithms and data structures
are speCified. Other aspects of software design include user interface design and database desig n. The output
of software de ign is specified in a SofJware Design Document (SOD) and is used as input to the
implementation phase. Software design is covered in detail in Part V.

Implementation
This phase consists of programming. which is the translation of the software design develo ped in th e previous
phase to a programm ing language. It also involves integration . the a sembly of the so ftware parts. The outPUt
consists of program code that is ready to be tested for correCtness. For agile techniques. desig n implementa-
tion and muc h test 109 arc performed in tandem .

Testing
In this phasc . the code produced durin g the implementat io n phase IS testcd fo r correctne s. Testing is
performed at three Icvels. First . Individual modules are tes ted by develo pers. econd. modules are integrated
and lested to e nsure that they interface properly . Third . once all the modules have been integrated, the e ntire
~ystcm is tested to e nsure that it meets the user req uirements. ystem testing is typical1y co nducted by an
indepe nde nt quality assura nce (QA ) tea m. Rcca l1 from hapter 2 that this testIn g proccs, IS called ""I,dalloll .
Once system testing has been comple ted, severa llevc1< of uSlOmer tcstin!! are co nducted . During brill Ir li"9
the software is as 10<" to the final rciea,e as possible. and i given to part o f the e ll ta mer community with th e
understanding lhat they report any defec ts the y And . The goa l is to uncover a set of problem, that could o nl '
be ruscovcred wllh lhi s type of "rcal -world" tes tlnl!. O nce beta testing is comple te, at' ,plalll( If 11'''9 IS
36 CHAPTER 3 SOFTWARE PROCESS

condu Icd o nlhc "fi nal" release of <u hwarc. AccCplan~('lcS(S arc omprised of a ~ubsel of <y<u:m le<ls, and aTC
condu Icd b e ither the cuStomer or a represcnlalivc of Ihe CUSlOmer lO ensure Ihal II mee ts the customers
nlena for relea e. o m lilli e a round of acceptance tcstong is cond uc ted prior to beta testing, to make sure
that the system mcets ert"i n e ntcria before it is given to cu,to me rs for beta testing.

Maintenance
Aher the sohware IS released to u tomers, the ma on le nance phase commences. During mainte-
nance, modiAcations arc made 10 the sohware that "rbe Ihrough one of the fo ll owi ng :

• The repair of software ddecls Ihal a rc dIscovered durin g no m,,1 customer use of the system

• ell lomer request for enhancements

• A desire to imp rove at tributes of the system suc h a pcrformance o r reli abil ity

Mod, fica t, o ns to the . oftware arc bundled togethe r, and new versio ns of th e software with these
mo di ficati o ns arc re leased . Maintenance is discussed in detail in C hapter 29.
Figure 3.3 shows examples of artifacts produced durin g each phase fur our example video store appl ication.

• Inception

" . .. An applica ti o n is needed to kee p track of vi deo rental s . . . "

• Planning (Software Project Management Plan )

" . . . The project will take 12 months, require 10 people and cost $2M ... "

• Requirements Analysis (Product , Software Req uire me nts Spec .)

" ... The clerk shall e nter video title, re ntcr name and date rented . The system shall . .. ..

• Design (Software Design Document, Diagrams and text)

.. ... classes DVD, Vid,oSlore , . . . , related by . . . "

• Implem ~ntatio n (Source and object code )

• . class DVD \ String title, . .. I...


• Testing (Software T est Documentation, test cases a nd test results)

" . . . Ran test case: Rrnl "Th, Ma ln'x" 001 OcI J , ro,l "Stoll'seui'" 001 Oct 4I return -T/',
.
tn' ·" 0" O~
Ma.x 1..1 f
0 • •
Result : "Stalli"uil" du, Oct " 200. balancc of $8. (comrt) .. "

• Maintenance (Modir.cd requirements, desig n, code, and text)

Defect repair, "ApplicatIon crashes when balance is $10 a nd attempt IS made to "G W'tb tbt
W.
,n d" ," rent 0"' I

Enhancement, "Allow searching by d irecto r."

Fllllre 3.3 The main phases applied to a video store application


SOFTWARE PROCESS MOOELS 37

3.2 SOFTWARE PROCESS MODElS

ftwan:: proces model deAne the order and freque ncy of phases in a project. The following sections
describe the most important process models, starting with the classical waterfall process .

3.2.1 The Waterfall Process Model

One of the oldest oftware process models was deAned by Royce [ I] and is called the wa t,rjall proms. Despite
its many weaknesse (described later in the section), the waterfall process is still in Widespread use today and
is the basis for many other more effective processes.
FIgure 1.6 in Chapter I illu trates the phases of the waterfall process . Note that Royce's mode l begi ns
with the requirements phase he did not include inception and planning phases. In practice, o rganizations
implementing a wa terfall process wou ld typicall y start with these phases. The waterfall executes in a
~cwentiaJ manner through each phase, conclud ing with maintenance. n,e
output from o ne phase is used as
input for the next, implying that a phase is not tarted until the previous o ne has completed . It is accepted in
waterfall processes that there is a small overlap between adjacent phases. As an example , some personnel wi ll
be performing the last part of requirements analysis while others will have already started the design phase .
The waterfall process is c haracterized by documents generated by the time each phase is completed.
These include requirements specification and design specification, for example . Also, there are usual ly
entrance and exit criteria between phases to e nsure that a phase is completed successfull y before moving on .
In practice, an iterative re lationship between successive phases is usually inevitable. For example , after
the requirements are comple ted, unforeseen design d ifficult ies may arise. Some of these issues may resu lt in
the modiAcation or removal of co nflicti ng o r no n. implementable req uirements. Thi s may happen everal
times, resulting in looping between requirements and desig n. Another example of feedback is between
maintenance and testing. Defects a re discovered by custo mers after the software is released. Based on the
nature of the problems, it may be determined there is inadequate test coverage in a particular area of the
software. Additiona l tests may be added to ca tc h these types of defects in future sohwa re releases. A genera l
guIdeline, often accepted to sti ll bewithin the wa.terfa ll framework , is that feedback loops should be restricted
to adjacent phases . This min imize potent ially expe nsive rework if the feedback were to spa n multiple phases.
An modified model ill ustrati ng this iterative relationship i sh ow n in Figure 3.4 .

time

ReQuiremenls

Design

Implementallon
Phases (aerlvilles)
Tesllng

Malnlenance

Figure 3..4 The waterfaU software development process In pracllce: fcedMck Is IneVitable
38 CHAPTER 3 SOFlWARE PROCESS

A n,.lor limitati o n of the waterfa ll pro.:e>, 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< <u h as timing, performance, storage, a nd ~
on an be discovered o nl y then . Even With thorough up-fro nt a naly,, ~, these kinds of factors arc difficult to
predi t until en ountcred during te' ting. o lutJo ns may require either complex de'ign c hanges or modiAc~ ­
tions to the req Uirements that the de Ig n 15 based o n, necessita ting Ite ration beyond adjacent phases
Discovering and repairing the e types o f ddect, <0 late in the developm e nt cycle ca n Jeopardize the project
schedule.
Major adva ntages and d isadvantages of the waterfa ll process are summanzed below.

Advantages

• S".plt 'llid tasy fo uSt: Phases arc executed and compl e ted senall y, with speCIfic e ntrance a nd exit criteria for
movinS between phases. O rde rly execu ti on of phases is easy to comprehe nd .

• Pracfiad for many yta~ and ptOplr I,aat milch txptritna ",iii, i~ The process is well understood , a nd many people
are com fortab le with its execution .

• Easy fo manag' du, fo fb , rigidi fy of fh, mod,l: Each phase has speciAc deliverables and a review process.
• Facililales al/ocahon of rrsourcrs (due to sequential nature of phases): Distinct phases fac il itate allocation of
perso nnel With distinct skills.

• Works "" II for smallcr proj,cls ",hm rrqui,rmcnls arr D'ry w,lI undt~ food : It isn't necessa ry to add complexity of
iteration if requirement arc well known up fTo nt.

Disadvantages

• R,qui"mcnls mu,1 bt h,o",n up fron l: It's di ffic ult to imagi ne every detail in advance. Most projects start out with
some uncertai nty, a nd mo re de tails are learned as the prOject prog resses.

• Hard 10 rs limalt reliably , T o ga in conAde nce in an estimate, there may be the need to design and implement
parts, especia lly riskier o nes. Estimates become mo re preCise as the project progresses.

• No f"dback of ,y,fem by ' Iakrholdm unlil afltr l" ling phaSt: The process does not facilitate intermediate versions.
Stakeholders often need reassurance of progress and confirmation that what is being develo ped meets
requirements.

• Major problem, ",ill, system artn·1 discolXfld unlil lal, in proms : The testi ng phase is where these problems are
found , but it leaves very little time for correctio n, resulting in potentially d isastrous effects on projec t
schedule and cost.

• LAck of par.Ilt/lSm : Each phase is executed to completion . Disjointed parts of the system could otherwise be
completed in parallel.

• inrfficitnl USt of mourers : T eam members can be idle while waiting for o thers to complete their dependent tasks
or for phases to complete. Also, someone good at requireme nts analy is is not neee sarily good at
programming.

Ikcause of fac tors like these, alternative (but related) proce ses are often emplo ed , and these are
covered in subsequent sections.
SOFTWARE PROCESS MODELS 39

3.2.2 Iterative and Incremental Development

The wa",rfall process is c harac terized by a seque ntial executio n through the phases. It is generally agreed that
the order of the phases d ictated by the waterfall i fundamental : ga the r requirements. c reate a sohware desig n
to realize the requireme nts. imple me nt the design, and test the implementation. The problem arises.
however. when this is caled up to gather all the requirement . d o all of the design. implement all of the code.
and test all of the system in a linear fashion [2]. Except for rhl' emallce' o( projects this is imP'1'ctical. As the
system is developed and renned , more i lea rned and a need arises to revisit each of the phases. That is,
software is mo re naturally developed in a cyclica l manner. where a part o f the system is deve lo ped and tested.
feedback is ga thered . and based o n the feedback more of the system is developed. This reAects the fact that
not everything is unders tood at the start of a proj~ct. Ilrraliv( processes accept thi s cyclica l nature and are
discussed in the rest of th is section . Figure 3. 1 is drawn in a way that reflects this.
~n ilcraliv< process is typined by reDba ted executi o n of tbe walerfall pbases. in whole o r in part. resulting
in a ren nement of th e req uire me nts, design. and implementation . An iterative process is incrm", lol if each
iteration is relativel y small. At the conclusion of SlI c h an iteration . a piece of operat io nal code is p roduced that
suppo rts a subset of the nna l produc t functionality and (eatures. Project artifacts suc h as plans, speci flcatio ns.
and code evolve during eac h phase and ove r the life of the project. Artifacts are co nsi de red comple te only
when the software is released .
As defined by Cockburn (3). incremental development is "a sch eduling a nd staging strategy that allows
pieces of the system to be devel o ped at different times o r rates and integrated as they are completed: This
implies that iterations need no t be executed serially, but can be develo ped in parallel by separa te teams of
people . Successive increments implement an inc reasi ng set o f functionality and features until the nnal
iteration . which produces the nnal product. Figure 3.5 illu.s trates this concept for a project with three
iterations. Note that the output of each testing phase is a working subset of the nnal p roduc t that
incrementally contains more functionality .
An iteration other than an incremental one is sometimes defined as "a self-contai ned m ini -project. with a
well-denned outcome: a stable. integrated and tested release" [2]. That is, each itera ti on is a self-contained
lime
1 •• •• • • • • • • • • ••• I •
• MIL EST 0 N E S:
First iteration completed X ,,, •


• Product released X
• • •
• • • ,• • •
SCHEDULE •
•• ,

•• • • ••
Iteralion' ~ 1 2 a
. - ••• _.•• •
.,_.- •
,
,• ._.,• •
••

,•

• -
Requlrements

• •

•• • ,•
analysls
1
•• ,

,• ,•

2
, •


• •, •

• ••

••




- .,•
• •
• -•
••
•• •


• •
• f-

Design td•
,
,


m
, ,•


0

:
• ,
,•
••
-


••

• •




• •
•• - •
• •
f-

co:


Cod Ing •• CD: •
CD: ••
- •, •
-• •




•,
_.•


• •
~


• , , •

• --
T...tlng
• •
•• 1 •• •• I 2 •• •
• [' I
,• • • • •
SottwarL-l SottwarL-l Final --1
Sub"t Subset Version

Flgure 3.5 The IteratiVe software development process: an example with three Itera tions
Sourc:t COCt:btxn, AI'R eit " UN&..e!I"K loocmofH.8I OoYelopment,'· JDnuatY 1993. hup'/lahstnl1 COCkburn USlUnravoUnx r!ncremontal ~ dCve.lQpn'lent.
.0 CHAPTER 3 SOFTWARE PROCESS

pro) t with It- ow n set of actlvitlc>, plan , o bjective , and tnea~urablc eva luation Crlterl. , The ' re lea<e" is a
workln~ vCrlilo n of <oftware that Is clther u>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 .1

•• , ••••• ·0_ •°
••••••••••••••••••

-.. Prototype Implements


,:~-
0

....

••
risky parts of this ~, ••

Prototype activity lirsl

Project
beginning Main project timeline time

Key:G= end of a unit 01 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


CHAPTER 3 SOFTWARE PROCESS

t
Payoff from building
prototype ($'s saved
per $1 spent) optlllUll full
expenditure project
on expenditure
prototype

0/0 expenditure 1000/0


0%
on prototype
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
Perccn~g.
<xcluding code
of prolOtyP<'
Estimated reu.., Net P.yoH
code reuscod
cost min max In appliation •
mm mOl( .~

ProlOlyP<' B D E C D-( . -C)B E- r .-C)B 1


fe.1Ure
J. CUI $10,000 $10,000 $ 80,000 $75 ,000
-
$40,000
50% $5 ,000
, -
soecnshots I
..,
2 . T ransac- $50,000 $10,000 $300,000 80% $0 $290,000 $145 ,000
lion secu rity
3. Complete $SO,OOO $10,000 $400,000 50%
-- $30,000 $200,000

$85 ,000
I
transac,t ion
- - I
4 . C us to mer $120,000 $20,000 $140.000 30% -$64,000 $56,000 - $4 ,000
tries on
clothing
J

Figure 3.9 Payoff calculation example for building a prototype for a clothing application
LI , 'J"" v
• Preventing lime wasted o n proposed requirements that the prototype shows are not reall y needed (e.g .,
mi nimum of th ree un needed requirements out of 100, $300,000 budgeted for the requirements phase =
$9000 saved)
• Im p le me n ti ng a sohware desig n for the "trying o n clot hes" feature, thereby retiring some development risks
(e.g ., esti mate that t h is wi ll save a minimum of one pe~on - week of design time = $2000)

• Rewo rk th at would have resulted fTOm the customer cha nging requirements only after seeing the developed
product (e .g ., rework minimum of three requirements at $3000 each = $9000)

The minimum savings therefore is $9000 + $2000 + $9000 = $20 , 000. Estimating the cost of building
the prototype ca n usc approximation techniques like those described in Chapter 8. An estimation of code
reuse can be performed by identifying the classes of the prototype and determining which are likely to be
usable in th e actua l app lication.
This type of estimation often consists of adding up the estimation of sma ller parrs, which is often more
feasib le . Bracketing each estimate between a minimum and a max-imum can help to make this process a little
easier for the estimator.
Once these estimates are made, the best· and worst ·case scenarios for each feature can be computed.
This is shown in Figure 3.9. The minimum payoff value is obtained by taking the most pessimistic
combination : the highest costs, the lowest g ross benefits , and the lowe t reuse percentages. The maximum
payoff is calculated correspondingly. For example, the maxImum payoff (the most optimistic alternative) for
the ' CUI screenshot" prototype feature is as fo ll ows:
[ma xi mum estimated benefit ] - [ minimum estimated com 1
= $80 , 000 - [(minimum estimated cost) x (percent not reusable )]
= $80 , 000 - [ $10 , 000 x 50% ] = $75,000
U CHAPTER 3 SOFTWARE PROCESS

v rJ~illB is o ne way to deal with the >pread bel ween bcsl and worst ca'c, The result ~ugke<!s a
[lO'lIIVC payoff for all propo 'cd prolotypc fcalures ex ep l fo r the "tryIn g o n clothes· (eature, whIch prOjects
- $4000, an ovcrall wastc of $4000. The latter negatI ve resu lt IS due to relatively low payoff, high
devciopment cOSt, and low rell<C,
It may be adVIsa ble for the prototy pe to evolve InIO the appl ication ilself, but thi' sho uld be planned for,
no t accidenlal. By their nature, prolotypcs arc rapidly co n,lructed and rarel y documen ted They can be
imp!cmented uSIn g langua ges that get re ult, quickl y but may be unsuitable for th e applicallon itself.

3.2.3.2 Feasibility Studies


It IS o metim~ unccrtain whether proposed requirement can actually be implemented in practice. In other
words, an entire project is at risk rather Ihan a few spcciRc requ irements. In addition, the project would not be
feasible If Ihe ri k were to be realized . In such cases, Jtasibll/l)' sludirs may be advisable. These are partial
implementations or simulations of the app:ication. For example, conSIder the fea sibility of a Java Internet-
based Encounter video game, and Ids say we suspect performance will be so slow that the game would be of
negligible Interesl 10 an yo ne . A feasibility study could consist of setting up a message · passi ng simulation at
the anticipated rale from a number of players, but with dummy content. Delays could then be estimated by
clocking the simulation .
Simulations can be expensive to create since they arc applications in themselve , sometimes requiring
software engineering artifacts of their own such as a requirements speCification! The author was once involved
with a si mulation of a large system und~r development. The simulati on grew into a large program , which was
needed while engineers developed the rea l system. No one took the requirements for the simulation seriously
because it was not "the real thing ." As a result, even though the development community relied on the
simu lation , the cost of maintaining and using it became astronomical. Making cha nges required tracking
down an employee who "knew the system." Feasibility simulations arc common in large defense programs that
invo lve extensive software and hardware.

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 4S

COST

Dele,uutE ntROUCH
EVALUATE
oe,Ec11V£l. 8108
AL i EJdU.l1VEI
A1.. ftRNATIV£S, 1DE>m'Y,
CONsntAJNTI RE SOLVE R.tSKS

RISK ANALYSIS

,
RISK NtAl. Y&lS

RISK ANAL YSIS


", OP EllA naHAl:
COMM'iiriEHT ., PROTOTYPE
PAR Ii flOtt RJSK -' ROTOiTP £,
'., AHAI,., PROTOTY PE.,
,, ~ ~R:OTO·
TYPE 1
"EVIEW -
ROTS PlAH
Uf'E CYCLE
- _
COHCEPTOF - -- -EKlLATlOHS
MOOELS

-- - -- BEHCHMAR KS

-
OPERA nON
PLAN SOflWARE
"an:
SOFlWARE OETA.D.. ED
DEVELOP·
MEHT PLAN
ReQUIREMENTS
VALIDATION
PRODUCT
OESI CH ... ... ...
DESlCN

" CODE
INTECRATION
OESK;H VALIDAnON '"
"HOttST AND VER'FICAl1OH UNIT "-
PLAN NEXT PLAN
" TEST
PHAS£S INTECRA·'
, nONAHO ,
\ ACCEPT. ' lEST
IMPLEMEH. \ ANtE TEST
TAllON 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 deliverable<. Ea rl y Itera tio ns produce eithe r model ,
emulatio ns, be nc hmarks, or pro totypes, a nd later Itera tio ns fo llo w a more waterfa ll· like process and
increme ntall y pro du " more complete versio ns of the softwa re Th is implies that ea rl y Iterations may
exclude srcp 5, and late r ite rat io ns may exclude <tep 4. Altho ugh Figure 3. 10 shows four Itera tion , the proces
doc:. not presc ribe a et numbe r of cycles, The numbe r IS die ta led by the <ize of a projc t, the number of nsks
id"nrified , and the ir rate of retire me nt ,
CHAPTER 3 SOF1WARE PROCESS

Ith ug h Boehm" ori!! inal conception wa, risk. drtven , the piral Model ca n also be driven by a
,eque n c f fun tlonallty sets For example, Iteratlnn I for an o nline video .on · demand appileatlon could be to
Implement the database of video, and it API , Itera tion 2 could be to implement the CU ls, and so on
Key advantases and disadvantages of the spiral model are li sted next.

Advantages of the spiral model


• Risks IIrr ,nm'"g,d ,arly m,d ,hrougholl"'" proem : Ri k, are reduced before they beco me problematic, as they are
considered at all stages. A a re<ult , sta keholders can beller understand and react to risks .
• oj'u'lIrr ro%rs as ,h, proj,e' progrrsscs It is a reali sti c approach to the devciopment of large·scale sof·tware.
Errors and unattractive alternatives arc eliminated early .

• PIn,,.irr9 is b,,," 111'0 iI" procrss : Each cycle in ludes a planning tep to help mon itor and keep a project on track

Disadvantages of the spiral model


• Compli a"d '0 u,,: Risk analysi requires highly speCific experti e. There is inevitably some overlap between
iterations.

• Mtry b, oo"kill jor ,mall projrclS: The complication may not be necessary for smaller projects. It does AOt make
sense if the cost of risk analysis is a major part of the overa ll project cost.

Boehm's spira l model has been very influential in giving ri e to many styles of iterative development
model , including, we believe, the unified process, discussed next.

3.2.5 Unified Process and the Rational Unified Process

The Unified Software Development Process (U SDP) was first described by Jacobson , Boach, and
Rumbaug h in 1999 [6 J and is an outgrowth of earlier methodologies developed by these three
authors-namely, Jacob on's "Objectory methodology ," the "Booch methodology" [7]. and Rumbaugh
et al : s Object Modeling Technrque [8]. The USDP is generically referred to as the U.ifird Proem (UP).
IB M's Rational Software division has developed a detailed refinement to the UP called the Ratio•• l Ulliflrd
Proms (RUP ), which is a commercial product providing a set of process guidelines and tools to help
automate the process.
The UP is a "use·case driven, architecture·centric, iterative and incremental" software process [6J.
Iterations are grouped into fou r "phases," shown on the horizontal axis of Figure 3. 1 I , lllcrpllcm, Elaboralimr.
COlls'ruelioll, and Tra.silloll . The UP's lise of the term "phase" is different from the common usc of the term.
In fact , referring to the figure , the term "discipline" is the same as the common use of · phasc" that we use in
thiS book.
Each UP "phase" consists of one or more iteration , shown across the bottom of Figure 3. 11.
Iterations are relatively short (e.g., threc weeks), the outcome of which is a tested , integrated, and
executable partial ystem . Iteration are built on the work of previous itera~ions, and thus the Anal product
is constructed incrementally . Each iteration cycles through a set of nine diSciplines, whi hare hown on
the vertic.1 axis of Figure 3. 11 : business modeling , requirements, design , implementation and test
activities, plus supporting activities slIch as configuration management , project manag menl , and environ-
ment [9J . Fur examp le , during an iteration some requirements may be cho. en , the desilln enhanced to
support those requirements, and the requirement. implemented and te ted . The hOri zon tal "hump ' next
to each discipline show the relative effort expended on each diScipline during iterations. For example, the

SOFTWARE PROCESS MODELS 47

Phases
Oil..: lpllne.
II II T.-n. I
Business Modeling •,
,,
Requirements ,

Analysis & Design

Implemenlation
Tesl
Deploymenl
,,
Configuration ,
,,
& Change Mgml ,, :,
Project Management

Environment rr~=::~~:::-;:== ::;:;;;;;::;:;:;~ ..----


I tr_ I EIob" Ebb' 2 ~ Ic.:;' I c:r I T~ I I T;r

Iterations

Figure 3.11 The unified softwa re development process: its " phases" vs. traditIOnal phases
SOUrce' Adapted from Ambler. S. w.. "A Manager's Intfoductlon to the Rational undlea Process (RUP)." AmbySoft (OeCember 4, 2OOS) , http://Www ambysoh..COOV
do't'mlOaclSlmanagerslntTOToRUP.pdr.

largest requ ire me nts effort is expend ed du ri ng Inception a nd Elaborati o n, and the large ' t Implementation
effort during Constructio n.
Th e fo ll owing arc desc riptio ns oi the work conducted during each of the UP "phase ",

Inception

• Establish feasibility

• Make busi ness case

• Establish product visio n and scope

• Esti mate cost and schedule, includi ng major milestones

• Assess critical risks

• Build o ne o r more p ro totypes

Elabora tion

• Specdy requirements in greater detail

• Create architectural baseline


• Perfonm iterative implementation of core architecture

• Refine rISk as essment and resolve hIghest ri k Items

• DeAne metrics
• ReAne project plan , Including detailed plan for brg lnlllng onstn.1 t lo n lIerallo n<
48 CHAP 1ER 3 SOFlWARE PROCESS

• oml letc remaining reqUirement

• Do Ilera tl vc IInplcmcntJfion of rema ining dC'ign

• 1110roughl), te't Jnd prepare system (or deployment

T r.nsition

• Conduct beta te'ts

• orrect defects

• Create use r m"nuais

• Deliver the system for production

• Train end users, cu tomers and support'

• Conduct lesson learned

Ea h UP phase concludes with a well -defined milestone , where key deciSions are made and specific
goals defined Figure 3. 12 shows these milestones and where they are fulfilled in the process .
The typical amount of time spe nt in each UP phase is shown in Figure 3. 13 ( IOj. However, this varies
depending on the type o( project. For example, projects that contain o nl y mino r enhancements with known
requirement may spend morc time in the Construction phase, while projects for which very little is known
about requirements may spend more time in the Inceptio n and Elaboration UP phases .
The advantages and disadvantages of the unified rocess are summarized below.

Advantages of the unified process

• Mosl asptcls of a prOllel art accolm lrd Jar: The UP is very inc1usivI=, covering most work related to a software
developme nt project such as establishing a business case.

• Tht UP IS malur< , The process has existed for several years and has bee n quite Widely used .

............ 1
I - CGnIIru-..Ibl ,.,...."

Utecycle ObJective. lItecycle In ltle' Operational Product


(LCO) Archlteclure C.""b lllty (IOC ) RelNn
• Scope concurrence (LCA) • Syslem Slability (PR)
• Initial requirements • Requirements • Requirements • Business acceptance
definition stability stability • Opera lions
• Plan concurrence • A,rchltecture stability • Prepared stakeholders acceptance
• Risk acceptance • Risk acceptance • Risk acceptance • Suppon acceptance
• Process acceptance • Cost acceptance • Cost acceptance • Cost and estlmare
• Business case • AeaHslk chance to • ProJect plan acceptance
• Project plan succeed
..J
• Project plan

Figure 3. 12 Objectives for the unified process


S<;IurU. ,.Mpte(l fromAJ'nblef. S W . "A Managor"s Introduction 10 the RDtJoMl unjf'ie<l Process (RUP) ., AmbYSoI1 (Ce c~n'lblt III. 200$)., httpl/Wwwlml:JVSOft.<OW
dOYmk'leOslmenagerSJntroToRUP octf
SOFlWARE PROCESS MODELS 49

UP Phaa•• - Typical Time DI •• rlbution

Transition Inception
10% 10%

Elaboration
25%

Construclton
55%

Figure 3.13 lYPical time distribution of the rational unified process's "phases"
SOurce: Adapted from Ambler. S. W . "A Manager'Slntrodoctlon [0 the Ra !MJoaI unified Process CRUPI "~ Ambysoft (DeceOlDef 4, 2005}" nttPJtwww.amoysoft.conv
dovJnkwk!managet"SfFltrOToRUP pdf,

Disadvantages of the unified process


• Tht UP was originally conctivtd oj Jor /nrgr projtclS, This is fine . except that many modem approaches perform
work in small self-contained phases.
• Th, procm may bt ovtrkill Jor smnll Proltc/s , The level of compl ication may not be necessary for smailer project .

Practitioners and vendors of the unified process have modified It to be morc like an agi le proccs ,
discussed next.

3.2.6 Agile Processes

This sectio n Introduces agile processcs. C hapter 4 is dcvotcd entirel y to agi le methods, and agi lity is
referenced and compared throu ghout this book
In 2001 . a group of industry cxpcrt~ , disillusioned with some ommo nly held software engi neeri ng
beltefs and practices. met to discus way to Improve softwa re development. Thei r goa l was to produce a et of
values and princ ipl es to help spced up development and effectively re~ po nd to change . The group ca lled
themselves the Agile Alliance, in cssence to capture th elf goa l or produ Ing a mcthodology that wa< efficient
and adaptable . The resu lt of their work was the MmllJrsloJor Agi/t SoJlu)(I(( D".,lopmtlll [ 1 11. . 1 0 knO\~n as the
Ag,k ManiJ,slo , which co ntains the va lues and pron iples they defi ned. All agil, software pro c< is o nc that
embrace~ and co n/o rm s to the Agile Manifesto. whi ch i, umm arized In Figure . 14 .
Ag"e processes are hrghly Itera tive and incremental They comm only cmpl oy the foll owing:

• Sma ll , close -knit tea mS



• Rt:gular, frequent , dr ~c ,pli ned ustomer reqUlremenh I11t c lln g~

• A code-centric approach, docu mentation nn an a' · needed bnSl< (e,g . h, gh·level reqlllrcment' statement<
only)
50 CHAPTER 3 SOFlWARE PROCESS

• .. . indi vidual s and interactio ns


o ve r pro e,sC' Jnd t o l ~

• . . . wo rkin g software

over o mprchenslvc docum ental ion

• .. , customer collaboration
ove r ontra cl nego tiati on

• . . . respo nding to change


over fo ll o wIn g a plan

Figure 3.14 Main points of the Agile Manifesto

• C u tom er repre entativcs wo rk ing w ithin th e team

• The use of use r sto ries as the ba sis fo r requirements end -to-end accounts of ho w uscrs need :0 acco mpl ish
indivi dua l tasks

• Rerncto ring, a kind o f d isciplined code Improvement explalOed full "" C hapter 24
• Pair programm ing, In whi ch tw o programmers work at a single wo rkstati o n

• Con ti nual un it· ccs ting, and acceptance tests as means o f setting customer ex pectations

Figure 3. 15 shows how the repeated iterati o ns o f an agile process arc executed over time. "Sto ry" is a task
required of th e application as th e eu tomer co nceives it.

Demonstrate
fulfillment Accumulating
of previous functionality J
stories
,,
,, Identity stories for th is iteration
,,
,,
,, • Interact with customer
,,
,,
, • Cement mutual undersranding
,,
,,
,, Implement stori es
,,
,, • Work incrementally
,
,,
, , • Develop test bank In parallel
------
,,
,,
---- --
----
,, Typical
,,
" ," Iteratio'l, _- --

nme; composed of equal iterallon Intervals ~

Figure 3.15 The agUe process


SOFTWARE PROCESS MODELS 51

Ke ad><antag $ and di advantage o( ag.le proce es arc ummaflzcd below.

Advantages of an agile process

• n.. praitel alw"Y' ha, d,,"o"'lrabl, ","/r" The end product o( each iteration is working software .
• DnJtlo/ltrS tn.d 10 b, mort •• o/illnl,d, Developers prefer to produce working art.lacts and tend not to like creating
documentation .

• C.'lamm a" abl, 10 /lrollld, b,u" ",/""""",1, b, a"St Ihry cnll s" II" ,"ol"i"g proJllc/,

Disadvantages of an agile process

• Probl""aric.1 for lnrg, appli alia" , Agile methods are more readil y used for smaller projects. There is debale
about their utility for large projects.

• Docum",lallon outpul is qutSliOHabl" Since documentation takes second place, there i a question a. to whether
necessary documentat.on will ever be produced.

3.2.7 Open-source Processes

Open·source software is developed and maintained by people on a volunteer basis. All project artifacts, from
requirements documents through sourCe code, are available 10 anyone . The re are several open -source
software development Web sites on the Internel Ihat aggregale and reference open source projects, including
SourceForge.net and Freshmeat.ne!. As of 2009, SourceForge.nel hosted more than 100,000 projects and had
over 1,000,000 registered users. Hosting sites provide source code reposi tories and utilities for projecl
management, issues discussion , and source control. The case studies in this book dlustratc two well known
open source projects, Eclipse and Open Office .
Open-source projects typically get started when someone develops an applicat.on and posts it to a host
Web site V.rtually anyone ca n propose new requirements, and since the source code is freely ava.lable,
anyone can implement requirements that arc not part of the o(ficial baseline. There is a process by which
proposals and implementations arc elevated in priority and a process for accepting new code and capabdity
into the basehne. If defects arc (ound, they are reponed and others may work on fix ing them . This process is
repeated, and the application grows .n capabdity and $tability . In this wa y, open -source projects arc
developed in an .terative manner. In addition, by exercising aA appltc.tion many times, the open - o urce
communtty affects a huge testi ng process.
Some reasons why an individual o r company makes a project open source arc listed .n F.gure 3. 16 and
3.17, a,n d reasons why they may nOI arc listed in Figure 3. 18. A pnmary reaso n to make a proj" t ope n ,ource
is to leverage a large number of resources that might not otherwi<e be avadable A principal reason to no t
make ,o(tware open source., to keep artifacts h.dden from current and prospc live competitors. o me (e .g.,
Ferguson [ 12] and Kapor) believe that o pen <ource may become the do minanl pro es lor produci ng
wltwarc
An ,nlerestlng art.cle wntten by Alall Jo~h dillstrates how Ihe ba nk Dresdner Kleim_on Wla sers leln
(DrKW) turned .t~ .nternally developed b.ck-c ndJa va integrallon too l, pe nAdap lcr, Into open <ollr C and
how It beneftted (rom the deci,lon . The (ollowinu "an 'XCC rpl (rom thaI Mil Ie
Samolades el.1 [ 1~ J studied ope n ' Iource d evelopme nl and compared .t w.th dOled s ure ..
>oftw.re Us.ng common me ln s, O code Qualtty was lound roug hl y equal to Ihat 01 _ , nnd 101lnd
to be supe-rior for mainta.nabd.ty . or at wo"t equa l n me o ( Ih el r result, nre Ih wn In F.gurn 3 19
and 3 lO .
52 CHAPTER 3 SOFTWARE PROCESS

open-source users find rewards in collaborative development


11 Alnn Joe"
1/ 1/100S hur i/www adtmas , o m/article .a<px1.d m 10544
Bo nk- pnde thcmselve o n pia ' In!! th.n~s close to the ve, !. 0 , when Drcsdner KlelOwort W asser'Ste .n's IT
grollp shared the code of O penAdapter, an intemally develo ped tool, w.th the developme nt commun.ty,
.t all ed 3 , em alion. "It was asto nish.ng: reca lls Steve H owe, DrK Ws Sloba l head of o pe n·souree
.nlt iJ lives. "They fo und .t dime"lt to believe a bank was o pen sourcing o meth ing."
pen dapter, a back·end Java integrat. o n 1001 thaI he lps integrate bank a pps w.th little or no
usto m ()rogramnllng, had become "a famolls piece o f so f,tware within DrKW," H o we <ays. "Half of the
decis .on to o pe n . ouree it into the w.der Ananci al communilY was to try to replicate that enthus iasm:
D rK\'v"s mot.ve fo r releasing the 1001 wa hardl y altru istic. By rcieasIIlg the too l to the wider
Anancial community , the ;nve<lmenl bank ho ped to beRe At fro m Ih c bug Axes and refineme nts other
programm ers in Euro pe and No rth America might make.
However, H owe and o ther o pen· ource experts wam that corpo rat.o ns' code·s haring projects
req uire a nllmber of safeguards 10 pro lec l intellectual pro perty and keep companies from becoming
un wi u ing v.ctlms o r d istributors of des trllctive code . Some co mpanies bel ieve such risks ourweigh the
potenlla l beneA ts and re ist o pen·source busines app"ca t. o ns. DrK Wand o lher Arms believe careful
ope n.source collabo rario n g.ves them a competitive advantage.

• •

Banking on open source


Dresdner Klci nwo rt W asse rstc," (DrK W ) believes it found development success wirh OpenAdapter by
creat.n g a va nation o n the co llaborative mo del the open·source community pioneered . . . . . "We
open sourced the 1001 within DrKW and told people that if they needed to change OpenAdapter
sligh tly, they were free to do that," Howe says, "A lot of developers decided they co uld make a name for
themselves by cont ri buting to the software ." Today, more than 100 applications in the bank use the
mtegra tion tool.
T o tap simdar expertise outside DrKW, the bank tumed 10 ColiabNet, a commercial project·
develo pme nt plalfo rm from ColiabNet in Brisbane, California. ColiabNet provides a number of
services, inclYd ing version control tools and discussion fon.ms common in free open ·source clearing.
houses such as SourceFo rge . .. . ColiabNet helped the bank establish a separate legal entity called Ihe
So ftware Conservanc y, which owns Ihe inlt,lIeetual rights to OpenAdapter.
The site publi shes the latest stable build of the sofrware, which anyone can download. Users can
also send in complaints and error reports and suggest bug Axes. So far, DrKW has received input from
devel opers at competing banks and from companies outside the financial industry. Collaboration
co nsists of lechnical subjects, nol information that involves trade secrets or conRdenlial customer data.
Devciopers .nterested in becoming more involved in OpenAdapler's evolution can gain access to
the source code by signing a legal agreemenl that assigns the intellectual property rights of Iheir code
to the Software Conservancy. About 20 developers now hold such status.

ompanies mI x and match opcn·source and proprietary processes according to buslncs nttds
F.gu re 3.2 1 suggests Ihal the pro porti on of o pen·source o r pro pnelary sofrware used. a bll IIle deci ion
ta ke n .n Ihe eonlex l of ex penses and revenues over t.me. An important factor is the expense of tn. lo ring and
• ••
malnta lnill g open SOurce
SOFTWARE PROCESS MODELS 53

@ Leveraging large number of resources


© Professional atisfaction
© To enable ta,loring and integratio n
© Academic and research
© To gain extensive testing
© To maintain more stably

Figure 3.16 Some reasons for making a project open source. 1 of 2

© To damage the prospects of a competitor's product


© To gain market knowledge
© To support a core business
© To support services
Figure 3.17 Some reasons for making a project open source, 2 of 2

® Documentation inconsistent or poor


® No guarantee that developers will appear
® No management control
® No control over requirements
® Visibility to competitors
Figure 3.111 Some reasons agamst making a project open source

Project , Total Code No, of Project


I
Mnemonic
Code
Application
Type
Size
(KLOCs) I ~1C!'asc'5
m('a u~d
Evolution
Path


,, Opel.tins 13 OSS project that ga""
I 'Y'km appliatlon I birth to a CSS project
while still evolvi"8 a OSS

Figure 3,19 Maintainability index comparing ass and CSS for the same application, 1 of 2
Scx.vQr ~, toanrVs, I SIbmC'IOS. L Artgclls, and A. Ofltonomoo " open source softwaro dOYOk>prnCOl 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
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 Sales. service. /


I
I productivity ....
I
Cumulative I
revenue I
I
I
I
Time
I
CumulaUve Open ~ource
expense " " :
development : maintenance
I
I
Proprielary

I

Fllllr. 3.21 Hybrid open-source/ proprietary processes


• CASE STUDY: STUDENT TEAM GUIDANCE 55

ColiabNet TeamForge: Structure & Features


My Workspace Community & Projects

'-- *"' • ..,..


' '''melt ' _

.. ..
-=..:-
I 'we&. AI'IJI' ICb
Pp'e;rtt
, i I

u...-.p.'I O'. +
t ...- ... " ' . . . . . .

Oft.4., ' .... _ .,.


"" $ : ...

_rapEl. ~

,:.elk 1M' ,","". do · dl

,.., 'tI 1'Ot-u.


\.Mit" Uk_40
_~..ub,no

lAc ....... .,.,


... .,.~'-

we"e", ' 1'Oj«U


• • 2,

M. 'I' "tOl'I/to.w
..,tfkU MId t ooh
b, p la~
(,,,"",.0-0_
eo
• 'i ,
prw. •
,.,,' ,--
..., 7,="
v, ..., ' 'ns
-- - " •

-- • ...
- ."' __ .0.111 I.

- C La
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 In what they produ e
• DtSi9" dorum(1,'alioll '(lids '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
56 CHAPTER 3 SOFlWARE PROCESS

Y u will he a,ked to ~c nera te speciO artd act<, and exa mple, WIll bc provIded , howi ng how real and
h i at hetl ca l tea m, 1(0 about develo pIng apD" atlOI1, We WIll o ft'cn USc the Encou nter VIdeo game case: study
a, all exa mple to dlu,trate team gUIdance
1any students look back o n the lf tcam proce,' as a Slgn lncant learnIng adve nture If the team
aVO Id, a few co mm o n i)lli all , th e adve nture an be a most enlI g htenin g and useful experience From
o ur i,ast experie nce , the bes t size for stude nt g roup, IS (our Or five . Any less and the workload fo r each
<tudent is toO great. More th a~ !lve doesn't afford all team members the opportu nity to contribute in a
mea nln g(ul way
T,p di tnbutcd th roughe ut th e te-xt arc desig ned to help groups maximize the benefit of group work. In
add,ti o n, cxerelseS at the e nd o ( th e chapter assign peclAc art ifacts to be developed as the prOject progresses
through the o ftware Ide cycle.
T he fo llo,"ing sectIo ns provide gui dance for hnld ing an initial team meetIng , developing a team
com muOIc;ltion plan. and exercisi ng the commun ica tion plan

3.3.1 Team Guidance Initial Team Meeting

T o start 0(1 ,he project , the team shou ld have an inItial meetlO g and make the decision sho wn in Figure 3.23.

Agenda
All meet lOgs should have a wnnen age nda and specific start and end times.

Team Leader
Decide who your Ars t team leader wi ll be (being a tcam leader provides yo u with valuable experience but puts
additional demands o n your time and communication skills) . To distribute the beneAt of team leadership
practice . It can be beneAClal to swa p team leadership about halfway through the projec t. Both team leaders
can be chose n up front , and they ca n back each other up in case of emergency.

i . Set agenda and tIme limits


2. C hoose the team leader.
3. Get everyone's commitmC!nt to required tim e.
o DeAne an expected average number o( hours per week.
o Cather da!es of planned abse nces.

4. Take a reali stic ce nsus of team skills.


o Commo n problem : inflated programming skill claims.

5. Begi n form ing a vision o( the application .


6. DeCIde how team will communicate.
7 Take meeting minutes with concrete .cllon Itcms.

Figure 3.23 initial student team meetlng-generai Issues


CASE STUDY: STUDENT TEAM GUIDANCE 57

Time Commitment
A big source of frustratIon in tudent teams is a lack of commItment of some team members. It is far better to
d, cuss commitment at the beginning than to try to fix a problem after the project is under way. To reduce
~he rc entment that follows when some team members feci they arc contributing much more than others, set
In advance an expected number of hours of commitment per week . This al,o helps to make members work
more efficiently .

Team Skills
For tudent projects there is often a trade ·off between producing an impressive · looking product and learning
new skill . To produce the most impressive product , team members would speciahze along the hnes of their
greatest strengths. This is a typical industrial mode . They may al 0 be tempted to sk ,mp on document.tion In
order to demonstrate more features . T o learn the most, however, team members need to try actiVIties '"ith
which they are inexperienced (e .g., team leade rs hIp). They also need to do thing rig ht. Teams deCIde how
and when to trade off between goals by speCifying when they WIll specia hze and whe n they wi.ll try new role
Instructors try to establi sh evaluation criteria that encourage learning.

Vision
All projects start out with a vision for the software to be developed In industry thIS is tYPI call y initiated by the
marketing department, which develop bUSIness req uirements fo r the product For ,tudent projec ts, the
product vision includes the purpo e of the application , major (u nctionality and operatio ns, and major ",puts
and outputs .

Communication Plan
Decisions need to be made as early as possible as to how the team will handle commUnicatIon . The next
section covers this in detail.

Meeting Minutes
During team mcetings, a member is de ignated to write the meet ing minute The purpose of meeting minute
is twofold. First, al l important decisions or agreements that are reached are recorded , ' 0 they are not forgotten
and can be referred back 10 if necessary . As an example, during the meeting it rna)' be decided that Coogle
Docs will be used for storing all project speciRcation . This decision is recorded in the meeting mInutes. The
second purpose of meeting minutes is 10 record unresolved issues that require follow up action. These arc
referred to as achon itrm s. Each action Item is assigned to one or more team members with a target date for
completion . An example action item might be that Joe is to investigate and recommend a sourCe o ntrollOol
for managing the project's source code, and is to complete his actIon In one week. It is a good Idea to revie,"
open action items at the start of each team meeting.

3,3,2 Team Guidance Communication Plan

When a softwa re prOjec t IS IOltiated in IOdustry, a set of project gUIdelines, 1001s, and commUOlcatlon
procedures IS tYPIcally established 10 ensure that the project IS cxecllled a effiCIently as pOSSIble ThIS hould
also be done for you r f(roup proje t.
Many team problem ari,<." (rom a failure to 01l1tnunicatc fully ThI S problem i nOt Itm ited to ,tudent
prOjcct,_ Real -world teams suffer from 11 as well. Errecl1ve verbal com01uOl ation means maklOl: sure our
thoughts are fully understood and I, steninll 10 what o thers arc ,ay'ng Th, " ntl al (or team' to be
58 CHAPTER 3 SOFTWARE PROCESS

I L"len 10 all Wllh on enl'" tl n

• Don't pre-judl!e

2 "ve all leam member; a turn

• ce Ihe value on every idea,

3 Oon'l make as,u mp" on

• Ask quesl lo n to clarify,

-\ , \'(fhc n in doubl , om munica le

Figure 3.24 Key precepts of communication

uccesshll. The pre epts shown in Figure 3.24 will h e lp you avoid ma ny communication problems. They
sound simple but ca n be hard to follow , especially during times of stress.
C reate pol,ei" for commun ica ting and sharin g informatio n with each other, oncludi ng gUi delines for
g roup ed'li llg and merging of documents, setti ng up a nd agreei ng to meeti ng times, sharing project artifacts,
and so o n
DeCide on procedures lor how yo u will ge nerate docume nts for the projec t. You pro bably ha ve to deal
wi th di ussing the scope and co nte nts of a document , writing initial dra fts, ed iting th e drafts, gettong group
agree me nt on edi ts, merging drafts and producin g the final document
Many teams-i ncludin g some stude nt learn s-a rc widely di stributed geogra phically, and the means of
commun ication becomes especi all y important. Large projects arc often developed by multiple groups at
mul tiple si tes, someti mes in multiple countries. Mergers, acquiSitions , "ollshoring," dis persed speCialists, and
joi nt ve ntures ofte n ro ult on people at multipl e si tes working together on projects.
An increasi ng number 01 products are available to lacilitate group work, including groupware, video
conferencing, and in tant messagi ng . Each com municatio n medium has speCific stren gths. In an y case, well-
run face -to -Iace meetings are very hard to beat. II possible, schedule re gular face -to-face meetings at least
once a week lor a n hour. It is hard to conve ne an unscheduled meetin g but easy to cancel a scheduled
meeting . You can make It a goa l to limit actual meetings to less time. However, il the committed time is
short-say a hall hour -you will ~nd It very difficult to make lo nge r meetings because people will build the
sho rt time Iomit in to their schedul es. If you think that your tcam may need to meet additionally, it is advisable
to agree o n when that would be each week. Set aside the time and aim to aVOid a meeting. This provides a
posi tive goal and it avoi ds the problem 01 repeatedl y trying to find a common time when meetings are
nee ded. When you set meeti ng times, specify an end time . Meetings typically expand to fill the allotted time.
You should always have an agenda for your meetings, otherwise your meetings will be less organized and not
as productive as they could be_
E-mail is an essential tool, but can be pro bl ematic due to unpredictable delays. Messages can become
unsynchro nized , damagi ng the threads of d ia logs. This is e pecially senous near the end 01 a project when
communica ti on is (TC:quent and of immediate importance
Use a shared Web Site, wiki , o r chat -ty pe faCility . For example, at the time 01 thiS writin!! , a number of
frec collaboration too ls arc available fTOm Coogle.
Do not merely state that you will use a particular tool such as Microsoh Word lor word processin,_
Specify a version number, and exchange a lew documen ts to be sure everyone c an read and edit them. Don't
c hange versions during the project without ensuring compatibility first ,
Document your decisions in a team (om... ". iratio. Pin. , as outloned in Figure 3.25.
SUMMARY 59

1 Meetings : TN'" ' vIII meet each Monday fro m .. to .. In .

tllHal do Plot rtpln ( In('(~lo -fa t nltttlt19 wtlh rt'"ott II1t(/II'9s u,lIns (('molt mttlh1gs arc
de.lr/Y .JJtt"hve.
2. Meeting alternative : Team members should keep Fndays open from .. to .. In case an additional
meetlng is required

Standards: Word processor, pread heet, compi ler, • •

4 E-mail : Pote · mails~; require acknowledgement]


nvtol (-milll is poor jar j"lflISiv( collaboratioll

5. Collaboration: Tools for group collaboration and discussion _


e .g. Yahoo Croups , Wiki too l, Coogle tools, ...
6. Other tools: Microsoft Project (scheduling), Croup calendar, • • •

Figure 3.25 Communication planning-forms of communication

3.3.3 Team Guidance Test Communication Plan

It is important to test the methods speciRed in you r Com munica ti on Plan so you can make necessary
adjustments as early as possible in the project. This will avoid scra mbling for alternatives a the project
workload increases .
Search the Web for the latest information o n a topic determined by the instnlctor. Note at least four of
Its baSIC goals and at least five of the techniques it uses. Have everyone in the group contribute ome
information. Create a document containing your group's results, and practice how you 'vIII utd ize your
procedures for group editing and reviews. How 'viII yo u o rganize thi random activity] H ow can you obtai n a
useful result instead of a conglomerallon of unco nnected text

3.4 SUMMARY

A software project progresses through a ~erles of activities, staning .t Its conccl>ti on .nd conllmllng all the
way through its release Project arc orga nized into phase , each with a set of aC!IVllies conducted during that
phase. A soflw.rt process preSCribes the interrelationship among the ph.,es by expressing their order and
frequency, as well as defining the deliverable of the proJect. SpeC ific sofrwdre processes arc called ,of'"'ar,
prow, ,"odd, or 11ft <yel, modd"
Most software process models prescribc a slmd ar se t of phaSe< and actlvitle< The difference b~twee"
models I< the order and frequency of the phases. The ph. es in lude planning , reqUirements anal SIS, deSign ,
Implementation , te ling , and maintenance
The walery.1I procc.s is one of the oldest and best known so ftw.re proces. modcl~ . Prole ts fo ll oWII1!; the
waterfall process progress sequentially through a senes of pho<es. \'(Iork tr.n ition< to a phase when work o n
the prevIous ph ase IS compl cted
/1".,,", and ,"cr""<tII"/ processes are c hara ten zed by repcatl'd exe ulion of the waterfall phosl's . "" ho le
Or ,n part, re>u ltlng in a reflncl11e nt of the reqUirement , de"gn , o"d Implementation . AI the on IU 51O " 01 an
Iteration, operational ode IS produLcd that uppom a ,ub~el of the nnal pr du t' lun 1I0 nolit)' Project
artifacts such a~ plans, > p ~Clh atlon<, and ode evol ve durinl! ca h pha~e and owr the Id e 01 tlw pr Ie t
Examples of lterallve Pfl)CC" s melude the <p lral model , the unlhed pro C" , and agi le pro C"t·<
60 CHAPTER 3 SOFTWARE PROCESS

A~,/, pro e"e< arc 1"8 hl itl'raII ve , and elllphas,ze workln~ ode Ih roughout, as wel l as frequent
,ntcra tinn.; with th e U\lOIlU.:r.
A PllllolyPt ' a partia l lI11pl emcnlallon of the largel app licali o n u clu l ,n ,dent"'}'ing and re llring rISky
part> of a projc 1. 11 can <o mel,m es be a way 10 ob lOln ,dea; aboullhe customer's reqUlremenls. An ,ncrease ,n
understandi ng whal. 10 come ca n ,ave expon ivc rework and rem ove htlure roa dbl o ks before they OCcur
lany tlcra ll c I>roce , 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 Manife<to (sec F,gure 3 14).
EXERCISES 61

Communication

For the following exercises, consider as a group how you will perform them , check the hints below,
then carry out the assignments .

TI . Decide who your team leader{s) will be . Note that being team leader provides you with
practice that may be hard to get otherwise.
T2 . Decide how your team will communicate, specify your communication tools and methods,
and test your communication methods. Be specific: YOll may change the specifks later.
T3 . Search the Web for the latest mfomlation on a topic determined by the instructor (e .g., the
TSP). Note at least four of its basic goals and at least five of the techniques it uses. Post the
references to the course forum or \'(feb site If there is one. and annotate your posting with the name
of your group . State individual or gTOUp opi nio n of the topic or issue.
Your team respo nse should be 4-7 pages long .

Hints for Team Exercises


TI hints: To distribute the beneRts of team leadership practice, It can be beneficial to swap team
leadership about halfway through the semester. Both team leaders ca n be chosen up fTont , and they
can back each other up in case of emergency. Such backing up is a good practice in any case, because
the probability of a team leader having to quit a project o r a class can be high . ote that the second
half of a project typically requires the team leader to make decisions more quickly than the first half
T2 hints : Examples are telepho ne, meetings, e-mail , forums , chat facilities , and Web sites.

I. Schedule regular face-to-face meetings at least once a week, if possible It is hard to convene an
unscheduled meeting but easy to cancel a scheduled o ne .
2. E-mail is an essential tool. but can be problematiC due to unpredictable delay . Messages can
become unsynchronized, damaging the threads (subjects) of dialog . This is espeCially senous
near the end of a proiect when communication is frequent and of immediate Importance .
3. Use a shared Web si te or chat.type facility . Free services are available at hnp://groups.yahoo.
com!, for example .
4. Do not merely state, 'We will use Superword for word processing ." Specify a version number,
and exchange a few messages to be sure. Don't c hange versions dunng the project without
ensuring compatibility Rrst.
5 Try out all the standards and methods you have chosen .
Throughout this program of study, validate your plans and inte"tions with practical tests
whenever possible. Try to u e at I~ast two independent tests. In genera l, assume that your project
Will be much more demanding In the future than it is at the beginning .
T3 hints: Usc th is activity to strc ~ your communication system . Forexample , you may want to set
up a Web site to which team members are to add new TSP mformation How will you orllaniu thi
random actlvlty7 How can you obtain a useful rc. ult In tcad of a conglomeration of unconne ted
text7
62 CHAPTER 3 SOFTWARE PROCESS

BIBLIOGRAPHY

I. Ro "O c, \: " ·M~n"t4lng the DC'v(lopmcnt o r Large Sohw3 rc YS It'lm o ncc:pts 3nd Tt'chnlquc'l: IEEE WESCON "70 , Aul\Kt
1970. pp 1- 9
2 BluMer, Kurt , .lnd Spence', I • 2007, "Mmt4~t"g hffolljW So/tuum DwdopMmf P,o), 's:' Addjson -Wc~IC)" , Peirson EduC1tlon, Inc.
kbum. Alistair · Unr.wdlllM I nc ~m('nl<ll Develo pment : )Jnuolry 1993 http://a ll~talr cockburn uYUnnvtilng+l ncre-mentll
.. devci opment l ;) cct~sc d November .s, 2()()<l j
... uSUnlano, MichJd, Olnd R. W dby "How Microsoft Builds SOhWolrt' ~ ( o",,"w,,.cotiopu: oj fJH ACM, Vol. 40, No 6( 1997), pp.53-6'
s. Boc:hm, B W "A Splroll M.1dd of Sohwan: Dcvc/opment and EnhJncemc:nl: IEfE (o",,,,,'n, Vol 21 . No. S (MayI988). pp 61-n
6 Jacobson. IV3r, J Rumbaugh , olnd C . Hooc h The lI" iflrJ SOfhj'fJrr Dmt/opl'flntl PHKnJ , Add,son . Weslc:y, 1999.
7. Sooch. CrJ dy Ob)trl-Onnttcd A"jll)'~ ' f (fltil [)cs.glf wit" AptJlir(,lIons, Addlson . W~Ic:y , I 99" .
8 Rumhaugh , James, M 8131111, W !'remcrlanl, F Eddy, and W , Lorenson , "Objut.OrindllJ Mode/mg m,J DtS'9"," Prenttce: Hall, 1990
9. LumJn, rol l S , Appl)'1"9 UMl Qlta Pallrm, Art ["'rodllC'l/olt to OU)tC'I-OrimItJ Aml/yr,s oJmI ON'9rt IInJ [krait"" Dt1J(U,,,rMtl," Prenlice t-UII ,
M

lOOS.
10 Ambkr, S. W " "A ,\iafttJ9rr, , .. ,roJIlCllo" 10 Ji)( Ral/oftal UK'fled Procm (RUPJ .. Ambyso (t (Dtccmber 4,2005) hnp:!/www.Jmbysoh.com/
unl flcdproccs ruplntrodu tio n.html (accessed November S, 2009 ].
1 I Beck, Kent , Mike Beedle , Ane VOln Bcnnekum , OInd AlistaIr Cockbum , · Man l rc~t o (or Agile Sohw;u't' Development,· feb 2001 . http://
a~plemani(est o org/ [accessed November S, 2009J
12 Ferguson, Charles, · Ho..... Lmux Cou ld Overthrow Microsoft ," T«lm ology Rrou1D Uun(2005 ). httpllwww.tcchnologyrevkw.coml
computmgl l4504! [acccssed November 5, 2009).
13 Samol .. das, loa nnls, I Stamdos, L Angel.s, ilnd A. O.konomou, "Open sourcc software devdopmcnl shou ld strive for t'Vcn grU(Cf
code mainliltnilbiluy: Co,"mUI'"cnlrolfs of tbe ACM, Vol. 47, No. 10, October 2004
Agile Software Processes

• How did agile melhods come about?


Planning
..... • What are the pnnclples 01 agility?

• How are agile processes carried out?

The Software • Can agile processes be combined


Development with non-agile ones?
Ufecycle

Design

Figure 4.1 The context and learning goals for this chapter

In the t9905, agile softwa re development came In lO being as an a ltern ",ve to the existing classl al
approa hes to ofrware engineering that were percelvt·d to be too · pro ess·heavy · TI,e e claSSical
approaches emphasize the need to plan projects In advJncc, cxpn:s, requirements In writing, provide:
"""tten deSign sa ti sfYi ng the reqUIrement , wrlle odc ba ed o n these de\lgn' an,fying the written
requiremcnts, and fina ll y 10 test the results A we ulstll<>ed in hapt er I and 3. how<'Vcr, Illany prOjects
(ollowlng the e steps exh ibit major prol lem, A primary rea,on I< that >takeholders do not ~ uallv kn w at the
mCeptlon of a proJeu entirely ,,,hat they reqUire Ag"e process!:, addre" thl< shan oOllng Thl' hapter
dc(,n~s w hat" meant by as"e dewlopment, des nbe< ,evera l peclfic softwa re proce"e. that adhere to allile
pnnclples and arc thus ons ldered .B"eprocc"e" and d"Lu ses h ow all " e and non -ag ile pr c'>es can be
coOlhtncd
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 <onwa re
d e c lo pm e nt pro",St. that th ey o mplnined were d o umenta tion dri ve n a nd pro css heavy. Their goal was
to produce a ,el of va lues and pnn ipks to help speed up development and effect ively respond to c han g~
ailing the mselves the AgIle All,ance , the g ro up's goa l was, In esse n c, to pro duce a d evelopme nt framework
:hal was dAcie nt and adaptable . Durin g th e 1990 , variou, Iterative so ftwa re mNhodologies were begi nn ing
to s"i n popularity. o mc we re used as the baSIS for the agi le fram ework These methodologies had dJffercnt
combinatio ns of o ld and new Ideas, but all shared th e fo ll owIn g c haracte ri sti c [ I)

• Clo<e co lla boration betwee n prog ramm ers and busi ness experts

• Face · to·l-ace communi catio n <as op po ed to d oc um e ntatio n)

• Frequent d e li very of worki ng softwa re

• Self·orga nizing tea ms

• Metho ds to c raft the code and the team so that th e Inevitable require ments churn was not a crisis

As a resu lt of t hei r mccting , th e Agile Alliance pro duced th e Agi le Manifesto [ I ) to ca pture th~ir
th o ug hts and id eas , and it is summari zed in Figure 4.2.
N o te that the Agi le Man ifesto IS not anti -metho do logy. Instead, its auth ors inte nded to resto re balanc~ .
For example , they embrace d esig n mo deling as a mea ns to belter understand ho w the software will be built,
but not prod uci ng dia gra ms that arc Rled away and seldom used. They embrace documentation, but not
hundre ds of pages th at cann o t practically be maintained and updated to reflec t c han ge [2J.
The fo ur PO Ints of the Agi le Manifesto form th e basIS of agile developme nt . The Rrst part of each
stateme nt speCifies a preference. The second part speCifies so meth ing that, alth o ugh important, is of lower
priority . Each of the four poi nts is described next .

Individuals and Interactions (over processes and tools)


For decades, manage ment practice has emphasized the hi g h value of commun icat io ns. Agile pract ic~s
emphasize the Sig nifica nce of hi g hl y ski lled ind ividuals and the enhanced expertise that emerges from
'"teractions among them . Altho ug h processes and tools are Important, skilled people should be allowed to

We are uncovering better ways of develop ing software by do ing it and helping others do it Through this
work we have come to value:

1. Individuals and interactions over process~s and tools

2. Working software over compre h e nsiv~ documentation

3. Customer collabor.ation over co ntrac t negotiation


4 . Responding to change over following a plan

That is, while there is value in the items on the right, we value the it~ms o n the left mo~ .

FIlii" 4.2 The AgIle Manifesto


AGILE PRINCIPLES 65

adapt the proce5 and modify the tools as appropriate to ge t their job done as efficiently as possible. As
suggested III [ 3J. agile ",ethods offer generative values rather than prescriptive rules, a nllnimum set of values.
observed in all IllIation , that generate appropriate practices tor specia l situations . Individuals and teams usc
these rulC'S when problems ari c a a basis for ge nerating soluti o ns that are appropria·te for the projecl.
ereali iry IS emphasized as a major means for problem solving. Thi s is in contrast to more rigid sofrware
proce e , whi h pre cribe a set of predetermined rules and force teams to adapt themselves to these rules.
Agile practices uggest that the laner approach is not effective and actually adds to the risk of project failure .

working Software (over comprehensive documentation)


orking software is considered the be t indicator of project progress and whether goals are being mel.
Teams can produce pages of documentation and supposedly be on schedule , but these are really promises of
what they expect to produce . Agile practices emphasize producing working code as early as possib le . As a
project progresses , sofrware functionality is added in smalllncremenlS such that the softwa re base continues
to function as an operatio nal system. In this way team members and stakeholders always know how rhe real
system is functioning .
Although Significant, working software is of greatly dimin ished value with out reaso nable documenta ·
tion. Agile practices emphasize that project teams determine for themselves the level of documentation that is
absolutely essential.

Customer Collaboration (over contract negotiation)


This statement emphasizes the fact that development team arc in business to proVide value to cuSlOmers.
Keeping as close as possible to your customer is a long-established maxi m of good business practice . Many
programmers are disconnected from the cuSlOmer by organizational layers and intermediaries, It is highly
desirable to remove this barrier. All stakeholders, including customers, should work logether and be on the same
team. Their different experiences and expertise should be merged with goodwililhat allows the team to change
direction quickly as needed to keep projects on track and produce whal i needed. Contrac ts and project charters
with customers are necessary, but in o rder to adapt to inevitable change, collabo ration is also nece sary [3].

Responding to Change (over following a plan)


Producing a project plan forces ream members to think through a project and develop contingencies .
However, change is inevirable, and agile practit ioners believe that change should no t only be planned for but
also embraced_ Very good project mana gers plan to respond to change, and rhis is a reqUirement for teams
operatlllg at the most effecti ve leve ls, as you will see when we discuss rhe hi ghest capabi lity levels of the
CMM I in Section III of this book. As changes to the plan occur, the team h ould not tay focu 'ed on the
outdated plan but deal instead with the changes by ad.ptlng the plan as necessary [3). Agile practices rely on
short iterations of one ro six weeks to prOVide timel y project feedback and IIl fo rmati o n necessary to as ess
project progress and respond as necessary.

4.2 AGILE PRINCIPLES

In addItion to the va lues dcscnbed in Figure 4.2, Ihe aUlhors of th e Agile Mani!e to oU llined a se t of ~uidi n g
prlllcipies that ,upport the manifesto. The,,, arc quoted from [ I) (bold added ).

• "Our nIghest priority .. to sa tisfy the custo mer through early and con tlnuo u. deltvcry f valuable suftware
• Welcome changin g requi remen ts, even lale In development. Ajlilc pro esses harness hange for the
OJstomer's competitive advanta~e .
66 CHAPTER 4 AGILE SOFTWARE PROCESSES

• Deliv~r working software frequently , from a couple of weeks to a o uple o f mo nth •. with a prefer nce to
tI,. shaner timesca le.
• BU5mess p~op l e and developer must work together dally throughout the prOject

• Build projects around motivated ind ivid uals. C,VC them the e nvironment and support they need, and trust
them to get the job done.

• The most effiCient and effective method of conveying Infonnation to and With," a development team IS
face-to-face conversation .

• Working software i the primary measure of progress.

• Agile process. promote sustainable developme nt. The sponsors, developers, and users should be able to
maintain a constant pace indefinitely.

• Continuous attemion to technical excellence and good design enhances agi li ty .

• Simplicity-the art oJ maXi mizing the amount of work not do ne-i s essential.

• The best architectures, requirements, and designs e merge from self-organizi ng teams.

• At regular interva ls, the team reflects o n how to become more effective , then tunes and adjusts its behavior
accordingly."

Many of these principles are implemented in prac tice by the agile methods de cribed in the next
section .

4.3 AGilE METHODS

This section describes some of the methods by which many agile processes practice the principles in the
Agile Manifesto.
Figure 4.3 shows the manner in wh ich agi le methods implement the Agi le Manifesto, a. fo ll ows. Agile
processes common ly employ small . close-knit teams; periodic customer requirements meetings; a code-
ce ntric approach ; documentation on an as-needed basis (e.g ., high-level requirements statements o nl y);
customer representatives working withi n the rcam ; rcfactoring; pair programming; continual unit-testi ng" and
acceptance tests as a means of setting customer expectations .
We next e laborate on the topics not already explai ned above.
Pa" programming is a fo nn of continua l inspection by one team member of the work of a teammate.
Typically, while one programs, the other inspects and devises tests. These roles are reversed for periods 0
time that the pair detennines.
Documenling 0" an a5-ntcd,d basi, usually ,"valves writing some high -level reqUirements but not detailed
requireme nts. These arc freque ntl y collected in the fonn of '"'' 5/0ries . A user story is a Slgn ltkant task that the
user wants to accomplish wit h the applicatio n. According to Cohn (4), every II er story consists of the
follOWing;

• A written description

• Conversations with the customer that establish a mutual understanding of It purpo e and content
• T eslS intendcd to validatc that the user story has been implemented
- - --
1. Individuals and interactions over and
tools

2. Working software over comprehensive


documentation
MANIFESTO _
3. Customer collaboration over contract
negotiation

RESPONSES :
4. Respond ing to change over fOllowing
a plan

a. Small, close-knit team of peers y y

b. Periodic customer requirements meetings y y y

c. Code-centric y y

d. High-level requirements statements only y y

e. Document as needed y y

f. Customer reps work within team y y


g. Refactor y

h. Pair programming and no-owner code y

i. Unit-test-intensive; Acceptance-test-driven y y

j. Automate testing y y

Figure 4.3 ways to address the principles of the Agile Manifesto

Examples of user sto ries fo r a video sto re applica ti o n are as fo ll o ws,

• "The use r ca n search for all D VDs by a opve n d irecto r."

• 'The user can establi sh a n acco unt tha t re me mbe rs all tra n ac tions wit h the c ustomer ·

• 'The u. e r can view all ava ilable in fo rmatio n o n any DVD "

o"lI"unl i"llractlo" a nd contac t With the cu to me r is ac hi eved In twa wa ys. Fi rs t, the wo rk periods ( 1- 6
wee ks, usually ) in whic h the each batc h o f reqUire me n t arc to be flll Rlled are speciRed With a tea m that
Involves the custo me r ('co nd, a cUSto me r re presenta tive I< e ncouraged to be part of the tea m.
TI,e e mphaS IS o n worki ng soflwart is rea lized by mea ns o f coding versio n o f the applica tio n a nd sho '"lng
them to the custo me r. These arc usually clo el y tied to corres po nding test< Indeed , Icsl-dnvOi drvclop",mt an
allile a pproach , actua lly has devel o pers wfIte test< even before devel opi ng the code
68 CHAPTER 4 AGILE SOFTWARE PROCESSES

Obtain hlgh-tevel - Oblaln requirements for


requirements next perlod's' segment

Relactor to
Relector to accommodate
clean up new
requ irements

Modify code and test code base


to handle additional requirements

• Typically 1-6 weeks

Figure 4.4 A typical agile development iteration

Rcfa 1011"9 is a process of altering the fonm of a code base while retainin g the same functionality . The
usual goa l of a rdacto rln g is to make the design amenable to the addition of functionality , thereby satisfying
the agile deSIre 10 respo nd "'CillO c hange. The very fact that the discipline of rcfactoring has been developed
IS a majo r f.clO r mak ing agile methods possible This book covers rdacto ring in Chapt.er 24 . Although
refactorin g is discussed latcr in the book , much of it will be useful before then and can be referred to
throughout the book.
Agile metho d. employ the developmen.t cycle shown in Figure 4 .4 . T y picall y , the requirements
are expressed in terms of lIser stories . Past experience in the project allows the team to assess its
_docily , an assessment of the relati ve diCficulty of tories and the rate at which it is able to implement
them
The schedule effects of agile me thods can be seen in Fib>tJre 4.5 . Planning is attenuated because there is
less to plan . Requirements analysis, design, and testing are often conRned to high levels. The emphasis is
mostly code ce ntered .

4.4 AGILE PROCESSES

"Agi le developmen t" isn't itself a spe iRe process or methodology Instead , it refer.; to any software proc('Ss
that captures and embraces the fundamental va lues and principles espoused in the Agile Ma.nifesto. The
following sectio ns illustrate and describe three agile processes as repre cntative examples.

• Extreme programming (XP)

• C rystal

• Serum
AGILE PROCESSES 69


Time line
Plan lor agile methods

C,"'X <,-. " '~I-. ...........~ ..........:.~;.o..~...... ""\"'~J:1: t</. ....


'.'~
. "'6_ . ___
••, • • , . ' ' V " ' '
-"--'--"."
. " .
.' -_.
_ "',,~ -t. _ . "" .
' ••

Implement in agile fashion

System tests not covered by agile method:

Figure 4.5 The agile schedule

4.4.1 Extreme Programming

In 1996, Kent Beck and co lleagues bega n a project at DaimlerC hrysler [51 using an approach to software
development that appeared to make marters muc h simpler and more efficie nt. The methodology he
developed and used became know n as Exl""" Prograrnrni>lg (XP) [6].
Beck [6] cites fo ur "values" gUidi ng extreme programmi ng, communication , sImplicity, feedback , and
courage. These are summarized in Fig,,"'s 4 .6 and 4 ,7. XP programmers communi cate continuall y with their
customers and fc ll ow programmers. TI,ey keep their design simple and clean , They obta in feedback by
testing their software, starting on day o ne. They deliver parts of the system to the customers as early as
possible and Impleme nt changes as suggested , With this foundation , XP programmers are able to
·courageously· respo nd to c hangi ng requi rements and techno logy [5].
XP was created to deal effectively with projects in wh ich requirements c han ge . In fact , XP expects
requirements to be modified and added , O n man y projects, custo mers start with o nl y a vague idea of what
they want. As a prOject progTesses and a customer sees working software , specifks of what they want become
progressively firm .

I. Communication

• Customer on site
• Pair programm Ing
• CodIn g st.1ndards

2, Simplicity

• M e taphor: e ntity names drawn from COmm o n met"phor


• S,mplest d eSIg n (or c urrent reqUIrements
• R.efac tOnng

Figure 4.6 The "values" of extreme programming, 1 of 2


SOuru- 8.:;)'... YMYt, •.~ PtOSfMlming Eltplak'wl EmbrAce Chang.," ~ddl50n·w8S1BV. '000
10 CHAPTER 4 AGILE SOFlWARE PROCESSES

I Feedback alwa y, a u!!hl

• onlJnual l c..~ "tln g


• Ol1tll1UOU' 'nlegra tl o n (al leasl dad y )
• mall ",lease (small e' l usdul feature ,el )

2 Courage

• Planning and esti matio n with u ~ t O lll cr use r stones


• a llectlve code owner-hip
• ustain ablc pace

Figure 4.1 The "values" of extreme programming, 2 of 2


SOUtre. Beck.. Kenl "Extreme Programming EkJ)Ialned' Embrar.e Chango," Addlson·Wesley, 2000

XP projecls are divided inlO ilerations lasting from one to three weeks . Each iteratio n produc~s
soft ware that is fu lly tesled . Al the beginning of each , a planning mecli ng is held to determine the COQ t~nts
of the iteration . Th is is "just · in . time" planning, and it facilitates th e mcorpora ti o n of changing
requirement s.
As code is devel o ped , XP rel ies o n continual integrati o n ralhe r that assembling large, s~ parately
developed mo dules. In the same spint , releases are modest in added ca pability . The idea is to bite off a small
amount of new ca pability, integrate and lesl it thoroughl y, and the n re peal Ihe process.
EXITeme prog ramming recog nizes Ihe all . loo . frequent breakdown in c usto me r devel o per reiation-
sh ips, w h e r~ eac h pa rry de velops a scpa ralc concep l of what's need ed and also h ow much th~ features
will cost to devel o p. Th e resull of Ihis mi smatc h is , all too often , a mad dash for deadlines, including
lo ng workin g ho urs and a n un suslainable pace. In respon se, eXlreme progTamming promot~s a modus
vive ndi thaI's susta mable in the lo ng term . In addition , it requires every developer to acknowledge up
front Ihat all code is everyo ne's commo n property , to be worked on a the project's needs require . In
o lhe r words, no code "belo ngs" to a prog rammer. This is in keeping wilh engineering practice , where a
bridge blueprint , fo r exampl e, is the product of an o rga nizalio n and nOI the personal property of
o ne desig ner.
XP is unique in usin g twelve practices Ihat dicta le how programmers should carry out their daily jobs.
These twel ve practices arc summarized next (7).

I. Planning Process . Req uirements, usuall y in Ihe form of user stories, are deR ned by cuslomers and given a
relative priority based o n cost esti mates provided by the XP team . Slories arc assigned to reieases, and Ihe
team breaks each slory into a set of tasks to imp le ment. \Y/e described user stories in Section 4.3.
2. Small Releases. A si mple system is buill and pUl inlo produclion early Ihat includes a minimal set or
useful reatures. The syslem is updated frequentl y and incrementally thro ughout the deveiopmenl
process.
3. Test-Driven Development. Un il tests are wrinen 10 leSI funclionality, before the code to implement
thaI functionalllY is aClually wrilten .

4 Refactorlng . Code is regularly modi fie d or rew ritte n 10 keep It simple and mainlainable Chang~.~
Incorporated as soo n as de Acie ncies are idenlified. We ,"troduced rdoc toring in S~tion 4.3 and cover It
in delail in C hapter 24

5. Design Simplicity. Desig ns are created 10 solve the known reqUirements, not 10 solve future rcqui~­
ments. If necessary, code will b~ refa lored to implemenl fulure dcsisn needs.
AGILE PROCESSES 71

6. Pair Programming . This was described in Section 4. 3

7. Collective Code Ownership. All the code for the system is owned by the entire team. Programmers can
mod,fy any pan of the ystem necessary to complete a feature they're working o n. Th ey ca n also improve
an part of the system .

S. Coding Standard. For a team to effectively hare ownership of all the code, a common cod,ng standard
must be fo llowed. 11,is e nsures that no matter who writes a piece of code, it will be easi ly understood by
the entire team .

9. Continuous Integration . Code is checked into the system as soon as it's comple ted and tested. Thi s can
b" as freq uent as severa l tim e per da y. In this way the system is as close to production quality as possi ble.
10. On-Site Customer. A customer re prese ntative is available full · tim e to determine requirements, sct
priorities , and answer questions as the programmers have the m. The effect of being there is that
commun ication improves, with less hard -copy docume ntati on-ofte n o ne of the most expensive parts of
a software project.

I I . Sustainable Pace. XP tea ms are more productive and make fewer mi stakes if they're not burned out and
tired. Their aim is not to work excessive overtime, and to keep themse lves fresh , healthy, and effective.
12. Metaphor. XP teams share a common visio n of the system by deR ning and using a commo n system of
describing the art ifacts in the project.

4.4.2 Serum

Serum is an agile methodo logy deve lo ped in the early 1990s . It is named after the part of a rugby ga me that , in
U.s. foot ball terms, is a cross between the kickoff and a quarterback snap . As deRned by the Merriam Webster
dictionary, a scrum is "a rugby play in which th e fo".ards of each si de come together in a tight fo rmat ion and
struggle to gai n possessio n of th e ball using thei r fect when it is tossed in among them ." In o ther words, scrum
is a process that follows "o rganized c haos." It is based o n the no tio n that the developme nt process is
unpredic table and complicated, and can only be deRncd by a loose set of activities . Within this framework ,
the development team is empowered to de Rne and execute the necessary tasks to succes fully develop
software.
The flow of a ty pica l sc rum project is show n in Figure 4.8.
A project is broken ,ntO teams, or scn,ms, of no more than 6-9 members. Each team focuses o n a e lf-
contai ned area of work . A scrum master is appoi nted and is responsi ble for conducti ng the daily se rum
meeti ngs, mea uring progress, mak ong decisions, and clearing ob tacle that get in the way of team progress.
The daily scru m meetings shou ld last no more than 15 minutes . During the mee ting the Scrum master,
allowed to ask team memb"r< o nly three questio ns [8]:

I. What ,tem< have been comp leted since the last serum meeting:
2. What issue< have been di covered that need to be reso lved)
3. What new assignments make sense for the team to complete untol the nex t scrum mee ting)

At the begonning of a projec l, a lost of cu<tomcr wantS and needs ,s created , wh. h IS referred to J the
"backlog," The" rum methodology proceeds by mea ns of aili le 30·day y les ca ll ed ' sprints.' En h spn nt
takes on a t of featu res from (he back log (or deve lop mcn!. Whole in a <print , the tea m is given cllmplett>
72 CHAPTER 4 AGILE SOFTWARE PROCESSES

every 24
hours

l S·mlnute dally meetings


1) Done since laSt meeting?
2} Have any obstacles'?
Sprint Backlog 01 Backlog 3) What will you do belore next
items 30 days meetrng?
assigned features expanded
•••• by team

New Functionality
Demonstrated
Product Backlog at end of sprint
Prioritized product features desired by
customer .

Figure 4.8 The serum work flow


SOUrce: QuoteCI and edited from t\rtf)'jfWvrIW coouolchaos.com/aboul

control of how they are to successfull y complete the spnnt. At the e nd of a sprint a customer demonstration is
conducted for the cuStomer. It serves several purposes, including [8],

t . Demonstrating to the custo mer what has been accomplished .


2. Giving th e develo pers a sense of accomplishment .

3. Ensuring that the software is properly integra ted and tested

4 . Ensuring that real progress is made o n the project.

At the co nclusion of the dem o nstration, the leftover and new tasks are gathered, a new backlog is
created r and a new spri nt commences.

4.4.3 Crystal

Crystal is a family of agile methods devel oped by Alistair Cockburn . Each Crystal method shares common
characteristics of "frequent delivery, close communication, and reRective improvement" (9 ). ot .11 projects
are the same , so differe nt Crystal methodologies were crea ted to address differences," project size and
critica lity. Figure 4.9 shows the different methodologies and the size project they are best suited to. Crystal
methods are characterized by a color, starting at clcar for smaIJ teams and progressing through to or""9'. mi.
and so on as the number of people increa ·os. For example, Crystal lear IS geared for smaIJ teams of
approxima tely 6 people, YeIJow for toams of t 0-20 people; Orange for teams of 20-40 people , and so o n, The
other axis deRnes the critica lity of a project, where L IS loss of life, E IS loss of es enllal monies. D IS loss of
discretionary monies, and C is loss of comfort . Note that the row for los of life" nOt shaded in Figure 4.9.
This is because Cockburn had no experience applying Crystal to the e types of projects when he .... ated th...
AGILE PROCESSES 73

L6
............. ,
,,,
E6

Clear

L; loss 01 life
E ; loss of essential monies
D ; loss of discretionary monies
C ; loss of comfon

Figure 4.9 Coverage of various crystal methodologies


SOUrce; Adapted trom CocXburn. AlistaIr, "Crystal Clear A Human-Powered MethodOlogy for Small Teams," Aadlson-wesJey, 2005

chart. Crystal Clear doesn't explici tl y suppo rt the E6 box, although Cockburn no tes that teams may be able to
adapt the process to accommodate such projec ts. Ano ther restrictio n of Crysta l is that it is al'plic2ble o nl y to
colocated teams.
Cockburn believes that deve lo pers do no t read ily accept the demands of fl"Y process (docu mentatio n,
sta ndards, e tc ). H e strongly recomme nds accepting thi s by Introduci ng the most limited amou nt of process
needed to get the job do ne successfull y, ma xi mizing the likelih ood that team members will actua ll y fo llow the
process.
All Crysta l methodo logies arc built around three commo n pri o rities (9}

I Safery in the project o utco me.

2. EffiCiency in development.
3. Habitability of the conventio ns (I.e ., the ability of devel o pers to abide by the pro es itself) .

Crystal projects exhib it seven prope rti es to varyi ng degrees (9)

I Frequent delivery .
2 Reflective Improvement.
3 lose commun ication

4. P -"ona l safety.
5 Fow,
6 Easy a"ccss to exp rt use rs
7 Technical ~nvlronm""nt With au to mated t('''tln~ , con If.:ura ti on manage men t, and Ircqllcnt In H:..:ratl n.
74 CHAPTER 4 AGILE SOFlWARE PRO ESSES

n,e I1r,t three p,opertl '~rc commo n to the ry\tallJmlly The others Cdn be ad ded ,n any order to
III rc."c the I'Ke llhood o f 1)l'o)ec t ,afety and SULtesS.

4.5 INTEGRATING AGILE WITH NON-AGILE PROCESSES

Th e advantage. 0 1 agile meth ods in lude the abll,ty to adjust eas ily to emcrlling and c hangi ng rC'Iu".ment'
n,c d,sadvantage in lude awkward ro le for de iBn and dowmentat, o n ockburn's Crystal fam,ly 01
meth dologies alrcady acknowledges that different k,nds of appllcallons must be treated d,fferently . L"Ven
when the metho ds are ag de .
oft",.re pro e. s, after all , oncerns the order in which we perform act,vities' Fo r example, deSigning
Ars t and then coding from the des'gn One extreme IS the waterfall process. As we have seen, there are many
IIm,talions in our ab d,ty to thorough ly perform the waterfall sequence:' o nce, or even a few times, 'terat,vely.
hangea ble and unknown requirements are a principal rea on Regardless of the development process we use,
we must make trade ·offs in deciding ho w ex tens,vely to pursue a phase befo re movlO8 to ano ther phase.
o nSider, for examp le . the issue of how much effort to spend on planning a software enterprise.
One extreme project situation is when we are certain of obtaining all of the requirements of the end
date , of the high ·level deSign , and of who wi ll be working on the job. In that case, we can and probably should
devel op a de tailed plan .
The other extreme prOject ,tuation is when ,_e have little idea of any of these factors , believing that
they wdl beco me clear only after the project is under way . In that ca e, planning at a detailed level would be a
wa te o f time at best becau e it could not be even nearl y accurate, and would probably even be misleading.
We ha ve no choice in this case but to begin the process , and revi sit the plan as required. The extremes are
Illustrated In Fi gure 4. 10.
Agile methods provide beneAts bur also costs, and these depend o n several factors . Some are shown in
Figure 4. 1 I.
In order to gain the advantages of both agi le and non·a gile' processes, we try to integrate them . The
means by wh,ch this can be performed depend on several !actors, but particularly on the size of the job. As of

100%
----------------------
• Can obtain all require",sntSr •
• Certain of end dale
• Certain of hlglHe.el design - "
..,
' .'

Advisable • Certain of personnel


,,
delallievel ,
01 plans ~HIGH DETAIL PlAN ,,
,
.- ,
~LOW
,,
_ _ _ _ _ _ _ _ _ _ _ _ Extent o(
,,
0% knowledge
100%

Figure 4.10 HOw detailed should plans be?

Some: authors c haracterize n n 'JKilc processes For C'x.lmplc. one practice j, to 311 them "plan ~based ." The- autho~
I

do not believe ,n a I\lOglc Ch"fiJcteri zatlon like thi~ of non-agile proc~s~C's; hence thc= blankf!'l tenn -non.oglle ·

INTEGRATING AGILE WITH NON·AGILE PROCESSES 75

Benetlts 01 Aglig Costs 01 Agile


@ Motivates developers ® Hard lor new panlcipants
@ Thoroughly tested. usually ®Sensltive to individuals
@Easler to estimate each cycle ®Hard 10 estimate lull lob
@ Responsive to customer ®Umlls learn size
©Always demonstrable sohware

Figure 4.11 Trade-ofts between agile and non·agile processes

2009, the conventional wisdom concerning the agile/non .agile split is shown roughly in Figure 4. I 2, The
larger the job , the more non-agile process is required.
Agile processes empha ize code first, whereas non.agile ones advocate coding on ly from well·
documented designs and designing o nl y from well·documented requirements. These approaches appear
to be almost contradictory, so combining (hem requires substantial ski ll and care . We will co ncentrate on
methods for doing this in large jobs, where th e c hallenges are greatest. We will ca ll the two options "oll-agile-
drivrn and agile-driu<II and will compare them .

4.5.1 A Non-Agile-Driven Approach

A common non·agile-driven approach is to initiall y approach the job without agility , then fit agile methods
Into the process after sufficient work has been done to define the agile ro les and portions. We develop a plan ,
create a ca rehll high. level design, and decompose the work into portions that can be implemented by teams
In the agile manner. One can superimpose upon each agile team a process by whic h the accumulating

Percent
agile vs.
non'agile
t
100%
.,-
-
C>
,
'c"
0
Z

..
i
I
SmaJ/ Large Job slzo

Figure ' .12 conceptual agJle/non-aglle combination options: some conventional wisdom, circa 2009
76 CHAPTER 4 AGILE SOFTWARE PROCESSES

- - - - - - - ; : : : : : - - - - - - -•• rima
I
Requirements
documentation

Design
2
documentation

._--......- ... . ", . - - --


Coding and 3
testing

System testing 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 77

Time

M I L E S T 0 N E S
First /teralion' completed X Product released X

SCHEDULE
Iteration number 1 2 3
• _. ' .
• w_._.
Requlrements
d ocumentatlon • • •
l' "Tf _.
• '- - --- - .
- .- - ---
oeslgn •I • • -t-
d ocumentallon '--
_ _ _N _
.- -- ._._- --t- .. • -- -'
Coding and ....i.
t estlng
- -.---- -- • - -, -- -
s ystem testing , 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 \
/~ \
f \
Requirements
documentation
'i : I
\
\
\
Design
' ''iL_ _.....J1
documentation

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".
78 CHAPTER 4 AGILE SOFTWARE PROCESSES

• TI,e need to collaborate close ly wilh cm lomors and other ,takeholders


• omtl'lUniCJIIOI1 over do umentatlon
• Frequent delivery of workll1!; software
• elf orga niz II1g reams
4

• TI,e need to embrace and plan for changing requirements

Any process that embraces Ihe fundamental values of the ag ile manifesto is considered an agile process.
Examples include extreme programmll1g , scrum , and Crys lal.
E '\Teme programmIng is ba ed o n four prin iples : communicat Ion . feedback , simphclty, and courage. It
promotes practices such a lest-driven development, refactorl ng, pair· programming , collective code owner·
ship. continuous integration, and on·sitc customer.
Serum deAnes a framework , o r a loose set of activIties Ihal arc employed by the crum team . At the
beginning of a project , a btl klog of work. or requirements, is identified . Deve/opers work on a subset of
reqUIrements in the backlog in 30-day Sprill!S . Once a spri nt begins, the team is gIven the freedom to employ
any methods deemed necessary to complete their work sucLessfull y. A customer demo occurs al the end of
each sprint. A new set of work is defined from the backlog fo r the next spri nt and the cycle continues.
Crystal is a fam ily of methodologies that address projects of differe nt size and crit icality . Crystal
methods share the following characteristics: frequent delivery, reAective improvement, close communication,
personal safety, focus , and easy access to expert users, and a lechn ica l e nvironment with automated teSling,
configuration management, and frequent integrati o n.
Agile and non· agile process ca n be integrated o n projects in order to gain the advantages of both . The
means by which this ca n be performed depend o n severa l factors but particularly on the size of the project. One
approach IS to Initiate a job without agility, then incorporate agile methods into the process after enough work
has been accomplished in defining agile roles and responsibi lities. Another approach is to initiate a job with an
agile approach until the outlines of an architec!l;re appear. At that poinl , non ·agile methods are used_This may
involve reintegrating agile programming again as described in the no n.agi le-drive n approach above.

4.7 EXERCISES

I. The Agile Manifesto favors working software over exte nsive documentation . Under what
circumstances can thi s calise problems if taken to an extre me]

2. . . In your own words, explain how agile processes adapt to and embrace cha nging requirements.
b. Describe a scenario in which this mi ght be counterproductive
3. Name three benefit of the XP practice of testi ng oftware from "day one," always having working
software available.
4. During the daily IS -minute scrum meeti ng, the leader is only allowed 10 a k the same thlee
questions . What two additional questions mig ht you want to ask] For each , explain lIS benefit
toward achieving the goals of the meeting.
5. In your own words, explain how Crystal adapts to various types 01 projCCts.
79

I Bcd. K<o~ /'.I,ke ~I<, An. VOIn Iknnckum, .nd AU"." Cocklxom, "MA.;J,,'" lor Aglk Sol'."", Dno<kop,... ( ·· Feb 200 I. hUpJI
OII'k" .. n,b,o.orW [>cee,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'..." Dno<iop"",,': Add;son·Wcsky. 2004.
S. Wells, Oon, -Ext" t Pr09'''.... '''f A c;..,.tlt ,,,,roJUfhOJl - hupJlwww (xlfcmcprogr.lmmln8 .0 rg/ racc~~d Novm1bcr IS , 2009].
6 Ike Kent, ooExtrtU P~'~.i"9 Ex,,"'iMd. .e..brder C'b.l~t." Addlson · W~ley . 2000.
7. }effriC'S, Ron. ~r~.cOffl: A.. Agilt SoJI1N~ I)n,dopmcn' Rncwrct " hup://xprogramming .com [accC'Ss.c:d November IS , 20091.
Ii. 8c:cdJe, Mike. M.. nlnc ()n.os, Yonal Sharon, and Ken Schwillx:r, -SeRUM, All atmsioll ~11r", """gtulg( fen ~roJlldioc roJfvNm
I ......~ iM' " http://jeff9.nhc:rland.comlscrumlscl'Wll...,plop.pdf [accc:ssed November 15, 2009]'
9. Cockburn, Alastair, "Cryswl Ctt.u,. A H"rfI,Q"-PDvxml MclboJology for S...all Tw",s." Addison.Wesley, 2005.
uality in the Software
Process

• Whal are the principles of managing


quality?

• How do you plan for "quality?'

• Whal are inspections and how do you


The Software carry them out?
Development
Ute Cycle • How do you carry oul
reviews and audits?

• How do you measure and improve


sohware processes?

• In wi1at way does CMMI assess


organizational quality?

• What does a sohware quality plan


look like?

Figure 5.1 The context and learning goals for this chapter

This chapter discusses the manner in which we integrate and manage quality throughout the software
development process. ThIS is an integral part of project planning. and it affects every phase of development.
As part of planning, documents are produced detailing the quality approach to be taken, including specinc
quality goals. techniques 10 be employed, melrics 10 be collected, tc~ts to be run , and t he manner i n which
PRINCIPLES OF MANAGING QUAUTY 81

• Quail! princIples
--<ovcrarchinll qualtty Iluidelines
• uality planning
--<Quality plan deAnes overall approach to Quality
• In peetlon
-peer processes focused on Quality
• Reviews and audits
-~extcmal Quality as essment

• Defeet manage me nt
-identiRcatlon , tracking, and resolution of defec ts
• Process improvement
--<continuous upgrading of process effectiveness

• Organizational quality
~engineering competence levels (e.g ., CMM I)

Figure 5.2 Quality in the software process

defeets are to be handled. All of these contribute to an effective development process with a focus o n qual ity,
result ing in the development of a high .quality oftware product. The integration of Quality in the software
process is summarized in Figure 5.2. Each topic mentioned in the figure is described in thi s chapte r.

5.1 PRINCIPLES OF MANAGING QUALITY

An overall approach to quality is guided by several principles . The planning and practIces described In thIS
chapter are implemented WIth these principles in mind, as follows .
F,rst and foremost , quality IS something the entire devel o pment team is responsible for . not ju<t the
quality assurance team . Thi i the meaning of the Rrst point in Figure 5.3, fOCUSing "con tinuously on Quality."
It IS thus an integral part of the development pro css, and each phase mu t incorporate qualtty practices. For
example, peer inspecti on arc carried out for each art if-act when it IS ge nerated . Dt' pending o n the artlfa t
under review, stakeh o lders from different hlnetions su h as market ing , cu tomer serv lcc, <oft ware develop ·
ment, customers , and so on participate in the inspection . Inspectio ns arc di, cusscd In detail in ectlon 5.4.
Another exam ple is test · drl ve n development (TDD ). which is I,revalent in various agile processes . It dictates
I

I. Focu. c.ontinuously on qualtty .

2 A qualtty assurance proce" must be dcAned


3. The or8aniz~tion must follow its qualIty assuran c process
4 . Ftnd and rcpair defec ts as early in the development pro CS< a\ po<>lble

Asur. 5.3 Key prlnciPles of manag1ng quality


82 CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS

If defect found . . .

Reason (by one estimate): ... soon after creatIon . . . at IntegratJon time

Hours to ..

.. detect 0.7 to 2 0.2 to 10



.. repa ir 0.3 to 1.2 9+

Total 1.0 to 3.2 9.2 to 19+

Figure 5.4 Cost to repair a defect. depending on time elapsed since injection

that developers write tests befo re co d ing, and then write code to pass their test . roo is discussed in more
detai l In C hapter 27
Q ualit y assuran ce (QA ) refers to actions taken to assure that a product under construction attains
reqlllred levels o f quali ty . The second and th ird principles listed in Figure 5.3 state that a QA process must
be defi ned and fo ll o wed. Thi s IS ho w so much quality has been encouraged by the International Standards
O rga nI za tIo n (ISO ) standard 900 I "Quality Systems-Mode l for quality assurance in d esign , develop·
ment , productIOn . in talla ll o n, and servici ng." Many compani e have c reated documents describing their
offiCIal Q A process. ISO In SIS ts o n the exi stence of such documents for companies seeking its certification.
H oweve r, I 0 recog ni zed that a do cumented procedure is only a part of quality assurance. In practice,
do um ented quaht y procedures are often ig nored wit h impunIty; hen ce ISO's second principle, which
e nsures that empl oyees actua ll y fo llOWIn g qua lity procedures. Quality planning is discussed in mo re detail
in Secti o n 5 3.
The fourth softw are quality principle listed in Figure 5.4 is to find and fix defects as early as possible: i.e ..
to prevent them from persisting for more than a sing le phase . Figure 5,4 provides dara fro m one of the author's
clients o n the relative cost o f allo wing a defect to persist. Many organizations have rried to measure the
difference in cost. and It is always found to be very large . A rule of thumb sometimes used is that a defcet
costIng a do llar to fi nd and repair soon afte r its creation costs a hundred do ll ars to fi nd and repair if del ivered
to the customer The main consequence of this principle is that it most often pay to spend significant
resources findin g and fi xing defects as earl y as possible rather than allOWing them to remain undetected and
active.
,

5.2 MANAGING QUALITY IN AGILE PROCESSES

Agile and non ·aglle projects arc equa lly concerned with producing quality products. but agile methods go
about this in different ways . In particular, agile response to t he prinCIples of Section 5. 1 are as follows:

I Focusing continuously o n quality


Agile processes fulfi ll this principle by creat Ing increments from close customer contact , b testIng th¢m
during development, and via prearranged customer acceptance tests.
QUALITY PlANNING 13

2. DcAn.nll a qual.ty as,uran e proces


Ag.le proccs rdy On rhe activities jll t listed for a QA pro ('55 , rather than o n documentation ueh as
the IEEE ·tand~rd di IIssed in this c hapter \'ifhcther th. .s sufAcient , especially for large projects,
remains 3 subje t of debate.

3. follOWing the organization' quality ",surance process


Whether or not one doubts the adequacy of agil.ty for quality .n large prOjects, team members arc
generall ",dl motlVilted , and they usually follow agreed· upon methods very faithfu ll y.
4. Finding and repairing defects a early in the development proce" as possible
Here, agile methods show their greatest stre ng th , s.nce they are code centric and thus try out
implementation and testing of the pieces as soon as II is possible

5.3 QUAUlY PLANNING

We begin planning for qualoty early in the development Iofe cycle . Documents arc written that denne an
overall approach, including quality goa ls and techniques for every deve lopment phase (the Software
Quality Assurance Plan ), how the product will be verified and va lidated (the Software Verincation and
Validatoon Plan ), and how testing is planned , specined , and reported (the Software Test Documents ). Th e
Software Quality Assurance Plan (SQAP) is desc ribed below, the Software Verification and Validation
Plan (SVYP) is described in C hapte r 9, and the Software Test Documents (STD ) arc descri bed In the
testing chapters of Part VII .

5.3.1 Software Quality Assurance Plan

The Software Quality Assurance Plan (SQAP) specines the overa ll quality plan , policies, and procedures that
will be followed by the team It provides guidelines so that quality aClions are nOt an afterthought but
something conSCiously and deliberately stnven for and practiced throughout the development proce s. It
orients the project toward prevention denning procedures for proactively mo nitorong and improving
processes and quality, ensuring that qualoty practices are defi ned and implemented, and ensunng that
problems are identified and resolved as early as possib le. T o do this, the QAt> answers the questions posed .n
F.gure 5.5
The rest of this section addro<se< these question in turn .

1. Who will be ReSponsible for Quality?


An ond.vidual or group is .dent ified as be.ng responsible for as<uring quality on a project. The Ind. vidual or
group is ta~ked with ensuring lhat quality is integrated into all a t.vol.e< . theor cxi<te ncc docs not alter th<'
princ.ple that quality .s everyone's responsibolity. For vcry small projects, there may be no exp lic.t A
organ.zat.on , making QA th e responsib.lity of the project man.geme.ll plan . Large projl' ts requore <everal
QA people, led by a QA manager ometimes an organization's QA manager is the QA lead on ,evera l
projec ts For truly large proJects, the QA funct.on has .t, ow n management h.erM h),. In the author'<
experience, a project requi re.; roughl y one QA person· month for every 3 to 7 developer per<on . months Tho.
excludes d~...,elo per te"i nll , wh.ch is u~uall y con ••dered internal becau,,, .1 require< ont.mate knowlcdg<· of th e
cks.gn and .mplementat.on. An example of e~ tomated QA requirement s Is summarized In Figure 5.6

2, What Quality DocumentatIon Is Generated?


The SQAP spec.f.es the docun1~n t s tt) be generated for a prOject and how they ar to be he ked for a ura y
Examples of do um~nts are the o ffw ar Requirement, . peclOcut.on ( l. oftwar Des.!!n Document
a. CHAPTl:R 5 QUAUTY IN THE SOFlWARE PROCESS

I \xfho wi ll he rc>pon,ible (o r qualhy)

A PC:f"\OI1 , a O1 anJ~('r. J group, an organiza ti on , etc.

2 ~ hat doc umentalion will be ge nerated to guide developme nt, venRcation and va lidat ion, usc and
malOtcOJn (' of the o ftwilrc7

3 ~ h at standards will l>e u<ed to e nsure quality)

D ocumentatio n tandards, codlllg tandud , e tc

4. \\'lha t metrics will be used to mo nItor quality)

Pro duct and proces, metrics

5. \\'lhat procedures will be used to manage the quality process)


Meetings , audi ts , reViews , etc.

6. What kind of testing will be performed)

7. \\'lhat quality as urance techniques will be used)

Inspections, proofs of co rrec tness, tests, etc.

8. H ow will defects be handled)

Figure 5.5 What's needed from a Quality plan

(SOD), Software VeriRcatlon and Validation Plan (SVVP), User Documentation, and the Sohware
Co nRguration Management Plan (SCMP). The SRS deRncs the requirements (or the software, and the
SOD describes how the software is designed to meet the requirements. The SRS and requirements are
covered in Part IV. The SOD and software design are covered in Part V.
The SVVP describes methods used to verify that the requirements speciRed in the SRS are the right set
of requirements, that the requirements arc correctly implemented by the SOD , and thai the design in the
SOD is correc tl y implemented by the code. VeriRcati o n methods include inspection , analysis, and testing.
Inspecti o n is described in detail in Section 5.4 . User documentation describes how the sohwarc shall be
successfully and correctly used . It also describes error messages and corrective action to take as a result. The
SCMP detai ls how changes to software and documents are managed , and is described in greater detail in
Chapter 7.

• I QA person per 3-7 developers

• Excludes developer testing counted as developer time

• Includes post-developer testing

• Ideally performed by external QA per onnel

FIgure 5_6 Typical estimate of QA requirements per developer


QUAlITY PlANNING as

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.
86 CHAPTER S QUAUTY IN THE SOFTWARE PROCESS

Projoct Management

IQ. PIIn 7ID I "


r-----__.: ,-EXPlains quality policies
,",' '-
Requirements , ....... \ ......... "-
Analysis "

.....---_--, I I \
~v.v PIIn 1cn2~ I '
t-- - Design
II
Explains verification

,
and validation procedures ......... __

........
--
---
_.
Implementallon
.........
-- ---- -1L _ li
_....
_....:
.. =--_.......J1
Explains plans, procedunts,
and test cases

Figure 5.7 The main IEEE software quality documents

I. Purpose 6. Reviews
6.I Purpose
2. Referenced documents
6 .2 Minimum requirements
3. Management
6. 2 . I Software speci ficatio ns review
3. 1 O rga nization
6.2 .2 Architecture design rcvie,,'
3 .2 Tasks
6 .2 . 3 Detailed design review
3.3 Responsibilities
6 .2.4 V&V plan review
3.4 QA estimated resources
6 .2.5 Functional audit
4 . Documentation 6 .2 .6 Physical audit
4. I Purpose 6 .2 .7 In -process audits
4 .2 Minimum d.ocumentation requirements
6 .2 .8 Managerial review
4 .3 Other 6.2 .9 SCMP review
5. Standards, practices, conventions, and 6 .2 . 10 Post-implementation review
metrics
6.3 Other reviews and audits
5. I Purpose
5 .2 o ntent 7 .- 15. See next figure

Figure S.B IEEE SOftware Quality Assurance Plan table of contents 1 of 2


Sourer. IEEE Sid 730-2002..
INSPECTlONS 17

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 <cClIo ns that lollow dl'Scrilx ~a h
01 th se,
CHAPITR 5 QUAliTY IN TIlE SOFTWARE PROCESS

I PCCO' pro eS5

2. pe IRed rob
3 Delcc t dete tio n i" lead of defee l repair
4 U se of heck!'sts

5 Arlif" t readiness
6 . Adequate preparallon

7 . Metrics COllec lio n

8. Time limll

1. Peer Process
Inspecli o ns arc co nduc lcd by a group of individual; who are familiar with the artifact under reView They may
be software engineers, members of other departments such as softwa re quality assurance, marketing, sales, or
cu tomers. The inspec tion is a peer process with an overriding goal of discovering defects The work ,n
progress is under inspection , not the performance of the author, and therefore it is not a supervisor·
subordinate process. An author is responsible mainly for the product he or she submits aJttr inspection, not
before. The work brought 10 the inspection should be the author's best effort, not a draft .

2. Specified Roles
Inspections work bcst whcn speCific roles arc assigned to each participant .
The moJrralor is responsible for leading the inspection and seeing that it is conducted in a productive and
ef~cie nt manner. The moderator schedules the meeting and ensure that it starts and ends on time. with the
latter bems accomplished by maintaining an appropriate pace throughout. It is very easy for participant.s to
get bogged down in details and to try to solve problems during the meeting. It is the job of the moderator to
prevent this from happe ning and to keep Ihe meeling moving along . However, the moderator must 31so
ensure that the pace is not 100 fast as to miss defects. When defects are identified, the moderator is
responsible for e nsuring that there is consensus from the team . Thu , to be effective a moderator should be:
technically competent The modera tor is also an inspector. TI,e job can sometimes involve sensitive issues,
such as having to moderate among hostile participants wilh differing opinions. As de robed by Wiegers,
"Moderators hould be trained in how to conduct inspections, including how to keep p3rticipan~ with strong
technical ski lls but low socia l skills from killing each other." [2J
The a""hor is the person responsib le for the work product itself, and repairs all ddects found (offline).
The author is also an inspector, looking for defects along with other inspectors. In order to avoid bias, the
author should not serve in any other role. Authors must remain objective throug hout the inspection and not
become defensive. This ca n be hard as others arc ~nding "faults" with their work.
The record" is responsible for writing down descriptio ns and classifications of th~ defec~ found,
and for recording the action items. If the inspection team is very smali, the moderator could also take on
this role, but it usually is best to have someone else assume this responsibility . The recorder is also an
inspector.
A "aJ" is responsible for leading the team through the work In an appropriate and thorough ",anner.
This person selects the most effective sequence for presenting the work product and answer qu~stions ~
by the in<peetion team. The reader i also an inspector. In many cases, the role of the reader is handled by the
moderator or author.
An i"sp, lor is a participant who attempts to identify dcfe ts in the artifact under review.
INSPECTIONS 89

All particIpants on an Inspectio n act as inspecto~, In addition to any other rcsp'onsibil,ties they may
have. It i important to invite people who can make a significant contribution and have the expertise to
identify defect to the in pection. Examples of people who should attend arc other prOject membe~, those
responsible for testing o r maintaining the product, and depending on what artifact is being develo ped,
customer and busi ness repre,entatives. Depending on the artifact being inspected, there may be a
requirement for specia lized inspectors. For example, a Joc""d ,"spec/or inspects for a specific criterion
(e.g., rellabiliry). A sprcial;z,d ;IIspec/or is a specialist in the area covered by the artifact under onspection
(e.g., a radar expert for a radar contro l applicatio n).

3. Defect Detection, not Defect Repair


Inspections should focus on identifying defects, and specIfically excl ude any discu sion of their repair The repaor
process is left to the autho r, and no time should be spent durong inspectio ns even suggesting repai~ . All repair
suggestions should be made offline. This is rypically one of the hardest things to control-many partIcIpants love
to discuss potential solutions and it is quite easy to fall onto intemlinablc tcchnica l discu sions regarding the best
approach. This IS where a strong moderator i essential. It is key to not let this rype of d,scuss,on continue and
instead to remind people that the goal of the meeting is to identify defects, not repaor them .

4. Checklists
A checklist can be very useful in providing gui dance to inspectors, describing specific areas to pay attention
to. Each rype of artIfact such as project plan , requirements peci~cation , design peclncatlon , configuratio n
management plan , source code, and so o n should have its own check lost, as each requires dIfferent areas of
focus . Example questions to ask when examining a requirement speci fica tIo n mig ht be as follows : Is each
requirement verinable by testi ng] Is each requirement uniquely identified] For code inspecti o ns, ques tI ons to
ask might be: Are there any variables that are unused or rcdundanols the code adequately commented] Good
examples of checkl ists can be found In (3).

5. Artifact Readiness
The artifact under review should be in the best sta te of readiness that the author IS capable of. For document
there shou ld not be many , if any , sections with "to be determined : Code should compi le cleanly \'(fhen a
group of people takes ti me to ide nt ify a defect that the author would have fou nd wi!h reasonable effort , a
significa nt amount of time is wasted .

6, Adequate Preparation
Inspections are not the sa me as reviews, manage ment overviews, or education sessions Inspectors have to
work. at the same level of detail as the author. (This is what make, inspections time ·consumong and thus
expensive.) The artifact under review is distributed several days before the meeting, all owi ng inspectors
adequate time to study the maten al, identify defec ts, and prepare questions to ask at the in pectlo n
Inspection.aidi ng software can save time by allowing inspectors to enter de criptions of defect they discover
while preparing The recorder accesses and ed Its these at inspection meetongs

7. Metrics COllection
During inspectIons, metrics arc collected and analyzed Examples of metries to colic t arc a fo ll ows:

• Number of defects discovered , by severiry and type


• Number of ddcc t ~ dl .covcred by each ca tegory of stakeho lder Inspe ting the artifact
90 CHAPll'R 5 QUALITY IN THE SOFlWARE PROCESS

• umber of del cet< per r~!!e rev Iewed

• Revle rotc (number of pOHe ho ur )

For , everi ty , a Impl e lo,,,f,ca ll o n su h 0' l' IIIWI , ",,"or, and lev'" ~o n be used For Iy pe , ca tc/jo " es such as
1l11 '3,m g uncti on, Inco rrect JlInctl o n, pcrrorrn ancc , il nd usabil ity an be used Thl ~ class ificat ion tOpIC IS
d,sc u,sed In e tl o n 5,6. 1
The me trl , w ll ec te d fro lll in pc li o n, arc analy zed and th e resu lts used lo r seveml purposes First, they
arc use d to pred, t th e dnc,e n y of future review If a company h., ", formatIon o n th e rate 01 rev,cw lor a
part ,cul ar am /oc t, ,t can u'e th at to predl t ho w lo ng to , hedul e lor a luture review of a SI mIlar art ,/a t
e o nd , co untin g the number 01 defec ts discove red dUrin !! each sto ge o f deve lo pment is useful ,n pred,c ting
th number 01 defe t, rn hllurt proJectS Even Illo rc spec d, c , o untln!! th e number 01 defects d,scovered by a
.r
p,rrhC'lllnrslnkrholdtr «- .g ., marke tIn g , cuSto lller, QA ) is also usefu l. For exam ple, dunn g a req uire me nts revIew
lewe r than ex pc ted ddc t are d, scovered by the customer represe ntative , ,t could rnd,ca te e Ither a lack 01
preparation o r 1111 und ers tandrn g 01 requirements by that perso n . In ei ther ca e , this would mise a red Aag and
a lollow-up Ill eeti ng WIth the custome r wo uld e n ue to und ersta nd the cause lor the discrepan cy .

8. Time Limit
InspectIO ns sho uld not be Illorath o n 'cssions, wh ,c h ca n occur if the mo de rn to r docs not keep th e meeting
mov ing along. After a certain am o unl of lime , participants will nOt be as foc used a needed_ Each sesSIon
shQuld be kept to a ma xi mum 0 two ho urs, and il it is no t completed by then a follow -up session should be
rescheduled

5.4.2 Inspection Process

The inspecti o n process loll ows an o rde rl y flow 01 steps, each adhering to th e princi ple described above. The
steps are ummanzed in F' gure 5. 10 .

1. PLANNING - - - .j Overview I
}
Non-nominal
/
process
2_ PREPARATION ....... _-- - -
--
Causal
- Analysis
Nominal
process
4. REWORK "- - - --
5.

Figure 5.10 The parts of the Inspection process, emphasizing the main sequence of actMtles
INSPECTIONS 91

1. Planning. The process begins w.th planning . Th.s oneludes decidong which inspecrion mttries to collect ,
identifying tool to be used in recording and analyzing these dara, dec.ding who will part.cipate on
in pect.ons and wh"n they w.1I take place, and distributing the materoals s~veral days prior to the
meeting . Typically, the moderatOT is re ponsoble for thcse tasks.
LA. Overview meeting . If necessary , an overview meeting can be organized to explain the artifact
under Inspection. Since meetings are expensive, this should be avoided unless obviously necessary .
2. Preparation . The next step for each inspection con ISts of preparation. Here, in pectors review the work
in compl ete detail al their ow n workstallons (e .g., c he king that the code under inspccl.on correctly
implements the detailed design ), pos ibly using checklisl provided for guidance Whal makes the
.nspection process valuable, but also expenSIve , is the fact that this lime' co nsuming process is performed
by several people in complele detail. The process .s not a "review," because inspectors work at the same
level of derail as the author In pectors frequenlly enter the defects they And intO a database (e g., Web·
accessible) together with descriptions and c1assiAcations. ThIS help to prevent duplo ca tio n, and it
minimizes unnecessary meeting time . Some prefer to u e paper to record their defects. and orne conSIder
the number of inspec(Qrs who recognize a given defe t to be a useful metric.
3. Inspection meeting. When every participant is prepared , the inspection meetin g takes place . Durong th.s
meeting , the participants honor their deSignated roles. Of I>articular importance is (Q not cry and solo,
problems that arc raised, but instead to ensure that they are recogn.zed as defects, to record lhem as
action items on ly, and to move o n.
4. Rework. Normally , the author is able to repair all defeclS, working alo ne. This.s the rework phase. If the
inspection meeting deCides, however, that the defects are so pervasive that a reinspecti o n ' 5 required,
then the item is recycled through the process.
4A. Causal analysis . If the defects are due to a mi su nderstandi ng or Widespread mISco nception , It may
be necessary to ca ll a separate mecling at which these causes are analyzed and discussed Again ,
since meetings are expensive, these should not be scheduled casually,
5. Follow-up. Aher the author repairs the defects identified during the inspectio n meet.ng, a brief follow· up
meeting is conducted at which the moderatOr and the author con Arm that the defects have Indeed been
repaired. This is not intended to bea detailed review by the moderator. Theonus forrepairison the author, who
is responsible for the work. If the number of defects repaired is high , a follo\~-up inspection may be required
6. Improve process. Organizations shou ld always analyze the efAcacy of their pro e ses and strive to
improve them . For Inspection , the group meets from lime to time to review the inspection process itself,
and decides how it can be improved . They exa mine the metric collected, including the Ii t of defec ts ,
and decide how the development process can be improved to reduce and/or prevent the same types of
defectS in the future .
Fi8ure 5. 1 I shows the average relative times for each inspection process step, u cd as reference data b
one of the .uthor's c1.ents
The Inspec ti o n meeting t.me in Figure 5. 1 I is shown as o ne hour for the sake of reference Ind ividual
compan.es or developme nt 8roups record .n'pection times and quanti lies in pected, and lhey e tllnatt' future
inspections based o n these historical data . The IIme< ,hown in Figure 5. 1 I may d.sturb the uninitlaled , wh
may wonder whether it rea lly does take that Io n!! to check code. Producong profe Slonal.qualoty produ t
~s .ndeed lake a substantial 'mounl of time, and a~y fa. lure 10 recog n.ze lhe true co t end. lip o n,um.ng
f.r more t.me in the end , Inspect. on, have bee n esti mated by .chan. and Mc e un k [4 J to o n'Ulne a, onu h
is 10· 15 percent of the development budgel.
92 CHAPT£R 5 QUALITY IN THE SOFTWARE PROCESS

One company's estimates


Planning 1 hr x (1 person)
Overview 1 hr x (3- 5 people)
Preparation 1 hr x (2-4 people)
Inspection meeting 1 hr x (3-5 people)
Rewor\( 1 hr x (1 person)
Analysis 1 Ilr x (3-5 people)
Total: 7-21 person-hours
Figure 5.11 Inspection time/costs per 100 non-commented lines of code
Inspecti on are expensive because they co n urn e the time of everal e nginee rs. Nevertheless, various
s tudle (fo r example, [ I ]) have h own that they payoff handsomely. This is due to the astronomical cost of
detecllng and repairing defects undiscovered untd cia e to delivery time. Quantified benefits of ,"spcctlOns
from sour es uch as IB M , ICL, and Standard Bank , for example, are summarized in [5 ].
Appc ndi x D of the case stud y sh ows an example of a form for reporting t he results of an inspection .

5.5 QA REVIEWS AND AUDITS

The QA organizallon works wi th th e project leadership to defi ne the manner in w h ich external quality
assessment will be perfonned , specifies this in th e SQAP, and execute it during the course of the proj~.ct .
External QA activities are either rrol(WS (sometimes called walk-throughs ), which are scheduled in advanc~ , or
a"dllS, which are not so scheduled_ A project can expect both types of activities. Figures 5 . 12 and 5 . 13 show th~
range of options for QA involvement in reviews and audits, starting fro m the most invasive to the least.

• Participate In a ll meet ings


Including fonna ll ve sessions and inspections.

• Review all documents


Participate in a ll inspec tio ns
(but d o not attend all meetings ).

• Attend final reviews and revie,,, all completed documents

• Review sci en completed documents


But do not participate ot herwise.

Figure 5.12 Options for QA reviews

• Audit at unrestricted random times


Includes visiting with e ngineers .
Includes inspecting any document at any time.

• Audit random meetings


• Aud it ra nd om ly from a speCified list of meetings

• Audit wit h notice

• No audi ting

Figure 5.13 Options for QA audits


DEFECT MANAGEMENT 93

Benofits of Frequent Intervention Costs 01 Frequent Intervention


© Helps in aSSessing prOject ®Time needed to get
status documents ready
© May help to improve process ® Engineer time taken to explain
or project ® OAtime

Figure 5.14 Comparing frequent VS. occasional QA intervention

Frequ~nt intervention by QA has the advantage of provIdin g QA personnel with greatly improved
understanding of the health of the project. but it may disrupt the project by frequently calling for documents
or for engineers' time. This trade·off is summarized in Figure 5. 14.

5.6 DEFECT MANAGEMENT

Projects encourage the submission of defect repOrlS by all team members. Usually, a screening process that
~nsures def~ct reports are valid and accurate is put in place . To manage defects, QA standardizes on the
manner in which defects are defi ned and tracked . These data can then be compared between different
projects so that estimates can be made rega rding new projects . We explain this standardization next.

5.6.1 Classifying Defects

Teams classify each defect by its stv"ily (how serious it is), priority (i ndicati ng when it will be handled), It s type
( th~ kmd of problem ) and its soure< (the phase during which it was injected). These classification arc
illustrated in Figure 5. 15.

• Severity
How serious is the defect?

• Priority
?•
In which order will defects be repaired?
? " ~
• Type
What kind of problem is involved?
- - -- L" '"

• Source
During which phase 1
was it injected?

1""'- 1
fl&ure 5.15 Defect classification
9. CHAP I ER S QUAUTY IN THE SOFlWARE PROCESS

No more than two decl,tona ar. required.

el. Defec, Hverlty 10 m%r

"I
v

else Defeel severity Is 'rlv'.'


2 Clasally a. "major"
V

Classify as "medium" Clasally a. "1r/vl.,"

Figure S.16 The triage decision metl10d applied to defect severity classification

A Si ngle severity classlncation scheme can be used for all artifacts. It is possible 10 be very discriminating
among levels of severity, but this consumes time. The results should be worth the time. One of the authors has
frequently e ncountered teams using diSCriminating classincation schemes that consume significant decision ·
making time and yet the data that they produce are not utilized by the organization .
Deciding the severity level of a defect fa lls into can sometimes be difficult. Triage is a useful and simple
decision -making technique when confronted with a large number of possibilities, a situation occurri ng often
in software engineeri ng. Utdl zi ng triage for defect classincation has the advantage of being fast to perform
because eaeh classification requires answering just one or two questions as shown in Figure 5. 16. Once a list of
defects develops, the team approaches the major ones first (they can be placed in order with the ' major'
category if necessary). Once they have becn attended to, the medium severity defects can be handled. The
team gelS to the trivial o nes o nly after this, if time allows.
A simple way to classify the severity of defects when using triage is shown in Figure 5. 17.
Although triage is fast, the three·category classincation lumps together all defects that fail requirements,
whether serious o r not. Thus, "name neld is not purple, as required" and "system crashes every minute' Ca
"shows lopper" si nce its effects are catastrophic for the applicatio n) are given the sa me severity, which is rather
extreme. Shows toppers usually need to be separa ted . To address this, the IEEE has deAned a more refined
classification of defect severity as shown in Figure 5. 18. The "None" category is added to collect unprioritized
defects.

• Major
Causes a requirement to be unsatisfied.

• Medium
Neither major nor Irioial.

• Trivial
Defect doesn't affect opera tion or maintenance.

Figure 5.17 Classifying defect severity by triage


DEFECT MANAGEMENT 95

• Urgent
Failure causes system crash , unrecoverable data loss, or jeopardizes personnel.
• High
Causes impairment of critical system functions, and no workaround solution exists.
• Medium
Causes impairment of critical system functions, though a workaround solution docs ex.ist.
• Low
Causes inconvenience or annoyance.

• None
None of the above.

Figure 5.18 IEEE 1044.1 Severity classification

A defect's Priority is the order in which the team plans to address .t. This is somewhat aligned with the
defect's severity but is not identical. For example, a defect can be classified as "urge nt" but it may not be
necessary to repair it immediately. For the sake of project effiCiency, fo r example , its repair may be batched
with a set of repairs to the same part of the product.
Different phases use different defect type classificatioll' . For example. a defect in the requirements may
concern ambiguity but "ambiguity" docs not apply very well to code. On the other hand, code may have a
logic defect but "logic" does no t apply to requirements in the same way. Some types of defects an common to
all artifacts, as listed in Figure 5. 19.
The 'OUret of a defect is the phase in which it was introduced (or '''jecred ). For example, you ma y d iscover
while testing a video store application that it does not-but should-accept the video /(, A Mad. Mad. Mad,
Mad World because the requirements document stated that no word rn a title should be repeated more than
once (supposedly to prevent bad data entry). Even though the defect may have been discovered during the
testing phase, its ,ourer phase was requirements analysis.

5.6.2 Tracking Defects

Table 5. 1 shows a typical way to track known defect.s . The information is u.s ed to manage ongoing work and
to record defect history for postmortem and estimation purpos~s .

• Omission
Something is missi ng.

• Unnecessary
The part in questio n can be omitted .

• Nonconformance with standards

• Inconsistency
The pan in question contradicts other part(s).

• UnciassiRed
None 01 the above.

figure 5.19 Common defect types across all artifacts


96 CHAPTER 5 QUAUTY IN THE SOFlWARE PROCESS

Man bug. tracking program, a.,<: indispensable 111 tra king "nd managing defects. Bugzil/a i< an cxample
of an o pen , o uree defect·tracking sy<tem. It was originally written by T e rry Weissman Bugz tlla fearures
in lude the foll OWing .

inter· bug depende ncies, dependency graphing, advanced repo rting capabilities ex te nsivc con·
Agllrability, a very well · under<tood and well . thought ·out natural bug resolution protocol, email,
XML, console, and H I I P APls. (It i ) available integrated with automated software conAguration
management systems, including CVS (6J.

Appendi x B of the case .rudy contains an example of the way in which defects can be reported, and
Appendix A contains an example of the way in which they can be tracked .

5.7 PROCESS IMPROVEMENT AND PROCESS METRICS

Even a very good process has to adapt to changes such as new technology and new kinds of requirements. For
these reasons, very effective software development organizations include a mtla·proass with every software
process: a process for improving the process itself. This usually takes the form of meetings at the end of phases
to review the effectiveness of the process used with a view to improving it for furure projects. A meta·process
is outlined in Figure 5.20.
To measure the dfectiveness of a process, an organization has to use it for several projects and then
compare the project metrics. Table 5.2 gives an example.
These results suggest that process U is the most effective, since it produces the best results in every
category. Process V is the worst for the opposite reasons. Matters are not often so simple, however. For
example, suppose that we had to choose between Waterfall and "Waterfall + Incremental." The latter process
is superior in defect count, developer cost, and customer satisfaction, but it scores worse in the other
categories. Making the call depends on the relative importance of the factors to the organization .
Figure 5.21 lists a sequence of actions that can be taken throughout the life of a project in order to
continually improve the process.
Figure 5.22 is an example of the kind of data that can be collected about the process. It is applied to the
process of collecting detailed requirements, which is covered in Part IV , but the table is applicable to most
phases. The numbers are illustrative only, and should not be regarded as industry standards. A comparison
with the organization's normative (typical ) data reveals deAciencies in the team's meeting process and in their
individual execution (i .e., the actual writing process). This exposes problems in meetmgs . for example, which
were subjectivc:1y evaluated 2 out of 10 by the team . It was determined (though not visible in the data) that the
meeting process would improve if the straw man proposal brought to the meeting was more complete i.e. an
explicit proposal that can be used as a basis for discussion .
The other problem observed in the example shown In Figure 5.22 seems to occur during the execution
step, where the actual work of writing the requirements is performed . The defect rate is higher than normal
(5 versus 3) and the self·assessed quality is a little below average (4). Comp.red with company norms, there
appears to be room to spend more time executing the work (i.e ., as individuals ), thereby redUcing the defect
count and improving the subjective self·assessment. You can observe from this process that a tandard for
counting the parts of the phase is fundamental to our ability to measure it. In this case, we are counl1ng
"detailed reqUirements," a concept that will be explained in Chapter 4.
Even in the absence of historical data , the team predicts what the values of the metrics should and will
be. With these advance predictions, teams tend to work better, and they tend to remember results. ll>e dat..
collected become the basis for furure historical darn. Man.ging all of this is not technically d.ffkult, but it Ns
Table 5.1 A typical way to track known defects

Defect Tracking
Discovering Responsible Date
NO. Name Description engineer engineer opened Source Severity Type Status
1 Checkout flicker Checkout screen 4 Kent Bain Fannie Croft 1/4/04 Integration Med GUI Being worked;
nickers when old begun V1 0/04
DVDs are checked
out by hitting the
Checkout button.
-t
2 Bad fine Fine not correct for Fannie Croft April Breen 1/4/06 Requirements High Math Not worked yet
first·nun DVDs
checked out for 2
weeks, as
displayed on
screen 7.

• • • • • • • • • • • • • • • • • • • • • • • • • • • Tested with suite ~


m
9023 l:l
-

• • • • • • • • • • • • • • • • • • • • • • • • • • • Resolved •

• • • • • • • • • • • • • • • • • • • • • • • • • • • • • •




:s
91 CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS

Inpul QVlpul

Prac1lces to
discard

Metrlc data
on multiple
projects Pract ices to
using the
retain
process

Practices to
Introduce

Figure 5.20 The process improvement meta-process

to be d o ne at th e sam e ti m e as many oth er urge nt ac t ivities. For t h is reaso n, t h e assignment of cl ear


respo nsib i lities and th e regular revie w o f th e m etric data are wor ked o ut at th is ea rl y sl age i n th e process. As
you wi ll see in the ne xt sectio n , process impro vemen t fee dback se parates g rea t dev el o pm ent o rg ani zations
fro m m erel y good o nes.

Table 5.2 Data from multiple projects used to compare processes

Waterfall +
Process -" Waterfall Incremental Process U Process V

Average over 10 projects:

Major defects identified w ithin first 3 months per 1000SLOC 1.3 0.9 0.7 2.1
in delivered product

Development cost per detailed requ irement 51 20 5100 58S S135

Developer salisfaC1ion index (1 to 10 ; best) 4 3 4 3

Customer satisfaction index (1 to 10 ; best) 4 6 6 2

Cost per maintenance request S130 5140 59S 5165

Variance in schedule on each phase : +20% • +70% - 10% +80%

00 aC1ual duration - projected duration


1 x projected duration

Variance in cost : +20% +65% - 5% . 66%

100 x aC1ual cost - projected cost


projected cost

Design fraction : 23% 51 % 66%


lolal dtSig . limt
lotal progralflm i.g timt
Humphrey: Should be at least 50%.
PROCESS IMPROVEMENT AND PROCESS MEI RICS 99

I . Identify and define metrics tcam will use by phase


Includt- . . tim~ spent o n research, execution, and review
· . size (e.g ., lines of code)
· .. number o f defects detected per un it (e .g., lines of code)
include Source
· .. quali ty self-assessment of each o n scale of 1- 10
main lOi n bell -shaped di stribution
2. Document t hese In the SQAP.
3. Accumulate hi to rica I data by phase.
4. Decide whe re (he metTic data will be placed .
As the project progTesses SQAP) SPMP) AppendIX?
5. Desig nate engineers (0 manage collectio n by phase .
QA leader or phase leaders (e.g., design leader)
6. Schedule reviews of data for lesso ns learned .
Specify whe n and how to feed back improvement.

Figure 5.21 A process for gathering process metrics

Requirements Document Personal


200 detailed requirements Meeting Research Execution Review Inspection

Hours spent 0.5 x 4 4 5 3 6

% of total time 10% 20% 25% 15% 30%

% of total time: norm for the 15% 15% 30% 15% 25%
organization

Self-assessed quality 1- 10 2 8 5 4 6
- - -
Defects per 100 N/A N/A N/A 5

per 100: organization NIA NlA NlA 3 4


norm

Hours spent per detailed 0.01 0.02 0 .025 0.015 0.03


requirement

Hours spent per detailed 0.02 0.02 0.04 0.01 0.03


requirement; organization norm

Improve st. awman Spend 10%


Process Improvement brought to meeting more time
executing

summary productivity: 200/22 = 9.9 detailed requirements per hour

Figure 5.22 COllecting project metrics for phases


100 CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS

5.8 ORGANIZATION-LEVEL QUALITY AND THE CMMI

· o/tWJ'" development orga ni za tio ns pcrlCldKally as,e S and upgrade their overa ll capabi llly . ln the 1980sthe
nonproht o ftwa ..: Engineeri ng Institute ( EI) establl<hed a classifi ca tion of capabihlle~ for contractors On
behalf of the U .. DcpJrtm e nt of Defen e (000). The DoD's plan was to restric t bidding o n government
<oft"'are developme nt o nt ra ts to contractors With ,pc ified capabi lity level s. The SEl's syste m, now
expa nded into the "pnb,I"y Mntllri'y Mod,1 1"" 9,"/ioll ( MM I), , ucceeded In providing concre te softwa re
~nginceri n l! competence goa l for orga ni za tio ns. Actually, the scope of CMM I IS la rger than software
e nglncerl ng , but we wi ll restric t our a tte ntio n to the latter, te rm ed CM.M I- W. Many o rganizations, defense
and commerC ial alike, ha ve used the C MM I and its predecesso r, the CMM , to as~ess the quality of thei r
devel opmc nt process.
Softwa re developme nt o rga ni za ti o ns are assessed at a CMM I leve l between I (worst ) and 5 (best)
TI,e CMM I di sti ngUi sh es two kinds of assess me nts: .'ag,d a nd (on ',n"o"' . Th e sta ged assessment consists
of Identl Rab le steps We Will no t dis uss the co ntinuo us ki nd here . Th e CMM I classifies staged
o rgan izati o nal capabi lity with th e steps shown in Figure 5.23 (fro m [7 )) . These are e labo rated on in
Table 5.3.

5.8.1 Level 1 : Initial

The "In itial" CMM I level is the mos t primitive status that a so ftware o rganization can have. Organizations
at level I ca n be sai d o nl y to be capable o f pro dUCin g software (i .e ., "someth ing") . The o rga nization has no
recognized process for software pro duction . and th e quality of products and projects depends entirely on
the indi vidual s pe rfo rm ing th e design a nd implementation . T ea ms de pend o n metho ds prOVided by
membe rs of the gro up w h o take initiative o n the process to be fo ll owed. Fro m project to project, these
could be very good o r very poor. The success of o ne projec t has little relatio n to the success of another
unless they are sim ilar and e mploy the sa me so ftware engineers. W h en a project is completed, noth ing
is kno wn o r reco rded abo ut its cost, schedule, o r qua lity. Ne w projects are as uncertain of success as
past o nes .
For rn a t organi za ti ons, th is is unacceptable.

• IncreaSing LevelS
OPTlMIZfNQ
maturity 'r
Level 4
QU4NTTTAnvUY
MAHAOEO

Level 3
DEfINED
,
Level 2
MANAGED

Level 1
INITIAL

Figure 5.23 CMMI model for organization with staged processes


ORGANIZATlON·lfVEl QUAlITY AND THE CMMI 101

Table 5.3 SEI specifications of capabilities required for each level (see [7J for a full description)
level. Title. and Summary Expected Outcome Characteristics
1.INITIAl.

Undefined; ad hoc Unpredictable; depends entirely on Organizations often produce


team individuals products, but they are freQuently over
budget and miss their schedules.
2. MANAGED Preceding level plus:

Measurement and control Project outcomes are qualitatively Respect organizational policies
predictable Follow established plans
Provide adeQuate resources
EStablish responsibility and authority
Provide training
Establish configuration management
Monitor and control: Take corrective
action
• •
Evaluate process and product relatIVe
to plans: address deviations

3. DEANED Preceding level plus:

Processes standardized Projects consistent across the EStablish process objectives


organization; qualitatively predictable Ensure process Objectives met
Establish orderly tailoring
Describe processes rigorously
Be proactive

4.QUANTITATIVElY MANAGED Preceding level plus:

Processes measured Metrics available on process; set quantitative goals for key
quantitatively predictable subprocesses
Control key subprocesses with
statistical techniques
Identify and remedy variants

5. OPTIMIZING Preceding level plus:

Improvement meta·process Processes improved and adapted Establish quantitative process


using process metrics improvement objectives
Identify and implement innovative
process Improvements
Identify and implement Incremental
process improvements
Evaluate process improvements
against quantitative objectives
102 CHAPTER 5 QUALITY IN THE SOFlWARE PROCESS

5.8 .2 level 2: Managed

11,c "Managed" MM I level applies to o rga ni zatio n, apab le of trackin g projec ts as they unfold Such
organizations make plans, manage co nfiguratio ns, and maintain records of project costs and schedules They
al 0 descnbe the functionality of ea h produ t in writing. It i. therefore pOSS ible to predict the cost and
sch edule of very si mil ar projects pcrfonllcd by a very Similar team .
Although level 2 orga ni za tions track projec ts, no tandard development process for the o rga nizat ion is
8ll arantced.

5.8.3 level 3: Defined

The "Defined" CMM I level applies to o rga ni zations that do ument and enforce a standard process. Suc h a
process I typica lly o ne of those described in the previous c hap te rs (waterfall, spiral , etc.). Some o rganiza ·
tio ns adopt existi ng sta ndards suc h as IEEE's, while o thers de fi ne their own . Ro ug hl y speakin g, as long as
manageme nt enforces coordi nated , professional standards, and e ngi neers imple me nt them unifOnll!y, the
orga nization is at level 3. Training is typically required for an o rganization to reach level 3. Teams are allowed
Aexibility to tai lo r the o rga nizatio n's sta ndards fo r speCia l c ircumstances. Level 3 includes o rga niza tion-wide
standards for project manageme nt, complete configuratio n ma nageme nt, inspections, design notation, and
testing.
Level 3 o rga nizatio ns lack ge neral predictive capabi lity. They arc able to make predictions only for
projects that arc very si milar to o nes perf'Onlled in the past.

5.8.4 level 4: Quantitatively Managed

The "Qua ntitatively Managed" CMM Ilevei applies to o rga nizati o ns that can predict the cost and schedule of
jobs. A commo n way to do this is to usc statistical techniques and hi storical data. Such an organization
c1assilles jobs and their compo ne nts; it measures and reco rds the cost and time to design and implement these;
the n it uses these me tric data to predict the cost and schedule of subseque nt jobs. As Humphrey has pninted
out, this is no t "rocket science," but it does require a significa nt amou nt of orga ni zation , as well as an ability to
analyze the data . Level 4 requires a complete, metric·oriente d quality plan .
Even though level 4 is a hi gh level o f capability, it is no t the highest. Software engineering c hanges rapidly.
Forexample, the object-oriented paradigm made rapid inroads in the 1990s, reuse and new component concepts
are having a growi ng impact. Future improvements and paradigms are unp",dictable. Thus, the ca pabilities of.
level 4 orga ni zatio n that does not adapt and Improve may actuall y decline over time.

5,8.5 levelS: Optimizing

Rather than trying to predict future c hanges, it is preferable to institute pem1ane nt proe,JurtS fo r ""king and
exploiting new and improved meth ods and tools. Level 5 organizations, at the · Opti mizing" CMMI level
build in prace 5 improveme nt. In other words, their process (actually a meta -process) includes a systematic
way of evaluatin g the o rb'<lnizatio n's process itself, investigating new methods and technologies, and the n
improving the organization's process. Many o rga ni zatio ns aspire to this imp ressive capability.

5.8.6 Relationship of the CMMI to the PSP, TSP

As we have seen, the C MMI is a measure of ca pability at the orga nizationa Vcorporatc level Wall~ Humphn:
and the Software Engtnceri ng Institute have also deA ned coord inated proce<s models a t the learn levcl.nd at
CASE STUDY: SOFTWARE QUAlITY ASSURANCE PlAN FOR 103

the indiv.dual engineer level. These are called the Tea .. Softwa,. Process (TSP) and the PtrSO,,,t/ SoftlDa" Procn,
(PSP), respectivciy. The PSP, TSP, and CMMI frameworks fonn a relatively coordinated set of capabilities
and procedures at the indiVidual, team, and organizational levels, respectively. We will describe the TSP in
the project management chapters and the PSP in the implementation chapters.

5.8.7 Relationship of the CMMI to Agile Methods

CMMI appears to be almost contradictory to agility because it is process heavy . However, CMMI and agility
are at different levels. CMMI is used to assess the capability of organizations as a whole to produce good
applications. Those that use agi le methods are just as interested in such an assessment as those that are not,
and it is reasonable to assume that CMMI will evolve to assess devc10pment organizations of all kinds.

5.9 CASE StUDY: SOFTWARE QUALITY ASSURANCE PLAN FOR ENCOUNTER

The Software Quality Assurance Plan (SQAP ) for The table o f contents of this SQAP follows that
Encounter is based on IEEE Sid 730-2002 Slandard for of IEEE standard 730·2002 in most esse ntial s.
Soflware Qua[ilyAs,uran« Plan,. The table of contents
was outlined in Figures 5.8 and 5.9. Revision History

ENCOUNTER SOFTWARE QUALITY


ASSURANCE PLAN
This assumes the existence of a method
Th aulbor i, indebled 10 bi, ,'udenls for inspeclion, of Ibi, whereby revision numbers of documents are
assigned.
do"" ..enl and for Iheir improv""o.,, 10 Ih, original.

Note to the Student,


Version I
Organizations usually have a standard quality
assurance procedure. The SQAP for each 1.0.0 E. Braude, created 1/ 17/99
project relics on this and provides project-
1. 1.0 R. Bostwick, reviewed 5/ 30/99, added
specific QA plans. We will effectively combine
substance to Sections 7 through cnd
two such documents here.
I . I . I E. Braude, integra ted and revised contents
5/ 31 /99

Approvals,
Version 2

2.0.0 E. Braude, significant edits of Section 5.2


Title ~ 1/ 18/04

Engineering Manager :1.1-0 6115104 20. 1 E. Braude, edits 1/23/04

2. 1.0 E. Braude, edits in many sections rc pond -


QAManager £WiWv.. 6111104
ing to reviews by student 6/ 17/04

Project Manager a. !J'Cuil1 617104


Table of Co ntents
I . Purpose
Author £"1KauiU 611104
2. Rcferen cd Do lIments
10. CHAPTER 5 QUAUTY IN THE SOFTWARE PROCfSS

3 M~l1 all~ m e nt

1 fRanl 2oltion Typically, mD't of the conten t of a SQAP are


2 Ta<k common to all of the o rganization's proJCClt.
3. Re,ponsibiliticS EngOlleers would need SImply to taIlor pans 10
3.4 QA Estimated Rc,ources the projec t in question.
4. Documenlation
4 . I Purpose
1. purpose
4.2 Minimum documentation requirements
4.3 O ther This docu me nt des ribes the means by wh,ch the
5 . Standards Encounter project will produce and maintain a h,gh.
5. 1 Purpo e quality product. It is also tnte nded to describe mech ·
5.2 Conte nt anisms for improving the quality assurance process
itse lf. "Q uality" is d~fi n ed as the degree to which the
6 . Reviews
applicatio n satisfies its requ ireme nts.
6 . 1 Purpose
6 .2 Minimum req uirem e nts
6.3 O ther reviews and audits There is no separate "scope" s~tion in the
7 . Test IEEE standard, so we have insened it bere.
"Scope" contains vital information sucb as
7. 1 Unit Test
whether this document appli~ to the first
7 .2 Integration T est
rdease only or to maintenance as well.
7 .3 System Test
7.4 User Acceptance Test
8. Pro blem Re porting and Corrective The scope of this document compnses the
Adion artifacts of all releases.
9 . T ools, Tec hniques, and
Methodo logy 2. Referenced Documents
10. Media Control See Section 4.2.
I I . Supplier Control
12. Reco rds Collection, Maintenance, 3. Management
and Retention
13. Training 3.1 Organization
14. Risk Management
15. Glossary State the rol~ that are involved in ensurina
16. Sqap C hange Procedure and quality. Actual nam~ are provided in Section
History 3.3. The process described in tbis case is a .....
of internal and exte"",1 quality as,unnce.
Appendix A - Metric History for this
Project
Appendix B - Problem Reporting Form This section assumes the description of the
Appendix C - Change Reporting Form organizational Slructur<: of the Encounter project
Appendix D - Inspection Meeting in 4.2 of th~ SPMP.
Report Form This document will r<:fer to the quality work of
Appendix E - Document Baselining d~velopers as "internal : In addition, for the Arst three
Checklist iterations of Encounter, a quality assurance enaine"r
CASE STUDY; SOFTWARE QUAUTY ASSURANCE PLAN FOR ENCOUNTER 105

will be designated who will be responsible to the • Carryi ng out the reviews and inspections spcciAed
manager of QA. The QA leader will take the lead for rn Section 6 of this document
project-wide quality Issues QA tasks will be referred
to 3S "" temal : • Unit lesting as per eCI manual 023 .2

3.2 Tasks 3.3 Responsibilities

State what roles will fulfill what job functions .


Summarize what needs to be done.

It is the quality assurance leader's responsibility


External QA tasks shall include, for all iterations:
to see to it that the tasks in Section 3.2 are performed
and to ensure that the prescri ptron s in this document
" Maintaining this document
are followed , including scheduling the reviews spec·
• Documenting the quality of the evolving product ified. For the first three iteratio ns, the QA leader will
and associated artifacts perfo rm all of the quality control (QC) functions .
For subsequent iteratio ns , the QC team ,
• Managing external review meetings
appointed by the QA department manager, will
• Ensunng that veriAcation takes place and logging take over this function . The quality leade r and the
verification QC team are responsible for all non ·unit testing.
(See Part VII of the book for background informatron
• Preparing for and attending all inspections on these types of tests). A description of the QC
• Post·unit testing as per the Software T cst team will be supplied.
Documentation The project leader will be respo nsible fo r
ensuring that inspections and unit tests are per-
• Engaging in activities designed to improve the formed . The schedules are to be placed in the SPMP.
quality assurance process itself

• Keeping the project leader apprised of QA prog·


No names are assigned to these roles here
ress through weekJy written reports
because they are in the Software Project Man-
" Carrying o ut the audits speciAed in Section 6 of agement Plan, which is their proper place.
this document Duplicating a name here would require us to
update more than one document when there
• Providing the development team with feedback
are changes.
from QA's activities
• Assign defect repair to softwa re engineers
The leaders de ignated in the SPMP are re o
• Identifying methods and tools for collecting and spo nsible for the quality of th eir respective areas
maintaining melrics (requirements, design, etc .). They shall e nsure that
the designated metrics are collec ted and that the
Internal QA tasks sha ll include, for all iterations: quality self·asse sments as outlined in cction 5.2 of
thi document Me onducted.
• Each team member responsrble for the quality of Each member of the Encounter development
hr~ or her work , as deRned rn this document team is responsrble for quality as spc iAed In ce tr o n
4.5 of the company document ' ual it resp n~ibrlr ·
• Marntaining an issue datahase
tres of engi neers at I." Thrs in ludes teSlIng
• Collec trng the metrics desill natc by thr~ and other rndividual method, and ornbrnatr o ns of methods
project documents in a las. ("unrt testinR') .
106 CHAPTER 5 QUAUTY IN THE SOFTWARE PROCESS

3.4 QA Estimated Resources • oftwa rc Vc ri flcallon and Val idallon Plan (SVVP)
11,,, e,nmated n ',our es reqUired fo r A un Encoun · • oftwarc VenAc.tlo n and Validation Report
( VVR) (No/t Th " book does nOt cover the
ter are as fo llows,
VVR )
• ne engineer working halftime for the Arst tI",d • Maintenance Plan
of the proje t
In addit io n to the<e documents, the Java <ource
• One engi neer work inS fu ll time for the ccond
code wi ll utilize Jnaadoc to ge nerate package., class-,
th ird of the project
and hlO ti o n· level docu mentatio n, (See httpi/java.
• One engi nter work ing full time for the last third of sun .com/)2 eI)avadod fo r Javadoc speCifications.)
the project
• An additional engi neer working half tllne for the 4.3 Other
last third of the prOJec t
- i ntenti onally left blank

4. Documentation

4.1 Purpose It is customary to make a comment like this SO


that no one wastes time looking for what may
The purpose of this sectio n is to ident ify the docu · be missi ng.
mentallon that wi ll be used to ensure quality.

5. Standards, Practices, Conventions, and


4.2 Minimum Documentation Metrics
Requirements
5.1 Purpose

Th is sec tion describes the standards, practices , con·


This ection lists all of the project documen· ventio ns, and metrics to be used for the Encounter
tation , since the documentation is a major project. These are intendcd not only to ensure
factor ensuring the quality of the product. qua lity of the Encounter product but also to obtalll
Note that the User's Manual is excluded, it qua ntitative metric data on the SQA process itself.
is a deliverable rather than a project document . These data arc to be used to help el evate the CM 11
level of Caming Consolidated Industries (CC I) fr.om
The following documents wi ll be produced , level 2 to level 3.

• Software Quality Assurance Plan (SQAP; this 5.2 Content


document)
• Software Configuration Management Plan (SCMP) Describe the standards, practices, con~n­
• Software Project Managcment Plan (SPMP) tions, and metrics to be used. Organintion-
wide quality goals can be supplied here or in a
• Sof·tware Requirement Specifications (SRS) separate appendix . Thc contents of this S(C-
• Sohware Design Document (SDD ) tion should be a speCific as possible, For
example , sta tcments such as ' quality should
• Software T est Documentation and the tcst doeu· be a< hlllh as po<slblc· should be avoided.
ment that It refers to (STD )
CII.SE STUDY: SOFTWARE QUAUTY ASSURANCE PLAN FOR ENCOUN IEft 107

Standards: An oj EjjrcliJ}f Comm"HlcalioHby Justin Zobel (Springer


The IEEE documentation standards as of July I , Verlag.
2004, w,th appropnate modiAcations. are to be TI,e codi ng conventions as lound at http}/java.
u ed for all documentation . The standards for Jav. sU I1 .comldocslcodeconvlhtmVCodeConvenlions.doc
ndoc commentlOg will be fol!owed as found at http]/ .html will be followed .
j."• .sun.com!j2 e!javadoclwriti ngdoccommentsl
mdex.hmll and http}/java.sun .comlj2se!javadod Metrics:
writingapi pecslindex .hrm L Documentation stan.
dards or templates developed by the company may
supersede these at the discretion of management. This section is liable 10 be extensive. The
Uni fled Modeling Language standards, as spec. numbers used here would be based on histori·
iAed in ... shall be used in th is project . cal data obtained from the group that is devel·
Refer to the Co nve nt ions section below for oping Encounter.
additional standards.

GCI's li st of standard metrics, found at http://


Practices: xxx, sho uld be gathered as speCified there. The
following includes some of them .
I . Because delaying qualiry is expensive, GCI Inc . For every process and document, metrics shall
strong ly encourages engineers to apply quality include the following ,
precepts while working, rather than as an after·
thought. This is referred to in the company as I . Time spe nt by individual s on preparation and
.
"internal qualiry." It includes all unit testing. revIew .

2. GCI lnc.'s policy is that the QA department 2. Number of defects per unit (e .g .. lines of code),
provides independent, external testing. The QA classified per Section 8 of this document.
department at GCI also has a role in educat ing
3. Quality se lf·assess me nt 01 the QA process and
engineers in the practice of internal quality and
performance on a sca le of 1 through 10, ap·
working with project mangers to ensure that it
proximately in a bell·shaped distribution; se ll·
takes place .
assessment scores wi II not be used fo r the
3. All project artifacts are inspected and are made evaluation of personnel by manage ment; failure
easily avail.ble to the tea m o nce released by the to produce them, however. may negativel y af·
developer. fect the evaluatio n of an engi neer by manage·
ment, however.
4. All project artifacts are placed under conflgura .
tion management, where the co ntents can be
~en by anyone in the team at any time ( ee the We would specify all metrics to be collected
Software ConAguration Management Plan for on this project. Possible metrics are described
details). in Chapter 6.

5. The development process i< to be reviewed at


least once for improvement, and the written The standard for defect classification is given '"
results forwarded to the software engineering cctio n 8 of this document.
laboratory (see Section 6.2. 10).
Quality Goals:
Conventions: G I quality goa ls for delivered products nre as
Where fellSiblc , wrlt,ng wnve nt Jon& hauld conform follows, measured in tenn of defc ts detected within
to the suggestions In Wri'IH9 for (omp""r cin,a Tb, two month< of delivery .
108 CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS

• known " rili al" or \ enous" defects rcmalll III one responSIble Lu,tom 'r representative. They w,1I
,lI\ delivered artifa t be led by the requtrement, leader, who WIll deter.
mine their frequency and scope
In additIon .

• Reql1lT1:mcnts. No morc than one "medium ," and 6.2.1A software Requirements Inspections
no more than three "trivIal " defectIve detailed After they have been revIewed, all requ irement, will
requirements per 100 be inspe ted in ac o rdance with GCI , Inc 's docu-
ment G I 345678 "Inspections and Review proce-
• Design : No mo re than o ne "mcdlllm" defect pcr
dures at GCI." Requtrements sections must be
nve diagrams. A "dtagram" is any Agure that uses
about a page of easily legible parts completed and sig ned within a week of beginning
the desig n
• P eudocodo No more than two "medium" defects per
1000 lines pseudocode is described In C hapter 19. 6.2.2 Architecture Design Reviews
• Code: No more than two "medium" defects per Th,s I a review of alternative architectures with the
KLoC ( 1000 lines of non ·commented code) entire team . The review will be led by the design
leader in accordance with GCI 345678 on a fre-
The data from thIS project are to be reported as que ncy to be determined . The team will provide
Appendix 1 to this document. feedback , which will be reAected in the final design.

6. Reviews and Audits 6.2.2A Architecture Design Inspections


After they have been reviewed, architectures will be
6.1 Purpose inspected in accordance with GCI, Inc.'s inspectIon
process manual , document GCI 345678. Architec·
The purpose of reviews and audits is to continua lly ture sections must be completed and signed off
focus engineers' attention on the quality of the within a week of beginning detailed design.
applicatton as it develops. Rroi,ws effect this in a
scheduled and thorough manner. Audits do so on the 6.2.3 Detailed Design Reviews
basis of random sampling with short notice. These are reviews of all proposed detailed designs In
the prese nce of the entire development team . They
6.2 Minimum Requirements will be led by the design leader, who will determine
their frequency and scope, but at least one design
review will be conducted per iteration . If possible,
Large projects require the full set of reviews
the architecture will be decomposed into detailed
and audit listed here . Student teams should tty
designs of its parts, and these will undergo separate
to conduct reviews and inspections of require- detailed deSIgn reviews.
ments and design , as well as postmortem
reviews. "Reviews· are discussions of proposed
6.2.3A Detailed Design Inspections
artifacts. "Inspections· are conducted on com-
After they have been reviewed, detailed desIgns will be
pleted artifacts presented to the team . The
inspected in accordance with GCI, Inc.'s inspection
SQAP d~s not call out inspections as a head-
process manual , document GCI 345678. DetaIled
ing, so the author has inserted section "A~s for
design sections musl be completed and _igned off
this purpose.
within a week of beginning implementation.

6.2.1 Software Requirements Reviews 6.2.3 Test Plan Reviews


These are walk -throughs of all proposed require - The e are reviews of all proposed test plans in the
ments in the presence of the entire team and at least presence of the entire team . They will be led b Ihe
CASE STUDY: SOFTWARE QUALITY ASSURANCE PlAN FOR ENCOUNTER 109

QA l..ader, who WIll detemlin~ their f~quency and exceptions arc at the discretion of the VP for Engi .
scope. The t t plan will be de o mpo cd into pans, neering . It is the project leader's re ponsibility to
and these will undergo separate reviews. schedule this review and provide the appropriate
documentatio n and software demonstrations.
6.2.3A Test Plan Inspections
Aft~r the>' have been reviewed, test plans will be 6.2.9 SCMP Review
in peeted in accordance with CO , Inc.'s inspection The QA leader shall review the status of configura.
process ma nual , document CCI 345678. Test pl.n tion management o n a monthly basis in a manner
sections must be completed and sig ned off within a indepe ndent of the procedures speCified in the
week of beginning testing . SCMP.

6.2.4 Verification and validation Plan Review 6.2.10 post-Implementation Review


As with all GCI projects, the Encou nter team shall
V&V is to be conducted by an independent team
co nduct post· implementation reviews to provide
(i.e., not associated with QA), fo llowing the process
d~tailed in CO 345678. The QA e ngineer will
data for future projects. These will include reviews
of the project phase just completed and reviews of
review the SVV plan prior to its execution .
the QA process itself. The QA team o r QA leader
shall fi le a process improveme nt report fo r every
6.2.5 Functional Audits
phase , and for the QA process itself. with the
The QA leader shall be responsible fo r auditing the
manager of the software engi neering laboratory.
product relative to the SRS. The audit will follow
company guideli nes in ' CO 8902: Rel ease
6.3 Other Reviews and Audits
Proc~dur~s. "

-intentionally left blank


6.2.6 Physical Audits
Prior to each delivery , the QA leader is responsible 7. Test
for checking that the physical software and its
documentation designated for delivery are complete
and the corr~ct versio n. This section describes how testing is to be
managed. The text here should refer to, but
6.2.7 In-Process Audits not duplicate. the software test documentation.
Proj~ct personnel should expect rando m audits of
their work. These will consi st of visits to the work The responsibi lities for testing were described
si~ by individuals or teams designated by division in cction 3.3. Refer to the Software Test Docume n ·
managem~nt . A day's no tice shall usually be given for tation for detail s o n testing Encounter.
all visits, but audits without notice shall Ulke place as
well. The subject of these audits will be the curre nt 8. Problem Reporting and Corrective
work of teams and individuals that has been alloca ted Action
to the project All project artifacts wi ll be made freely
available to all leam members and auditors at all
times. It w111 be organized in a clear, standard This section explains how defects come to be
fash Ion, so that audits will be po<siblc wilhout any recognized, described, and repaired. They do
nOltCe. not follow the details of IEEE standards. The
reader is refelled to the IEEE standards, as wdl
6.2,8 Managerial Review as 10 Humphrey [H) for additional defect
The Encoun~r prOJe t shall he rcvlewed by the VP $c:verity and IYpe lassl/lcalions.
for Enl!IOeenng during the first week of every month .
110 CHAPTER 5 QUAUTY IN THE SOFtWARE PROCESS

The team will us,," the lJugzilla defect manage . The code nnd ps,udocod, defects tyP"S arc a~
mcnt system . [oilows,

• Syntax
Instead of describing 8ugzllla, we will de·
scribe a hypothetical manual ddect system • Logic
for the sake of clarity, even though a soft· • Data (I e ., allows a wrong variable value)
ware-based system is common practice and
• Insecure (allows unacceptable security breach)
far preferable. Such sysu,ms also allow for a
dialog thread involving, typically, testers and
The workflow of a defect status is:
devciopers.
I . Open: defect found by tester

The Problem Reporting Form to be usrd by the 2. Assigned: defect assigned to an engineer
Encounter development team in response to a soft-
3. Corrected: defect nxed by engi neer
ware problem report generated by QA is shown in
Appendix B. 4 . Closed : defect closed by tester
To use this form , engineers should retrieve the
form from www .a.b .c .d . The defect number will If the defect is reopened, the defect will move
appear automatically , and the site will ensure that from the Corrected state to an Open state.
the appropriate fie lds are fi lled in. The QA leader will create and the QA team will
The values for s"miry arc as follows , maintain a database of problem reports that describe
the defiCiencies, discrepancies, and anomalies for
• Crilieal, Causes the application to crash with sig· Encounter. They will ensure that defects are con-
nincant frequency Siste ntly recorded on this form and that they are
routed and repaired in a consistent manner. Problem
• S,rious, Causes at least o ne documented require·
reports shall be routed in accordance with the
ment to be unmet
SCMP. Full traceability as to their effects and status
• T rioial , Could be allowed to stand ad infin itum shall be maintained, including after they are repaired.
without impeding the user from exercising a re- After iteration three, when a problem is
quired feature encountered, the QA manager will distribute the
problem report to the members of the Change
• Mtdium : Is neither serious nor trivial
Control Board (CCB). For the first three releases,
the configuration specialist will carry out the func-
The documentation defect types are as follows :
tions of the QA team, and the projcct leader will
perform all of the CCB functions in accordance with
• Incorrect
the SPMP. The CCB evaluates the problem report
• Missing material and then assigns a priority to the report of either
j",,,,,dinl,, 10 b, do"" or oplio"nl. The problem report is
• Unclear
then assigned by the CCB to the Encounter devd-
• Ambiguous opment team , QA, or CM for resolution. The CCB
determines the schedule for problem report .(solu·
• Incomplete
tion based on problem report priority and analysis
• Redundant (within or between documents) report results . After the problem in the report is
corrccted, the QA team review thc results .nd the
• Contradictory
QA manager reports on the review to the cca If
• Obsolete nccessary, the process i repeated .
CASE STUDY. SOFTWARE QUAlITY ASSURANCE PLAN FOR ENCOUPlTER 111

9. Tools, Techniques, and Methodologies addillon, the QA team verofles that the so ftware
media arc duplocated using only the procedures
QA re hnlquc~ Include the aud,ting of standards,
identified in the CMP. SQA acceptance Is indicated
rt:qu iremen~ rra ing, de" gn venncatlon . software
by an SQA stamp on the media label. The SQA audIt
In'l'«l1ons, and the verin atl on 01 1 mlal methods. report for media co ntrol are intended as fllrther
The QA tool, o n.i t of software verincation pro- evi dence that QA procedures have been foll owed
gTams. checklIsts, med,a labels, and ac eptance All backup medIa WIll be stored olfsite as described in
stamp . Checklo ts ",ill be obtai ned fTO m the com- the SCMP.
pan 's software engoneering laboratory, and tailo red
for En ounter. These arc augmented by NASA
11. Supplier Control
checklists at [9). C heckl ists include the following :

• Review checklist are used at formal meetings, for


document reviews, and for inspectio ns. This section concerns re lationships with sup-
pliers 01 software and hardware. h describes
• Checklists will be used for verifying the qualIty of how and by whom these relationships are to be
the following activitie and documents· PrelimI - handled.
nary Design Review , Critical Design Review , Test
Readiness ReView, Functional ConAgurati on Audit,
Physical ConRguration Audit , SRS, SDD , SPMP, The SQA team verifies all commerCIal third-
and Software Development Folders. party products provided by the suppliers during in-
coming inspection by reviewing the packing slip that
• Separate checkli sts and form arc used for software
identify the products and theor version numbers. The
audit purposes.
QA manager is responsible for en uring that all thord -
party software and hardware meets the expected
reqllirements. TI,e products WIll be va lida ted by the
This book contains checklists throughout. QA manager through installarion and accepta nce tests.
These checklists involve meeting and inspec - A QA representative will be responsible for te tlng all
t10n procedures, for example. T cams often new versions_ He will also be responsible for the
begin with published checkli ts, and augment relationship wit h the external vendor.
thelil according to additional spcciAc needs of
thelf projects. 12. Records Collection, Maintenance,
and Retention
Additional SQA tools, techn iq ues. and meth -
odologies for config uratio n manage ment arc de-
scribed on the SPMP. This section describes how phy ~ical records
will be handled and who will be responsible
for them . Include disk ,Ies that arc not under
10. Media Control conAguration control.

Describe the meaM by which d,sks, tapes, and Th e SQA record< colle ted and ar hIved ,hall
so on will be managed on lude the fo ll ow on g,

• T •• k reports
TI,e SQA team verifies that the ,,,ftware mcdi a
are bwlt and co nfigured per the CM P and th3t • AnOll1aly report, not handl ed 1» l t he rCB"lar problem.
authorized chanRes have hee n ," ~ ra ll ed and te,tcd In rcrortinli oncehan l 111
CASE STUDY: SOFlWARE QUALITY ASSURANCE PLAN FOR ENCOUNTER 113

Appendix A: Metric History for This Project

preparation Review
Defects Time Time
Defect Expected Actual Expected Actual Expected Actual
Product Unit Rate Rate Time Time Time Time

-t-
SCMP Section 1 minor defect
per section
+
SPMP Section 1 minor defect
per section
SQAP Section 1 minor defect
per section
SRS Section 1 minor defect
per section
SOD Section 1 minor defect
per section

SIP Section 1 minor defect


per section

SWP Section 1 minor defect


per section

SWR Section 1 minor defect


per section

Requirements D-Requirement 1 medium and


3 trivial defects
per 100

Diagram 1 minor defect


per 5

Pseudocode KLOC 2 medium


defects

COde KLOC 2 medium


defects

Code Defects

A frcc online tool ca lled "Refa to rl t" fTom hup j/www re f. tont. om s hallll~cd b , the Projc t 1"nol:cl to
estimate LOC. N 1..0 • and LO .
112 CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS

• lem a",. including rc:conlmcndl1tion" 10 rl"SpOnSI · record,n/! mctfl es QA Will also conduct monthly
ble partlc, three-hour cla>'es for development team members 10
keep them Informed of qua lity goa ls, lools, and
o Logbook of QA" tivl tics
tec hl1lque< T tJm members ca n waive atlendance
o Audit report at the,c meellnt;( by sco flng perfectly on a muiliple.
hOlce qUIz available al GCllmomhly/SQAlquiz.
o igl1ed-off checklist< from reviews Jnd audits
Ea h team member is reqUIred to attend a
o Mlllutes of inspections three -hour course on wntll18 slyies and conventions
conducted by QA .
o Metrics for the QA process itself

Besides verifying the archive procedure speci- 14. Risk Management


Red in the S MP, QA shall separately archive its
QA tea," members are encouraged to Identify risks
OW" records at least once a week . These records arc
as early as pOSSible and direct them to the project
retained throughout the operation and maintenance
leader The procedures for risk management are
phase.
speCified in Sectio n 5.4 of the SPMP.

13. Training
15. Glossary

• • • •

Includes SQA training speciRc to this project.


16. SQAP Change Procedure and History
The SQA o rganization will conduct an initial • • •
four-hour orientation on quality for the development (The material in the following appendices was
team This will include a pre entation o n the metrics supplied by Jane Dyson .)
to be used and a workshop on how to use tools for
114 CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS

Appendix B: Problem Reporting Form

lOde lllumhcr:_ _ _ _ _ _ _ _ __

2 Pro po«d by · _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __

3. Documcnts I scctions affcc ted : _ _ _ _ _ _ _ _ _ _ _ _ __

4 . Documcnt dcfc t ty pe.

3. Mis ing matcrial

b. L1nclear

c Ambiguous

d. Incompl etc

e Redundant (within or between documents)

f. Contradicto ry

g. O bsolete

Source code affec ted (fo r source code defec ts):

5. Packa ge(s) _ _ _ _ _ __

6 . 0.ss(es)'_ _ __ _ _ __ _

7 . Met hod(s)_ __ _ _ _ __

8. Severi ty :

a. High

b. Med ium

c. Low

9 . Code defect type :

a. Syntax

b. Logic

c. Data (i.e., allows a wrong variable value)

d. Insecure (allows unacceptable security breach)


CASE STUDY: SOFlWARE QUALITY ASSURANCE PLAN FOR ENCOUmER 115

10. Phase mjected (earl,est phase with the defect).

a. Requirements

b. Architecture

c. DetaIled design

d Code

e. Implementatio n

II . Detailed descriptio n: _ _ _ _ _ _ _ _ _ _ __

12. Priori ty: a. ___ Immediate b. ___ Intermediate c ___ Deferred

13. Reso lut ion : _ __

14. Status: a. ___ Closcd b. ___ Opc n


Sign -off:

15. Description and plan inspected: _ _ __

16_ Resolution code and rest plan inspected: _ _ __

17. Change approved for incorporation , _ _ _ _ __

Appendix C: Change Reporting Form

I . Change number: _ __
2. Proposed by: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __

3. Documenlslsections affected: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ __

4. Reaso n for change or addition :


• • •

5. Enhancenlent:_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __

• • •

6. Decails:
• • •

Signatures:
Descroption and plan inspected (QA tcam leader) _ _ __
Resolution code and test plan inspected (QA team leader) _ __ _
hang" approved for incorpor.Jtlo n (Team leader) _ __
116 CHAPTER 5 QUAUTY IN THE SOFlWARE PROCESS

Appendix 0 : Inspection Meeting Report Form

A ompl cl cd I", pc li on " kC lin g Report must be ,.,el uded at the end of each document. Only the latest report
i rcqlllrcd .

Inspection Meeting Report

PROJECT:

DATE: STARTING TIME : ENDING TIME:

PRODUCED BY:

TYPE OF INSPECTION: 0 INITIAL INSPECTION 0 REWORK INSPECTION

DOCUMENT NUMBER AND REVISION :

BRIEF DESCRIPTION:

APPRAISAL OF THE WORK UNIT:

0 InspectIon not completed (co ntinuatio n sc heduled for )

0 No further inspection required

0 Minor revisions required

0 Major revisions req uired

MATERIALS PRODUCED

0 Issucs list (Not Au thor's Responsibility)

0 Issues list for Au thor

0 Traceabi lity Issues)

participant Role(s) Org.fDept.


Author

Moderator

Recorder

Inspector

Inspector

Inspector

Inspector

Inspector
CASE STUDY: SOFTWARE QUAUTY ASSURANCE PLAN FOR ENCOUNTER 117

Inspection Meeting Report Issues Ust

ISSUES, NOT FOR AUTHOR


Issue Issue must be resolved prior to Document Assigned To Response
Baseline? YIN
1.

2. etc.

ISSUES FOR AUTHOR

Issue Re~onse

1.

2. etc.

Appendix E: Document Baselining Checklist


Document Baselining Checklist

Item Comment I Initials

0 Inspection Meeting Report completed and all issues resolved .

0 Revised document sent out for consensus after Inspection.

0 All comments accepted via Word's Track Changes. Track changes feature
then turned off.

0 Check for clean requ irements traceability completed. (SRS only)

0 All high-level requirements have been allocated to detailed requirements.


(SRS only)

0 Final traceability report generated and stored. (SRS only)


118 CHAPTER 5 QUALITY IN THE SOFTWARE PROCESS

5.10 SUMMARY

Quaht practi es arc IIllcgrJ ted throughout Ihe devciopment process Thcy 'tart wIth planning, when
, pc If, documents u h a the Sohware Quality A\Surance PI.n (SQAP) and the Software VenAcalion and
ValIdatIon Plan (SVVP ) are produced , describing the qua lity policie" procedures. and practIces to be
Implemented.
The QAP is the m.,t er qu. hty plan and specifies the people and o rganizati o n, rcspon,ible for quality.
the proJe t documentallon to be produ cd , the metric, to be co llec ted , the procedures to be practIced. and
the techniques to be IInplement ed . It IS an impo rtant document as it sets the expectatIons regarding quality
early in a project and helps guide its implementation .
In pections are an important qllality technique that involve peer reVlcw of all project artIfacts including
documents, test plans, and code . Their goa l is to identi fy defects as close to their mtroduction as possible so
that they can be repaired quickly. Co nsiderable research has shown that the cost to repair a defect increase
dramatically the longer It i all owed to per;ist in the software.
Quality reviews and audits by a quality assurance (QA) orga nization are benencial. An external QA
group IS mdependent of the people developing the softwa re and o ther artifacts and can objectIvely assess
quality. Again , a sess ing quality and addressing it throughout the devel o pm ent process helps identify
problems as earl y as possible.
Problems arc identi fied by team members throug hout the development process and are submitted as
d4rcls. A scrcelll ng process is implemented to ensure that the defects are accurate and va ltd. A classilkation
system is employed to understand the severi ty of each defect and priority fo r its repair. In addi1ion,
maintaining metrics such as number of defects, time to repair, and so o n is useful for comparison with other
projects and in making estimates for future projects.
Improvi ng the effective ness 01 the overall software process is accomplished throug h implementation 01
a meta · process. Th is inc ludes the co ll ection of pl ocess merrics, and meetings at the end of projects phases to
analyze the metrics. In additIon , lesso ns· learned meetings are co nducted at the end of a project to analyze
project successes and identify areas of improve ment.
The Software Engi neeri ng Institute has deve loped a comprehensive meta·process for assessi ng an
o rganization's overa ll capabi lity . The process is ca lled the Capabil ity MatUrity Model IntegratIon (CMMI),
and it de Rnes several leve ls of ca pabil ity and maturity an organization can measure itself against. The levds
range from the lowest, Levell Initial , to the hi ghest, Levell Optimizing . At the Initial level an organization
can produce so.ftware but has no recognized process. At the Optimizing leve l, an organization implements a
meta · process for process improvement

5.11 EXERCISES

1. In a paragraph , explain why it is important to document quality procedures at the beginning of a


projec t rather than later on.
2. The number of people attending an inspection can have a direct impact o n the effectiveness of the
review. list the di advantages of having either too few or too many people attend an mspect ion.
3. Give two advantages and two disadvantages to using standards for documentatio n of the various
software phases.
4. Why is it generally a good idea to. have a cross· functional group be parI of an inspection team
What type of review (that is, during what development phase) might It not be a good ide.
BIBUOGRAPHY 119

5. Your instructor will pair up student project teams. Conduct an inspection of an ani fact produced
by the other team, such as a SCMP or SPMP. Use an inspection checklist, such as one found in [3].
to guide your in pection.

6. Give an example of a delecr that might be clossiAed with a hi gh severity but a low priority. Be
spcciAc with your answer.
7. (a) In your Own words, describe each of the CMMI levels.
(b) How does applying the CMMI levels promote organizationaJ quality7 Explain this •
In a
paragraph or two, using your own words .

BIBLIOGRAPHY

t. Figan, M. "Design and Cod~ Inspections 10 Reduce Erro~ 10 Progr.sm Devdopmrnt " flL\.1 SYJ/.nII) J01Inwi. Vol IS, 0 3, 1976,
pp. 182-21 1.
2. Wiegers, Kilrl. "-Improvlng QUJ hty lluough Soft ..... a~ Inspections: Procm 1.. ~C1, 1995. http llww\Ol' procc5SImP3ct c.omlanlclesl
inspects hIm! [accessed November 15. 2009}.
3. Wiegers. Karl, "Goodies for Peer Revie.....s... PrOC'rf$ Impacl, 1utp 11W\tt"'W prOCCSSUT\polCl com/pr....,good,,:, [olccosed ()'.'cmw 15
2009)
.. Gchani , Naronn, and A. McUunck, "SojtWtJr, SptCIji. af/(7PI Ttd""qulS. " InternatIonal Computer Science ~nes, Addlwn -Wesley. 1985
5 Cllb, T., and D Cr.aham. " Softuu~rt 'nJPtrIlO"." Addl~n · Wes ley, 1993
6. Bugzil1~ . hnp:llbugzi lla orglaOOu t html [accessed December 10, 2009 ]
7. upability Maturity Model )!': lotegr.nion (a 'MIS:-" J, Version I I, hup Jlwww !!oC' emu cdulpubldocumenl oz·reportv pdfl
02 ln0I2 .pdf [,cc..sed December 8. 2009 J.
8, Humphrey. Watts 5., -A D'SClpli"( for 5<lfrID4r( E"9It,(rn"g:' SE I ~ ru:s In So hwarc Englnccnng, Addt~n · Wc-slc'Y . 1995
9. NASA Goddard Space Flight Center Software Assurance Web Stte-. hItP:llsw·as5Unncc gsfc.na5a.gov/dl sctpltncSlqua ltty/ tndcx php
(2006) [,ecessed November I 5, 2009]
Software Configuration
Management

• What is the purpose of software


configuration management?

• What activities does it consist of?

• How do you plan for configuration


The Solrware management?
Development
Ufecycle • What tools are available to support it?

• How is configuration management


handled in large projects. in praclice?

Figure 6.1 The context and learning goals for this chapter

Many artifacts are produced in the course of developing a software product, uch as specIfications (e.g.,
requirements, design), source and executable code, test plans ond test data, user documentation, and
supporting software (e.g., compilers, editors) Each undergoes numerous reVISions, and keepIng tTack of the
vanous versions needs to be managed in a reliable and con istent manner. Soffware Configuralion 1\ InnagC!lloll
(SCM) IS the process of identifying, tTacking, and storing all the artIfacts on a project. In the context of SCM,
each 01 these artifacts is referred to as a ConAguration item (0 ).
SCM ACIIVmES 121

1 conrnbut to overall software quality in that it supportS a reliable way to control a project's
arti~ ts For c ample, the (]vI proces ensure that the proper source mes are included when building the
softw,re, tern and that the orrcct project documentatIon IS retrieved when required .
1any , tlvitie contribute to configura tIo n management . including identiAcalton of artifacts as
configuration items, storage of artifucts In a repository, managing changes to artifacts, tracking and reporting
these changes, auditing the CM proces to ensure it's being implemented correctly , and managing software
builds and relea cs. Many of these activitIes arc labor intensive, and SCM systems help automate the process.

6.1 SOFTWARE CONFIGURATION MANAGEMENT GOALS

We first define the overall goal of software configuratIon management: b.,,/i"t .-Itly, outrwrilr .-Irfy. 'tumio",
Q.d disasltr rtCoorry.
Baseli n" safety is a process of accepting new or changed Cis fo r Ihe current version of the developing
product (the baseline), and safely storing them in a common repository so that they ca n be retrieved when
needed later in a proJect.
Overwrite salety means that team members can safely work on Cis simu llancously , and changes can be
applied so they do not overwrite each other. Overwrite safery is needed when the follOWing kInd of sequence
occurs.

1. A. Engineer Alan works on a copy of CI X from the common reposi tory.


B. Brenda simultaneously works on an identica l copy of X.

2. Alan make changes to X and puts the moddled X back in the repository.
3. Brenda also makes changes to X and wants to replace the version of X in the com mo n repository WIth the

new versIOn .

Overwrite safery assures that Brenda's changes don't si mpl y replace Alan's, bUI Instead are added
correctly to Alan's.
Reversion occurs when a team needs to revert to an earlier version of a CI. This IS typically reqUired
when mistakes transition a project to a bad state-for exa mple, when it is found that a new version of a CI
turns ou( to cau.se so many problems that it is preferable to revert to a prevlou verSIon . ReversIon requIres
knowing wh,ch version of each C1 makes up a previous version of the project
Disaster recovery is a stronger form of rcversion-it is thc process of retainIng oldcr versions of an
applicatIon for f\Jture use in case a disaster wipes out a newer version .
These four goals, fundamental for configuratio n manage me nt , arc summari zed in F,gure .2.

6.2 SCM ACTIVITIES


There are several SCM acttvitie and best pracltce th at arc Impl emented to successfully meet the gal. JUSt
descnbed They are maInly the following .

I . ConfIguration Idenltficalton .

2. Saseltne control
3 Chan!!e control
4. Version contm/
' 22 CHAPTER 6 SOFTWARE CONFtGURA liON MANAGEMENT

• B.seline S.fety
n<ure that new or c hangcd Is arc .fely storcd In a repository and can he retrieved when neussary

• Overwrite Safcty
En ure that engineer, hanges to the 'arne I arc applied corre tiy

• Reversion

Ensure ability to revert 10 earlier version .

• Disaster Recovery
Retain backup copy In case of disaster

Figure 6.2 Major goals of configuration management

5 Configuration auditing.

6 . ConRguralion tatus reporting.

7 . Rele.se management and delivery.

Each of thcse IS desCribed in the folloWing ections.

6.2.1 Configuration Identification

The first step in configuration mana gement is to ident ify a project's artifacts , o r configuration items (CIl, that
are to be controll ed for the proJect. As deSCribed in the introduction , candi date C is include source and object
code, project speCifications, user documentation, te t plans and data, and supporting softwarc such as
compilers , editors, and so on . Any artifact that wi ll undergo modification or need to be rerrieved at some time
aher its creat ion is a candidate for becoming a CI. Individual fi les and documents arc usually C is and so are
classes. Individual method may also be C is, but thIS not usually the case . A CI may consist of other Cis.
C is are too large when we can't keep track of individua l Items that we need to and we are forced to
continually lump them wit h other items. Cis are too small when the size forces us to keep track of ite ms whose
history is not relevant enough to record separately .
Once selected, a C I is attached with identifying information that stays with it for its lifetime. A
unique identifier, name , date, author, revision history , and st.tus are typical pieces of information
associated wit h a CI.

6.2.2 Baselines

While an artifact uch a source code or a document is under development , it undergoes frequent and ", formal
changes. Once It has been formally reviewed and approved, it forms the basis for further development, and
subsequent changes come under con tro l of configuration management poli ies. uch an approved artifact is
called a bas"i", . IEEE Std 1042 defines a baseline as a " pecificatlon or produ t that ha been formally rcviewrd
and agreed to by re ponsi blc management, th.tthereafter serves as the basis for further development , and can
be changed on ly through fo rmal change control pro cdure "
Baseline, not only rerer to individual C I< but also to collection of Cis .t kc proje t milestones. The
are created by recording the ver>lo n nllmber of all the Is at that time and .ppl ins a Version I.belto uniqud
identify .t. Milc>lones can occur when ,oft ware is internally rdca<ed to a testing organization, or when a
SCM ACTIVITIES 123

A baseline is an individual or group of Cis


labeled at a key projec1 milestone.

Each version below is a baseline .

.. 0.3.4.2 .. 0.3.4.3 v 0.4.1


/ - CI 's
Update Removal Addition

A1

E3 05

figure 6.3 Transitioning from one baseline to the next

version of software IS packaged for release to a customer. For example, a new software version is created and a
set of source files and documentation that constitute software release 1.0 are grouped together, given a unIque
label such as "version 1.0," and are recorded as belonging to the same baseline. This allows all the fi les
constituting software release 1.0 , and their correct versions, to always be correctl y idenllfied and g rouped
together. If files belonging to a baseline are added . deleted , or modiAcd , an updated baseline is crea ted with a
new version number. Figure 6.3 illustrates ,his concept.
Once baseline are created and labeled, they are utilized in a proJect for three primary reasons ( I],

I. Reproducibility

2. Traceability
3. Reporti ng

These are explained next.

I . Reproducibility means that you can reproduce a panicular software version o r set of do umentatio n
when necessary . This i required during product development as well as during ma intenance . For
example, software is shipped to customers, and different cu tomer ma y usc different vcr ions In thc
meantime, the project tcam is developing a new software release, and as a result is updating many of the
Cis u.s ed in previous software releases If a problem is reported by a customer nonn ing an o lder software
verSion, because It was saved as a baseline the o lder versio n can by resurrected by the projc t team and
used to identify and repaor the source of th e problem .
2. Traceability means that relations hips between various project artifacts can be e tabllShcd and re og ·
nized. For exa mple, test cases can be ti ed to requirements, and requ irement> to deSIg n.
3 Reporting mea ns that aJ) lhe cleme nt o f ~ ba c line an DC dctennlned and the o ntenlS of various
ba e1,ne~ can be com pared Th,s apab,loty ca n be ulllozcd when trying to Identify problem I l l ' n,''''
relea<e of software. Instead of performong a length y debuBgi ng effort , diffcrcn e< In , ource file, bet\ ee n
the previous and current o ftware verSIons ca n be analyzed Th,s may be enotlgh to Ide ntl! the wlIrce 01
the problem If no t, knowing exactly what c hange< occurred ca n pOInt to rOlential rOOl callSC', 'reed,ng
up the debuggIng effort a nd leading to faslcr and ca<ier problem resoilltlon B. ,dllle, arc al 0 ,,,dlll to
ensu re: lhatthe corr t fIles arc <-on talned in the exe lItable me o f a software ve"ion. Th" IS tI < d thllin/-:
Cl)n~gunHlon aud,ts, and " covered in c tio n 62 .5.
124 CHAPTER 6 SOFTWARE CONFIGURATION MANAGEMENT

6.2.3 Change Control

onfiS\lratio n items undergo han!!" throughout the course of development and ma intenance:, as a result of
error con'cctio n and enhancemenl. Defects d iscovered by rest lnll o rgan Izations and customers ne~esSltatc
repair Rel ease of software in lude e nhancements to eXIsting fu nctio nailty or the addition of new
hlnctionality . 1'"119' cOl1 lrol, . 1 0 known a co nAguration control , includes a tivltl e. to request. evaluate ,
approve o r disapprove, and implement these changes to baselined I [2].
The formality of these activitIes varies g reatl y from prOject to project For example, requesting a change
ca n ran ge fro m the most informal no d irect oversight for changi ng a C I- to a fo rmal process filling out a
(om, or request lI,dic"ung th e I and reason for change, and ha vi ng the request approved by an independent
group of people before it ca n be released . Regardl ess of the formality of the process, c hange contro l involves
Identification, documentation , analysis , evaluation , approval , verificatio n, impl eme ntatioIl , and release as
described next (2).

Identification and documentation


The CI in need of change is identiRed, and d ocumentatio n is produced that includes ," fo rmat ion SLtch as the
fo ll owi ng:

• Name of requester
• Description and extent of the change
• Reason fo r the chan ge (e .g., defects fixe d )

• Urgency
• Amount of time required to complete change
• Impac t o n o ther Cis or impact on the system

Analysis and evaluation


Once a C I is baselined , pro posed changes arc analyzed and evaluated fo r correctness, as well as the potential
,mpact o n the rest of the system. The leve l of anal ysis depends o r the stage of a project. During ea.rlier stages
of development, it is custo mary for a small group of peer develo pers andlor the project manager to review
changes. The closer a project gets to a rel ease milesto ne , the more closely proposed changes are scrutiniud,
as there is less time to recover if it is incorrect or causes unintended side effects. At this latter stage, the
eva luation is often conducted by a change contro l board (CCS), which consists of experlS who are qualined to
make these ty pes of decisions. The CCB is rypically compri sed of a cross- fun ctional group that can assess the
impact of the proposed change. G roups represe nted include project manage me nt , marketing, QA, and
development. Issues to consider during the evaluation are as follows ,

• Reason for the change (e.g., bug flx , performance improvement , cosmetic)

• Number of lines of code chan ged

• Complexity
• Other sou rce flies affected
• Amou nt of independent testing req uired to validate the c hange

C hanges are ei ther accepted Into the current release. rejec ted o utrI ght, or deferred to a ubsequent
release .
SCM ACTIVITIES 125

Approval or disapproval
Once a change request is evaluated , a decisIon is made to eIther approve or djsa pprove the requesl- Changes
that arc technically sound may still be disapproved or deferred. For example, if software IS very close to being
rele~sed to a customer, and a proposed change to a source file reqUIres many complex modificatIons, a
deC! Ion to defer repair may be in order so as to not destabilize the software base. The change may be
scheduled for a h'Nre relea,e .

verification, implementation, and release


Once a change is approved and implemented , it must be verified for correctness and released .

6.2.4 Version Control

Version control supports the management and storage of Cis as they arc created and modI fied throughou t the
software development life cycle. It SllPPOrtS the ability to reproduce the precise sta te of a CI at any point in
time. A configuration management SYSlem (al 0 known as a version control system) automates much of this
process and provides a repository for SlOIing versioned Cis. It also allows team membe rs to work on artifacts
concurrently, Aagging potential conflicts and applying updates correctly.
A good version con trol system supports the following capabilities,

1. Repository

2. Checkout/Checkin
3. Branching and mergi ng
4. Builds
5. Version labeling

These arc explained in the fo llowi ng sections.

6.2 .4.1 Repository


At the heart of a version contro l system is the repository, which is a centralized database that sto res all the
artifacts of a project and keeps track of their various versions. Repositories must support the ability to locate
any version of any artifact quickly and reliably .

6.2.4.2 Checkout and Checkin


Whenever a user needs to work o n an artifact , they request access (also known 35 ch,cko"l ) from the repository,
perfonm their work , and store the new version (also known as ch,ckill ) back in the repository. The repositOry is
responSIble for automatically assigning a new version number to the artIfact.
Files can usually be checked out either lock,d or ""'ock,d. When checking out locked, the file IS held
exclUSIvely by the requester and only that perso n can make modin atlon to the file and check in tho e
changes. Others may check OUt the fi le unlocked, which mean s it is read ·only and they only receIve a copy
Concurrent wnte pnvileges ca n be achieved by branching, which IS explainod in the next section.
When checkIng 111 a Ale , versIon control systems record the user making the change and ask the person
to includ.e an explanation o( why the Ale was changed and the nature o( the changes ThIS makes it ea>ler to
see how a Ale ha~ evolved over tIme , who has made the changes, and why they were made
126 CHAPTER 6 SOFlWARE CONFIGURATION MANAGEMENT

File A

(a) John branches. _---.... (c) Sally branches


v1 .2 01 fila A / v 1.2 otfile A
1.2
o o
' -__~ (d) Sally mod~ies
(b) John modifies her copy 01 v 1 .2 of
his copy 01 vl.2 of ~__-.... ~---.... tileA
file A
1 1
1.3
(e) John merges his ..........__~
changes to me A (f) Sally merge. her
changes to file A
1.4
(g) v1.4 contains both
sets of changes

Figure 6.4 Branching and merging changes

6.2.4.3 Branching and Merging

Projects are Illos t ofte n developed by teams of people . Version co ntro l syste ms provide mechanisms to allow
team members to work on the same se t of files concurre ntl y (branching ) and correctl y apply changes to
common files 0 that no ne are lost or overwritten (mtrging ). This is also known as overwri te safery
Figure 6.4 depicts an example, in which Jo hn creates a branel, by checking out versio n 1.2 of file A. A
branch is a private work area in a version control system that allows you to make changes to baselined files
without conflicting with other team members. John maintains a private copy of the fi le o n his branch and
makes his changes. Concurrently , Sall y also needs to work on file A. so she creates he r own branch and checks
out versio n 1.2 H er copy starts out the sa me as John's si nce he has not yet checked in his updates. O nce)ohn
finishes his changes, he c hecks in his mes to the reposi tory, and the file is given a new version number 1.3.
Later, Sally finishes her modifications to A and wants to check in the file . If the version contro l system allowed
her to just replace the current copy of file A (versio n 1.3, which now includes John's changes) with her copy,
John's changes would be lost. Instead , the versio n control system supports mrrgl"g , which intell igently applies
Sally's changes to version 1.3 and creates a new version 1.4 with both of their cha nges applied cor reetly. If the
set of c hanges are made to various parts of the same fi le , the system ca n usually perform the merge operation
automa tica ll y. If the ::hanges conflict wi th each other, as when the same lines of code are c hanged, the system
Wi ll ask the u or to merge the c hanges manuall y. In this case the system will sh ow the user which lines overlap
so that person can apply the changes correctl y.

6.2.4.4 Builds

Version contro l systems provide support so as to reliably and reproducibly compile and build the latest
version of software fi les into an executable , usable file . A user ca n specify which branch of code to build from ,
all OWing concurrent development. In addition to the executable Ric, builds produce logs containing lhe Rle
versions comprising the build .
SCM ACTIVITIES 127

6.2.4.5 Version Labeling

<rsion are rea ted by applying a label to all fi les olllprismg a software build. The label is u ually a version
number su h as ' version 1.0". This allows software vers,ons to easil}, be referenced and reco nstructed if
n essary, and supports the onsrruction of baselines.

6.2.5 Configuration Audits

As defined by IEEE 1028 · 2008 (3]. a software audit is "an independent exami nation of a software product ,
software proce , o r Set of software processes performed by a th ird party to a sess compliance with
specifications, sta ndards. contractual agreements, or other cri teria." In the contex t of co nfi guratio n manage ·
ment, the goals of a configuration audit are to accompl,sh the following :

• Verify that proper procedure arc being followed , such as formal technica l reviews.
• Verify that SCM policies, uch as those defined by change control , are followed .
• Deterrnine whether a oftware baseline is comprised of the correct configuratio n item . For example, arc
there extra items includcd 7 Are there items missing7 Are the versions of ind,vidual ,tems correct(

Configuration audits are typically conducted by the quality assurance group.

6.2.6 Configuration Status Reporting

Configuration sta tus reporting supports the development process by providing the necessary ,nformation
concerning the softwa re configuration . Ot her parts of the configuration process, such as change and version
control, provi de the raw data . Configuration statu reportin g includes the extraction , arrangement, and
formation of reports according to the requests of users (4 J. Configuration repo rts include such infomlat'On as
the following·

• ame and vcr ion of Cis


• Approval h,story of changed Cis
• Software release conte nts and compamon between releases

• Number of changes per CI


• Average time taken to change a I

6.2.7 Release Management and Delivery


Release management and del,very define how <oftware products and documentation are forma Ii),
controlled As defined ,n IEEE 12207 · 199R (5] . "m.,ter cop ,c, of code and document at,on hall be
maintaIned for the I,fe of the software product The code an d docu11lent ati on th a t ont01n ",fet or
sccunry enl.eal funct,ons shall be handled , stored , p"ckaged J nd dcl,verl·d ,n ac ord3 ncc w,th the
po"c,e~ of the organ, zatlons InvQlved " In ot her word , flol, 'eS ml"t be llnpl cmen ted t c"""c that
(,mee softwa re and documentation is rclca,cd ,t onust be archIved safe ly and '"l'liahl y, and an J lw a,,~ be
retrieved for future use .
128 CHAPTER 6 SOFTWARE CONFIGURATION MANAG MENT

I Inlrodu tlo n 3 . 3 .2 o nflK"rati o n contro l


3. 3 2 . I Requ estIng changes
.2

3.3 .2 .2 -valuattng c hanges
3 2. I rgJ nl ZJtlo n
3 .3 .2 . 3 ApprovIng or dt<.pprovtng
3 .2 .2 1\·1 respo nslbtlltl c, changes
.2.3 App ll able policies, directl vcs. end 3. 3.2 4 Im plem enti ng changes
pro cdu re~
3 .2.4 Ma nagcllIe nt of the M proce>' 3 . 3.3 o nfiKuration status accounting
3. 3 .4 onfigu ration evaluation and rCVlews
3. 3 M activi ties
3 3.5 Interface co ntrol
3. 3. I o n~g u ra tl o n identi fica ti o n
3 .3 .6 Subcontractor / vendo r control
3 .3. 1. 1 Idc nti fy lllg co nfigurat io n
Ite ms
3.3.7 Re lease manaKement and delivery
3. 3. 1.2 Na mIng co nfig urati o n items 3 .4 SCM schedules
3. 3. 1.3 Acq uinn g config uratio n

Items
3.5 C M reso urces

3 .6 SCM plan mai nte na nce

Figure 6.5 IEEE 828·2005 Software configuration Management Plan table of contents
SOUrce IEEE Std 828-2005

6.3 CONFIGURATION MANAGEMENT PLANS

T o speci fy how the softwa re co nfiguratio n is to be managed o n a project, it is not suffici ent me rel y to poi nt to
the co nfi gura tt o n manageme nt tool that will be used. There is mo re to the process, suc h as what activities are
to be do ne, how they arc to be im plemented, who is respo nsible fo r implem enting them, when they will be
completed. and what resource are req uired- both human and mac hine [2]. The IEEE has developed a
standard for oftwa re config uratio n managemer,t plans. IEEE 82 8· 2005. Th is ca n be very useful in maki ng sure
that all bases have bee n covered In the process of C M. Figure 6.5 shows the re leva nt conte nts of th is standard,
whI ch arc Included in C hapter 3 of the plan.
The topics to be pecificd in Sectio n 3.3 of the SCMP arc largely covered in Section 6.2 of th is chapter.
Sectio n 3.3.3 of the SCM P doc-uments the mea ns by whi ch the st"tus of SCM i to be communicated (e.g., in
writing. o nce a week). Sectio n 3.3.6 applies if a C M tool is used o r if configuratio n management is handled by
a ubcontractor The IEEE sta ndard describes the purpose of each section of the above outline in detail. IEEE
828 · 2005 ,s used in the Encoun te r case stud y later in th is chapter.

6.4 CONFIGURATION MANAGEMENT SYSTEMS

Fo r all but the most tri vial applicatio n. a co nfig uration management system (also known as a version control
system) is indispensable fo r mana8m8 all the artifacts o n a project. Microsoft's SourceSafe™ i in commo n
use. VS is a commo n enviro nment. as well as Subversio n and others.

6.4.1 Concurrent Version System (CVS)

The Concurrent Version System (CVS) is a commonly used, frec, o pen ource configura tio n management
system. C VS Implements a client-server architecture, With users running client V softw3l'e o n their
CASE STUDY: ENCOUNTER VIDEO GAME 129

• Up-Lo·dare

Is id~ntlCal to the latcst revision in the repo ItOry.


• Locally Modified

File has been edited but has not replaced latest revision .
• N""ds a Patch
om~one else has committed a newer revision to the repository .

• Needs Merge
You have modified the nle but someo ne else has committed a newer revision to the reposi tory.
• Unknown
Is a temporary fi le or never added .

Figure 6.6 File status possibilities in CVS

machines, and a CVS seTVer storing a repository of project fi les. Users check out projects (using the chtekoul
command); make changes; check in (usi ng the com mil command); and merge with the changes of others who
checked out at the sa me time (using th e updQI' command ). C VS automatically increments the version number
of fi les or directories (e.g., fro m 2.3.6 to 2.3.7). The status possibilit ies for a fi le are shown in Figure 6.6.

6.5 CASE STUDY: ENCOUNTER VIDEO GAME

What follows is a configuratio n management plan for


Title Signature Date
Encounter. The Softwa re Configuration Manage·
ment Plan (SCMP) for Encoun ter is based on IEEE
Std 828·2005 Standard for Software Configuratio n
Engineering Manager ".:;....., 6/ 15/ 04

Management Plans. The tabl e of contents of the QA Manager £. 'Wiluv. 6/ 11 /04


relevant sections is outl ined in Figure 6.8, which is
Chapter 3 of the IEEE specificanon. project Manager a. !I~"itJ. 6f7/ 04

ENCOUNTER SOFTWARE CONFIGURATION Author l.. $ 'QU4c 6/1/ 04


MANAGEMENT PLAN

APPROVALS Revision History

Note: to the Student, This assume<; the existence of a method whereby


It ii a good idea to have cach team member revision numbers of documents are assigned.
Sign off on the phYSIcal document. This pro·
ces, focuses their attention on the fact that
Versio n I
they Ire accountable for Its contents, and they
will be more likely to ensure that It Is the I 0.0 E. Br""dc ' re.ted first d",ft 11/9
dowment they intend
1.1.0 R. Ilosrwick · Rr viewed 1/ 10/99
130 CHAPTER 6 SOFTWARE CONFIGURATION MANAGEMENT

I 1.1 E. Braude. Expanded 3.2 1/ 18199 A , pc ifl ~ engine r, prOVided by the A or~a .
nlz.llon, woll be d e"~ n ate d "s the "conAguratlon
1.20 E Braude· Reviewed for re lcasc5/ 18199
!eadcr" fo r Ihe durati o n of the pro) ·ct
1.2. 1 E. Braude, r-inal edltong4/ 30/99
3.2.2 SCM ReSponsibilities

Version 2
tatc the tasks that each role must carry out If
2.0 .0 E. Braude: Significant edit of section xx thi is not tated, essential actiVitieS will not be
S/2/99 done, and ome activities will be done by more
2.0 I E. Braude: edits S/ 13/04 than one team member Include backup reo
sponSlbilitie~ In case the main individual is

The table of conte nts of this SCMi' follows that incapacitated .


of IEEE standard 828·200S .

3.1. Introduction
3.2.2.1 Configuration Leader
This Software Co nfiguration Management Plan
(SCMP) describes how the artifacts for the Encoun ·
"Responsible" does not necessarily imply that
ter video game project arc to be managed .
the individual does all of the work merely
that he or she organizes the work and sees to it
3. 1. 1 Definitions that the work is done.
Approved Cis: Cis signed off by project management
Artifact: A Anal or interim product of the
project (e.g., a document , source code, object The configuration leader shall be responsible
code, test result) for organizing and managing configuration manage·
Master Ale: A particular designated Ale for this ment (CM ). Whenever possible, the configuration
project, defined in Section 3.3. 1.2 leader shall discuss CM plans with th~ devdopment
team prior to implem entation. He or she will main ·
3.1.2 Acronyms tain this document (the SCMP). The configuration
CI: configuration item-an item tracked by the Ieadcr is responsible for the installation and main ·
configuration system tenance of the conRguration management tool(s)
CM: configuration manageme nt-the process of speciRed in Section 3.2.3. Archiving is to be per·
maintaining the relevant versions of the project formed in accordance with department policies
SCMP: the Software Configuration Management 1234S .
Plan (this document) The SCM leader shall be responsible for ac·
quiring, maintaining, and backing up the configura·
tion tools used He or she shall also develop a plan of
3.2. SCM Management action if tools become unsupported (e.g., by dis·
continuance of the vendor). Additional respon Ibili ·
3.2.1 Organization ties of the configuration leader are stated in Section
3. 1-3 .6.

5..... ho .. this is be manaRed. Supply role


10 3.2.2.2 Project Leader The project INder and
(.), but lID names or R:lponsibillties. Names his or her manager will take over the config\lration
In: supplied In a liter section. leader's function only under exceptional circum-
stances. They are respon<oblc for knowlnll all the
CAse STUDY: ENCOUNTER VIDEO G6~E 131

rd""ant means of access [0 documents throughout 5. CM passwords should ~ changed in accordance


the life:: of the project. The project leacler shall ensure with corporate security practices, with the fol·
that arch iving is performed in accordance with the lowi ng addition, No password shall ~ changed
policies In Section 3.2.3 below. until the project leader, h is manager, and the
Additio nal responsibilities of the managers are manager of QA have all been notified and have
stated in Sections 3.3. 3 and 3.3.4 . acknowledged the notiRcati o n.

3.2.2.3 Engineers It is the responsib ility of eac h 6. The prOject leader and department manager are
engineer to abide by the CM rules that the configu. to have complete access to all documents under
ration leader publi shes. Engineers are also referred to co nfiguration at all times. Access verificatio n
' Standard Engi neering Respo nsibilities," docu ment form www.ultracorp .division3 .accessVeriRcati on
56789. is to be subm'tled evety two weeks by the project
leader to his or he.r manager.
Additional responsibilities of the engineers arc
stated in Section 3.3 below . 7 . The Encounter project will u e SuperCMTool
release 3 4, a configuration management product
3.2.3 Applicable Policies, Directives, and b), SuperCMT001.
Procedures
These are fictitious names.
Activities such as CM are generally conducted
in accordance with group or corporate guide-
8. Arch iving is to be perfonned in accordance with
lines. Student teams should identofy and li st
de partment policies 12 3456.
their policies in this sectioa . Policy 3 should
be included .

3.3. SCM Activities


I . Configuration management for th is project shall
be carried o ut in accordance with the corporate 3.3.1 configuration Identification
guidelines for configuration management , cor·
po rate document 7890 versio n 6 (8/ 15/98 ).
Th is section states how conAguration items
2. In accordance with division software improvement (Cis) come into being and how they get their
policies, midstream and pOS1· project review ses· names. Witho ut such procedure being 5tated
sions are required, where improvements to these and followed , chaos results.
guidelines are to be doalmented for the benefit of
the o rganization. These sessions are required to
help prepare the d ivision for level 5 CMM certl fi ·
3.3.1.1 Identifying Configuration Items The
cation. The sdf·a sessment rt.'SUlts are to be sent to
project leader shall be rcspon ible fo r identifying all
the manager of Software Self-Assessment wi thtn
Cis. Engtnecrs wishing to pro pose Cis shall secure hiS
three weeks of the assessment session. All "room
or her agreement, via c·mail or otherwise. If the project
for improvement" section are to contai n sub tan·
leader is unavailable for one busi ness day fo llowi ng the
tive matenal , with speCific example .
engi neer's c·mai led proposal for inciuslO n, the config ·
3. All curre nt and previo usly released versio ns of uration leader shall have the authonty to a cept the
Cis will be rctalned. proposed item.

4. The master Ale (defined in ection 3 3. 1.2) can be


accessed o nl y by the conngu rallon leader and , In 3.3.1.2 Naming Configuration Items The on -
his Or her absen e, the department manager figuratio n leader shall have the rt"Spons,blhry fo r
132 CHAPTER 6 SOFTWARE CONFIGURATION MANAGEMENT

labellOg all Is T he file co n vc nll O Il~ shall be a, o ntrol th rough upcr MTool A read·only version
fo ll ow, of th e I IS ava .l ablc to all englnce r~ Under no
cirwm<tance, maya n enSIOcer transfer a I directly
Root directory , Encount er to anyone
ubd, rcc tory R or DD or ..
3.3.2 Configuration Control
File N· N· N xxx correspond",!; to ve""on N.N.N
For example, vc r Io n 2 'I 8 of the SR will be o n This section spells out the procen whereby
me Encounle r/S RS/2_ 4_8.0<1. configurallon Items are changed. This prDCeH
should be Aexible enough to allow Quick
The texl m~ Master 10 Ihe root directory states changes, but controlled enough to keep
Ihe versions of the Is that compri e Ihe current and changes very orderly so that they improve
prior tates of th e prOjeCt For exa mple, Master could the application, not damage it.
melude mfo rmati on such as:

The current versio n of Encounter is 3.7. 1. It 3.3.2.1 Requesting Changes As specified in the
compn everSio n 2.4.8 of the SRS, verSion 1 4 Software Project Management Plan (see Part III ). the
of the SOD. team will designate an "inspector engineer who is
allocated to each team member. Before requesting a
The previous version of Encounter was 3.6. 11 .
change, engineers must obtain an inspection of the
It comprised version 2.4.8 of the SRS, version
proposed change from an inspection team or, if this
1.3 of the SOD.
is not pos ible. from their inspector engineer. To
Thi s Informatio n shall be maintained in a table request the incorporation of a changed Cf into the
of the followi ng form . baseline, form www.ultracorp.division3 .Encounter
.submitCi must be submitted to the configuration
Encounter SRS verSio n SDD version....
leader and the project leader, along with the changed
Release CI and the original CI.

3.3.1 .3 Acquiring Configuration Items 3.3.2.2 Evaluating Changes

In specifying this section , imagine the most For larger proj~ts , a group of people, often
stressful part of the project, which is the called the Change Control Board, evaluatrs
implementation phase, involving several peo- and approves changes. SlUdent teams must
ple in parallel. The process has to be very make this process reasonably simple.
orderly, but it also has to allow engineers
reasonable access to the parts of the project
so that they can start work Quickly. The project leader or designee will evaluate
all proposed changes. The project leader must
also specify the required Quality standards for
Engineers requiring Cis for modification shall incorporation .
check them out using SuperCMTool's checkout
procedure. Note that SupcrCMTool prompts the 3.3.2.3 Approving or Disapproving Changes
user with a form requesting an estimate of how The project leader must approve proposed changes.
long the checkout is anticipated , and store this If the project leader is unavailable for thn:e business
mformation for all requesters of the CI. Anyone days follOWing the submission of a proposed change,
requiring a CI that is currently checked out should the configuration leader shall have the authority to
nellOtiate with the current owner of the CI to transfer approve chan!!es.
CASE STUDY: ENCOUNTER VIDEO GAME 133

3.3.2.4 Implementing Changes Configuration efforts will be subjoct to random


audits throughout the project's hfe cycle by the
IV&V team .
To avoId chaos, it is natural to give to the eM
leader the responsib,l,ty for incorporating
changes; this can create a bottleneck at imple.
3.3.S Interface Control
mentation time, however. Before this "c runch" The CM system interfaces with the project Web site.
This interface shall be managed by the configuration
occurs, the CM leader should find ways to
leader.
remove this bottleneck by distributing as
much work as feasible to the engineers making
the changes. 3.3.6 SubcontractorNendor Control
The con~guration leader shall track upgrades and bug
reports of SuperCMT001. He or she should be prepared
Once a CI is approved for incorporation into with a backup plan in case the maintenance o f Super.
the baseline, the co nfi guration leader shall be reo CMTool is discontinued. This plan is to be sent to the
sponsible for coordinating the testing and integra· project leader within a month of the project's ,"ception .
tion of the changed CI. Thi s should be performed in
accordance with the regression test documentation 3.4 SCM Schedules
described in the Software Test Documentation . In
particular, the configuration leader shall coordinate
the building of a version for testing . Version releases TI,e SCM schedule can be prOVIded here, or
must be cleared with the project leader, or with the combined with the project chedule in the
manager if the project leader is absent. SPMP. In the latter case, this section would
not repeat the schedule, but would merely
3.3.3 Configuration Status Accounting point to the SPMP.
The configuration leader shall update the configu·
ration summary at least once a week on the project
configuration Web si te www.ultracorp .divi sion3/ The schedule for configuration management
EncounteriCo nfiguration . SuperCMTool's sta.(Us reporting , archiving, and upgrad ing is shown In
report will be a sufficient format for the summary . Figure' 6.7.

3.3.4 Configuration Audits and Reviews 3.5 SCM Resources

The configuration leader will require an estimated


In industry, random audits are often employed.
average of six hours a week to maintain the system
They are not commonly conducted by student
config urati on for the fir t half of the project, and
teams due to a lack of resources, although
t,_elve hours a week for the seco nd half We have
rome teams have carried them out successfully.
cho ' en no t to call o ut separately the time spent by
PeriodiC reviews, as part of the regular team
the ot her team members o n configuration
meetings, do not take much time , and they arc
management.
recommended .

3.6 SCM Plan Maintenance


The project manager shall schedule a review by
the CM leader of the cnnfiguration at least once
every two weeks, preferably a. an agenda Item for a All project documents undergo change
regularly scheduled weekly project mee tIng The throughout the duration of the project. The
CM lead~r shall review CM status, and report on SCMP is especiDlly sensitive to change, ho",·
the proposed detailed pro edures to be fo ll owed at ever, because It controls change Itself.
code and ontegratlo n time
134 CHAPTER 6 SOFlWARE CONFIGURATION MANAGEMENT

Month 1 Month 2 Month 3 Month 4 Month 5


1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
Stable eM 4
-- - ----
- - --- '. '
• Ve ndor backup plan due
- - -- -
eM reviews
Ufftff tttH
eM process
Im provement
session
- --- I
Random IV and V audits
I

Figure 6.7 Configuration management schedule

Due to the Importa n c~ of a stable SCM plan , all difrerent so urce code access requirements. Most are
changes to this document mllst be ap proved by the de velopi ng their own plug " ns, which are exten ·
entire Ctvl team sions to existing Eclipse code and fu nctio nal ity,
In vic w of the soft\\fare de velopment o rganiza · and o nl y require access to Ecl ipse source code
tlon' goal to anain CMM level 5. the conR ll urati o n for debu gg in g their work. Others may want to
leader will do the following for the CM process change existi ng Eclipse sou rce code if they are
improvem ent se sions: Rxing a bu g, o r add code if the y are develop ing
a feature . Th ese develo pe rs require write·access to
• Review the effective ness of this plan Eci ipse code .
Source code is managed in Eclipse using CVS
• Qua ntify 10 se due to defects In this plan
(Concurrent Versioning System ), which is the de
• Re view the effectiveness of Super CMT 001 facto version co ntrol system fo r open source proj·
ects. Eclipse integrates a built ·i n CVS CUI, making
• In vestigate the literature fo r new CM meth ods;
version control very easy to use . CVS implements a
q uanti fy the costs and beneRts of improveme nts
c lient· server architec ture, with the Eclipse repository
• Investigate new CM tools housed o n a ce ntral server at dev.eclipse.org that
stores all the Eclipse source code.
• Sugges t speciRc improvements to this CM process
In ge neral there arc two classes of Eclipse users
• list the beneRts of improvements as follows ,

• Provide cost cstimates on effecting the improvements


I. Those that want to read andlor modify Eclipse
• Prioritize the costibeneRt ratios of all the slIg · code but don't have write access to the CV
gested chan ges reposi tory

2. Those that do have write pemlissio n for the


6.6 CASE STUDY: ECLIPSE Eclipse source code and can modify and update
the CVS repository . These people are call
CONFIGURATION MANAGEMENT IN
(o mmllttrs
ECLlPSE 1

Open o urce projects such as Eclipse arc developed The fo llOWing IS quoted from [7) and d~cri~
by geographical ly dispersed e ngineers who have these t'Wo classes of lI<ers .

I This section is bilsed on information rrom (6).


CASE STUDY: ECUPSE 135

Anonymous CVS

For pc::opl~ who actually want to change Ecllp e code but who do not have the required commit rights
In that area, all clements of the Ecl,pse proje t arc available via anonymous access to the development
repo itory. U 108 anonymous acce> you can checkout code, modify it locally, but cannot write it
bad. to the repository. Th,s is handy if you would like to fix a bug or add a feature . eet the code via
anonymous access, do your work. and then pass the work on to a commilter for inclusion in the
reposi tory. ..
All committers mu t use SH (Secure SHeil ) to acce the CVS repOsitory if they wish to use their
u er id and password (o.e. , If they want to write to the repository).

Full CVS

Developc::rs WIth commit right have individual user ids and password, in the Ecl,pse prOject
development reposItory. As a committer you can use SSH (Secure SHeil ) to connect to the CVS
rcpository as follows . .... Once your information is authenticated , you can browse the repository and
add projects to your workspace. If you do some changes that you'd like to contribute, after testing and
enswing that you have followed the contribution guideline~ , you are free to release your changes to the
rcpository . Of course, you can only release changes to projects for which you have commit rights.
Note that you can use the SSH protocol and your Eclipse user id to access projects for which you
arc not a committer, but you will not be able to release changes.

These points arc summarized in Figure 6.8. • Major- thi s numb('r i incrcmcnlcd each time
there is a breakage in the API
VERSION NUMBERING • Minor-this number i increme nted for "extemally
visible" changes
Eclipse plug·ins use a versio n·numb""ng scheme
that captures the nature of the c hanges implemented • Service-this indicate a bug Ax or ot her change
by the plug.in . Versi on numbers are co mposed of not visible through the API
four parts as follows : • QualiAer-thls indicates a partIcular build
Major. minor. service , and qualifer. Major. mitior.
and suvir! are Integers, and qualifltr IS a stn ng.

OHiclal
Eclipse
Code Write access
Base with password
(CVS)

General
User

Com miller

Figure 6.8 Eclipse configuratIon management


136 CHAPTER 6 SOFTWARE CONFIGURATION MANAGEMENT

Firs t develop me n t s trea m

I 0.0

Second development s trea m

I 0. 100 (ind ica tes a bug flx )


I I 0 (, ne w AP I hJ bccn Introduced)
Thc plug -IO ship a, I 1.0

Third dev~ l op m ~ n t s tream

1.1. 100 (IOd,ca tes a bug flx )


2.0.0 (indi ates a brca kln g c hange)
The plug-in . hips as 2.0.0

Mai nte na nce stream afte r I . I .0

I. I. I

Th e plug" n ship as 1. 1.1

Figure 6.9 Eclipse plug-I n version num bering ' of 2


Source, EclIpse Wilt!. I'lttPl tw1ki eclIpse OrgIVersion_Numbenng.

The exa mple shown In Figure 6.9 and 6 10, applicatio n programming Interfaces, and shipping to
take n fro m hnp j/wiki .ec ilpse .o rg, s ho ws ho w the the community are rcAected in the numbering in
versio n numbe r c h anges as a result of plug· in devel - partic ular ways.
o pment. The descripti o n sh o ws that bug fixcs , new

6.7 STUDENT TEAM GUIDANCE: CONFIGURATION MANAGEMENT

Student tea ms sho uld create a Software Configuratio n Management Plan (SG\1 P) for their projcct using IEEE
Std 828· 2005 as a template and the Encou nter SCMP in Section 6.5 guidance . The rest of this section
descnbes how to o rga nize fo r this task.
co
'"'CI>"
-
"
II:
First dey stream

-
Second dev stream
Malntenonco 51'~m ef'tef

Third dey stream

Figure 6 .10 Eclipse plug-In version numbering 2 of 2


Sour" EdIpse WIkI, hUP:JIWlIeJ.ecllps8.cwgNOfsAon_Numbtf1ng
SUMMARY 137

1. Roughl ske tc h out your SCMP


a Detemlme procedures for making changes.
a Omit tool references unless already identified o nc .
a 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.
138 CHAPTER 6 SOFTWARE CONFIGURATION MANAGEMENT

A ~c l'equIJ-cmCIll of ,1, the abdllY to reproclu e Ihe precIse "alc of all I, 01 any POlf11 In lIme A VCI';lon
Iltra l , '>tem (al,o kn own ", a cOllfigurallo n manaK me nl sy,tcm) au to mal ,mu h c,r th IS proce,s and provide< a
rcP<"' t )ry for to nng ver<loned Is It also allows team mcmlx:" to work on artlfac" concurren tl y. flagging
pote ntial (",Oi" and appl 1118 updates o rrcctly. Vor<lon cOlltrol 'y,tcm, In lude hlnclionality for c hecking In
alld c he kin g out Ale , bran hing and l11erlli nK. building Ihe sohwa re, and crcaClng softwa re vc rslo ns.
o ntlgllratlo n audIt<. wh,ch arc tYPIcall y co nduc ted by the qua l"y as urance g roup, arc used to en'IUre
that agrced upo n M pro edures and po l, c,es arc bei ng fo ll owed , and tha I ,oftwa re being produced"
o rnprised of Ihe carre t co mpo ne nt,.
onflguratl o n <latus reports support th e aud,t proces by proVIding a detailed h,story for each CI
including wh e n it was reatcd Jnd mo dified . how It was modi fied . and by whom .

6.9 EXERCISES

I. In your own wo rds , deA ne the term cOHfigliralion il,," and desc ribe Its purpose .

2. \'(Ihy is it necessary fo r compilers to be idcntiRcd as configuratio n items? Describe a scenario that


illustrates whe n th,s is l1l'cessary .

3 Describe the four goal of configuratio n l11anageme" t in your own wo rds. and explain why each is
important.

4 . If you are devel o ping a software app lication usi ng an incremental process, at what points would
you minima ll y c rea te baselines)

5. Explain the difference bel'ween change co ntro l and version control.

6 . Agile processes pro mote conti nuo us integration. which results in branching and merging at very
frequent in tcrval (as ofte n as every few hours). Describe one advantage and disadvantage of
branching and mergi ng so freq uentl y. Describe one advantage and disadvantage of branching and
merging less frequentl y.

7 . As mentioned in the T eam Guidance sectio n (Sectio n 6.6), forsmaliteams it may not be necessary
to utilize a n aut omated conRguration management syste m. Describe the process you would follow
to perfo rm branch ing and merging wit h out such a sy tem .

8. Research a configuration m"nagement system such as Subve~ion or CVS. Describe how it


implements the seven SCM activities listed in Section 6 .2.

TEAM EXERCISE
For the team exercise. consi der as a group how you wil l perform it, check the hints below, and then
carry out the assignment.

eM Plan
Produce a software configuration manaBeme nt plan for your team project using IEEE tandard 828·
1990. The case >tudy should guide your team. but your document will be mo~ SPCCIOC, I't'Rectlng t~
BIBUOGRAPHY 139

panicular resources avaIlable to you. Do not include material unless it contributes to the document's
goals. Avoid bottlenecks and unnecessary procedures. Include procedures for what to do if people
cannot be reached and deadlines loom.
Bdore you begin . estimate the number of defects per page the team thinks it will discover during
the fi nal review. Keep track of and report the time spent on this eHort by individual members and by
total team effort . State the actual defect denSity (average number of defects per page). Assess your
team's effectiveness in each stage on a scale of 0 to 10. Summarize the results using the numerical
results, and state how the tcam's process could have been improved.
Criteria,

I . Practica lity , H ow well does the plan ensure that docum ents and their versions will be secure,
coordinated, and available7 (A = plan very likely to ensure coordination and availability)
2. Specifics, H ow specific is the plan in terms of suitably naming places and participants7 (A = no
doubt as to what engi neers must do)
3. Process as essment and improvement, To what degree did the team understand the strengths and
weaknesses of its process, and how speCific are its plans for improvement7 (A = full , quantitative
understandin g, with plans for improvement very speCific and realistic )

Hints forTeam Exercise

Do not fi ll in sections that arc as yet unknow n; add only parts that you are confi de nt of being able to
implement within the semester. Make your plan realistic. For example, don't state that "all other team
members will review each contributor's work" unless you are reaso nably sure that this ca n be done
within the probable constraints oi your project. It is too earl y to make any assu mptions about the
architecture and des ign of the application .

BIBLIOGRAPHY

1 8cllagio, David, and T Mliligon. "Softwa re Co nRguratlon Management Strategies Jond IBM Rational C lea rnsC' A Practical
Introductio n,· IBM Prcss/PcMson pic, 2005, p 7
2 "IEEE Standard for Sortware Conflguralio n Manogcmcnt Plans: fill Srd 8 28 - 2005 . August 2005 .
3 "IEEE StJndard for Software RcvlC' ....·s and Audits," JEEE Std lo n - l OOS, August 1008
4 Ha~~, Anne M J, "ConMJlt'tJ llon Mand91'n1(r1' Prr"cipl,I and PractICc," Addlso n.Wesley, 2003, p. 25
S "Systems and so hwau: cn8tnt't'nn~-So ft''A'art' Ide cycle procc'ic;;cc;;,· IEEE Sid 1220 7·1008 Second edItion. January 2008 , p 69
6 Eclt psc, http}I""",,'W ecl Ipse 018 (acC('sscd AuA'U'i' 13, 2009 ]
7 Echpsc-. hup Jlwww eclipse org/eci lpsc/ [Jccc ..scd Augllst 13, 2009 )
principles of Software project
Management I: Organization,
Tools, and Risk Management

• How are software development


prOjects organized?

• What is an appropnate team size?

• What happens when teams are


The Software
geographically distributed?
Development
Ufacycle
• What tools and techniques are
available to support projects?

• How do you handle risks?

• How are projects managed In


practice? In student teams?

Figure 7.1 The context and learning goals for this chapter

SoltlDa" project ""'H"9c""Ht is the process of planni ng . organIzing. and monlto nng the development of a
oftware prOject from its Inception to its completion . It incorporates a set of tool s and technique practIced b
the person or people responsible for a project during every phase of develo pment. The person respon ible I
the proJcct ",aHa9" (a tenn usually u cd for larger projects) or tca", lcad" (a tcnn typically u cd for smalkr
PRINCIPLES OF PROJECT MANAGEMENT I: ORGANIZAnON, TOOLS, AND RISK MANAGEMENT 141

• Customers are sddom sure 01 what they want.

• ustomers change their requirements and plans may not be updated.


• It i hard to estimate up front Ihe magnitude of the effort required .

• It.s hard to coordinate the many requirements , the design elements corresponding to each requirement ,
and the correspondi ng code.

• There may be unforeseen technical difficulties to overcome .

• It is not easy to maintain constructive interpersonal team dynamics . Time pressures cause stress, and [earn
members have differing opi nions.

Bur rbm ohslaclts co .. all br oV(rcomr/


Figure 7.2 SOme challenges of software project management

projects or teams). Sometimes the perso n responsible is called the project manager and has o ne or more
subordinate team leaders. In all cases, these people practice project management. C ritical to the success of a
project is the organization of the project team . Many different organizational structures are possible . each
with a set of strengths and weaknesses.
It is very difficult to deliver a quality, full y accepted softwa re application o n time and within budget.
Figure 7.2 gives some of the main reasons . Software project management addresses these issues by
incorporating a range of activities and structure into a project , including project orga nizati on, {ools, and
support, management of project risks, project estimation and scheduling, project docume ntatio n and
tracking. These are summarized in Figure 7.3 and explained in this chapter.

• Organization
o How is the project team structured?

• Project Management Tools


o What tools are available to support project mana gement?

• RJsk Management
o H ow arc risks to the project's success identified and mitigated ?

• Estimation
o How long will the projec t take to o mplete and how many resources are reqUIred ?

• Scheduling
o What are the different parts of the project , in what order will the y be completed , ,nd who will work
on each part]

• Documentation and Monitoring


o How j~ a project plan c rea lcd , a nd how i, the plan monito red to c n<urc th,t the proJcu is I rowe<s.n.,;
on lime and w.th.n budget?

Fleur. 7.3 What does software proJeCI management add ress?


'42 CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT

T he rest ot Ih" ch"p ter foeu,,,s o n the o rga nizatio nal stru ture" too ls, and rISk management that
support proJ Ct managc ment T he next hapt er, whl~h ompletes our d,scuS<lOn o( prOject managcment
pri nCiple" cover meth ods that an be employed, Includln~ cst unatlon , sc hedu llnl(, and planning

7 ,1 SOFTWARE PROJECT ORGANIZATION

The way," whic h a compan y is o rga nized has a direct bearing on how proJeu, are executed, Some
ompanlcs rganlze around th c lf proJec ts. In these companu.:s pro)cl.l managers have t(rcat autonomy, with
team member di rec tl y reporti ng to tht'm. O ther o mpanie orga",ze arou nd functional areas such as
devci o pment, marke ting, fi nance , and so on , givi ng projec t manage rs respo n ibility for monitoring and
reporting o n proje t progress. O ther compan ies empl oy an organization that mixes both of these In ge neral,
there are three type of orga niza ti o nal Slnl c turc : projtCf-orjwttd, j 'Hlcliotl -oriw ttd , and m(lfrtx . W e examine each of
these," the ect lo n that (ollow.

7.1. 1 project-Oriented organization

In projecl-orien ted organiza tions , personne l arc o rga nized around the projects of t he compa ny. When a new
projec t is initia ted, a project manager is assigned to head up the projecl. O ne o( their first tasks is (orm ing the
team , whi ch is made up of new hires or people who are finishing o ther prOJects. The project team comprises
people from multiple functional area such as marketing, fi nance, development, and so o n. Team members
report to the project manager, who is thei r ult imate boss. They are attached in all ways to a parti cular project,
and have no o rganizational affilia tion with peo ple o n other projects . This type o( o rganization is illustrated in
Figu re 7.4.
The principal rca on to o rganize around projects is to develo p loyalty to the project rather than to the
functiona l manager [ I]. Since employees are dedica ted to a si nglc project, they can focus their ti me and
energy o n that project. Th is increases the predi ctability o( sc hedul es as there IS less chance of team membe rs
spending unschedul ed time o n other projects. H owever, th is type of o rganization has the potential
disadvantage of isolat ing engi neers professio nally and redUCi ng the amount o( reu e and profeSSional
stimulatio n between projects as a resu lt o f this isolat io n.

Senior
Manager

Prolect Project Project


Manager Manager Manager

Project Team Project Team Project Team


(Mar1<etlng, Finance, (Mar1<eting, Finance , (Mar1<eting, Finance.
Sohware, OA) Software, OA) Software , OA)

Figure 7,4 project-orlented organization


SOFTWARE PROJECT ORGANIZATION 1U

President

Finance Marketing Oevetopment OA

Finance Marketing Sohware OA


Managers Managers Managers Managers

Finance Marketing Sohware OA


Personnel Personnel Engineers Engineers

Figure 7.5 Function-oriented organization

7 _1.2 Function-Oriented Organization

F","ction-orirnttd organizntiolls arc a very common type of structure. A compa ny is organ ized IntO groups based on
their fu nctions , such as marketing, Anance, development , QA , and so o n. Th is type of structure is dlus trated in
Figure 7.5 .
In this form , functional orga nizations have projects, but the scope of their prOjects IS lim ited to the
boundaries of ,heir group responsibilities. As an example, if a software functional group is working o n the user
interface (UJ ) software of a larger software product , only the UI software being developed is considered the
current project fo r that group.
Functional managers in this kind of organization act a project managers. re pon ible for the" projects
as well as the hiring, Aring, a nd salaty of their team members. Managers may be responsIble for multiple
projects. TI,is structure has the advantage of clear and responsible decision· makin g c hannels However,
because managers arc responsible for multiple projects , their knowledge of proje ts is nece sari ly limited by
their available time. In addition , they must wei gh carefully the needs of each and e nsure that they don't favor
one over the other. If one of their projects is falling behind schedule, for example , they may shift personnel
from another project to the lagging project . ThIs may cause a delay," the other project.

7 _1 ,3 Matrix Organization

A-latrix organization, are a c ro s between project - and function -oriented organizations. They try to gain the
advantages of both project-onented and function -oriented organizatIOns. In a matrix orga nizatio n, employ -
ees belong to a functional g roup (e.g ., marketing, engineering ) but arc loa ned to projects based o n the"
expertise_Thus, a software eng,"eer's supervisor- who" responsible for evaluating that person-would be a
member of the softwa re engIneering fun tlonal unit . Within ea h project o n which the person is ,,'orking,
howl>ve r, he or she would be supervI sed by a project leader Eng,"cers arc u uall y In vo lve d o n a regular baSIS
with one project, sometimes two, but ~e ld om mo re.
FIgure 7_6 illustrall><; the reponing srru lure of a matfl x organlzatron In lh" .tm lUre, a prOject manager"
aSSIgned to each project For example, Oscar Man IS' mcmber of the marke ting depanment alld a<signed to the
airline r=rvati on proJec t, headed by Al PruItt For all proJe t-related aCtiVItieS, Oo;car repom directly 10 I
144 CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS. AND RISK MANAGEMENT

Project

Malrix rgani zll tlon Airline Bank Molecular Fluid


reservation accounting analysis mechanics
project proiect project project

Proiect AI Pruitt Quinn Ruth Pella Fred


manage me nt Full lime Parker Full tIme Parson<
dept Full time Full tIme
.--
Marketing Oscar Mart Pete Merrill ue More Elton
-
'"oc: dept Oulia Full time Full time Half tIme Mar~ton

--
v
c:
Pitt, mgr) Full time
::>
Ll-.
Engineering Hal Egberts Ben Ehrlich Mary Len Engels
dept Ooe • • • ••• . , . ." Ericson • •• •••

Roth, mgr) • • • •••

Figure 7 .6 Matrix organization

However, Oscar's boss is Julia Pill , a manager in the marketi ng department. Julia would consult with AI when
doing performance apprai sals.
An advantage to this approac h is that project managers maintain focus and have responsibility for the
success of the .. projects . Functional managers are focused o n the content of their functional area and can
more easi ly coo rdinate the efforts of their g roup members, some of whom may work on multiple projects For
example . the software manager of a database group might recogn ize that multiple projects have similar
requirements for accessi ng a database . The manager can coordi nate a software design that is ge neral enough
to be used by multiple projects. We will consider team size next.

7.1.4 Agile Organization

Agile teams consist of technacal people. The .. principal no ntechnical contact is with the customer. Stili,
function s of the kind mentioned above conti nue to be required. An example is Anance . Every o rganization
needs to understand the costs and benents of projects. Agile teams become adept at estimation , and so nnance
people-who are not part of the agile team itself-have good shon ·term data and forecasts but are required
to be agi le as well. This is because agi le teams are not plan -driven . n,e upshot is that the nontechnical people
must base their work on good but relatively short-term data.. They perform their work by interacting with the
customer and WIth the development team .

7.2 TEAM SIZE

To be precise, a "team" is a group of people who work closely together on a daily basis. One mIght imagin~
that the appropriate size of a team depends strongly o~ the size of the application (large team for large
applications, etc.) but th IS is not so . Large teams (not necessarily groups-keep the deRnitoon of "team' in
mind) have the advantage of div iding the work Into many pans but the disadvantage of communication lhat i
TEAM SIZE 1U

I
Effectiveness
per developer Developer communicales
regularly with 11 people.

Developer
.r~- communicates
O~-- regularly with no one.

3 7
I I
Number of people with whom
developer must interact frequently
Key: 0; engineer
f"tgUre 7.7 Options for team size showing extremes

time-consuming and error-prone. A significant aspect of such communication is the need for tea m members
to explain what they are doing. Having to keep forty people up-to -date on a daily basis , for example, requires
a lot of meeting time. In his ciassic work , Th, Mylhical MnH -MoHth [2]. Fred Brooks pomted out that adding
!><,ople to a failing project invariably makes mailers worst . In other words, for many projects the disadva ntage
of increased communication channels, which are panicularly heavy during the learning process of new team
members, may often outweigh the advantage of divisio n-of- Iabor.
What is the optimal size of a team ? This is a mattcr of trading off the benefit of haVing many helping
hands against the cost of communication among them . The optimal size depends on the nature of the projec t,
Routine projects can usually benent from larger team sizes because a lot is understood about what each person
should do. Let's consider extremes for a typical project, shown In Figure 7.7. The vertical axi reAccts the
effectiveness per developer.
Experience of the authors and others shows that the number of develop,:rs with whom each developer needs
to interaa on a regular basis should normally be between three and seven. (Humphrey (3) suggt'Sts four to elght.).
Formal studies on the effect of team size on performance are rare. At one extreme shown in Figure 7.7, the developer
works without interactmg regularly with anyone on an individual basis. Although no time i spent on
communication, such isolation typically results In misunderstandin!." of what is required of that developer, leading
to a relatively low level of effectiveness. At the other extreme, the developer has to intern t regularly with so many
tndiv,duals that there is not enough time left to perform development itself, again resultinG in relative
ineffectiveness. In panicular, true "regular communication" could entail speaking with someone for an average
of approximately two hours a week_ If an engincer were In regular communtcation with ten others, then fully one
half of his time would be spent communicating, leavmg only half of the week for hIS tndivldual contnblItion. Project
organizers, whether planning twenty -person or hundred-person projects, have to a count for thiS. Figure 7.8
Illustrates these potnts as follows. If you pick a team size such as three and draw a venicalline, it into,..;e ts the
blue area between two values of 'effectiveness per developer ' TI,e inexactn""s of this measure leads us to talk in
telms of ranges rather than absolutes. We arC interested in picking a team ,izc that yields the most effiCIent work on
a per-developer basis. Figure 7.8 shows this occumnlj between team siz"" of about three and seVen
As the number of participants in a prole t grow>, an orilanlzation where everyone is a peer b<:comc -
ImposSible to usc because thft number of commu nica tio n llilk (between all of the pairs) grow . With the square
of the number of panicipants Three people entail three Itne, of o",munl 3tion, four pt'oplc cntatl ix, nyC
people ten, six pee. pic fifteen . " people rcqlttre (II - I) + (II - 2) + ... + I = II (/I - 1)12 hnes of Olnrllun lcat lon .
This grows With the square of H ne hundred people would have til participate rCHttlorly In 4,950 lines 11
communlcationl One alternative for laflje pro, e~t' 1< the orga nizotilln ,huwn til l' lgttrc 7 _, In whic h peN
146 CHAPTER 7 PRI NCIPLES OF SOFTWARE PROJECT MANAGEMENT I' ORGANIZATION, TOOLS. AND RISK MANAGEMENT

r Dovoloper communlcalos
Ellectiveness regularly with 11 people.
per developer Approxlmat"
optimal ra ng" Communlca llon lime
outweighs /)Onefils 01
Interaction.

Developer communlcales
regularly wllh no one.
" No communlcallonllme is
lost. bul developer is too
Isolated and has no help. ,•
7

Number ot people with whom


developer must interact frequently Key: 0 = engineer

Figure 7.8 Range of optimal size for beneficial interaction

Team of leaders

Figure 7.9 A peer organization arrangement for larger projects

groups remain small , and one member of each group is deSignated the communicator with the other peer
groups . This type of organization tries to preserve the benefits of small teams. but it harnesses the large
number of people to bui ld a large application . Note that team leaders have double the amount of
communication rime than non · team leaders.

7 .3 GEOGRAPHICALLY DISTRIBUTED DEVELOPMENT

Independent of whether a team IS project-oriented , fun ction -oriented, or m.trixed, team members maY be
either collocated or geographically distributed . The latter prese nt a unique et of challenge
Managers naturally try to make usc of worldwide programming talent to optimize costs and improve
quality , a process sometimes called oifsbonn9 . The Internet and collaboratIon tool have mad .. offshonng
increasingly practical. n,e
per-hour costS of remOle progra mmers are traded off against the ommunlcation
GEOGRAPHICAllY DISTRIBUTED DEVELOPMEHT 1. 7

• me ofR e arca
+ ideal for group commun Ica tIon
- labor rates suboptl1nal

• Same city , different offices communIcatIon fair


+reasonabl y good communication
+ common culture
- labor rates suboptimal

• Same country, diflerent cities


+ common culture
- communication difficult

• Mul ti -cou ntry


+ labor rates optimal
- communication most difficult
- culture issue problematical
,•
Figure 7.10 Possible locations of distributed team
SOc.rce. GraphICS reprodUCed wtth penTlfssion from COrel

problems incurred by physica l remoteness . TIlls trade ·ofl depends large ly o n the degree of need for continual
interaction wIth the customer. Options lor remote tcams are illustrated in Figure 7 10.
Bob Schudy , a colleague 01 the authors who has extcn ive experien e wIth offshon,,!:, lists its
advantages,

• Work can be done around the clock

• Good ·quality work is available


• There is potcntial for cost savi ng

He lists the lollowing a, dIsadvantages .

• Incre'hed ddfi ulry lor the offsho re per<;onnel to understand reqU1remenlS

• The lack 01 IOIomlal " hallcr" thaI an smooth progre"


• Tim d,fference< lor (VIrtua l) meellngs
148 CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I' OflGANIZATION, TOOLS, AND RISK MANAGEMENT

Costs 01 OHahorlng
Benefits 01 OflshQriog ® Communications hampered
@ Lower oltshore labor rales ® Cultural dilteronces
© Work continues during U,S. ® Increased projecl
night time management coslS

Figure 7 ,11 TO offsilQre or not to offshore


• urprises in ski ll CIs
• Travelmg ills, e pec lall y for westerner; in the East

Schud y includes Ihe following in his remedies for these disadvantages,

• Meet face -to -fuce initially and periodical ly ,


• U se various media (c ha t, VO IP, conference calls, etc.) .
• tv'ake sure there is strong on ite management'.

o rne of the trade -o ffs that arc accounted for in deciding whether and how muc h to offshore are shown
in Figure 7 I t _
Figure 7 , IllS an e xample of how a project can be distributed among "ncar-shore" (same country; remote
locatio n ) a nd offs ho re , Fi gu re 7 . 13 shows how tasks coul d be allocated in a distributed development project _
The particular allocations are shown as exa mples o nl y, and were quoted by a group at IB M _
IBM lis ts the methods in Figures 7 14, 7, t5. and 7, 16 for dealing with distributed development The word
· reqUlrements" in the Rgure refer; to what is needed about the process, not the reqUirements of anyone application_
CDD stands for geographically distributed development. UML is a deSign notatio n covered in this book.

--.,
!{l -.,'"
.-5
'0
--., -.,
---!:!.'" --
'-'
~ <:
c
'-'
E
<:
<:
<:
E
<:
--!{l'"
=>
'" --
,0
-
'-' 0
8.
E
>.
-.,c-
0 -g
--
'"
~ 0
<:
0
u => .,
c 't::
w- e. U
0
0 -
0
a..

Figure 7 .12 Example of how tasks can be allocated In a distributed development project .
Souru 18M, c.opyr18t't (j ;l lntcmallonal BuSiness MacJllnos COrporation, rtPrInted WIth pOfmlSSlOr\, httDJlwww3 software ibm comlibn'd,./'plltl,~~'¥'"
weblgvkleslGC34 2500 00 IXl'
GEOGRAPHICALLY DISTRIBUTED DEVELOPMENT 1_9

In -house team Remo te subcontracto r

• Business analysis • Testing on pre· release builds


• New feature development and related testing • Testing maintenance rc1ea es of current version
• Requirements: capturing, doCUmenting, and • Build and deployment
managing
• Selected project management
• System architecture, modeling • Mainta ining current version
• Project management • Unit testing components modiAed during
maintenance
• Creating and modifying requirements for
maintenance

Figure 7.13 An allocation of tasks


SOUrce IBM, COP'Il'IgTlt ,~ Intemaoooal Business Machines COrporation. reprlnle<l wlUl pel tlUSSIOO, httrJ:J/Www· l28.ibm comIdeveloperwurts/ratJOl'\lWllbraryl
aprOSIcammaranollndex.html.

- - ---~~-~ --
REQUIREMENTS IBM RESPONSE

United leams despite • Enable brow<er-based access to Ihe same knowledge base for all teams
diverse languages and • Provide easy access 10 guidelines, template and tool mentors based on
cultures underl yi ng best practices
• Visually communica te discipline workAow and interactions wilh the Unined
Modeling Language (U ML)

Reduc tio n in work • Imple me nt a fTamework based on core process workflows fro m business
transfer issues modeling through deployment
• Use a phased approach to software development that detads execution for
each disci pline

Easy-to-navlgate pro · • Jump-slart planning and gel new team members up to speed fast with
cess that is not over· knowledge assets and guidance
whelming for users • All ow users to create personal process views that are central to individual
needs
• Provide intuitive naVIgation wi th a browser- based interface

Demonstrated progress • Track metrics th roug h out the project life cycle
toward expected return • Report on variance measurements and adjust process to ach,eve desired results
on investment for CDD • Track project progress and quality through quantitative analysis
projects

AbIlity to assess and • Maintain a broad and deep understanding of an organization's capacity, skills
manage distributed re- inventory, total workload and resource de mand
sources efAc lcntly • Optimize ski ll usage with resource planning to align mission-cntical resources
with h,gh-priority projec3

Figure 7.14 Tools and methods for distributed development, IBM. 1 of 3


SOlI" I:BIA., copyngtlt (' internatiOnal ~5 MaChines Corpotillon, reprinted wltn pet'mlsslOn. nnp JI'WItWl softwatO iOOl C
\': eblpArx:lGC34'25CO<X:I pdf
150 CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT

I cmo nstrated proBreSs o Track metncs throughout the projecl life Lycle
tow."d expeLl<'d return o Report on vorian e measurements and adjust proc~s to achieve: dcsl~d ,eoul~
o n II, ,,'lInerll for ,I D
o Track project progres and quality through quantitative .oalysls
prOjects

Abrlity to assess and o Maintain a broad and deep understanding of an organiUltion's capaCity, skills
manage dr stributed rnventory, tOl.1 workload and resource demand
resources efAcrently o Optimize ski ll usage with resource plannrng to alrgn mission-critical resources
with high-priority projects
Scalable projec t o Centra lize sensitive schedu le, budget and resource data while allowing
management so lution secure, high -performance access anywhere in the world
o Implement native scheduling, resource loading and ·what-if" scenarios that avoid
performance issues by integrating with third·party scheduling products
Consistentl y executed • Capture and reuse successfu l GOD engagement models, work breakdown
processe structures and workAows to ensure execution against IT governance re-
quirements and best practices
• Enable reusable project templates and task guidance based on a proven
process, so teams never have to start planning from scratch

Accurately tracked • Accurately track labor expenses and budget for time and materials or fixed-
labor costs for in ·house bid resources
or external re ourers

Figure 7.15 Tools and methods for distributed development, IBM, 2 of 3


SOUrce; IBM, copynght ~ InternatIOnal BuSiness MaChines corporation, reprinted with permisSIon. htU>:t/WwW3.soltwure.it>m convlbmdVpub/softwaretrabOflall
weofgl"udeslGC34-2500-00 pdf

- -
REQUIREMENTS IBM RESPONSE
Quick and easy Imple- • Facilitate discussions, set up chat rooms and combine team calendars with
mentati on to start col- ready-to-use templates
laboratin g in days, not • Leverage out-of-the box functionality that users can customize themselv~
mo nths
• Centralize installation on one server

Consolidated work arca • Create a centralized location to post and share project documents that can
where team s can more be viewed and modified by other team members
effectively com muni · • Share team member project calendars
care and co ll aborate on
• Track feedback from other team members
project issues
• Enable the creation of forums and partiCipation in threaded discussions
• Allow team members to share files in real time via Web conferencing

Figure 7.16 Tools and meU,ods for distributed development, IBM, 3 of 3


sou('~ 10M. eopyngnt Intem800n81 Business MachInes coworatJon. repr1otl!(l with pmml$:Sloo. nttoJMww3.50ttwate Ibm.
webigWoeslGC3H5OO<lO pdf
THE TEAM SOFTWARE PROCESS 151

-
IBM RESPONSE
n demand omnlunl .
• Let users know which team members are available for collahoratlon through
carion optIons for di . IOregrated presence awareness
tributcd team mcmbe"
• PrOvide lOstant messaglOg fo r real . time, ~~on · to·person communication

• Leverage browser·based confcre nci ng to share presentations and meeting


materials
b.!,ty for all di para!e • Enable full-featured browser-based a nd mobile access to presence , instant
project membc~ to e· m saging and team spaces
curdy conneCt to the
team workplace
through the intranet,
Interner o r mob.!e
devi es
Figure 7.16 (Contmued )

7.4 THE TEAM SOFTWARE PROCESS

Te.am s avoid reinventing procedures thar arc common to everal sohwan: devci opment proJects- O rgan iza .
tions create procedures or gUi delines in adva nce for tea ms to apply . \'(fans Humphrey's Tm., Soj,","" Proem '"
CTSP) [3] does this in a detailed manner. The TSP proVIdes gllidance to gTOUpS o n each of the prole t
development phases aftcr requirements analysis. Humphrey has reponed encollraglng re lilt in estabhshlng
matunty goa ls and procedures for software teamwork. The objective of [he T P are sho wn In Figures 7. 17
and 7. 18. Whether or not a team uses the TSP, much can be learned from It. TSP share, ,everal charactenstlcs
with agile teams, sllch as the autonomy of teams . TSP is heaVIl y metric·oriented , and alt houg h ag .!e me th ods
are not, they do take seri ousl y the velocIty measure.
The TSP's emphaSIS on team inillative and bottom -up interacllo n encourages an In r<'ased degree of
profe sionalism among so ftware eng inee r For exa mpl e, H umphrey Slates that it is unprofcs<1 o nal fo r
enginee~ to prOVIde management with sc hedules that ca nno t be accomplished , cvt'n ,,,he n requested to
do so. He counsels negotiation In such a sitllatl o n The phdosophy here IS sllll1lar to that for agdc project'

• Build self·dlrec ted tea m ~


• 3-20 c ngln ce~
• establtsh 0'''' goa l\
• es tabltsh ow. process a nd plans
• track work
• how manager\ how 10 rn anagt: (came;
• <-oaeh
• motrvaLe
• sustain peak perforllla" e

figure 7,17 Objectives of the Team SOftware Process, 1 of 2


SotHt;B GfIlPh'Cl r8Qfodu'~ 'HIm r~ f,om COt I
152 CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT

• cierate MM Improveme nt
• make /\'IM 5 "normal"
• · Provlde Improvement 8U1de llnes to hi gh-maturity organizations"

• "Facilitate university teachin g of industrlal .grade teams"

Figure 7.18 Objectives of the Team Software Process, 2 of 2

Professlo nalt sm, Humphrey reminds us, involves an oblt ga tio n to Serve society responsib ly, In addition to
serving employers Also nOleworthy is the TSP's emphaSIS o n " oaching" by managemen t external to the team.
Managemcrrl I expected not simply to give orders and specify deadl ines, but to provide guidance, tools, and
ot her required resources In this respect, TSP is beller able to handle teams with varyi ng degre'!s of experience
and kills. T Pi orga ni zed around Iterations of the waterfall sequence; It requires that the team "launch" each
iteration at a mee ting where a number of predeAncd Issues are addressed. Humphrey provid(~ numerous
detailed scripts and checkl ists to support the TSP. Figure 7. 19 su mmarizes these points regarding TSP
The phases can be iterated severa l limes, requiring several launches. Launch is lies to be settled are
shown in Figure 7.20.
Humphrey recommends that the items listed in Figure 7.21 be produced by each phase launch. Much of
thi is covered by procedures and IEEE documents discu"ed in this book .

7 .4 .1 Introductory Team Software Process (TSPi)

Formal training for TSP is beyond the scope of a stude nt team working together during a softwa,e
engineering course . For exa mple, it requires t he already extensive Personal Software Process. The TSPi is
a sca led·dow n versio n of the TSP designed to At in an academic semester. The TSPi roles arc /tam ltadt!',
drutlopmt>llmaHagtr. pla""",g maHagtr, quality/proem ",."ag" , and support "'all.g". In the TSPi the "support manager
is responsib le for obtailling and 'upplying all the tools and environments, such as compiler., fo r ~xample.
Humphrey describes a spcciRc emester.long schedule for the TSPi , consisting of three it~rations ( h~
ca ll s them "cycles") as hown in Figure 7.22 .
The Idea of this schedule template is that data obtained from each cycle is used to estimate the metncs
for the next cycle. Cycle 1 is comparatively long because it includes the team's first progression through th~
stages. It is intended to be a "minimal function workin!: subset of the final product." Cycle 3 is long enough to

• Team initiative

• Bottom -up interaction

• Professionalism among software engineers


• Negotiate schedules
• Emphasis on "coaching" by management Provide guidance, tools . and other reqUired re ources
• PartiCipants required to be PSP trained
• Organized around iterations Each requires a "launc h"
• Numerous detailed scripts

Figure 7.19 TSP praC1ices


SOFTWARE PROJECT TOOLS AND TECHNIQUES 1S3

o Process to be u cd
o QuaillY goal
o 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 Fallback posHio ns
o What to do if plan no t approved
o fallback positio ns
o Define team ro les
o 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 iO SOftware EngJneenng)." Ac1C!rSOO W """ey. 2000, P 496 GraphICS
reprodUCed WIth ptlllll ssaon from 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
154 HAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT

1 1 1 1 1 1
Week -- -
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5

Milestones
Cycle 1 launch
• Cycle 2 launch
Delivery

<dele 3 launch
I
1. Stralegy
2. Plan
3. Requiremenls
Iteration 1 4. Design
5. Implemenlalien
6. Tesl
7. PeSlmenem

Iteration 2 1. Stralegy ....


,
I ,
Iteration 3 •
I
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

• • • onfigll ralion management

• • • Managing requirements

• • • Drawing deSi gn especially UML

• • • 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 155

BUi1dcosl ! Bwcosl Comments


multi-year costs nol accounted for
- : : : : thousands)

Supplies $ 0 $40 Putchase Ajax engine


••••••••••••••••••••••••••••••••••••• • •••••••• ••••••••••••••••• ••• •••••••••••• •••••• • ••• • • •••••••••••• • •••••••

FirSI-jlerson perspeclive $ 5 $ 0 Ajax has Ihis fealure


•••••••••••••• •• •••••• • ••••• ••• • ••••• ••••••••• ••••••••••••••••• . ............................................
"

3-D $10 $ 1 Cuslomlze Ajax applicalion


•••••••• • •••• ••• ••••• •••••••••••••••• • ••••••• • • ••• ••••••• • ••••• • ••••••••• ••• ••••••••••••• •••••••• • •••• ••••••••
Lighl refleclion $15 $10 Cuslomize Ajax applicallon

TOTALS $30 $51


""" •
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~
, S6 CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMEm

Iknefl! of Bencftt of
Weight Language 1 una....' 1
Factor (t - / 0) 1 10 10 = besl I to 10 = bHt
Internet -friendly ) 8 2
-
Familiarity to deve! - 3 9
ormcnt tea m
-8

Compilatio n speed s- 2 8
Runtime speed o n ,- 7 3
processo r p

Score -3 .. 8 + -8 .. 3 + -5 • 2+ -3 * 2 + -8 .. 9 + -5 * 8+
-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 157

Number of ....eks
before del/very Schedule
Quality Defect count

Number of
Cost Number of engineers
requirements Functionality 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


158 CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I. ORGANI ZATION, TOOLS, AND RISK MANAGEMENT

,
ProJocted cost
($)
Taraet: 100% ... ' ...... - Tarael: $70K

\ ...,\
Pro1ected , Projected
I > '-00%
(unct/onallty - - - ~S=8'itl;::'SIif.led5-+---~,..-- schedule
( % requirements (fatal weeks to
saUsfied) ,.,.. _.., comp/ele)
'.'.
\•
Taraet: 4 defectsIKloc ... .................... . Targel: 30 wl<s
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<lll s sh o rt o n two o f th e vanables
but pe rfo rms we ll fo r th e o the r two. Th is visualizati o n helps a project manager to alter prio rit ies and achieve
goa ls In an cve n manne r. Fo r cxampl e, the leader o f the project re presented in the figu re sho uld cut costs and
push fo r a n inc rease in func tio nal ity, even if !h is results in hig her defect rat es and lo nge r project duratio n .


Projected cost

Taraet100%
--- -----
,
Acblfl: •

90% .' ................... Target; $701<


,
•,
,
Projected' , ProJ«ted
(unctlonallty' - - - - schedule

• Tal!!8\:
Aaa/: --- ,,
1.5
, 30 wI<s
•,
--- AIifwI:
20 . .
qu.llty

Figure 7.30 Bulls·eye figure for project variables on a particular project


RISK MANAGEMENT 159

Organizational

I . The team may not have the reqUired Java skills to exccute the job on time because several of them
have no t used Java in a bus: ness environment.
2 . We ma y lose a team me mbe r.
Technical
3. An off-the-shelf database mana ge ment system may not be versatil e e nough to cover the types of
operations required of a vIdeo store.
4. We Intend to u e Web services, but no o ne in the team has used these before.

Figure 7.31 Example risks in video store a pplication

7.6 RISK MANAGEMENT

All projects invo lve a degree of risk. These arc issues that ca n potentially cause problems such as a delay of the
schedule o r increased project costs. Figure 7.3\ shows some risks from the video store example.
We try to confront risks as soo n as possible rather than waiting fo r them to confront us in the proces of
build ing the application . Th is is ca lled risk maun9"",,, I. and it consists of the activities in Figure 7 32 .
Perhaps the hardest part of risk manageme nt is iden ti Rcatio n , because it requires imagining parts of the
process that may not seem at first to harbor a ny risks. Once a risk is identified, it is important and vety useful
to express the risk with as much precision as possible . For examp le, "a team member may get sick" is too vague
a descriptio n. Much bette r would be "sick ti me will exceed the company norm by 50% due to an unu ual
number of youn g parents in the team ."
Figure 7 .33 illustrates a way to thinking about ri sks, It shows two obstacles to a project .
We ge nera l.ly dea l with risks wi th o ne of two di fferen t stra tegies. They arc cOllq.usl (such a building a
traffic ligh t at the roa d ) or nuoida"" (e.g ., routing the path around the h ouse). These two strategies arc
Illustrated in Figure 7 .34 .
Teams develop a plan to address eac h risk and assig n an individual who sees 10 it that the plan is carried
out. The c halle nge here is to develop a concrete plan and avoid ge neral statem e nts such as "we will alil ea m
Java: For exa mple , we ca n address the "inadequate Java ski lls" risk mentio ned in Figure 7.3 \ by conquest :
'Tom , Sue, a nd Jack wi ll pass level 2 Java cert inca tion by Dece mber 4 by attending a Super Education Serv.ces

I. Identify risks by imagini ng all worst -c ase sce narios: lasts for approxi matciy Am thtrd of project.
2. Analyze each risk to understand it potential impact on the project.
3. Typically too man y risks give n time . H e nce , prioritize .dentiAed risks lO e nable foc u on most enou .

4. In dealing with each risk, c hoos< to conquer or avoid it. Co nquering 0 risk mea n In vesti ga ting it and
takIng action so thac the eve nt docs not mate rialize Avo ldin\;\ mea ns c h angi ng plans so that the I sue
never occurs.

5 F,nally , develop a pla n to retire each ri k

Figure 7.32 The main risk management activities


160 CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I' ORGANIZATION. TOOLS, AND RISK MANAGEMENT

Risk 2: House blocks path

Risk t: Road blocks path



••





Project
start

Figure 7.33 Retirement by conquest or avoidance risk examples


SOurce CraPhlcs reproduced wrtn J)efmlsslon rrom Corel

Intermed iate Java cour ·e." Alterna ti vely, the risk can be retired by avo idance: "Use C ++ instead of Java"
(assuming that the team is skilled In C+ +). A reti rement strategy for the "Web services know ledge immature'
risk IS to set up a couple of sa mple Web services and write access code for key Video store functions that use
them . If the resu lts are satisfactory, we will have empl oyed risk reti rement by conquest.
Table 7. 1 illustrate o ne way to perrOm) risk prioritization . First , the risks the mselves shou ld be
deSCribed fully . The priority de pends o n fac to rs such as the likelih ood of the risk and the seriousness of its
impact on the project. A h,gh,prlorit y task has a low.pri ority ",,,.lur because people usually rerer to their
"highest priOrity" a priority number I The more expe nsive it is to deal with a risk. the lower its priority. In
particular, when managing a risk becomes a very large amou nt of work, we may be better off not working on it

2. Retirement by
avoidance

Risk 1

1. Retirement by
conquest

Figure 7.34 Retirement by conquest or avoidance


SOcxee GraohJC:S reorOCluced wltn pc:.j.lkslon from COf~
Table 7.1 A way to perform risk prioritization
~

Estimated
likelihood of Estimated Estimated cost priority number
occurring (L : l · l0 impact (1:1· 10 of managing (lowest number Target
with 1 low est with 1 lowest (M: l-l0 with 1 handled first) Retirement Responsible completlon
No. Title IIke-lihood) Impact) lowest cost) (11 - L) . (1, - n . M plan person date
1 Insufficient Java 8 9 9 3 . 2 . 9 = 54 See note 3 Jared 10/ 15
skills: See note 1

2 WebSeMces 3 7 2 8 , 4·2 = 64 See note 4 Jen 8/3


immature: See
note 2

• • •

'"-
V>

"
3:

i
m
3:
m
!i
......
...
162 CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I; ORGANIZATION. TOOLS, AND RISK MANAGEMENT

In ad an ~ at all, but simpl y dealing wllh the ,,'ue In volved when It aCluaJl y arlS", I or exa mple. If the o nly
wa to anticipate a mk "to Om li1J t an expen Ive Imulatlo n, thell we may simply have to acce pt the risk
Note I 11,c n<k I< that the team docs nOt ha ve enoullh <kdl,n java to handle th programming reqUired
by thi s proJe I wllllin the time reqUIred
Note 2. The rI k I that altho ug h Web ervlce: le:chno l08Y b a good ~ h oicc . technica ll y ~ peak inR . It "
ne,,, to the industry at the time of thi S prOJect. and it, Imm atunty ma y c rca le dlff,cult, c<
Note 3. jen, Oscar, and All should pas level two java cc rtdi atl o n hy ctober 15 by attend ing an Ajax
Edu atl o n ervlces Int<mlcd,atc java o ur<e.
No te 4. jcn will msta Jl three \X-' cb servl es typi al of DVD Inventory manage ment, and run 1,000 tYPical
transac ti o n against these, gathering timing data .
N o t every risk can be dealt wllh earlier than it natural occurren e. T o take an ex treme: example , suppose
that the team ha a week to add slg niA,ant functionality to an app lica tio n 11,e goa l would be. Add the
capability to how future investment growth graphl ca Jl y for a Anancla l appltcat lo n. There is probably Intle to
be ga med from performing nsk analySiS and reti reme:nt m thiS case. Since the time frame is so short, the team's
time may be belter spe nt si mp ly sta rtmg the deSign at once. Doing so takes a chance, but the time requ ired for
risk analysis may not leave enough time to do the job.

7.7 STUDENT TEAM GUIDANCE: ORGANIZING THE SOFTWARE PROJECT'S MANAGEMENT

This section describes how the student team o rganizes for the development task, prOVide a hypot het ical
account of interactions among students, and gUides students in producing a Software Project Management Plan.

7.7 .1 Team Guidance Student Team Organization

Student teams are usually organized as peers. T o make pecr teams effective. the team leader encourages
consensus but keeps the chedule firmly in mind, making clear and timely deCisions when requi red. In ruden!
teams, team leaders tend to mtervene too "ttle. Meeting drag 00 unreaso nabl y in the quest for consensus or
agreement , and the team leader is not experienced enough to make a resoluti o n. Being Arm Without alienating
team members is a valuable skill. A ke y to this IS en uring that team members' opi nions are respected-
whether adopted o r not.
Fi gure 7.35 lists the steps for orga nizing a team . particularly a student team .
One effective management arrangement for a team is to pair up developers by haVIng them work
together some-or even all-of the time. The lalter is called pair programmi"g . Another way is to deSignate
team members as leads for the project phases with a backup for cach oT ypi ca ll y, the lead and the backup work
together, o r the backup serves as a continual in pector. ready to take over the lead role If necessary The
project arrangement shown in Figure 7.36 is deSigned to make each perso n the backup fo r the actiVity on
which his or her primary activity is dependent.
Once a projec t leader has settled the procedural aspect< of team organization . it IS time to consider what
really counts with team members: how they feel about what they are doing. If a person belongs to a motivated
and well -organized team . he will probably enJoy his work and the team wtll probably produ e a good
product. People are motivated when they are respected and arc engaged in an activity that the feel ennch
them . Part of each member's Job is to create those conditions for himself and others The project leader
creates a well -organized project by settmg schedules and limits, with the team' as=ment. In partl ular.
when it comes to meetings the issues In Figure 7.37 can be u<cful
In the case of srudent team • """"" cOIII"bulloll i often a major pI' blem . some team members ma ' fed
that a member is not contributing enough. A team member who fecls this way ,hould di us< the I ue With
the project leader If there IS genera l agreement about this , thc prole I leader hould s!><,ak privately to the
STUDENT TEAM GUIDANCE: ORGANIZING THE SOFlWARE PROJECT'S MANAGEMENT 163

I. Sdect team leader.


Responsibi lllies:
o e n ure that all project aspects are a tive
o All all gaps

2. Designate leader roles and document responsibilities.


team leader: proposes and maintains . SPMP
configuration manageme nt leader: ... S MP
qualoty assurance leader: . .. SOAP. STP
requirement manage ment leader: ... SR.S
design leader: .. SDD
implementation leader: . " cod, bas,

3. Specify leaders' responsibilities .


o propose a straw-man artifact (e .g., SRS, design)
o seek team enhancement and acceptance
o ensure that deSignated artifact is maintained and o bserved
o maintain corresponding metrics if applicable

4. Designate a backup for each Icadcr

Figure 7.35 One way to organize a team

individual. If no significant change is observed in that person's behavior after about a week, the proJect leader
should confirm th ~ team's concern and th en di scuss th e issue with the instructor. Instruc tors will either
remove the individual from the team or discuss wa ys to app o rti on credit accordingl y.

7.7.2 Team Guidance Team Meetings

One activity regularly requircd of project managers is to hold meetings. Figure 7 38 lists som e good mee tin g
practices from which all team members can benefit.
The ite m s marked with a si ng le asrensk sho uld be perfo rmed before the meetIn g . Since gro ups are
not particularly good at c reatin g artifacts from sc ratch (especially designs ). it is far better for someo ne
to bring to the meetin g a tentative ("straw · man") ve rsio n of the artifact to form the ba sis fo r di scussi on .
For example , the design leader brings a t<ntative desi g n . or the team leader brings a :cntative work
breakdown . The version shoul d not be overly speCific, becau e th e re must be plenty of roo m for input
by the members.

Team leader
Configuration management leader
Ouality assurance leader
backs Requirements management leader
up ...
Design leader
ImplementaJlon leader

Figure 7.36 A wwy to back up leaders within a learn


162 CHAPTER 7 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT I; ORGANIZATION, TOOLS, AND RISK MANAGEMENT

In ad an e at all , but '1"'1 Iy deallnll wIth the IS~ue involv d when It a tuall y aro \e, I' or example, 01 the only
wa to antIcipate a ri>k i, to co n,lO~1 tan expemive ,imu lation , lhen we ma y ~ Impl y ha ve to aLeepl the r"k.
Note I The rosk 0< that the leam duc, nOt have enough ,k oll, n java 10 handle the programmIng requored
by tillS proJe t wIthin the lime requIred
N o te 2. TI,e ri k I that a lthoullh Web erv lce lechno lollY "a good ChOILl', tec hnIcally spcak,ng, It IS
new to the Industry at the tIme of thIS prolect , and ItS Immaturoty ma y reatc dolf'c ult,e,
N o te 3. jen, Os ar, an d Alf ho uld pa,s level twO java c<rtlfi atlon hy O c tober 15 by .nc ndong an Ajax
EducatI o n Services Inte rmed,ale java course
Note 4. jcn will install three Web services typical of DVD oowcnlory management , and run 1,000 tYPIcal
transactions agaInst these . gathero ng toonlng data .
Not every nsk ca n be dealt with ea rl ier than ItS natural occurrence To take an extreme example, suppose
thai the leam ha a week to add sIg ni fica nt functionality to an applicatIon . The goal would be. Add the
capability to sh ow future ooweStm e nt grow th graphIcally for a fi na nc Ial app l, ca ti on . There IS probably lIttle to
be gaoned from performong risk a nal ysis and r!:lorcment in this cascoSince the lOme frame is 0 short, the team's
time may be better spe nt SImply tarting the desig n at once. DOIng so lakes a c hance, but the tome required for
risk anal YS IS ma y no t leave enough time to do the job.

7.7 STUDENT TEAM GUIDANCE: ORGANIZING THE SOFTWARE PROJECT'S MANAGEMENT

This section describes how the student team o rganizes for the development task, prOVIdes a hypothetic<ll
account of interactions among students, and guides students in producing a Software Project Management Plan .

7.7.1 Team Guidance StudentTeam Organization

Student teams are u uall y o rga nized as peers. T o make peer teams effective, the team leader encourages
consensus but keeps the sc hedule Rrmly in mind, making clear and timciy deciSIons when required . In tudent
teams, team leaders tend to intervene too little . Meetings drag o n unreaso nably in the quest fo r con ensus or
agreement, and the team leader i not expe rienced e noug h to make a resolutio n. BeIng Rrm without al,enating
team me mbers is a valuable skill. A key to thi s is e nsurong that team members' opi ni o n ane respected-
whether adopted or not.
Figure 7.35 lists the steps for o rga niZ Ing a team , partIcularly a student team .
One effective manageme nt arrangement for a tea011 IS to paor up developers by haVI ng them work
together some or even all of the time. The latter is ailed pnir progmml.i"9 . Anot her way is to designate
team me mbers as leads for the projec t phases with a backup for each . TypIcally, the lead and the ba kup work
togethe r, o r the backup se rves as a continual inspector, ready to take over the lead role If necessary. The
project arrangement shown in Figure 7.36 is desig ned to make each person the backup for the actIvity on
which hi s o r her primary activity is de pe ndent.
Once a project leader has settled the procedural aspects of team orga nization , it is time 10 con Ider what
really counts with team members, how they feci about what they arc doing If a person belong to a motivated
and well·organized team , he will probably enjoy his work and the team will probably produce a good
product. People arc motIvated when they arc respected and arc e ngaged In an activit that the ' feel enriches
them. Part of each member's Job is to create those conditions fo r hIm elf and others. The proJe t lead«
crcates a well ·orga nized project by sellIng schedules and limits, with thc Icam's agreement In partIcular,
when it o ones to mee tings the issues in Figure 737 ca n be usefu l
In the case of student leams, ""tv'" (o"'/lb""o" i, often . majOr problem · som~ team member> m3\' fc-el
that a member IS not contributing enough . A team member who feds th" wav ,hould dISCU<, the I su~ WIth
the project leader If there is ge ne ral agreement about tl"', the proje t leader ,hould spea ~ provatcl ' to the
STUDENT TEAM GUIDANCE: ORGANIZING THE SOFlWARE PROJEcrS MANAGEMENT '63

I. Sd«t [cam leader.


Rcspons,b,l i tics:
o en . ure that all prOject a pects arc active
o fill all gaps

2. Designate leade r roles and document responsi bilities.


team leader. proposrs and 'MI"la;., .. . SPMP
configur<ltion management leader: . .. S MP
quality assur<lnce leader: . . SQAP, STP
requirements manage me nt leade r: . .. SRS
design leader: . . SOD
implementation leader: .. cod, base
3. Spedfy leaders' responsibilities .
o pro pose a str<l w· rn an artifact {e .g., S RS, deSig n}
o seck team e nhan eme nt and acceptance
o ensure that designated artifact is mai ntai ned and ob erved
o maiorain correspond ing me trics if app licable

4. Desi gnate a backup fo r each leader

Figure 7.35 One way to organize a team

individual. If no significant change is o bserved in th at person's be hav,o r aft r about a week , the prOject leader
should confiml the team's co ncern a nd the n d,scuss the issue with the Instructo r Instructors will either
remove the Ind ivi dual fro m the team o r di cus ways to apportion cred it accordingl y

7.7.2 Team Guidance Team Meetings

One activity re gularl y req uired of project mana gers is to hold meetings. Figure 7.38 list some good meeting
prac tices fro m which all tea m members ca n benefit.
The items marke d with a si ng le asteri sk sh ould be performed before the meeting. Ince groups are
not partic ul a rl y good at creating artifacts from sc ratch (e peCiafly designs ), it is far better for omeone
to bring to the meeting a tentative {"st raw . man"} versio n of the artifact to form th e basis for d iSCUSS io n.
For exa mple , th e d e ign leader brings a tentallve design , o r the team leader brin gs a tentative work
breakdown. The ve r ion s h ou ld no t be overly speCific , because there must be plenty of room for input
b y the me mbers.

Team leader
Configuration management leader
Quality assurance teader
backs
Requirements management leader
up .. ,
Design leader
ImplemenlaUon leader

Figure 7.36 A way to back up leaders within a team


,~ CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT I: ORGANIZATION, TOOLS, AND RISK MANAGEMENT

• Develop an . genda In ~dva n ce of mec lIn g, with everyo n 's 'I!rccmenl.

• SCt lime limits (or meeting a a whole and for each a!le nda item . Allow exIra lc n or Aft.en mInutes for
unanll clpated Items.

• Designate SO meone to tak e minutes, ilt Icas t for a l ion i tems.

• At mcetll' g, begin by brieOy reviewing the age nda a nd tIme limits.

• De,ill na le o meonc 10 walch lime and warn of time lim ils.

• Insist o n o ne person speaking at a time . Listen to people, even if their idea seem ourrageous. (Probably
aren't )

• Move unproductive d i cu sions offline.

Figure 7.37 Planning and conducting meetings

Man meeting participants, but especially students, compla in that meetings last too long WIthout
acco mphshing e nough. \'(rhe n the approximate time fo r discussio ns is ag reed to in advance, however,
members tend to focus o n th e issues te be resolved, and meetings ca n be quite effective. Decid ing when to
all ow (urt he r discussion and whe n to break il o ff is a duly of Ihe learn leader. The keys to doing this are
whether the discu sion is productive, and whether lhe discussion of the present topic is preventing the
di scussio n of more impo rta nr o nes, g iven the time remaining. II is al so the leader's task to ensure that the
discu sion remallls focused and that a conclusion is reac hed. At times, the leader must step in and make a
decisio n, because co nsc n us is nOI always possible. The member recordin g ac tion items also records decisions
take n. Th,s should generall y be do ne 111 a crisp form-minutes are meant primarily to remind everyone of the
decisio ns made.

I. "DistrIbute Start time, e nd time, and agenda with approxi mate times.
o li st impo rtant items fi rst .

2. ·Ensure that "straw ·man" Ite ms arc pre pared .

3. Slart o n time
4 . H ave somco ne record action items.t

5. Have someo ne track time and prompt membe rs.

6. eet agreement o n the age nda and timing .

7. Watc h timin g throughout, and end on time.


o Allow exceptio ns for important d iscussio n.
o StOP excessive discussio n; take ofAine.

8. Keep d iscussio n o n the subject.


9. ··E ·mail ac tion items and decision summary.

·in advance o f mCelln!! lactions membe" must perform ··aflcr meetlO l!

Figure 7.38 Team guidance team meetings


SUMMARY 165

I . (;(,t agreement on agenda and time allo atlon


2. (;(,t volunteers to:

... record dcci ions laken and actIon items


. .. watch time and prompt members
3. Repon progres on project schedule _ •
10 tnUl

4. Discus strawman artifact( ) - x mill

5. Discuss risk retirement - fO min

6 . , 7., ... < more agenda items> (I nclude metrics and ['rocess improvement])
n Review acrion items 5 mUl

F'lgUre 7.39 Specifying agendas

One good management practIce is to create and follow agendas for meetings. Some items, such as
concise status reviews, arc almost always appropriate. Risk retirement (cove red in Section 10.4 ) sho uld be a
mandatory agenda item at most meetings during the first third of the project. Metrics and process
improvement are sometimes appropriate topics. These are discussed after a phase has been completed,
not necessarily at every meeting. An examp le of a generic age nda is shown in Figure 7.39.

7,8 SUMMARY

Software project management is the process of planning, o rganizing , and mo nitonng the deve lopme nt of a
software project from inception to completion . A project is typically headed by a project manager, who IS
responsible for the daily project activities.
Companies can be organized in severa l different ways, each havin g an effect o n how a project team is
organized and run . In a projtct-arir>lttd organization , people arc organized around the projects of the compan y.
Every employee is assigned to a proJect, which is their primary focus. In aJ"ncilon-aritlltrd organizati o n, people
~long to a functional group such a.s marketing or sohwar-e development. Each functional gro up has its own
projects centered around their area of responsibility. Managers assume the ro le of project managers A mnlnx
organization is a cross between project· a nd function ·orien ted organizations. Employees belong to a
functional group (e .g ., marketing , engineering) and are loaned to projects based o n their cxpertise They
directly repon to their functional manager, who is responsible for directl y supervisi ng the m Thcy also
indirectly repon to the project manager, who IS respo nsible for the daily actiVIties of the project.
The size of a project team has a direct effect on the success of a project. Team that arc large ca n d ivide
tht work into manageable pans, However, large teams have the dIsadvantage of requiring communication
that IS time -consuming and error· prone_ Expenence shows that the optimal number of people WIth whom a
person needs to interact with o n a regular basis hould norma ll y be between three and eight.
Not all prOject tcams arc colloca ted W,th the advent of lIs'"g rem ote developers , project teams ma y be
split across conti nents Th, s is known as off hOrlng . There arc many advantages to u ing remote tcams, IIc h
as COSt savi ngs and the benefh of qu.),ty work . H owever, the re a rc di sadvanta ges to be over o me, slic h as time
zone differences, cu ltural differences, and potential communIcatio n ddn lIltles. Se tting lip reglliar fa <' · W·
lace m«tmgs and having strong o n 'Slte manageme nt arc key elements to mak,n g offshOring work .
Watts Humphrey's Ttam oJllQart Procm (TSP ) deAnes a <c t 01detail ed procedure< for buildln~ prOject
SM

tCams, establi5hing team /loal" and di stnbutlng ream ro les It c mphasiz.', team mitiatl ve and encourages an
166 CHAPTER 7 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT!. ORGANIZATION, TOOLS, AND RISK MANAGEMENT

in n:" , ed dcl!'"cc of rrofe",onall<11l among 'oftW"I'C enHineers . A.. an c~am pl , Humphrey stale. that It IS
lInprofes 'ional forengin ccrs 10 provi d~ managemenl wil h ,e hedul e.that ca nnot be accompl,shed , even when
,..,que,ted to do so.
ProJe t m""ager and team< carry Out many lask< a, part of Ihelr job, 'ncludlng project scheduling,
onhguration management , reqUirement< man.gement, drawIIlH de"gns, building code, and testing As mu,h
as po <oblc, the utilize auwlll.ted 1001, to .uppon their work n'e e tools arc someti mes ca lled computer·
aided software e nglnecnng ( A E) 1001s.
\'(then plannin g and developing an application, existing .oftware may be avadable that can form th~
ba IS for the ne\~ applica tion . In order to determine whether It makes se n e to budd from scratch or lev~rage
e istlng oftwa re, project teams make a rationa l de I<ion by compannl! the costs of ea.c h option .
Another decisio n to make I the usc of programming language. A decisIOn · making table helps to
dctennine the pros and cons of differenl language choices
Projectl11.nagers have severa l vanables at their disposal that are manipulated as they manage a project ,
0" , ,c/"d,.l" qualilY. andJ'lllcl,oual,ly . C hangi ng one va riable has a direct effcct on the others For e~ample , .
project manager may wanl to speed up a prOject by pull ing in th" compl etion date ( chedule). In that case,
one or morc of the o ther variables must be adjusted-you cannot pull in a schedule unless you change
somethlllg else. The manager must reduceJ,,"clio"al,ly , add resources (co I), or reduce qualify. Bulls·eye 6gur~
can be usefu l in visuali zi ng these va riables in a project and as an aid in seeing how each va flable affects the
others.
All projects co ntain some amount of ri,k, which arc issues that ca n potentially cause problems such as.
delay of the chedule or increased project costs. Risks are o f two basic ty pes. Orga"izalional risks are primarily
caused by peo ple's behaVior, such as resigning fro m the company. T«h",ral o nes are caused primarily by errors
III hardware or software. uch as a defect in a third ·paTry app lication. Early in a project risks are identified and

mitigation strategies created . Each risk is actively man aged througho ut the project.

7.9 EXERCISES

I. a. De cribe in your own wo rds the st.ructure of a project.based organization , and explain how it
promote the successfu l delivery of software.
b. Name twO lo ng· term disadvantages of a project-based o rga nization.
2. a. Describe in you r own words the structure of a function·based o rganization , and explain how
it promotes the successhtl ddivery of softwa re.
b. Name two lo ng. te rm disadvantages of a hillctlo n·based orga ni zation.
3. a. Describe in yo", own words the structu re of a matrix organization , and explain how it
promotes the successfu l delivery of software
b. Name two lo ng·tem, disadvantages of a matrix organization .
4. Write a paragraph explaining why adding people to a project docs not ne essaril Imp ro~

It
schedule and may worsen it .
5. Co nsider a project team you have been a m ~ mber of, either as part of a student leam Or in industry
De'cribe the o rga nization of Ihe tcam, and des ribe in sufAc ient detail two a peets th~t worked
well and two that did no t work well

6. Consider a softwa re prOjec t under devel op m ~ nt , with half of the e n 8 lnc~rs In one \lOle zone and
the o th er half in another time zone twelve hou rs away H ow would 011 recomm .. nd the pro)CCt
BIBUOGRAPHY 167

t~am be organized) Describe two challeng~ that need to be overcome due to the time.zone
difference.

7. a. Explain how a bulls·eye diagram can help visualize the progress of a software project.
b. Suppose you are managing a project that has the following goals,
·Cost: lOOK
· Schedule, 12 months
· Quality , 12 defeetslKloc
. Fun·e tionality, 90% requirements implemented

Draw a bull -· eye diagram that shows on ly one of these goals being met or exceeded.
8. Why plan for risk identiAcation and retirem ent when developing a project plan) In a paragraph or
two, answer thi s in your own words.

9. Describe a kind of project under which risk identiAeation and retircment would pro bably "01 pay
off. Explain.

10. Suppose that your team IS tasked to implement a system that provides Web· based books. l1,e
application is intended to execute on desktops, be downioadable, and be automallcally upgraded
over time via the Internet. You arc to assume the following ·
i. The team includes employees who are based at a new offshore Site.
ii . The application is to be rcady in a month .
iii . Preliminary plans call for a Java implementation on a PC model that is due 10 amve in two
weeks. No one in the team is ,.ell versed in Java . They all know C. + we ll.
You arc concerned about the risks associated with items (i) and (II i) above. Explain the kinds of
risks these are , your speCific responses, and the kind of soluti on YOll arc propo ing.
II. You have been tasked to build a ystem for managi ng online DVD rentals. Descri be four plausib le
risks and indicate how you would retire them. Be as concrete as possi ble in describi ng the ri sks

BIBUOGRAPHY
I Heldman, Kim. "PMP P'O)'C1 !vt4M#Cfflml Pro/mlo",,' Exam Sillily CIl/dr," SybexlWll t'y Publ lshlO~ Inc .. 2007 p. 17.
2 8rooh. Frederick P., '7bt My/b,eDI A-tan·M01'Irh Essays on SojlWilte Ett9,"cmn9. Altnll'crsary EJ,hon Addl;;on.\X!c<;ley . 1995
3 Humphrey , Walts S .. "1,.,,011111, 110" 10 ,bt Tcom Soilll'llft Proem (1lH Sfl Smd '" ojllN " E"9t"(m"'9'~" Addl ..on · \'(I~lcy, 1000, p 496
.. Iht' MOlht'r of All So hwilrc Pro,ec ls,· BIA.5i"lH \Vuk, Fc:bnlJry 22 . 1999
principles of Software project
Management II: Estimation,
Scheduling, and Planning

....nnlng • How do you estimate the cost of a


sohware Job?

• What are good ways to go about creating


a project schedule?

The Software • What does a Sohware Project


Development Management Plan look fike?
LIfe Cycle
• How are prOjects planned in practice?

• What are good ways for student teams to


plan their proJects?

Figure 8.1 The context and learning goals for this chapter

This chapter explaIns the methods that prOject managers use to e timate the ost. of a prOject and way
to <chcdulc If It also explains how to wnre a project plan.
COST ESTIMATION 169

1.1 COST ESTIMATION

The proc:<:sS of esrimating project co (i.e., for Axed ca pabilitle , quality level , and schedule) often starts at
fS
the inception of a projcct and continues even after coding has begun . There are severa l speciAc techniques
used to estimare cost that are described in the following sections. Before doing so, however, let's examine
how plecise we can expect such estimates to be.

8.1.1 Estimate Precision

When a project is ini riated , the team ca n typicall y have o nl y a vague idea o f its cost. TI,e more we learn about
the requirements for the product and the more desig n we perforn1 , the more precise we ca n be about its cost.
This is illustrated in Figure 8.2. Since complete precision is a practical Impossibility in most cases, a range is a
good way to express projected cost. There is always a need to estimate a 'ball park range" from a summary
requiremenfs statement , hence the cost estimation following conceptualization shown in Figure 8.2.
Our assumption here is that the goa l consists of auaining a set of capabi lilles rather than starti ng With a
fixed amount and asking what capabilities ca n be implemented for that amo unt (a related but different
process).
The fourfold <sri mation error shown in Figure 8.2 is from a study reported by Boehm [ 11. For an
application that will eventuall y cost $ 100,000, for example, estimates made after the application's concept has
been developed can be as low as $25,000 and as high as $400,0001We use various techniques to sharpen our
esti mate of a project's cost as earl y as possible , which amounts to reducing the height of the vertical lines In
Figure 8.2. O nly at the latter e nd of implementation can we have complete confidence in our estimates. (The
estimates are far less useful at that time, h oweve r, si nce most of the fu nds will a lready ha ve been spen!!)
It puzzles some people that we ca n eve n begin to think about the costs of a project without detailed
requirement.s , but this is a common practice in o the r Acids. For exampl e, one can gain a ro ugh estimate of the
cost of building a h ouse without any desig n or detailed requirements. One can use rules of thumb such as

$4

Rough range of cost estimates after


_ - - - <'(lOceptualization phase. Assumes
evenlual, actual cost of $1

Conceptual-
Ization $1 $3
phase $.25
_ _ Rough range 01 cost estimates
a ller requirements analysis
Requirements $1
$2
analysis
$1
I Design I
I Implementation

I lntegrationITeat I•
Fleure • .2 Range of error in estlmatlng costs narrows as the project progresses
170 CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING

"" u,e, In th IS area O,t about $ 100 per "ll'are foo t to budd: dnd so J I ,C)OO. ,(]uare. foot house w.II c.ost about
$ 100,000
A good way to appro. " proje t cost estima ti o n at the very early sta~e' of a project IS to develop
c,t ima te in severa l independe nt way, a nd the n combin e th e re<ults. One an eve n weigh the estimates
obtained a cording to one's level of co nfide nce in each of them
It takes expericn e to properly u e cost estllna tio n too ls, and the first time one uses them the re,ults are
often unrel iable. \'(Iid, time, fcedba k. and ca libra ti on , however, one lea rns to usc the m with increasing
precision The rest of thi S sec tion desc ribes the te hnl ques used to « timate projects in summary form . The
c hapte r then describes them "' detail.

8.1.2 Estimation Methods

Cost esti mation methods fo r agile projec ts, described in ectio n 8. 1.6, focu o n esti mating rhe upcoming
itera tio n ("sprin t" in scnlm te rn,s), based o n its requ ired user story o r stories, as well as experience from past
itera tio ns. These arc small ·sca le estimates but it is part and parcel of the agil e philosophy that large projects
arc composed of sma ll deliveries. Now let's turn 10 estimatio n of projects in the la rge that are not necessarily
agi le in whole or in part. Whether o r not o ne actually uses the methods described, they do contain many
hard ·won ideas that ca n be con figured for various situations, including variations in ag de estimation .
Figure 8.3 sho ws a typical road map for the earl y estimatio n of project co t a nd duratio n. The next
section shows an example of the usc of lines of code and past projects. The function point methodo logy and
COCOMO (Construc tive Cost Model) are explained below.

8.1.3 Estimating Lines of Code without Function Points

This section discusses ways to estimate lines o f code at a very earl y stage, well before any design has been
performed. O nce desig n work is performed , the me thods are based o n the parts of the design and become far
more precise, as ind icated in Figu re 8.2.
Several estimation methods , no tabl y the COCOMO and COCOMO II model , de pe nd o n the number
of lines of code. "COCO MO " stands for Boeh m's "Constnlc tive Cost Mo del" [ 1]. At the very earl y stages of a
project . COCOMO may not sou nd very useful because coding is a long way off when o ne is in the project
planning stage . By compari ng the product with other products, however, esti mating hnes of code may well be
feasible . For example, we could estimate that our current sate li ite co ntTOI job is comparable to our last satellite
job, which requi red 3 millio n hnes o f FORTRAN . H owever, our currenr job has the add itio nal requirement of
being able to mo nito r hurricanes. It may be possi ble to roughly e timate the ize of th is additional piece based
on other hurrica ne trackers (700,000 lines of FORTRAN , for example). When impicmentation languages
change, mdustry ·standard language conversio n factors arc used.

I. Usc comparisons with past Jobs to e timate cost and duration d irectly or to estimate line of code
and / or
Use function point metho d to estimate lines of code.
i. Compute unadjusted function points.
ii. Apply adjustment process.

2. Use lines of code estimates to compute labor and duratio n usmS (II) fo nmula .
Figure •. 3 A roadmap for estimating the cost of a software project
COST ESTIMATION 171

Orglniutions wonting above Cap;lbillty Maturity Models level I must be able to record the person -
hours Ind duntion of the pans of jobs. In the ab ence 01 such data, we would have to compare our Encounter
"dec Illme, for "xample, with other game . It is difficult, impossible even, to obtain data directly from
comp;lnles other than one's own, although trade publications and general industry studIes sometimes provide
pI~1 data. For example, we may know from industry announcements that "BugEye Inc." has worked on its
rw: iI same for two years, The announcement may even mention a number of programmers. Such data is
suspect, however, sin e companies regard their development knowledge as a corporate asset, and commonly
or underrepon numbers as the case may be.
In the absence of historical data , it may be necessary to compare the project with related projects,
(simulations, lor example, in the ca e of our video game). Let's say that we have very little experience
programming gam~, and some experience programming simulations and Java. Our lines-aI-code estimation
may have to be something like the follOWing :

lance wrote a nongraphical simularoon of a simple queue in C. + , which required about 4-8 pages
of code_ At about 30-50 non -comment lines pcr page, this totals 120 400 lines. We will assume
that Java requires the same number of lines. The first commercial release of Encounter has 4-15
such queu~ and 30-90 additional components of comparable size to make It interesting, so that
yields between [( 120 lines) x ( 34 components)] minimum and [(400 lines) x ( 105 components)]
maximum as our range, or approximately 5,000 to 42 ,000 lines of code. The use of graphics
multiplies the effon by 1.5 to 4, depending on the degree of sophistication , so this gives us a range
01 1.5 x 5, 000 to 4 x 42 , 000 = 7 .5 to 170 K-lines (thousands of lines) of code. (NoI" The case
study in this book encompasses a prototype. which is far less ambitious than Ihe version o n which
this estimate is based.)

By documenting such data o n a spreadsheet, we establish a baseline, and we ca n then sharpen our
estimates as the project goes forward . Note that the range 7 .5 to 170 K-lines is consistent With Figure 8.2, in
which a 16-fold range in es timate is expected at the conceptualization stage. The preceding calculation is a
bottom -up approximation , sillce it estimates the cost of the whole from the cost of the pans.
An example of a top -down approximation follows , lIsi ng indu try data (or, preferabl y, historica l data
from the organization performing the work). Suppose we know that a very good video game required the
servIces 01 5-20 expert programmers for 1- 2 years. Since we can invest only 1/ 10 of the amount that was
invested on that ga me , we WIll assu me that ours will ha ve about 1/ 10 of its ca rability. A suming 5-25 lines of
(fully testedl) Java code per day, this yields
( 1/ 10 capability of th,,(amous game) x (5 - 25 lines per day ) x (5 - 20 programmers) X ( I - 2 years)
X( 48 - 50 weeks pcr year) x ( 35 - 60 hOllrs per week )
~ 4_2 - 300 K - lines of code

This range is different from the bottom -up «timate obta illed previously , but it helps to grollnd our ideas
about the job'~ magnitude, Since the method" ed this lime is quite different .
Free estimation tools, 'u h a, those at www.con<lrux com , arc also avai lable on the Web.

8_1,4 Function Points

SUrtlllg In 1 ~79 WIth All recht (2 ), th e mo re (undame nt,,1 nOli on OfJ""Cllo" pO;III. wa> developed to assess the
size of a prOject Without ha Ving to kno w II, de<i~n and WlthOLII havln B to mah any a pnori a"u mltio ns .boul
code SIU . The fun c lIon pOint lechnlque " a mean s of ca lthralinll Ihe capab;),tles 01 an appli ation in •
unIform manner, a, a \In!!l. numb r. Th" nllmb r can Ih,-n he ",cd to e tlmare Iln e~ 01 code, o<t, and
'72 CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II; ESTIMATION, SCHEDUUNG, AND PlANNING

durat.on by cOl1l parison with th e fun t.on pOint values 0 1 ot her proJects . Functton POtllts arc a\tra<.t.ve .n
oncept , s",ec they try to /let to the hcan 0 1 a future produc l" ca pability H owever, It take. a grcat deal of
rra ti e to appl y them in an accura te and o", .Stcnt manner

8.1.4.1 Calculating Function Points

Funerion pOint calculat. o n compri ses th ~ following teps '

Function Point Step 1


Ide nttfy th e luncltons (e .g ., "retrieve ," "dISplay") th at the app lica t.o n must have. The Inte rn a ti o nal Function
Point U ers Croup (lFP U C ; ee [3)) has published c riteria as to what constitutes a "fu nct .on" of an applicat.on
in th is e n e . TI, ey consider user-le vel functiona lity, rather than programming -level functions as in C
Typically , a function is the equivalent of processing a scr ee n o r form on the mo nito r. For o ur role-playing
vi deo ga me prototype , for example, we ca n .dentify the followi ng fun ctions.

I e t up the c harac ter representing the playe r.

2 . Encounter a rorelgn character.

Function Point Step 2


For each such function , compute its funct io n point co ntribution from the sources shown in Figure 8.4
The followi ng summarizes the sensc o f each contributing factor. The g uidelines have to be carefully
fo ll owed , otherwise it is hard to o btain consistent estimates .

• Exlmlal j"puls, O nl y inputs th at affect the function in a differe nt way fro m each othe r are counted as
sepa rate . Thus, a funct.on of an application th at subtrac ts two numbers would have EI = I , no t EI = 2. On
the o ther hand , if the character A ca n be input to req uest an addition and S for subtraction, these would
contribu te 2 to EI.

• Exl,,,,"1 ou lpuls, Only o utputs that account to r true eparate algo rithm .c o r no ntrivial funct io na lities should
be counted . For exampl e , a process that o utputs a charac ter in several font would be counted as I ; ellor

Internal
External Log;",,' Fifes
Function
Inquiries
~
• (ILF)'
(EIN) •

~ LagIcII
cf External
External OUlpuls
Inpuls (EO)

, Internal logical
File grouping of user
data into files

Figure 8.4 Function point computation for a single function


SOtJrC.t' IluemaUof\ll Ful'lCtlol'l PoInt Usen Group. nUp'JMww.lfpug 0fJ
COST ESTIMATION 173

PARAMETER imple Complex

Ext. inputs El • • • J or • 4 or • • • 6 : I I
Ext. outputs EO )( • •
• or • • 5 or • • • 7 :
I I
Ext. inquiries ElN )( • • • J or • • 4 or • • 6 : I I
-
Int. logical files lLF )( • • • 7 or • • • 10 or • 15 : I I
Ext. logical Ales ELF ) ( · .. 5 or " 7 or .. 10 = _
I I
Count Total I I
Figure 8.5 Function point computations (IFPUG)

messages are not counted . Chart representatio ns of data are counted as 2 ( I fo r the data and I for the
formatting ). and data sent to separate nontrivial destinati o ns (e.g ., printer) (3).

• Ext""al inquiry: Each independent inquiry is counted as I.


• Inttmal logical files : This counts each unique logica l group of user data crea ted by or mainta ined by the
application . Combi nati o ns of suc h logica l g roupings arc not counted; each functional area of the
application dealing with a unique logical grouping increases the count by o ne.

• Extmsallogical files: This counts each unique gro uping of data o n fi les external to the app hca lio n.

Function Point Step 3


As shown in Figure 8.5, each o f these parameter values IS the n fac to red by a numbe r, depend ing o n the degree
of complexity of the parameter in the applica ti o n . IFPUG [3) has publi sh ed derailed description of the
mean ing of · simple" and "complex" in this context.
Applying this process to the two selec ted functions of the Encounter video game me nti o ned above, we
obtain the s preadsheet tables shown in Figures 8.6 and 8.7 . These fig ure arc hi ghl y pre liminary , but the y do
beglO to provide estimate parameters for the job . The lo tal unadj usted func tio n point e limat e for th ese twO
Encounter fun c tio ns is 25 + 16 = 41 .

Function Point Step 4


Next , one computes weights for the fOllrteen ge nera l hara tcristlcs of th e project. ea h bct"'een 0 and
This is shown for the twO selected Encounter funclions in Figures 8.8 and 8 9 . \Vlc have actually u cd a range
for tach o( these to reAe t our cu rre nt uncertainty abou t the ap pl ica tio n. O ncc again , It takes on iste nt
expenence 10 assc~s the appropria le values for th e e variab le . For example, fa to r 6 a<k< (or th e dcgre~ 01
CCrta1l1ty lhal on line data entry IS reqUired . We are crta ln Ih at lhe u<cr will need 10 inpul c hara lCfl<tIC ( r
(he game c haracters, a nd ~o the va lue chose n IS the hi~hc t, nve
The total Genera l harac te n SlK, va lue ( I throul!h 14 ) Is betwee n 24 alld 41.
174 CHAPTER & PRINCIPLES OF SOFTWARE PROIECT MANAGEMENT II : ESTIMATION, SCHEDUUNG, AND PLANNING

Imp/" MedlulII Co mp/eK S"b- Total

olm' Factor COInI' Foclor (ormt Faclor lolal,

Ext. Inputs I 3 I 1 6 13

comm.,nts: Nmn, Ready/ move Qualities

Ext. outputs o 4 o 5 o 7 o
Ext. inquirks o 3 o o 6 o 25

Int . logical Ales I 7 o 10 o 15 7

comments: Data about the user's c haracter

Ext. inl.,rface Rles I 5 o 7 o 10 5

comments : Data about the user's character

Figure 8.6 Unadjusted function point computation for first Encounter functions: "Set up player character."

Simp/It Medium Complex S"b- Total

(D util factor CO lmt Factor counl Factor lolal,

Ext. inputs o 3 o . o 6 o

Ext. outputs 1 . o 5 o 7 ,
co," mtHts; R,porf Oil ",,,/I,
Ext. inquiri.,s o 3 o o 6 o 16

Inl. logical Ales f 7 o 10 o 15 7

commel1ts: Data about flu user's charnelcr

Ext. inr.,rface RI"$ f s o 7 o 10 5

- COIII""" I, 011 aba., /'" .,"', cbaracttr

Figure 8.7 Unadjusted function point computation for Orst Encounter functions: " Encounter foreign character."
COST EST1MATION 17 5

Incldenlal Average EssenliBi


0----- 1----- 2 ----- 3 --___ 4 _____ 5
None Moderale Significant

Ca" Study
1. Req uires backup/ recovery7 0-2
2_ Data communicattons required, 0- .
3. Distributed processi ng functIOns ' o
4. Performance critical , ]-4
5. Run on existing heaVil y utihzed environmenO 0- .
6. Requi res online dara entry' 5
7. Multiple screens for input' ' -5
(co""",ud)

Figure B.B General characteristics for function point adjustment. numbers 1-7

Function Point Step 5


Fi nally , th e (adjusted) function point total is ca!culated by the formula shown in Figure 8 10 This equation
tates that if there are no special demands at all on the apphcatlon ( tora l ge neral characteristics = 0 ), then the
fu nction poinr mea ure should be sca led down from the unadjusted (raw ) score by 35 % (whIch explains the
' 0 .65") . Otherwise the measure should be caled up from the unadjusted amount by o ne percentage po int for
each general characteristic unit.
For the case study, a reasonable allocation of ge neral cha rac tenstics is shown In Figures S.8 and 8 9 . The
total value of these is between 24 and 43 , so the Rnal (i.e ., adjusted) funct Io n poi nt computati o n IS
41 X [0.65 +0.0 1 X (24 to 41 )] = 41 X [0.89 to 1.06] ", 36 t0 43

8.1.4.2 Converting Function Points to Lines of Code

Once accurately obtained. function poi nts arc very useful. For example, they can be used a ompariso n
met rics. allowing organizations to estimate jobs based o n function point mernes of previou Jobs. They can be
converted to lines of code using tandard tables. lines of code can then be used to estimate total effort In
person- months as well as duration (see the next section o n COCOMO ). For example, [4] estimates 5 3 hncs
of Java source per function poi nt. Using th is factor for the Encounter example, we anticipate

Incidental Average Essenlial


0----- 1 2 ----- 3----- 4 ----- 5
None Moderale Signlficanl
Case Study
8. Master fields updated online, ]-.
9. Inputs, outputs , inquiries of Rle complex' ,- 2
10. Internal processing complex .-]
II Code designed for reuse? 2- '
12. ConversIon and installation included? 0-2
13 Multiple installatIon in d.rfcrent organizatIons? 1-3
14. Must facliitate c hange and ease of usc by use r? '-5

figure B.9 General characteristics for function point adjustment numbers 8- 14


176 CHAPTER S PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING

(Adjustcd) Fun tio n Points =


(UnJdju,tcd fun ction pOints] X
[0.65 + 0.0 I X ( lolal gcnera l charac teri stics)]

Figure 8.10 computation o( adjusted (unction points

(361044 ) 53"" 1. 9 - 2.3 K-Hne of Java source As expecled , thi s is much lower than the previous estimates
of -\.2 -300 and 7.5· 170 K-lines of Java source. This is true because " applies to o nl y two "function s' for
Encounler, whereas the larger e limale were for a full game.

8.1.4.3 A Further Function Point Example

Let's consider a system that tracks Video rentals. We will conRne the appJ.cali o n to a cus tomer-oriented
appl icatio n, in which customers rent videos and need informalion about availability.
\VIe assume that the application requires two Poles only, o ne for custo mers and a second for videos. The
unadjusted functi o n po int computation is as shown in Figure 8. 1 I .
Now we estimate the adjus tment faclors , as shown in Figure 8 . 12 , yielding a "General Characteristics'
total of 35 .

Simple Medium Complex Sub· Tolal

cotmt factor COUIII factor COllttl factor lolal,

Ext. inputs 2 3 f 4 o 6 /0

Na ..t , pi,. , Vidto dala

Ext. outputs o 4 I 5 o 7 5

Amosml dut

Ext. inquiries o 3 f o 6 Jl

- ncpla""'io", Availability

Int. logica l files 2 7 o 10 o 15 ..


- ncplaoallO" Customers, Videos

Ext. interface Ales o s o 7 o 10 o

Figure 8.11 Unadjusted (unctlon point scores (or vide store example
COST ESTIMATION 1n

None tncidental Moderats A vs"'ge Significant Essential


0---1 2---3---4 5

1. Requires backup/recovery' ... ... ............ .. ...... .. .


2. Data communications required' .......... ....... ... .

0
3. Distributed processing functions' .... ..... ...... .. . 0
4 . Performance critical, •• • •• • •••• •• • • • • • • • • • • • • • • • • • • • • • • • • • )

5. Run on existing heavily utilized environment7 ,


6. Requires online data entry' . .... ... .. ................. . 5
7. Multiple screens for inpun ..... ..... .. ... ... ... ...... . )

8 . Master fidds updated online' ... .... .. .. ............ . . 5


9. Inputs, outputs, inquiries of files complex, .... . 2
10. Internal processi ng complexL ... ............. ... '" ,
I I. Code designed for reuse' .......... ... .... .... ... .. . . 3
12. Conversion and installation included' .... .... . . 3
13. Multiple installation in different o'lls ., .... .. .. . 3
14. Must facilitate change case of usc h y user' .. . 2 Tolal
35

Figure 8.12 FP adjustment fa ctors for video store example

The Function Point formu la gives


Function points = [unadjusted fu nction points] x [0.65 + 0.01 x (total general characterIStics )]
= 33 x [0.65 + 0.0 1 x 35 ]
- 33

This yie lds 33 x 53 = 1, 749 lines of no n-comm ented source lines of Java code .
The function point method is summed up by Capers Jones in [5], a practiced advocate of function pOInt
applicatio n. See also [6 ].

8.1.5 Estimating Effort and Duration from Lines of Code

O nce lines of code have been estima ted , either throug h use of historical data, by companson to related
projects, or via function points, they can be used to estimate labor reqUIrements and prOject duratIon uSIng
Barry Boehm's COCOMO model [ I) COCOMO is based o~ the idea that project outcomes, plo tted as
graphs, have a consistent basic shape A para meterized formula is found for the shape, so that to obtain the
graph for a particular project, he si mpl y has to detemline the parameters fo r it.

8.1.5.1 COCOMO I

Boehm observed that the labor required to develop applicatIons tends to in rea e faster than the applicalto n's
SIZC. He found In his init Ial rc earch that the exponentIal fun Iton, WIth exponent close to 1.12. expresses thIS
rtlationship quite well Boehm's model also says that the duratIon tncreases exponentia lly \ IIh the erfon , but
WIth an exponent less than 1 (the exponent used III th , case is clo e to 0 35 ). Th,s rell t, the observalto n that
.fter. c;.,n.atn sIze (the "knec' In curvc (2)), additional reqUIred effort ha on ly a gradual lengthenIng effect on th~
time It takes to complete the project TI,CSC are illustrated In F,gure 8 13, wher~ L ",ho n for "Iine< of ode '
178 CHAPTER 8 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT II: esnMATloN, SCHEOUUNG, AND PLANNING

(1 ) ellort' lor
Increasing LDC
(2) Duration lor , '2
(y _ 3.. . ) ,
Increasi ng ~
ellort'
(y _ 2.5 .. 0.35)

Exponent < 1
> 1

Applies to design through Integrlll/on lind testing


' Ellort = total person-months required

Figure 8.13 Meaning of the COCOMO formulas


Source Boehm., Barry. " Sol tware EngIneerIng EconomIcs," Prentice Hall, 1981

U lng data fro m num erous projects, Roehm estimated the parameters fo r these re latio nsh ips, assuming
an e xponential re lations hip. H is fo rmulas arc illustrated in Figure 8. I 4 . In this system, organic applications an:
stand-alone applicatio ns suc h as classica l (i.e ., no n -Web-enabled ) word processors or our Encounter case
study . Embrddrd applicati o ns are integral to h ardware -softwa re sys tems (e .g ., an anti lock braking system). S""i-
dew hed apphcatio n arc in between . A Web-enabled Encou nter, for example , is semi -detac hed: it is not
o rganic , but neither is it as heavi ly e mbedded as the code in an antilock braking system, for example.
En counter would commU ni cate with the Inte rnet via signals that are o nly occasiona l when compared with the
frequency o f C PU Instruc tion execu tio n.
Boehm's mo del says r,rst that the required effort and durat ion ha ve separa te models (fo rmulas) fo r each
ty pe o f appli cat ion (differing in factors a and b). For examp le, a sta nd-alone job with 20,000 lines of code
would take 2.4 x 20 1.05 '" -I person -mo nths duratio n if organic (stand -alone) but about 3.6 x 20 1.2'" 76
person-mo nth if e mbedded _
The duration formu la ca n be expressed directly 111 te rms of line of code (KLOC) as follows:
Duration = c x Effon = c x (a
l
X KLOCb)J = c x i X KLOCIJ

At nrst glance, Boehm's duration fo rmu la may appear strange because the relations h ip between effort
and duration seems to be simpler than his form ula indicates. For example, If we kn ow that a job ,..,quills 120

Effo rt in Person-months = a X KLOC


Duration = c x Effort'

Software Project a b
- c- d-
-
Organic 2.4 1.05 2.5 0 .38
Sem i ·detached 3.0 I. I 2 2.5 0.35
Embedded 3.6 1.20 2.5 0.32

FIgure 8.14 Original COCOMO I formulas


SolKco Bco'1m, BatTy. "SOftware Englneetlng Economics," P,oouat Hall.. 1981 ,
COST ESTlMAnON 179

pc:r.;on .months, and we put ten people onto it, won't it get done in 12 months? This would indeed be the Ca3e
if we could usefully and con istently employ all 10 people on the project from day 1 through day 365 , but this
is not usually possible Consider, for example , day 1 Since all the engineer.; can't know much about the
project (it has just begun ), what u dill activities could all ten engineers do that day; It follows that if we
allocate 10 engineer.; (Tom the first day , the 120 per.;on .mo nth job w,1I actually take longer than 12 month .
Boehm's duration fonnula has the strange property of being Independent of the number of people put on
the jobllt depends only On the size of the job. Actually, the formula assumes that the prOject Will have roughly
an appropriate number of people available to it at any given time (for example, one on day I , th irty on day
100, assuming that is what's needed).
Boehm's model , whi h has been tested extensively and is widely respected , has been refined over time,
and has been largely updated with the more complex CO OMO II , described next. A great deal of practice is
required to use even COCOMO I effectively. It i< best used along With an independent method and a healthy
dose of common sense (sometime called a "saOity c heck") . U"ng Boehm's basic formula on the prototype
ver.;ion of Encounter (conSISting of two basic hIOction ), With 4· 300 K·hne. of code, we obtain 10 to 1,000
pcr.;on.months of effort , and 6 to 35 months in duration, as shown in Figure 8 15.

8.1.5.2 COCOMO II

COCOMO (I ) is somewhat identified with the Watcrfall process because it does not speCifically account for
iterative development. It mu t be used anew for each iteration , and docs not account for factors such a
whether the iteration is early or late in the process. For this rca on and others, Boehm updated it to
COCOMO II. (See, for example, httpi/sunset.usc edulresearch/ COCOMO IIl) The n of COCMO I can be
interpreted as a scaling factor. COCOMO II replaces it with a product of various scaling factors F F" SF"
"
SF <, and SF, . This al lows for a more refined set of parameters. The b parameter In COCOMO I expressed the
number of times KLOC is multipl ied . CO COMO II replaces thIS with a product of seventcen quantillc EM ,

K b approx.
-a - -
Effort nK" b

LO 2.4 4.2 1.05 10

HI 2.4 300 1.05 1000

c P d approx.
- - -
Du~lion cP" d

LO 2.5 10 0 .38 6

HI 2.5 1000 0 .38

Flaure ' ,15 using COCOMO I to estimate the magnitude of the Encounter effort
180 CHAPTER 8 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT II: ESTIMAnON, SCHEDULING, AND PLANNING

Effort In Person ,mo nth s


= {I X n, ,'?EM,

w here n = 1.0 I + L,
I' SF,
EM, ore multiplica ti ve cost dnvers
SF, a rc sca ling cost dri ver

Figure 8,16 Basic COCOMO II Formula


SOUrce Boehm, Barry. " SO/tw;lfC ErlS'lncerlng Economics," Prentice Hall, 1981 . httP l/sunset uscec!U/researchlCOCOMOIV

(so eoch replace KLO in CO O M O I) These arc called l11ulliplica l,", co,1 d,,",,,, and they allow for m o r~
re~ nem c nt in dc>cribmg the produc t and project.
The CO OMO II Effort fom1U l. is shown in Figure 8. 16. 11,e sym bol ] (cap ital p) is the product symbol
For ex,mpl e, n:
,k' means I ' X 2' X 3' X 4' .
Fi gure 8. 17 lists the ty pes of the quantities SF, and EM}' The SF, parame ter, for examp le, allows for
fac tonng in the maturity o f the develo pment o rgani za ti o n. The SF, parameter allows for the degree of risk
re maining in the projec t. The va lue o f SF. is hi gh for initial iterations a nd low for later ones The EM ..
parameter account for the modern practice of developi ng in several physical locations. Each of th~
porametcrs has a de fi ned scale.

8.1.6 Assessments for Agile projects: Story Points and velocity

This eetion di scusses esti mation techniques for agi le projects . In o rder to commit to delivering capabil ity
at the e nd o f a cycle , a team must assess th e effor! req uire d . As with fun c tion points, ,lory pOlnls are a means
by which to measure the size of a story as it relates to implementation . Unlike function po ints, however,
which attempt abso lute measure me nt, Sto ry points are a relative measure . In other words, they compare
sto nes w ithin a project o nl y. Th e size ra ngc is typically betwee n I and 10, and the size of a Story is based
on the team's hi story o f implementing stories in past cycles of the project. One way to establish story
poi nts is to take a n executed story that the team considers to be average, assign it 5 story points , and use it
as a yardstick (or fu ture stories . Another is to select a vcry small implemented story, count it as 1 point, and
thcn calculate all o ther stories as multiples o( it . A mo re sophisticated way is to create a plot as shown in
Figure 8. 18 .
A big ad va ntage of agile meth od s is that they involve man y entire creation cycles. In a pure waterfall,
team member find it difficult to estimate the size and completion time of a job because they will not
usuall y have performed o ne just like thi s in the past, with the same participants. Agile methods, on the
other hand , facilitate th e assessment of how much completed work a team is capable of producing by
relying o n observed past performance within the same project. Recall that in physics, velOCity is defined as
di,'a"ct co"md p" lime 'IIIil. Similarl y , agile project velocity is defined as the amolln l of fun "o"alily lilO',."lta ""
unil. This translates into story points per cycle. Assuming the constancy of cycle (e.g ., alway two weeks),
the reliability of a ve locity calculatio n depe nds only o n the ability to accurately as ess story points With
the ex perie nce o f repeatedly making thi s estimate, te om mcrease their estimation accuracy as the proJeCt
prog resses. Sec Figure 8 . 19.
As effective as this kind o( agi le estimation is, it requires augmentation when larger scale estimation i
required. The reader is referred to ohn, Agilt Eslimaling and Planlling , Prent.ce Hall, for example, for further
reading.
COST ESTIMATION 111

- - -
Sym. Abr. Name
-
SF, PREC Precendentedness
SF,
,
FLEX Development Flex,bility
,... - -
SF, , RESL Architecture and Risk Resoluti on

SF. TEAM Team cohesion

SF, PMAT Process Maturity


- - -
RELY Required Software

EM , DATA Data Base Size


-
EM, CPLX Product Complexity

EM, RUSE Required Reusabili ty

EM, DOCU Documentation Match to life-cycle Needs

EM. T IME Time Constraint

EM, STOR Storage Constraint

EM . PVOL Pladonn Volat ility

EMg ACAP Analyst Capability


-
EM IO PCAP Programmer Capability

EM" AEXP Applications Experience


-
EM" PEXP Platfonn Experience

EM " LTEX Language and Tool Experience

EM PCON Pe ~o nncl Cont inu ity


" 0>

EM T OOL Use O f Software Tools


"
EM , 6 SITE Multi ·Si te Development

EM 17 SCED Required Development Schedule

Fl&ure ' .17 Basic COCOMO II cost drfvers


~" 8OllYrl. Barry. ·'SQftwate Engineering ECOOOiTiJCS," Prentice HaJJ, 1981 , htlP IIS1Jnsetusc edlJ/reSoeNd'VCOCOM08I.
182 CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II' ESTIMATION, SCHEDULING, AND PlANNING

10 Upper bound

, Estimated size In story points


• • Actual size In person·hours
~
0


• •
t , Com pule past e rror %

• 01 2. Estimale using compaMson ,
I 3. factored by Irend in past errors %
0
0 1/

1 2 3 4 5 6 7 e Cyclo number

Figure 8.18 Estimating story points

• DeAnitlOn , Number of story points the team ca n execute per cycle

• Relies on history of perfonnance and consistcncy of story points


a \'qit hln this project and past ones

• Depe nds on accurate story poi nts

Figure 8.19 Velocity in agile development

8.2 SCHEDULING

Project estimates are used as input for co nstruc ting project sc/"d" I". Teams develop schedules so that
everyone knows what to expect, ,. hat to do, and when to do it. Figures 8.20, 8.2 I , and 8 22 step through a
tYPical schedule construction using a spread; heet . Substa ntial projects arc best' perfo nmed with specialized
tools such as Microsoft Project .
Softwa re project sched ul ing confro nts a fundamental c h icken .and·egg problem , as fo llows. Part of a
software e ngi neering project is to ga ther the requi re ments but until we know the requirements fo r the
application , we ca n't say h ow lo ng it will rake to do the job and so, strictly speaking , we can't schedule it.
There are severa l approaches to breaking out of this loo p. One is t'o develop a sche dul e o nly afte, the
req uireme nts ha ve been speciRed . Although thi is logical, it is no t often used. The main reasons fo r thi arc a
follows ,

I. As me nti o ned befo re, it is usuall y imprac tical to specify all req uireme nts up fro nt.

2. Management uSllally needs to know llP front how much time the project will consume and how muc h it
will cost.

A common way to approach these issues is to begin With deadl ines and to ae am pi ish as mJn of the
important requi reme nts as possible with the speClAcd time and Ananei.1 resources , and the n to i~rate this
process. For the purposes of dIScussion, this is the approach used herc.
The AT'i t step is to show the deadline for ddiverables to the cus to mer. In Ollr ca e , we wtll <lIPPO (' that
the custo me r wants to <cc a prototype aller fo\tr week < and Ihe completed proJcct after f lit month O ne
I T I I I 1"
I Schedule for VideoStore Application I I
I I
4- January
1 2 3 4
February
1 2 3 4
March
1 2 3 4
Ap ~1
1 2 3 4
May
1
t t
Milestones Prototype X X Freeze requirements Final product X

t I

. -- - -

Figure 8.20 Building a schedule part I-setting milestones

1 2
-
3 4 1 2 3
-
1

l'i - '" -
~' -
~
:r:
m
o
C
Figure 8.21 Building a schedule Part II-shOWing phases c
z
Cl

e:
~

\:
2
~
~
CD

"0
4 4 1
-
2 3
-z
;0

-
n
"0
f;;
V>
o."
~

~
;0
ITt
"0

e'"
ITt

~
~
m
;::
ITt

1 I 1 ~
1 1 1 1 1 1 1 1 --
"

1 1 1 1 1
-• ~ I ' I I ~;::
11111 11111 1 1 1 4

-o~
z

~
I
ITt
g
C
Z
Figure 8.22 Building a schedule part III- showing work breakdown structure '"

~
Z
o
"0

~Z
-Z
'"
THE SOFTWARE PROJECT MANAGEMENT PlAN 115

Oependendes: subset of schedule Critical paths: sequences of dependencies

---.,
-

---i-, '
-
phise I dBHllled - -
- -
I
phue I delilled •

---
I
,
--r-- -
-
phase II detailed

- -
Figure 8.23 Dependerrcies shown in schedules

technique used in setti ng a sc hedule is to build in buffers to compensate for factors that we don't or can't know
about. For example, our schedu le assumes four weeks per month , whICh provides at least o ne unscheduled
week. This is shown in Figure 8.20. Some project managers frown on approaches like thi s because they hide
things.
Now we work backward from the mil estones to show the times for the various phases, as shown in
Figure 8.21 .
Finally , the team needs to ensure that people are availab le to do the work . This requires a work b".ktiown
"ruc'u" (WBS) showing who will do what work. Figure 8.22, for example, Includes a WBS
In the example of Figure 8.22 , the last week of design requires Just o ne person and the first week of
implementation requires twO eng,neers .
Schedules show the intended o rder of tasks. 11 task A is schedu led to be performed prior to task 13, this
docs not necessari ly imply that 13 depends o n A. For example, we may have selected the order because it i
more convenie nt to perform task A befo re /J. However, if task X depends on ta k Y, then task Y should be
scheduled to complete before task X begins, and the dependency should be made clear on th~ s hedu1c.
We can denote dependencies o n a schedule, as show n In Figure 8.23 These become ,mportant
whenever we want to aller the schedule. They are al so necessary in detennining the proJect's rillcnl pnl" : the
sequence of activities that ",usl be performed, and the order in which they must be performed To ummarize:
The dependencies form a subset of the schedul e, and the crit,ca l paths are seque nce of depend ... n ies

8,3 THE SOFTWARE PROJECT MANAGEMENT PLAN

The prOject plan is docume nted <0 that everyone knows what to do and when to do ,t . There are many
formats forsu h a plan. We will use IEEE Soltware Project Management Plan ( PMI') standard 105 · 1 98 for
this purpose. TI,e table of contents for 1058 · 1998 I< show n in Figure 8 24 , and is used 111 the ca e ,tudy 111
186 CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING

I Overview /) Tech nica l process plans


1. 1 Project ~ul1lrnary 6. I Prote , model
I .2 Evo lution o f the S PMP 6 .2 Mellwds, lOols, and te hn lqucs

2 Refe re nces 6.3 Inlras lruc lU'C plan


6.4 Produc t acceptance plan
3 Den nilions
7. Su ppor ti ng p rocess p lans
4. Project organ iution
7 . I Configuration manage ment plan
4. I Exte rnal interfoces
7 .2 Verification and validation plan
4 .2 Internal struc ture
7 .3 D ocumentation plan
4 .3 Roles and responsib il ities
7.4 Quali ty assuranc e plan
5 Ma nage rial p rocess p la ns 7.5 Reviews and audits plan
5 . I Projec t start·up plan
7 .6 Problem resolution p lan
5 .2 W o rk plan
7 .7 SubCOnl"raClOr man.gement plans
5.3 C ontrol plan
7 .8 Process improvement plan
5 .4 Risk management p lan
8. Additio na l pla ns
5 .5 Project closeout plan

Figure 8.24 IEEE 1058-1998 software Project Management Plan table of contents

Section 8.4 . The IEEE standard is someti mes viewed as belonging only to "document-heavy" projects. In fact ,
its parts should be used when and o nl y whe n they provide value . Agile project leaders can gain by perusing
the topics and dec iding how a nd when the issue me ntioned is to be hand led . Non-agile projects are not
bound to usc a ection unless the effort IS worth it. Prob lems arise w hen needed issues arc igno red and when
docume ntation is used for no productive purpose.
Section 1. 1 in the SPMP-the overview-sh ou ld ide ntify the project but should not cover its
requireme nts (i.e ., descriptions of its behavio r). These arc cove red in the Software Requireme nts Specifica·
tion , described in Part " of this book. Repeating th at materia l in the SP{\'IP would violate the principle of
single· source documentation (to say each thing in one place only). Section 1.2 dcscrib", t he ways in which
the SPMP itself is expected to grow a nd c hange. The Software Co nAguration Management Plan (SCMP)
hould have been developed by th is ti me (see C hapter 6), so that versions of the SPMP can be properly
controlled . A reference to the SCMP is provided here.
Section 4. 1 describes the ways in which orga nl ZJtions wi ll co mmunicate with the development team
This depends o n t he project's stakeho lders (the people w ho have an intere t in it). For example, how will
engineering interface with marketing (regu lar meeti ngs, E-mail, etc .) Section 4.3 speeiAes the responsibili.
tics of project personnel.
Section 5.2, the Work Plan , caR co ntain the project's schedule. Section 5.3, the Control Plan, peciAes
who will manage , con trol , andlor review the project, together with how and when this IS to be done. For
example, sen io r management needs to know how projects arc progressing, so we would de. cnbe the process
for keepi ng them informed here. Risk ma nagement (Section 5.4) was described in hapter 7.
Constraints on the languages and tools used are provided in the "technical proce s plans: L"CtlOn 6 for
exa mple, 'This project shalilisdava from Su n, versio n 1.2. 1, and Rational Rose versi,o n I: Section 6. 1 refers to
the software development process to be u<cd (e.g., wa terfall , spiral , incremenral ). Possibll' ·organlZational
struclure<' were discussed in C hapter 7. Section 6 can ,"elude ,"fonnatlon On reuse requ",:ments
CASE STUDY: ENCOUNTER PROJECT MANAGEMENT PLAN 187

In Section 7, the • upponing Process Plans references or dc:scnlxs activill'" that suppon the
development process, such as configuration management and quality assurance. If the suppon function is
descrilxd in separate documents (e .g ., the configuratIon manage ment plan or the quality plan ), we reference
those document ·. Otherwise, We describe the upport hlnction In full. These and other aspects of the SPMP
are explained fun her In the ca e study at the end of this pan of the book.
The reader will find a ample SPMP for the Encounter cases study in SectIOn 8.4 of thIS chavter, wh,ch
conforms to IEEE standard 1058· 1998 Excerpts from management documentatIon for the Eclipse and
OpenOffice open source projects can be found in ections 8.5 and 8 6 res pectively. In compari ng them , the
reader will notice the benefits of using a standard but also some of the limitallons in ncxlbility.

8.4 CASE STUDY: ENCOUNTER PROJECT MANAGEMENT PLAN

The Software Project Management Plan for 1. Overview


Encounter sh own in thIS section i based on IEEE
SId IOS8-199B Slandard for Soflware Pro)tCI M"'''9''"'''' 1.1 project Summary
PI.ns. Figure 8 .24 is lhe table of content for the
doc ume n t. Note to the Student:
Approvals This should be at a hI g h enough level that 11
does not need to change milch over time.
Derads should appear in sub equent sections,
TItle Signature Date
not this one. This summary should not substi·
Engineering Manager !I. '}onI.> 7/ 15/ 04 tute for any pan of the requirements document.

QA Manager £WiUn. 7/ 11104


Thi s projecl is organized to produce a role·
p laying video ga me called Encounter ThIS ga me
Project Manager a. ~.u jU 7/7/ 04
will be developed in several stages Ince the customer
Author £. !1J.tl uA~ 7/ 1/ 04 intends to specify the requirements in <ta ges, wllh
each stage following the demon tratlon of each ver·
Slon. The early versions arc intended for educa tional
purposes, as examples of som....are ensmcenng prac -
tIce, and a legacy sy<tems on whIch students may
Revision History
build their own video game . The later versions are
expc:clcd to be either freeware: gam(") or commerC ial
Version I
products marketed by a ga me market ing organ ization
1.0.0 E. Braun: Created first draft 6/ 1/98
1.2 Evolution of the SPMP
1.1 .0 R. Chadwick: Revlewcd 1/ 1 1/99

I 1.1 E Braun: Expanded 3.2 1/ 19/99 Explai ns how and by whom this document will
be maintained. It will have 10 be mo(hfied In
1.2.0 R. Chadwick: RevIewed for release 5/ 19/99
severa l ways (e .g., with a more detailed sched-
1.2 . 1 V Brahms: Final editing 4/ 30199 ule as more is known about the reqUlremc.-nts ).
If a concrete plan is not Pllt In place to
Versio n 2
maintain this docum"nt, It will be worked
2.00 E. Braun : Updated to 1998 standard on sporadically or not at all.
5/18/2004
188 CHAPTER8 PRINCIPL 5 OF $OFlWAREPROJECTMANAGEMENT II: ESTIMATION. SCHEDULING. AND PlANNING

h" docum ent wdl be m a '"t a ll, ~ d o n a SPMP = Softwa re Project M anagement
wC('k ly h. <o b •he projec t lead er. It .s subJc t Pla n (th is document )
to o nfo llurat' o n m. nage ment by mea ns of th e SRS = o frwa re Requ irements
.\11' It 0< th e projc t l eJd c r' ~ r~ s p o n . •bil.t y to pcci fi ca tio n
subl111t th. s do um ent a< a I. and to h 'e p .t up to SDD = o ftware De ign Document
date T his SPMP ma.nl y fo ll o ws th e fo rm at of IEEE STP = Softw are T est Pla n
10 8 I · 1998 tbd = ro be decided

2. References
4 . project organization
[IEEE) Th e appl. able IEEE standards are pub lished
on "IEEE Standards Collecti on," 1997 edition.
4.1 Externa l Interfaces
[MPA L5) Th.s document is to co nform to the
company's "MaSler Pl an for the Attainment of CMM
Level 5 " Name the people and organizations with
[Braude) l1,e princi pal source of textbook ref· whom the team shou ld communicote.
erence matenal is 50fl.,ort E"gi""",'g , A" Objtcl-On-
mltd PmptClovt by E. Braude (Wiley, 2000).
The projecttcam will interface with the fo llow.
ing individuals and organizat ions, VP, Engi neering
3 . Definitions (for tech nical and standards direction), Marketing
CI = Configuration Item (for requi rements), Came Laboratory (for advanced
CMM = Capa bility Ma turity Model, the game features). and the quality assurance engineer.
SE I's model fo r o rganizationa l
imp rovement 4.2 Internal structure
IEEE = Institute of Electrica l and Elec-
tronics Engineers Figure 8.25 shows the organ izati o n of the Encounter
QA = Qua lity Assurance project within Camin g Industries Consolidated.
SEI = Software Engineering Institute, The project will be organized as a team of peers
Pittsburgh , PA with designated roles. The role are team leader,
SCMP = Software Cor-figuration conRguratio n management leader, qual ity assurance
M anagement Plan leader. requirements management leader. design

President

j"' I IV&VI
VP Marketing VP Engineering I
•" I Soltware
I
- Englneerlng
Labs
" . Game Lab

." Game 123 Encount. r SOA

Figure 8.25 Organization of Gaming Industries Consolidated


CASE STUDY: ENCOUNTER PROJECT MANAGEMENT PlAN ,,,

Requiremcnts
Team CM QA Manaaement
leader Leader leader Leader Leader Leader

Ualson VP Marketing Software


Engineering •
engmecnng•

lab

SPMP SCMI' SQAP SRS SDD Code


Responsibility STP base

Figure 8.26 Encounter project responsibilities

leader, and implementation leader. In addition . there 5. 1. 1 Estimation Plan


are liaison roles to marketing and to the software
engineering labora tory .
As a project progresses, our ability to estimate
its cost and duration improve (but also become
4.3 Roles and Responsibilities progressively less useful). This section explains
when and how we intend to perform these
The responsibilities of the participants in the project • •
estimations.
are shown in Figure 8 .26.
Being responsible for a doc ument Includes the
following , Estimations of prOject cost and duration Will be
made following the specification of hi gh -level re o
• Making sure that the document is created on time quirements (using funcroon poonts), detailed require ·
ments (uSing a method to be determined), and aftcr
• Having the team leader identify the writers of the high- level design The latter estimates will be made
document by com pari o n with past projects
• Keeping the document up· to-date throughout the Before beginnrng requirement analYSIS, we
project life cycle have estimated the size of this effort in three differ·
ent ways:

s. Managerial Process Plans 1. Usin g an informal top·down e tim.te based on


the expenence of team members With somewhat
sim ilar p,oJects.
5.1 Project Startup Plan
2. Usi ng a to p·down approximation with industry
game development data.
This seclion spc:cifles the planning activities thaI
will be conducted once: the project is under way 3. USing fun tion pOint on two known function s,
It IS i plan 10 conduct planning- . meta·plan, if extrapolating to the cnllre application .
you like.
The results are shown on Figure 8 27
'90 CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDULING, AND PLANNING

Mini Max Comment

( I) 170

(2) 4.2 00

(3) 1 1.4 46 1.9 · 2.3 for two identified func ti ons, 6 ·20 times as many in
comple te a pplication

Most conservative 1 1.4 300 Maximum o( minimums and maximum of maximums

Least conservative 4.2 46 Mini mum o f min im ums and minimum of maxi mums

Widest range 4.2 300 Minimum of min imums and maxi mum of maximums
- - -
Narrowest range 1 1.4 46 tvtaxi mum of min imum s and m inimum of maximums

-
Figure 8.27 Very rough estimate of application size prior to requirements analysis

Th e impleme ntation leader wil l e nsure that all


There arc many ways of presenting this data, team members arc supplied with the selected devel·
dependi ng on the needs of manageme nt and the opment environment within two weeks of project
development staff. So me of these are shown in starr .
Figure 8.27. In the absence of wrinen require-
ments, estimates are necessarily very rough. The 5.1.4 Project Staff Training Plan
estimates themselves can be an appendix to this All staff me mbers whose Java profiCiency level is less
document instead of he re within the body, and than "advanced," as defi ned by the Ajax certification,
updated as the project progresses. will be trained by Uni versal Training Inc. courses
wit hin the (irst mo nth of the project. The objective
will be to attain advanced· level profiCiency.
The reaso n fo r the very wide ran ge is tha t the
figu res have been obta ined with negli gi ble interac·
5.2 Work Plan
tio n wi th the customer.

5.1.2 Staffing Plan 5.2. 1 Work Activities


The ro les will be fi lle d as fo ll ows.

5.1.3 Resource Acquisition Plan ThIS sectio n specifies how the work will be
subdivided .

This section indicates how resources will be


obtained other than staff (computers, soft· Th~ work o n th iS project w ill be diVide d inlO
ware, etc .) con Aguratio n manage me nt, qunlity a<surance (i n·
eluding testi ng), reqUirements annl is, d", lgn, and
CASe STUDY: ENCOUNTER PROJECT MANAGEMENT PlAN '9'

Leader Fadlitator Marketing QA Game lab Risk


Rc:sponslbilty liaison liaison liaison retirement

Report at wc:c:kly meeting x x x x


Orculate wc:c:kly report

Orculate biweekly report

Orculatc: monthly report I.

·Report forma ts

1 see CI 34 : "monthly project status fo rm"

2 sec CI 87: "mo nthly marketing status form "

3 see CI 344 : "weekly QA status form "

4 see CI 48 : "biweekl y game lab result form"

Figure 8.28 Program monitOring and control

Requ .
Team CM QA Mngmnt Design Implementation
Name uader uader Leader Leader uader Leader

Ed Braun X X

AI Pruitt X

Fern T ryfill X

Hal Furnass X

Karen Pders X

i.JailOn with VP Eng. Marketing Soft. Eng. Lab

Rgure 8.29 StaHlng plan for Encounter


192 CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING

Monlh , Monlh 2
-Mon,h 3 Month 4 Month 5
, 2 3 4 , 2 3 4 , 2 3 4 t 2 3 4 ,2 3 4
SCMP complete , Begin system testIng '
, SOAP complete Delivery ,
Milestones
, SPMP rei. , complete
Freeze requirements '

Iteration'
,
Iteration 2 I I
Risk Identification
and retirement Preg:. for maintenance I I
Figure 8.30 High·level chart of tasks with fixed delivery date, ordered by completion

imp lementati on. The prOject roles and responslbili . 5.2.4 Budget Allocation
ties are shown in Figure 8.26 . The budget allocation, shown in Table S. I, matches
the work breakdown structure shown in Figure 8.32,
5.2.2 Schedule Allocation and includes an additional 10 percent to cover
unantIcipated cOSts. Loaded I labor rates arc $4,000
per week.
11 we are given a Axed completio n date and
have identiAed the process that we will use, we 5.3 Control Plan
may have enough Information to provide a
high.level schedule. We increase the amount
of detail in the schedule as more becomes The IEEE describes this section as ' ",etria,
known about the design. reporting mechanisms, and contlol plocedlUcs
necessary to measure, ~port, and conllol the
product requirements, the project scheduk!,
The schedule is shown in Figure 8.30. Refer to budget, resources, and the quality of worlt
the SQAP for the schedule of quality activitIes. processes and work products.'
It is usually advisable to schedule regular
5.2.3 Resource Allocation team meetings (typically weekly; sometimC!S
The work breakdown structure is shown in rlgure short daily stand·up meetings). When there
8.31 . The bottom line shows t~e person · month is no business to conduct, such meetings can
available for each month . easily be canceled. On the other hand, sched,
uling a meeting on short notice m~y be
We have not yet pcrfonned any design, so it is when team members have other commitllknlS.
too early to name the engineers who will work Even teams that work to~ther every ~y need
on speCific pam. These names will be added to schedule negular review meetings to avoid
he~ after the designs for the various configu· drifting. The meeting convener should __
rations have been detennined. mally cancel a meeting if there ~rc no qcncIa
it~~lmIiS.

I Ie , Including bc:ncAts
CASE STUDY: ENCOUNTER PROJECT MANAGEMENT PlAN 193

Month 1 Month 2 Month 3 Month 4 Month 5


- r-,--.--!- - - ---.----.-+---.-....,..-,--+-.---.--.--1
1 2 3 4 1 234 1 234 1 234 1 234
SCMP
Milestones 6 SQAP
Complete testing 6
6 SPMP rei. 1
6 Freeze requirements Delivery 6
Iteration 1
Tasks
..... Risk I&R Iteration 2
....!.;;;"""""..............""'"
E. Braude 11111111111111111111

J . Pruitt 111111111111111111

F. Try1111 1111111111111

H. Fumass 111111111111 1111111

K. Peters 11111111 1111111

F. Smith (tech support) .5 .5 .5 .5 .5 .5 ~ .5 .5 .5 .5 .5 .5 ~ .5 .5 .5 .5 .5 .5

TOTAL 5 . 55 . 55 . 55.55.55.55 . 54.54.54.54 . 54 . 54 . 54 . 54 . 54 . 54~3 . 5

F'1gUre 8.31 Work breakdown structure. excluding clerical work

The ~ ntire team w, lI meet at the begi nn,ng of nece sary. The team leader wli l inform the team by
~ach phase (reqUire me nt s, d esig n, and imple me nta · Thursday at 4:30 p.m. if the lotter meeting is to take
tio n) within each it~rati o n . There w,lI be wee kl y place .
project m~e t ing< on Tuesdays from 10:00 a.m. to
noon. T ~am members are requested to keep Friday 5.3.1 Requirements Control Plan
mornings from 9:00 a.m to I I :00 a.m. o pe n fo r an The req uirements leader will report to the project leader
additio nal meet ing, in case suc h a meeting becomes o n the status of the SRS in wnting each Tucsday.

5.3.2 Schedule Control Plan


Table 8 • 1 Budget allocation T he project leade r wi ll report to the tea m o n the
Month Number Allocation status of th e <c hedule in Wrltln!! each Mo nday .
1 596,800

2 S96,8oo 5.3.3 Budget Control Plan


The rrojectlcader wi ll rcpurtto management on the
3 S87,120
<tatus o f the bucl~e t in Writin g ('very so o nd Mo nda\' .
4 S87,120

5 S77,440 5.3.4 Quality Control Plan


$445,280 T he A representallve wi ll I" v,de wnlten re f' rt-
Total
to the manaR ' r nr
QA , w llh copie. to th e proJ
...•
~

'"
""z
;!1
n
-
""m
Impact a."
RIsk Tide likelihood 1- 10 Retirement Priority (lowest Ta'llet V>
a
(details 1-10 , . /east , =/east Cost 1- 10 numb~r Responsible Completion
• alven above) likely impact , =/owest handled first) Retirement / Mitigation Plan Engineer Date ~
cost '"
IT'
-0

1 Superi mpose 3 10 1 8 Expe rim e nt wi th Java images P R- 1/99 '"-ma


images <:l
:;::
2 Deficient 9 6 8 80 H .T .. K.M .,V.I.,and L.D to H. L 4/ 15/99 >
z
Java skills Jttc nd trai ning course begin . ~
IT'
ninS 1/5/99 at Ultra T rai ning :;::
m
Corp. obtai n Java level 2 ~
certl nca tio" by 3/ 1/99 and -m-
"

leve l 3 ce rt ifica tI o n by 4/ 15/99 ~


-
:;::
3 Alan Gray 3 7 9 288 Susa n Ferns to In Sp t::Cl all of SF. Continual -~
a
maybe Ala,,'s work z

pulled off ~
th is project :r
IT'
o
C
C
• • • • • • • • • • • • • • , .. - Z
->
C>

Z
FIgure 8_32 sample risk analysis for Encounter case study o

~z
-
a
CASE STUDY; ENCOUi'ITER PROJECT MANAGEMENT PlAN 195

kader, on a chcdule to be determined by the and eve n if they are, we do no t know ho w lo ng it


manager o f QA . Will take to come up to speed. ThiS co uld dama ge
the project irreparabl y.
• ••
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 5.5 Project Closeout Plan
be reported to all project personnel and managc .
ment , regardless o f the plan in th is document. 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


Here is where we describe the process to be
used (waterfa ll , iterative, etc.).
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 6.1 Process Model
performed adequately by a team whose Java Th e first two versio ns of this project wi ll be executed
skills have deficiencies. 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
Figure 8.32 shows a format for risk reporting
The seco nd iterati o n will result in versio n I of
and retirement. Each project meeting i to have an
Encounter. The number of subsequent iteratio n
agenda item for risk identification brainsto rming and
and the naruro of versio n 1 arc to be decided afte r
reporting o n risks that have been identified.
the custome r has witnessed a dcmo nsrratlo n
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, 6.2 Methods, Tools, and Techniques
superimposed on backg ro und image . No o ne in
the team has experien ce with placing th e im age o f a The Encounter projec t will usc Rational Rose™ for
character against a backg ro und witho ut carrying a design and will be Implemented In Java O bject.
rectan gle alon g with th e c harac ter. We do no t O rientatio n is to be used thro ugho ut. Javadoc wlil be
know whether th i is easy , difficult , o r impossi bl e used fo r documentatio n as mu h as possible (sec the
to do. SR fo r this requireme nt) Refer to ectlo n 2. 1
Ri sk N2: "De fic ie nt Java skill s" indicates the (process model) fo r a de cripti o n o f the process.
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 6.3 Infrastructure Plan
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 The En o unto< team Will reqUire model 9 1234 P s,
With th is. W e do no t know whethe r th e ca pabil it ies Internet access, 100 G il torage o n FeliX. and the
that our cu, to me r ha in mind are doable wlthJ ava , Ajax team co llabo ra tio n applicatio n upport.
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.


<i'ts f the aut hor<' comm nl<
6.4 Product Acceptance Plan
ECLIPSE DOCUMENTATION
" Ianageme nl and "We, lo r re pro,c ntat lves will r,nal-
T he ho me page for "pse documentation IS at
Ize acccp tan e c ntena ' \fit hill three weeks or proJcc t
start A cp t. " cc tests w il l take p lace a t the M e ht tp j/www.ecli psc.org/eclipseh ndex.php "docu-
me ntati on .' T h iS ",eludes use r manuals Documen -
office with", a wcek of the proJect comple tio n date .
tation IS classified as a subprojec t in Itself

7. Supporting Process Plans


Note to the Student:
Documentat ion is so substantial that it is
designated as a (sub )project unto itself.
Thi s section references plans supporti ng pro -
cesses that span the duration of the software
project such as the SCMP, SVVP, a nd SQAP. ORGANIZATION OF THE ECLIPSE PROJECT

The Eclipse project conSISts of several 'Top-


8. Additional Plans Level Projects_" A management committee is
respo nsible fo r each of these . Each top-l~eI
N o ne project consists of several (non -top-Ievel)
projects. Each project has a project lead, the
project p la ns, a nd the developme nt team _The
8.5 CASE STUDY: PROJECT MANAGEMENT developmen t team consists of developers and
IN ECLIPSE "committers." Only the latter have the author-
ity to comm it artifacts to the baseline_ These
The material In thi s section is quoted , edited , or
are explai ned later in th is section . This is
adapted fro m the Ecl ipse Web sites as the y existed at
largely special to open source projects.
various pOints In time. It is no t a formal SPMP but
rather a descript io n of h ow projec t m..na gement is
Sec Figure 8.33 for the project tructure_

Proposed Eclipse Project Structure and Roles

Top Level Project A Top Lovel Project B Top Level Project C

Project 1 Prole~ 2 Project 3 Project Management Committee (PMC)

ProJOC'Ilead Development Toam Subsystem(s) Project Plan

Comm.nors T""
lask2
T.... 3

Figure 8.33 EcJJpse proJeC1-ploposed structure and roles


SOtNce: Ed.pose Protect. hltp'J IWWW ecJ~ org.IOr'gIOOCuIllE ntslECllpseS2(C s 'llocltnentYa2OProceS$1It202OOJ~ t 1_OK2QF~pdf
CASE STUDY: PROJECT MANAGEMENT IN ECUPSE 197

CHARTER FOR THE ECLIPSE TECHNOLOGY small , informally structured prOjects that add new
(TOP·lEVEl) PROJECT capabl),ties to the Eclipse software b.se (l ncub.tors
Stream). fos ter gre.ter communtty .w.reness and
underst.ndlng of Eclipse (Education Stream). or
The "Eclipse Technology Project" diflers ITOm
explore researc h ISsues in Eclipse -re levant dom.ins
the "Eclips.... Project." The following document
uc h as program m"'g I.nguage , tools, .nd develop-
includes a description of project management
ment envlfo nments (Rese.rch Stream). The Eclipse
in Eclipse. It is fou nd .t http-Jlec1,psc .org!
T echno logy Project IS Inte nded to :
technology/ technology -ch.rter.html and h.s
been reform.tted and .nnotat .... d by the author.
I . Provide the o pen source commun ity with a
As described below, • project can migrate from
lighter-weig ht .Itern.tlve to the I.rger scale,
being an "Eclips.... Technology Project" to be-
more strucrured development activities carried
ing an .. Eclips .... Project: This "ch.rter" docu-
out by othe r PMCs, .nd
me nt mainly d .... cribes organization .nd
manag.... ment. Without committing this kind 2. C rea te o pportu nitte for rese.rc hers, ac.de mlcs,
of thing to paper, there would be little c hance and educators to playa Significant ro le Within
of a successful outcom ..... the Eclipsc com munity

overview Scope

A "Scope" seClion in • docume nt often refers to


This is a good overview. It includes the overall
the scope of the document itself, th.t is, the
motivation lor the project and, as with.1I good
exte ntth.tthe document is intended to cover.
overviews, does not attempt to provide com-
Th.t is not the case here _ This section de-
ple!e descriptions. It starts by providing the
scribes the scope of the .ctu.1 Eclipse Tech-
motivation for Eclipse.
no logy Project .

The Eclipse Tec hn o logy Top-Level Project


The scope of the Eclipse T ech nology Project
(the ' Eclipse T echnology Project") is an o pen source
Will encomp. s a Wide v.nety of small prOjects rather
sofrware researc h and development proJec t. whi ch
than a few large o nes. Although .ntlClp.tln g e no r-
encapsulates three related activity streams. each of
mous diversity In the coment of these aClIvitle , from
which is based o n or uses the Eclipse Platfom, andlor
a process·oriented viewpoin t the y will all share
Eclipse Tool s: important common characteristiCS, which argues
(or a commo n management envelo pe:
I. Academic research projec ts and o ther explora-
tory investiga ti ons ("Research Stream'), • Focus on pr<compe titive development .nd rescarch
2_ Development of educational matenals , tNc hing
" Use of inform.1 development processe
aids • and courseware ("Education Stream"),
• Fluid projec t track ing due to frequent pl.n hanges
3 Incubati on of smail -sca le . innovative platform
and tools projects ("Incubators Stream"). " Flexible mdcsto nes that adapt b.sed o n partial
results
MiSSion • Sma ll teams

The mISsion of the Ec),pse Te hno logy Projec t IS to • Rcsour e comm itm e nts te ntalt ve, due to vol unte~r
pruvlde a ho me With", the Ec),p>c Foundat io n for labo r o r la k of ponsor funding
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 rCl110vtng ob,r" 1«, so lVIng problem" and resolv.
o ther E Ilpse Foundation Proje ts ing conflIcts.

• Ensunng that prOjeL t plans arc produced.


n,e Eclipse T ec hno logy Pmjt t serves as a
inSIe pOint of fo us for such teams, and provides • WorklnS WIth the Eclipse Management Organlza .
the m wit h a h o me wllhin the Echpsc commuI1Ity tion (the EMO ) to c'tabhsh the development
. In man y cases uccessful Researc h Projects wi ll processes a nd infrastructure nceded for the devd.
evo! c into IOcuintor I and Incubator.-. in turn ma y opment team to be errective
migrate to oth er Projc 1 ManJgcmcnt 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 . . . Documents should explain abbreviations lhe
Arst time they arc introduced, like lhis, but
also include them in a glossary SO that the readrr
project Management Committee
knows where to look for an explanation. 1ne
reader is expected to know the meaning of "the
This section speciAes the Eclipse project man· Eclipse Management Organization: This is
agement by specifying the responsibilities of normal , the project management for a softw~
the project manageme nt committees. developme nt effort typically reports to a higher.
level person or body within the company.

The projects under thi s c harte r are managed by


a group known as the Project Management Com· • Reco mmendin g new projects to the EMO .
mittee PMCs are expected to e nsure that,
• Recomme ndin g the initial se t of project commit·
ters for each new projec t overseen by the PMC,
• Each projec t opera tes effec ti vcly by providing
and e tabl ish ing the procedures consistent with
leaders hip to gUide the project's overall direc tio n
thi s charter for votin g in new committers.
and by removing obstacles , solVing prob lems, and
resolVing conAlcts. • H elping to ensure that the projects overseen by the
PMC have e nough contributors, and working to fill
• All project plan s, tec hni cal documents, and repo rts
vacancies in role .
are publicly available.
• Produci " g "how to get involved' g uidelines to help
• All projects operate usi ng o pe n source rules of
new pote Atia l contributors get started .
engagement: meritocracy . tran sparency , and
open panicipation . These principles work to · • Coordinating rel ationsh,ps with other Eclipse
gether. Anyone ca n panici pate in a project. This Foundation Projects.
ope n Interaction, (Tom answerin g questions to
• FaCilitating code or other donations by individual
repon ing bugs to makIng code co ntributions to
or companies .
c reating dcsig n~, enables everyone to recogni ze
and utilize the Contribut ions. • 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 (This IS the overall controlling body for
projcctJs overall direction in a manner con~i s t e nt Eclipse.)
with the Eclipse FoundatIon Architectural Roadl11ap.

• Providing assistance and <upport to the developers regarding contributio ns proposed under Ilcensrs
and rescar hers workIng o n the prOject by other than the 'tandJrd .,., ,,,..d by EcI,p5C
CASE STUDY: PROJECT MANAGEMENT IN ECUPSE 199

• Working Wifh the EMO and committers to ensure monitor the main roject mailing list and the devel -
that in-bound contributions arc made in accord- opor mailing lists for all projects and components
ance with the Eclipse Foundation IP. they are overseeillg.

(Jntenectual Property) Roles

Policy. Many roles in an open source development are:


typically different from commercial develop·
• Acting as a focal point for the community in ment roles. They depend on volunteers and
re:p=enting the projects it oversees. not paychecks. For that re:ason, there: is In-
creased potential for participants to come and
go. This document de;cribes policies to deal
Since Eclipse is open source, this documenta. with this.
tion has to include procedures that ensure the
continued existence and health of the Project
Management Committees (PMCs) themselves. The projects under this charter arc operated as
meritocracies: the more you con tribute , and the
higher the quality of your contribution , the more
The PMC lead is appointed by the Board. The you are all o,,'ed to do H owever, with this comes
initial PMC is selected by the PMC lead. Thereaher, increased responsibi lity.
to become a member of the PMC, an individual must
be nominated by another member of the PMC and Users
unanimously approved by all PMC members.
In the unlikely event that a member of the PMC Users are the people who use the output from the
becomes disruptive to the process or ceases to project. Output will typicall y consis t of software and
contribute for an extended period, the member research . Software in this context means intellectual
may be removed by unanimous vote of remaiOlng properlY in electronic form , including source and
PMC members. PMC members may resign at any binary code , documentati on, courseware, reports ,
time by delivering notice of their resignati o n to the and pape~ .
PMC lead.
The PMC is responsib le for produci ng and Developers
maintaining the project charter. Development
must conform to any rulcs or processe outlined in Users who conrribute soft\vare or research become
the charter, so a change to the development process developers. Developers are encouraged to partici -
may necessitate a change to the charter. C hanges to pate in the user newsgroup(s), and should monitor
the charter are approved by the board the developer mailing list associated with their area
The work of the PMC is shared by the PM C of co nrributi o n. \XIhen appropnate, dc velope~ may
members. All PMC member arc expectcd to con- also contribute to development desig n discus io ns
tflbute actively In particular. PMC membt-rs arc related to their area of conrnbution. Developer are
expected to take responSlb"ity for overseeing crtain expected to be proactive In reporting problems In the
areas of work in the project, and reporting to the bug tracking system .
PMC on these arcas.
Active participation in the user new<group and Committers
the appropriate developer ma"IOg lists IS a responsi ·
bllity of all PMC members, and is critica l to the Develope~ who gIve frequent and valuable ontnbu ·
~ccc~s of the project. PMC members arc reqUired to tions to a project , or compo nent of a proJcct (Ill the
200 CHAPTER g PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II ESTIMATION, SCHEDULING, AND PLANNING

ca,c o( large proJcct,), an h,ve Ihelr 'talll' promoted omm llleT> arc reqUITed to monitor the devel·
to that o( J • (1II1mIIlC( for that project or omp!}nenl op r m.dmg Ii t .<soc,ated With all prOjects and
~,p<'t.tivcly A comnllllcr h", wTite access to the sou~e compo ncnts for which they have commit pnvdeges
de repo>l tory (or the .«ocIJted proJcct (or o mpo· ThiS 1<" ond ltJon of being granted <.Ommit righi, to
nem), and gall" votlllS rights allowlnB them to affect the prOject or component. It IS mandatory bccau~
the fu t\J~ of the proJcct (or compone nt). commltters must participate in votlllg (which In
orne ca,es reqUIres a certam minimum number of
votes) and must respond to the mailing list III a timely
The followlIlg par<lgraph describes a formal !-ashion in order to faCilitate the smooth oper<l"on of
process , which is e senllal to the smooth the project. When a commille r is gr<lnted commit
running of the Eclipse project. rights he or she will be added to the appropnate
mailing !'sts. A com mitter must not be unsubscribed
In order for a developer to become a committer from a developer mailing list unless theIT aSSOCiated
o n a particular project overseen by the PMC, another commit privileges are also removed .
comminer for the some project (or component as Commirters are required to track, participate in,
appropriate) can nominate th,t developer, or the de· and vote on relevant discussions in their aSSOCiated
veloper can ask to be nominated. Once a developer is projects and components, There are three voting
nominated , the committers fo r the project (or compo· responses: + I (yes), - 1 (no, or veto), and 0 (abstain).
nent) will vote. If there arc at least three positive votes Committers are responSible for proactively
and no nega tive votes, the developer is recommended reporting problems in the bug tracking system ,
to the PMC for commit privileges. If the PMC also and annotating problem repons with status informa·
approves, the developer IS converted into a comminer tion, explanations, clarifications, or requests for mo~
and given write access to the source code repository for information from the submitter. Committers are
that project (or component ). Becoming a commincr is a responsible for updating problem report. when
privilege that is earned by contributlllg and showing they have done work related to the problem .
discipline and good judgment. It is a responsibiliry that
should be neither given nor taken lightly. projects

The work under this Top · Levei Project is further


A good management document anticipates organized into projects. New projects must be con·
negative circumstances like the following . siste nt with the mission of the Top. Level Project, be
recommended by the PMC, and conRrmed by the
EMO. Projects can be discontinued by decision of
At times , comminers may go inactive for a
the board.
variety of reasons. The decision.making process of
When a new project is created, the PMC
the project relies on active commincrs who respond
nominates a project lead to act as the technical
to di cussions and votes in a constnlctivc and timely
leader and nominatcs the initial set of commit~rs
manner. The PMC is responsible for ensuring the
for the project , and these nommatlons arc approved
smooth operation of the project. A committer that is
by the EMO . Project leads arc accountable to the
disruptive , docs not participate actively, or has been
PMC for the success of their project .
inactive for an extended period may have his or her
commit status removed by the PMC.
Active participation in the user ncwsgroup and Project Organization
the appropnate developer mailing Ii ts is a responsi·
bi lity of all committers, and is critical to the success This section describes the o ....niDliun of
of the proJect. Committers Jre required to monitor projcclS within Eclipse,
and contribute to the use r newsgroup
CASE STUDY: PROJECT MANAGEMENT IN ECUPSE 201

G"oen the fluid nanu'e of EcI ,p<e Te hno logy report, and papers, coursewarr, downloads o( reo
Projects, organozational c hanges arc possible , in par. lease" and thIS c harte r.
t,cul • .., d,viding a Project into components; dividing a
Project into two or more independent ProJect . and o General Mailing List-Ma,ling list for develop·
merging t"'o or more Projects into a song Ie Project. In ment dl scu sions pertaining to the project as a
ea h case the initiative for the c hange may come whole or that cross projects Th is mailonB list IS
either fro m within the Project or from the PMC , but open to the publoc.
the PMC mu t approve any ch ange, and approval o Project Mailing List-Development maili ng list for
must be confirmed by the EMO. technica l di scussions rel ated to the project. This
If a project wishes to di vide into compo nents, mailing lost is ope n to the public.
commit privileges arc no nnall y gra nted at the com .
ponent level , and the committe rs fo r a given com . o Compone nt Mailing List-Development mailing
ponent vote o n issues specific to that component . list for techn ica l di scussions related to the compo ·
Components are established and discontinued by the ne nt. This mading li st IS o pe n to the public.
PMC When the PMC creates a component it ap·
points a component lead to ac t as the techn ica l The Development Process
leader and names th e initial set of comm itteTS for
In this section, the phrase "release cyde" wi ll refer to
the component. The compone nt lead is designated
a signiri'cant block of project activity , which corre ·
as a committer fo r the project and represents the
sponds to an ac tu a-l rel ease cyele in the case of
component in discussions and votes pertaining to the
incubators or Education Projects , o r to a majo r stage
project as a whole. Component committers do no t
of a phased Research Project.
participate in votes at the level of the project as a
whole, unless they are also the component lead .
In cases where new projects are be ing created , This assumes an interactive development pro·
either by splitting or by mergi ng , the usual proce· cess. However, each iteration is actually released,
dures as set forth in this c harter are fo llowed . In and so must be a usable version of the product.
particular, developers will not necessanly have the
same rights after an o rganizatio nal c hange that they
enjoyed in the previous strucn" e . Each project lead must produce a development
plan for the release cycle, and the development plan
must be approved by a majority of committees of the
project. The plan must be submitted to the PMC for
review. The PMC may proVide feedback and advice on
This section is a useful checklist for most the plan, but approval rests with the p,oject committees.
softwao-e projects.

The document mandates he re that each project


The PMC works with the EMO to e nsure the provide a requirements document. It would
required infrastructure (or the project. The project have been better to be more speCific about
tnfrastructure w,lI ,"elude, at monimum: where such documents arc deployed : it is not
easy to And Ectip e requirement docume nts in
o Bug Database Bugz ilia database for trac kin g bug< prac tice, and It Is questionable that they exist in
and feature requests many cases. Even for non ·open source project ,
It an be dlmcult to understand the extent of
o Source: Repository - One or more V reposi to ·
doc ume ntation . This IS sreatly larifled wilt'n
roe, COntalnin/! all the ~oftware for the projec ts
an organization stondardi zes o n documt'nt a·
o Web Ile- A W eb \lte Will onta in in formati o n t'on types (e.f( ., selected IEEE ta ndards).
about the proJect, In 11Idlll~ docum e ntallOn,
202 CHAPTER 8 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT II" STlMA TlON, SCH DULING, AND PLANNING

EJLh proj t mll<l ide nt lly , and make , vailahle


Th" docume nl docs not eS labllsh quality
0 11 Its cb .. he , th e rcqulrc mcnl C:; .1nd pnontl zall ul1l.i
goal As a resull, there ,s s'gn,hcant vanatlO!>
it i \ orking al't' II'\! ,n the curre nt re i , e cy Ie, In
in the qua li ty of Edpse prOjeCIS, A commer·
addll,on , each proJe l n""t PO,l J release p lan
c ial e fforl would be ",uc h more , pc(.,nc ,n this
sh o wll1 g the date and co nt e nt o f the nex t major
res pel. L
rel ease , in ludlng any mJJo r mdc .. to ll c!t. and must
kee p this plan lip to date
T h e o mm itters o f a prOjec t o r compo ne nt All development techn,cal diSCUSSIOns are con·
d eCIde whic h hanges ma y be o mmittcd to the ducted u Ing the development mailing lists, If d,scus-
m" tel' code hase o f a project o r compo nent , respec · sio n< are held offl ine, the n a summary must be posted to
ti vely Three + I ("yes" votes) \Vllh no - I (" no" votes the mailing list to keep the o ther comminers informed.
or vetoes) a rc needed to approve a code hange,
Vetoes must be fo ll owed by an exp lanati o n fo r the Licensing
veto within 24 ho ur or the veto becomes invalid , All
vo tes are co nduc ted v,a the devel oper mailing list All co ntribut,o ns to projects unde r this c h arter must
assoCia ted wi th th e prOjec t o r compo nent. adhe re to Ihe Eclipse Foundation Intellectual Prop ·
Special rules ma y be eSlabli he d by the PMC e rty Po licy ,"
for prOjec ts o r co mpone nts with fewer than three Eclipse i o rganized into the Platfo rm , JOT,
co mmitters. For effiCIe ncy , o me code c han ges and POE subprojects as fo llows [7].
fro m so me contribut ors (e ,g " feature addit io ns,
bug Axes) ma y b e app roved in advance , o r ap ·
p roved ,n prinCip le based o n a n o utiine of the In describing the management of • projcct, it
work , in w hi c h case th ey may be comm itted Arst may be necessary, as here, to refer to particular
a nd c h a nged as needed , wi th co nnic ts reso lved by requirements or design issues. Otherwise, we
majo rity vote o f the co mmitters of the project o r try to separate project processes from require·
compo ne nt, as appli cable , ments , Requirements are not known during the
The master copy of the co de base mllst res ,d e Arst iteration of project management docu·
o n the projec t W eb site, where it is acce si bl e to ments but they do become known more during
all users , de vel opers , and c o mmitters, Committe rs subsequent iterations,
must c h eck the ir c h anges and new work into the
master code base as promptly as po sible (subject to
any c heck · in vo tin g rules that ma y be in effec t) in Platform
order to fosler co llabo ratio n am o ng widel y di stri ·
buted gro ups and so that the late t work is always 'The platfo m, project provides the co", frameworks
availabl e to everyo ne , The PM C , responsible for and services upon which all plug . in '"-xtensions are
workin g with the Eclipse Foundatio n to establish a created . It al 0 provide the runtime in which plug ·
release e ngi neering and build process to ensure that ins are loaded, integrated, and executed. The primary
builds can be reliably produce d on a regular and purpose of the platfom, subproject" to enable other
frequent basis from rhe ma ster code base and made tool developers to ea ily build and de liver integratro
available for download from the projec t Web si te . tools."
Builds in this context are intended to include not
only code but also reports , documentation , and JOT
courseware.
Each project is responsible for establishing test "The JOT (lnlHl Droclopm(nl Tool ) proJcct provides the
plans and the level of testing appropriate for the tool plug. ins that implement a Java IDE Sl'pportil18 lhe
project , developme nt o f any Java applicatIOn, IOciUdlO8 E II~
CASE STUDY: PROJECT MANAGEMENT IN ECUPSE 203

"I<I8"ns. It adds a Java project nature and Java


p"rspcctive to the Eclipse W orkbench as well as a A method of prOViding some shon·t¢rm doc·
number o( views, ed,tors, wIzards, builders, and code ument history.
lI1~rg,"g and refactoring tools. The JOT project
allows Eclipse to be a development envIronment (or
itself.' PI,as, smd com",mls aboul Ihis drafl p"'n 10 Ih,
ecl 'pse·[email protected] d",t/op<r mailin9 li" .

POE
As an application, Eclipse has f,al1ms . As a
'T he PDE (Plug.I" Dwt/opmrool En voro"mnl l) project platform, Eclipse has to have an API stl, a
provides a number of views and editors that make means for interfacing with il (or programmers
is easier to build plug . ins for Eclipse Usi ng the POE, extending It.
you can create your plug·in manifest file (plugon
xmll, specify your plug· in runtime and other required
plug·ins, define extension points, including the or Thos document lays out the feature and API set
specific markup, associate XML Schema files with for the next feature release o( Eclipse aher 2. 1,
the extension point markup so extensions can be designated rel ease 3.0 (Why Eclipse "3.0") .
validated, create extensions on other plug.in exten·
sion points , etc. The POE makes integrating plug·ins
easy and fun ." A hyperlinked table of contents like the fol·
These subprojects are further decomposed . For lowing is useful. Notice the emphasis here on
example, the Platform subp roject is broken down deliverables and schedule, expressed in the
into componen ts. Each component operate like a first item .
project unto its ow n, wi th its own se t of com m it·
ters, bug catcgorie5, and mailing lists. These are as
follows [8], Release deliverables

Release milesto nes


Project Name DeSCription
Targct operating environments
AnI EclipsclAnt integration
Compatibility with previous releases
Compare Universal compare facility
Eclipse Platform subproject
• • • •
Java development tools UDT) subproject
Plug·in development environment (POE)
DRAFT PROJECT PLAN FOR ECLIPSE subproject
RELEA.SE 3,0

The following is excerpted and quoted from the This part is a seop" statement. It also specifies
projec t plan for release 3 of Eclipse [9]. It provides the management of this document and pro·
an example of a specific project plan when compared vides an overview.
with the c harter
LAsI rwistd Friday, J.nuary 30, 200< (' ",arb
1.lmsli09 chan9cs IInC( Ih, prtOIOU S drnfl of Oclob" 27, Plans do no t materialize Ollt of nowhere, nor are
2003 ) . they entirely stiltic To ensure that the plannong process
CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDULING, AND PLANNING

I tran<po",nt and open to the en tire E itp<c commu · WIth the preVIOllS re lease as the starting pOInt,
nlty, we (the E Ilpse PM ) po t plans In an embryo nl !his i< the p lan for how we wi ll enhance and Improve
fOnll and revise them dl roUg holl t the release cy Ie It h xinl! bUf(s, imprOVIn g te<t coverage, documen ·
ta tt on , example , performance , usab tl lty, and so on ,
are conSIdered routt ne o ngoing mainte n an~ aCTivl '
PM:: = Project Management Contmi[t",e .
tic, and are not Includcd In thIS plan unless they
wou ld also invo lve a SIgn Ifi cant c hange to the API or
The Irs t part of the plan deals with the impo r. feature set, or involve a sig nificant amount of work.
tant matte rs of re lea c deliverables, release mil e· All interesting (cature work IS accounted fo r in thIS
stones, target operatin g envi ronments. and release- pla n.
to·release compa ttbility. These are all things that
need to be clear fo r any release, even if no featllre
This provides more on the sCOp'" of thIS docu·
were to change.
ment. The activities listed are cODsidered
The remainder of the plan consists of plan items
"mainte nance: covered in the last pan of
for the various Ecli pse subprojec ts. Each plan item
this book . A three · part scheme for require·
covers a feature o r AP I that is to be added to Ecli pse,
ments priority is used , with the added ore·
or some aspect of Eclipse that i< to be improved. Each
jected" category. This merely k","'P' track of
plan ite m h as its own e ntry in the Eclipse bugzilla
requirements that were proposed at some
database, with a title and a concise summary (usua lly
point .nd rejected.
a si ngle paragraph ) that exp lains the work item at a
SUitably high e nough level so that everyone can
readily understand what the work item is witho ut The c urrent status o( each plan item is noteel
haVi ng to understa nd the nitty ·gritty detail.
Committed plan item A committed plan item
is o ne that we have decided to addr""s for the
Note that, in place of a detailed requirements
release .
document, the detailed requirements are effec·
tively provid",d via the Bugzilla database, where Proposed plan item-A proposed plan item is
there is no real distinction between required o ne that we arc considering addr""sing for the
fearur"" and a bug in what's been implemented. release. Although we are actively inves:igating
Bugzilla is an open source defect tracking appli· it, we are not ye t in a position to commit to it or
cation. 5<-e httpJlwww.bugzilla.org/. A refer· to say that we won't be able to address it. After
",nee on Eclipse's specinc use of Bugzilla is at due conSidera tio n, a proposal will either be
httpsJ/bugs.eclip"".orglbogsldocslhtml committed, deferred, o r rejected.

Deferred plan item A reaso nable proposal


• • • •
that will not make it in to this release for
orne reason is marked as deferred with a brief
no te as to why it was defellcd. Defellcd plan
A seri"" of dots, as her", (an "ellipsis), indicates items may resurface as committed plan item at
that the .uthor omitted material from the a later point .
original in the inrer",st of brevity. The activi · Rejected plan item Plan items that were pra-
t;"'s listed in the next paragraph are consid",red posed but judged unworkable are marked as
Nmaint",nancc: the topic covered in the last rejected plan items, with an accompan ing Slun'
p." of this book, mary of why they were dlsml sed. Keeping tT3Ck
of rejected Items avoid, repeatmg the di. ion.
CASE STUDY: PROJECT MANAGEMENT FOR OPENOFFICE 205

This is more or I~sstria8~ classiRcOflon ,


a 8.6 CASE STUDY: PROJECT MANAGEMENT
except Ihill ilems considered and rej~c ted FOR OPENOFFICE
are milinlilin~ lor reference.
The case tud y ,n thi S sectio n pro vides excerp ts fro m
the O pe nOffice pro ject management plan Fo r the
most pa rt. we will use the same headings as fo und in
Release oeliverables the offiCial O pe nOfnce docume ntatio n

The release deliverables have the sa me fo rm as


previous releases, namely ,
OPEN OFFICE PROJECT GUIDELINES
o Source cod~ release fo r EcI,p c ProJect, ava il able as
versions tagged "R3 0" in the Ecl ipse Project Note to the Stude nt:
CVS repository . n,e fo llo wing is take n fto m h ttp Jlwww.o pcn.
o • • • •
o fRce o tg/ d ev d ocs/guidel ine s. html . with
mino r editing. It is titled ' CUldelines fo r Partici·
Release Milestones pating on OpcnOfficc.org' and constitutes a proj·
ect manageme nt subject.
Release milestones occurrin g at ro ughl y six· week
intervals exist to facilitate coarse ·grained plann ing
and staging . The milestones are as fo llo ws. OpenOfflCe.o rg IS an open source prOject
th ro ug h which Sun Mic rosystems has relea ed the
tec hno logy fo r the S t a rOffice!T~" prod uc ti Vity <uite
Sun spo nsors a nd part iCipate on O penOfnce o rg;
There is an attempt here to pace milestones at CollabNet hosts and helps manage the project The
regular intervals to facilitate regular communi· overa ll name 01 the Project is OpenOffi e o rg, as is
cation . Oth~rwise, long gaps wo uld occur in th e name of the oftwa re product.
which no communication is guaranteed, which O pe nOfflCe.o rg's ma on features Include the
is undesirable . fo llo wing ,

• Downloadab le sources and informa tion


o Friday June 6, 2003-M ilesto ne I (3. 0 M I ), stable
build reflecting progress • Commun ity and commun i allOn mcc harllsms,
such as mailing lISts and fo rum
o Friday Jul y 18, 2003-Has been tested and vali ·
dated In the targe t o pe ratin g co nfig ura tio ns Ii ted
O pe nOffi e.org has cstabli hed the necessary
below.
fac dot ies to make thi S open ·sour e tech no logy ava" ·
o
• • abl e to all inte re<ted pa rti ci pa nts. Pnnclpa i projec t
objecti ves a re a fo ll o ws,

o Es tabl IS hm e nt of open, XML· ba<ed standards fo r


The remainder of the mat e rial at http ,llwww. of Ace p rod uc ti Vity fi lc fo rm ats and la nguage ' lIldc ·
ecl ipse .org/ec I i p se/deve I0 pmen tl ec Ii pse_ pe nde nt bind"' gs to compo ne nt AP I.
proj~c,-plan_ 3_0 . html c onsis ts o f require·
ments, and are excerpt e d In C h a pter 18, th e • Ope n a c'\!!o to the source.' code: Vl a V ver-C; lon·
~quirements Analysl part of thl ~ boo k. 111 8 to e nanl e ",nova tio n for bUil ding the next
or
~c n cra ll o n ope n-network pro du [lVll seNI C: '
206 CHAPTER 8 PRINCIPLES OF SOFlWARE PROJECT MANAGEMENT II. EST IMA nON, SCHEDULING, AND PLANNING

GOVERNANC E OpenO/A e participant: members, ckvelol'Cn,


and prOject leads . The e are explained next."
For a proprietary project, thIs would corre-
spond to a management section.
MEMBERS
penOfRce org I governed b), the Communtty
"Members" rders to those persons who have JOIned
CounCIl , which is constituted by member> from the
the project by regi tering WIth OpenOfficc.org and
Open fA e .org community . They creJled the charter
have a u ername A member may not have subscribed
establishing the ouncll ll,e Council holds penodic
to a mailing list, and a subscriber to a mailing list who
meetings by IRC a well as conducting business via
is uSing Ihe project may not have registered, only
discu [email protected] .org mail list. Both IRC
tho e who have regIStered arc members. It IS strongly
records and mail · ltst archives are public Agenda items
encouraged that all members joi n the general and
may be proposed by any member and should be sent to
relevant specinc prOject lists as well as joining a
[email protected] .org . For more informa-
particular project. Initially, one can only Join as an
tion, go to the Council Web ite.
observer, a role that allows one to contribute to the
The following ections describe guidelines
project and otherwise participate in it.
regarding technIcal roles and responsibilities at
OpenOffi e org and handling of source code. Sub·
stantia l enhancements or mod lAcations of these DEVELOPERS
guidelines need approval of the Communiry Council.
For guidelines on the protocols for proposing Written rules like these are essential for get-
projects 10 OpenOfflce.o rg , please sec Protoco ls for ti ng the job done. Without them, there would
Project Proposal. be c h aos a nd no OpenOfnce.

ROLES AND RESPONSIBILITIES Project members who give frequent and valu·
ab le contributions to a project can have their status
Everybody can help no matter what their ro le. The
promoted to that of a "deve loper" for that project. A
more a person gels involved in the project . the more
developer has write access to the ource code repos,
h e or she develops a trusting relationship with
itory . A "content developer" has write access to a
others. Those who have been long ·term and valuable
project's documentatIon but not to the source code
contributors to the project earn the right to commit
In order for a contributor to become a developer,
directly to the source repository.
another developer has to nominate that contributor
OpenOfflce.org respects the rights of its com·
The project lead may convert the contributor into a
munity to post messages and use the mading lists to
developer and give write acces to the source code
further the aims of the project. In fact , we cncour·
repository for the project.
age people to usc Ihe mailing lists. To this end , we
Al times, deveiopers may go inactive for a
will do our best to I,mil "spam" and to ensure that
variety of reasons. A developer who ha been In-
communication among community members I car-
active for six months or more rna lose his or her
ried out politely and efficiently . We have posted
status as a developer. In Ihis ase or if the value of a
some "Mai l·List Guidelines" that detaIl our
developer's contributions dimlllishe wTit~ access
I

commitment.
may be revoked by the responsible project lead.
A commItted change mu<! be reversed if thi
We would sute here something like the fol- requested by the =ponStble project lead or b the
lOWing: "There are several categories 0/ Commllnity Counetl or i" delegates and the condItions
cannOI be Immedlatelv salt ned by the equiv.>1 I1t of a
CASE STUDY: PROJECT MANAGEMENT FOR OPENOFFICE 207

'bug fu, commit The situation must be rescinded c harge o f. Any member o f the affected projec t may
bcfoit the cha~ can be included in any public release. 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
This belongs on a location whe~
Commun ity C ouncil IS requ ired to revoke project
ipOLi8c ruI~ lI~ gIVen for committing code to
OpenOIficf:. 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
project leads can be fo und in the Irs. of projects.
There are three main categories of public projects in
OpcnOfAce.org : SCHEDULE

• Accepted projects ("projec ts") See httpl/d,:velopme nLopcnoffice.orglre leaseslOOo_


2_0_timetable.htrnL
• Incubator

• Native-lang SOURCES

All accepted projec ts must have two leads. It is


up to each project to determine the actual cor.te n. of This section is effec tivel y a Software Configu -
the roles each lead will take o n . Nati ve- lang and ration Manageme nt Plan .
incubator projects may have o ne lead . Size and
complexity are the determining factors : a large proj - The codebase is mai nta ined in share d info rma -
ect requires two leads .
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
P,-esumably, the ~qui~ment lor two commit- Web fro nt end _
ted project leads minimizes the risk that a lead All sourc e cod e co mm itted to th e p roject'
becomes unavailable, thereby threatening the re posi to ries mus t be cove red by LC PL and S ISS L
health of the project_ This is a facet of risk Fil es in the rcp o itory must conta in a h eade r
management.
acco rdin g to th e O pen OfRcc.o rg te mpl ates (avai l-
able fo r code and makefi lcs). Co ntrib uto rs of
source code large r .h an s mall c ha nges must have
A project lead is res po nsibl e fo r givin g guid - sig ne d the JO Int copy rr g ht a sig nme nt fo rm before
ance and directions fo r his o r he r project a nd it part the ir co ntributi o n can be comm itt ed to the
in the OpenOffk e .o rg e ffo rt _ The lead es pecia ll y rep osi tory .
should make sure that q uestio ns abo ut his o r her Strai ghtlo rw ard patc hes and fea ture Impleme n-
project are answered a nd tha t a frie ndly and up - tat ions can be committed wi tho ut prior no llce o r
portive enviro nm e nt is c reate d . Co ntributio ns. mail- di scussio n. Doubt ful c hanges and large -sca le over-
list diSCUSSions, and fo rum inte rc hanges. as we ll .s hauls need \0 be d iscussed before comm itting them
is>ucs and other adminis tra tive duties should be into the re pository . An y c hange th at affects the
handled in a n e ncourag ing a nd pro du li ve fa hlo n. se mantics o f a n eXIstIn g API hrnc tion. co nfigura tI o n
Los o f project lead ~ t a tus may occur no . o nl y datal o r Alc fo rmalS o r other major arc3!t m us t re CIVC
due to contrtbullo n inac t iVIty (as descrtbed fo r de - a pproval A proJe t lead may Info rma l! ap prove
velo pers ) but a lso because o f m lSsrn g ful Alime nt of c ha nge< with in h,s or her project n,e re are .h ree
responsibilitIes fo r the projec t the project lead is 10 dIffe re nt ty pes of c han ges·
208 CHAP IER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGE MENT II ESTIMATION, SCHEDULING, AND PLANNING

Info Informational notice about an API


IOtO prac tice by a h ypothetical stude nt prOject
,
change; no developer action necessary,
Recommended Use the new API as soon as possible. team, using the Encounter case study as In
The old API is obsolete and might go example.
away In the near future. New code •
should always use the new API.
Required Not com plying with the new API will Before beginning the Software Project Man ·
break the build or cause runtime failure. agement Plan (SPMP), t he team met at least o nce to
Developer acbon IS mandatory.
diSCUSS the prOject in ge nera l te rms, a nd Ed Braun
wa elected a team leader. The configura tio n man·
This gives a grea t deal of d iscreti o n to project age me nt plan (SCMI') and quality plan (SQAP) were
leads. A more fo rmal process, involving more written.
people , may be Impractical for an open source
project like this. PREPARING FOR THE PROJECT PLANNING
MEETING
Proposal< for mterproject changes of type "rec·
Well befo re the mee .ing , Ed looked through the
ommended" or "reqUired' must be published wi th the
IEEE SPMP headi ngs (refer to Figure 8.24 ) for the
sugg"'ted change date to the interfucc d iscussion ,
major issues, and drafted material for each of them . in
mailing hst After o ne week of review, a change
t he cascoof the Encou nter vi deo ga me, he co nsidered
announcement mus t be published to thc interface
th ese to be the project o rga nizatio n (primary and
anno unce mailing list Dunng this announcement
backup roles, and their responsibilities) (Section 4.3
period, dependi ng projects have to prepare their
in Figure 8. 1), risk manage ment (5.4), and the sched·
projects fo r the changt-s so that t he fo llowi ng build
ul e (5.2 ). Ed also drafted a brief parag raph for
Will not break They are n..-sponslblc for reflecting th e
Sectio n 1.1 (project summaty ). He left the staffing
c han ge In th ei r proJect , no t the requester. W ithin the
plan blank (i.c., who nils what ro le) because he felt it
two weeks of diSCUSS ion/a nno uncem ent, project leads
best to have membe rs volunteer for roles at the
may ra ise a Aag, and project leads majority has to
meeting. He planned fo r th e remain ing issues to
deCide about ca ncellation o f the c hange requt-st.
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· i a .ec hnical task that requires sig nifica nt lead time,
agement of the OpenO fficc project. They arc and IS best done by o ne or at most two people.
not intended to be complete. 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.
8.7 CASE STUDY: STUDENT TEAM
H e included "attaining quality goals," "developin g
GUIDANCE
so met hing that the members ca n usc" (a favorite of
his), and "complete project o n schedule" as opt;ons
TI'l is section describes a hypothetical account of inter·
fo r thc top prio rity. He was pretty su re that the group
actions among students as they prepare and conduct a
project planning meeting, and guides students in would ag ree to a flat ro le · based o rgani za tion as
producing a Software Project Management Plan . d esCribed in ection 9 4, so he wrote this into the
straw man document.
8.7 ,1 Team Guidance: Steps to a Project V ia e· matl , Ed asked team members to think
Management Plan for Encounter about the ns ks that they consider threatening to
the project , and to send write -up to him 48 hours
Note to the Srudent: befo re ,he meeting, in the fom, of Table 8, 1 in
This section explains how the principles Sect ion 10.4 . Karen was concerned about the
explalOcd in this part 01 the book arc translated 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 209

lind d~crib"d this risk a speclRcally as she could . suggested . Hal pushed very hard for a buffer
She also ~searc:hed companies that provide o n-SIte week in which no tasks are assigned . Karen
training 3t short notice. Her step -by-step rIsk pointed out that no work hould be aSS Igned
~ti~ment plan was included in the malerial she during the week before the midterm . There was
sent to Ed. Hal Furnass had a concern about super- also a discussion of using a simple waterfall to
imposing images in Java , and he sent h is n sk avoid the compl, cat ,ons of revisiting document ,
identification and retirement write · up to Ed . The but thI S was dismIssed as not reRecting the real
latter collected these in the straw man SPMP, and world . Fern pushed for Incremental development
listed them in priority. because she wanted to begin coding as soon as
Ed then drafted the following agenda for the possible , but there was little support for this
m~ting . because the team did not even have architecture
Meeting to be held in Engineering 397 at 10:00 yet . Members felt that "quality" was an area they
a.m. to 11 :30 a.m. Friday, September I needed the most practIce with
Arter considerable debate about building an
1. Appoint record keeper and time keeper (5 min · eXCIting computer game, the team decided that
utes, 10:05) "the attai nment of the specified quality parameters"
would be its top priority. It ,",'as recog nized that a
2. Approve agenda and times for this meeting (5
minutes, 10: 10) quality ga me worth playi ng was ou t of the questoon
in the time available, and that the actual capabi lities
3. Review SPMP sections supplied by Ed (25 m in· would be have to be minimal. When the tea m arrived
utes, 10:35 ) at role allocation, Karen volu nteered Immediately for
the "design leader" role . There were three volunteers
4. Allocate remaining SPMP section to writers (20
for "imp lementation leader" and no ne for QA leader
minutes, 10:55)
Ed compromised by suggestIng that two of the three
5. Arrange review process (via e-mail andlor meet - people plit roles as QA and implementatio n leaders,
ing) (5 minutes, 1 1:00) switch ing halfwa y throu g h the semester. The other
• roles were filled , and Ed reminded them of their
6. Brainstorm for additional risks ( 10 mlOutes,
responsibilities , and of theIr addotional backu p ro les,
11:1 0)
as stated in the SPMP.
7. Rev iew action items (5 minutes, I 1: 15) The dis cussion of h ow to allocate the wflting
of the SPMP went over its planned I,mot , but the
8. Miscellaneous business ( 10 minutes, I 1:25 )
discussion was productive and to the point , so Ed
did not try to curtail it. It was de cided that on ly
Ed e -mailed the agenda and his straw man
two team members besi des Ed would write the
SPMP to the team members two days before the
SPMP , and the rest would reVIew their writing ,
meeting, and asked them to read it over before the
since ot would be too difficult in a <hort time to
m~ting . His version of the SPMP contained all of
manage more peo ple writing . After 10 minutes,
the IEEE headings .
the team found itse lf diSCUSSIn g very small eC'
tions, and Ed Cllt off di SCUSSIon , promISing to
THE INITIAL PROJECT PLANNING MEETING resolve the mall differences offline , and c · ma il
the two member concerned a dctaol ed allocatIon
At the meetIng , Ed asked Fern to re cord action of the sect ions The team deci ded that th e writers
ILems and major deciSIons, and asked AI to watc h would complete their sec tion s by Froday at 600
the time and remInd the team if It exceeded p .m ., and Ed would cre atc the d ocum e nt from
planned l,mits, It wa s unders tood th at the se two th ese and CIrc ulate th e results to the team b
roles would rotate among the members In futllr., Saturday at 3.00 p .m Everyo ne ,,, o uld prOVIde
meetings Most of Ed's Id eas were accepted . Sev. co mm e nt s to Ed b y unda a t 3:00 pm ., Jnd Ed
eral c hanges to Ed's proposed schedul e we re would take all of the<e co mm en t< Int o a count t
210 CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDULING, AND PLANNING

110allzc the do lIment A tcn tatl c meeting was se t weekly !Hne was selected which members would keep
for l ondo at II · 0 a m . In Arts 283 in C" C It was available, but would be used only If reqUired.
nece ory, and Ed was ta ske d wit h Informin!! th e
team by unday ni g ht at 8.00 p .m. w he th er the /
The case srudy contains material concemmg
meetinS wou ld be reqlllred or not.
liaison activtties. These are shown for illustra-
Fern reviewed the dcci ion made , who was to
tio n purposes, and would not normally be the
"'nrc what sect ions , and when the duc dales were ,
res ponsibility of stude nt teams. Some teams
The meellng adjourned.
mi ght want to designate a member as liaison to •

the instructor. Thi s is usua ll y best performed


COMPLETING THE PROJECT MANAGEMENT
by the team leade r. If the project has a true
PLAN
customer (i.e., the project is not just an inven·
tion of the team itsel f), then a liaison to the
In wrillng the document details, the team rea lized that
custome r would be required , the requirements
vanou issues had not been disQJsscd at the meeting,
leader wou ld normally ha ve this task. If the
Including th e deta ils of "mo nito rin g and contro lling"
projec t were an agile o ne, a customer repre·
(Section 5 3 in Figure 8.24 ) Hal's Init"! write·up of
<entative would be part of the team.
this section spoke or man y meetings at which the
project was to be reviewed , but most of the other
member< fe lt that many of the meetings were un · 8.7.2 Team Guidance Software project
necessary . After reading several propo als, Ed tned to Management Plan
resolve the c·mail discus ion by proposing that project
monitonng be accomplished at weekly meeti ngs, sup- Stude nt teams shou ld c reate a Sofeware Project
plemented by meeting at the inception of each phase Ma nage me nt Plan (SPMP) fo r their project using
(which he would try to fold into weekly meetings as IEEE Std 1058· 1998 as a template, the Team Guid·
well ). The team agreed. To allow for the possibility ance in the previous section, and the Encounter
that more project meet ings would be needed, a second SPMP in Section 8.4 as guidance.

8.8 SUMMARY

Projc:ct costS are estimated as early as prOject Ini tiation, well before the requirements arc defi ned. The earlier
the estimate is made the greater the margin of erro r, and we therefore use ranges as a way to calculate
estimates. For example, during c..onceptualizarion , co t estima tes ca n have a fou rfo ld estimatio n error,· afte r
deSign , a ewofold error.
Project eStimates are done by nrst fi nding something objective to measure , such as lines of code (LOC).
Since this is done before any code IS ...'ritten , the applicati on IS compared to the LOC of si milar or related
software produced in the same company, and the LOC of the new app lication is extrapolated fro m that.
Ano th er way to produce LOC is to compute f.II Clioli POilil' , which objectively measure the intended
fu nctionality of the new software. The function point calcu lation produces a si ngle number that is then
converted to lines of code using a standard conversion . Once LOC arc calcu lated, the COCO 10 model can ,
be used to compute an eHort estimate.
Agile projects can be estimated by the use of story points, whic h are assigned based on a compa ri on of
new stories to existi ng stories. For example, an average story 1S give n a score or 5, ilnd all new Slories art'
compared to that story. ,
Once an estimate is made, a detailed schedule is constructed that lists all the tasks, their duration, th.,r
dependence on each other, and the resource assigned.
EXERCISES 211

A ...
project
" plan is created that includ es aII prOject
. .m format.on
. ..ncludml!
. project
. organization , roles and
respons.b.Iot.es
. ' project estimate • sched U Ic, an d ns' ks . It aIso mcludcs
. references to such doc'Ument5 as
configurallon management , and verification and valodation plans.

8.9 EXERCISES

1. Describe in at least one paragraph at least two consequences of failing to develop a written project plan.

2. Suppose you are tasked with computing the numbcr of function poi nts for a small application .
Assume the application implements the following functionality measures, all of which can be
c haractcrized as having medium complexity:

- number of external inputs: 4


- number of external outputs, 5
- number of external queries: 2
- number of internal logical files : 2
- number of external files : 3
- Suppose also that the application has the following ge nera l characteristics:
- requirements backup, 0
- data communications: 0
- distributed processing: 1
- performance critical : 2
- hea vi ly utilized: 1
- online entry: 4
- multiple screens: 3
- master fidds: 3
- RIc inquiries: 2
- internal processing: 3
- reuse: 2
- conversion and installation : I
- multiple installations: 0
- change and ease of use: 5
Compute the number of function points for this application .
3. Cost estimation is important , but can you cite. circumstance under which .t is probably not
worthwhile performong at all? Explain yo ur answcr.
4. Give one major advantage and one major disadvantage to the use of function points on estimation

5. Ust a part of the SPMP that you r student tcam IS probably unable to supply at this stage of the project.
Th.s refers to a part you will have to return to after mo re work has Ix.'en performed on the prOject

6 Explaon why project planning is considered one of the phase in the software Io fe cycle and al 0 an
umbrdla act.vity that stretches acros several phases
212 CHAPTER 8 PRINCIPLES OF SOFTWARE PROJECT MANAGEMENT II: ESTIMATION, SCHEDUUNG, AND PLANNING

TEAM EXERCISE

SPMP

Develop a oftw.re Project Manageme nt Plan for YOllr project. Use (or tail o r, or improve upon) the
IEEE sta ndard, as shown ," the cas. srud y bel ow, Include at least two ite ratio ns ," the sche dule, Obtain
a roug h estimate of the size of the produc t,
Befo re you begi n, es timate the number o f defects per page th e team th inks it will discover during
its fIOa l revlc,,'. Keep track of, and report the time spent by individual members and by total team j
effort in the fo llowing stages: research , docume nt preparation , review (including inspections). Show
the actual defect density (ave rage number of defects per page). Assess your team's effectiveness in
each stage ," a scale of 0 to 10. Summarize in a narra tive, usi ng the numerica l results, and state how
the team's progress could have been improved . The team is encouraged to usc additional metrics if
they co ntribute to effec tiveness in this and future efforts.
Criteria: I
I. Degree of clarity o f the plan and addendum (A = very clea r writing; all specifics included,
especially of risk retirement)
2. Degree of realism of the plan and addendum . (A = sets realistiC goals a nd procedures (neither too
ambitious no r too modest»
3. Extent to whic h the plan and addendum include all relevant speCifics. (A = > 95% of knowable,
relevant specifics included)
4 . Exte nt to which the plan and adde ndum exclude irrelevant mate rial. (A = < 5% if details supplied
Irrel eva nt)
Usefulness of you r self·assessme nt.

BIBLIOGRAPHY

1.iJ<x'hm, Barry -Sojhm1rc EltglPlccnrtg EC01l0FfllCS, ~ Prentice Hall , 198 1


2 Albrtthl , A J, "Mea surmg Applicauo n Development ProductiVity: ProadrflJ' of fix )oi,,' SHAREICUIDEflBM APPOCIlII01f DtlJtlopst7ll
S1"'Posnlllt. Octo ber 1979, pp. 83-92
3. I nternatIonal function POlOt U sers Croup (D~cmbcr 1999) htlpj/~. ifpU8 org ( acccs~d November 15. 2009]
4 ·'Functton PO'"t Ungu.1ges Table VersIon 0 ," Quant ltiltlVe: Sohwilre: Management . Apri l 2005 hnpJIwv.'W q-s-m coml1q c rcsourccsl

5
funcllo n.polnt -Ianl!:'uascs-tablellnde:x.html {JccC'Osc:d November 15. 2009 }
jonc-s, Caper;, "Ap plied SojJIl,jj rf McalVfrI'Il"I1 Clobnl Alfo1 /y5IS oj P,o;/wCfl('nf)' a1fd Qwa/Jty,·' 3rd edLtLon, McGraw- Hill Osbome M~dl.l, lOOS ,

6 Dorfman , M , and R A. Thayer (ed'\: and contnbu lon.). "Software: Enslntc:rtn8." IEEE COIII~rtT SOC-IrC)', No,,~mbc:r 1999_
7 Ecl ipse:. httpJI""",,-w.c:c1tpse:org/cclipscli ndex php [acccmd December 10, lOO9]
8 Ec1tpsc. hnp,J/ww'W eclipse orglplatformlindex php
9. Eclipse. http IIwww.«lipscorw.C.CI I.... c/de:vdopmc:n tl«Jlp<;c_pro.tc~_ploln_3_0 hlml ,
uality and Metrics in project
Management
"

• How do you cultivate a quality


mind-set in a project?

• What are examples of project matries?

- The Software
• How do you use metries 10 improve
proJects?
Development
Life Cycle • What Is a software verification and
validation plan?

• What is a good example of a planned


verification and validation?

Figure 9.1 The context and learning goals for this chapter


Soft'wa re qua hty docs nOI come about by a ci d e m Achieving II Slarts by cu ltivolm g a quality culture
withm the prOject team . It also req uires careful plann ing and mo nlto nn g, with project manaKcrs continuously
asking ques lio n suc h as the fo ll OWing Ihro ug h o ut the h f~ of a projecl.

• Is the prOject on schedule ) Is it late)

• Arc too many defec ls being d , covered ) Too few )


21. CHAPTER 9 QUAUTY AND METRICS IN PROJECT MANAGEMENT

• Are dcle ts being Axed too slowly)

• I testing progressing at the desired pa~e )

Agile teams become adept at answeri ng these questions for tcam · level work. Continua l interaction wlth
the ustomer, short, mutually deAned spri nts, and con tinual testing mcan that questions like these arc being
continually asked and answered In the co ntext 01 the team and customer rcpre entative. On the other hand,
the scope of the project can exceed a single group, in which case various non .agile techniques a re applied a,
well.
As introduced in Chapter 2, the answers to these and si milar questions are provided by metrics, which
arc data collected and analyzed throughout a project.
Examp les of project metrics are dtftclS ptr KLOC (thousa nd lines of code), lilltS codtd ptr ",an-",onl/, (MM ),
and Irst case f'Xtcuti01f rale. Each provides an objective measure of a project and its processes. Metrics are an
important tactical tool of Ihe project manage r. They allow tho manager to continuously assess project quality
a nd c hedule, identify problem areas, and gai n Insights into the project that allow him o r her to make
proactive decisions to head off problems. As an example, if during the testing of the software an unusually
high number of defects are discovered in a particular soltware module, action ca n be taken to proactively
remedy the root cause, such as conducti ng a co de inspection, redeSigning the module, or executing unit tests.
Without metrics, it is difficult to know how a project is executing and the quality level of the software. Metrics
help

not only current projects but also future o nes. This is because future projects base metric targets o n pa.st
ones.
Targets must be established to effectively utilize the metrics collected. For example, if 50 teSt cases are
executed during the nrst week 01 system testing, is the testi ng team making good progress or poor progress)
The answer depends o n the test case execution goa l deRned during project planning. If the plan called for
executing 100 te t cases, then lhe answer is poor progress; if the plan was 20 teSt cases , then the answer is
good progress. This also aS$Umes a Standard for "test case." The goa ls are establi shed by analyzing metries •
collec ted during prior projects and using them as baselines.

9.1 CULTIVATING AND PLANNING INTERNAL QUALITY

T"'rmal quality rders to the quahty activities undertaken by the development team itse lf. Th is calls for
cultivating a quality culture among the development tcam , an attribute of good leadership. The essential goal
here is a sense of shared responsibi lity and pride amo ng the team members. Fundamental gai ns in a quality
attitude accrue when the project ieader continuously ensures that the work is very o rde rl y, and that the team's
effort 3_fC focused on appropriate: pri orities.
We plan for the management of a projecl and its internal quali ty assurance procedures at the same time.
Internal qual Ity procedures, standards, and habIts arc active throughout the project management plan , the
requ.irements, the design, and the code.
Exltm,,1 provision for quality is specified in a eparate set of documents, the quality assura nce plan, the
verification and validation plan, and the test documentation . The relationship of internal and externa l quality
activities is illustrated in Figure 9 .2.
The interna l management of quality is as much a mind-set as a document ct. It begin with a
ir
conRguration management plan that ensures con iSlc nl and 5.tlfe documentation. (For example, we were t'O
implement the wrong versio n 01 the design document, the code would not match the requirements for the
impie.mentation , and thus would hardly be a high-quality productl)
Most project management plans de ignate team member; with specific responsibilities. Table 9. 1 shows
an exampl e of respon ibility designation in which each member also has a backup responsibility. Each activity
PROJECT METRICS 215

Internal quality actIvItIes /


Plan pro/eci} Introduce continuous quality att~ude

Perform
reqUirements Include tests lor each requirement
analysis
-
Create
design
Include tesls lor each unit

Implement Perform unit tests


Perform Inspections
-
---"r ------------- - ------------ -- ----- --- -- -
Plan QA , V&V
"
External gualirt activities

Perform quality assurance


Perform system testing
-
Figure 9.2 Managing quality-internal and external activities to promote quality In projects

leader promotes an atti.tude of quality for his activity. The backup members can act as palf Inspectors for each
leader.

9.2 PROJECT METRICS

Proj'c1 ",,'rics are those that apply across the board or ha ve broad implications during a project rather than
being vety focused . The metrics process starts by identifying which mctries to collect . setting target goals for
each . and regularl y monitoring and reviewing them th roughout the project. Th is is described in detail in the
sectio ns that follow .

Table 9.1 Example of responsibilities for documentation, with backup


Name Primary Responsibility Backup Responsibility

Alice Jarman Team leader configuration management

Bruce Stern Configuration management security

Bob Crowder Internal quality Team leader

sarah Fournier Security Internal Quality

Hans Ughtman Requirements Release

Vladimir Norsk Design Requirements

John Green Implementation Design

Susan Klein Release Implementation


216 CHAPTER 9 QUAUTY AND METRICS IN PROJECT MANAGEMENT

9.2.1 Identification

DUri ng proje t planning, the metries to be collected are Identified . Some arc applicable to all phases (e.8.,
defect ) wh.le o the rs o nl y apply to a spec.fic phase (e.g, test case execution ). While there are many metric< to •
chose from . some of the most usefu l arc as follows [ I ].

• Project mile tones


• Testing progress
• Defect detection and defect injectio n per phase
• Defect resolutio n

\Vle discuss each of these next.

Project Milestones
A plan IS created early in a proje.c tthat contains a detailed schedule. including milesto nes, which are concrete
objectives that must be achieved at speCific times. A project manager monito rs the progress of a pmject
against these milestones to determ .ne whether it is on schedule. Project scheduling and the establishment of
milesto nes were covered in Chapter 10. The obvious metric here is the number of days between a milestone's
schedule and the day on which it was actually reached.

Testing Progress •
A test plan is usually constructed before any formal testi ng commences . It includes information regarding the
types of test cases to run and detailed information regarding each test case. The most common mctrics to )

collect during formal te ling arc the ralt oj ItSI cast t'Xtculioti and the )lumbrr oj passrd ttst cast'S , With these two
metrics, project mana gers ca n determine whether testing is proceeding on schedule.

Defect Injection and Detection
Defect metrics are probably the most common type of metric collected. Defects occur during each t
development pha e, but such defects may have been incurred (or "injected") during a previous pha...
The drJecr dclrcl'ion ratt is measured for a given detection phase and a given injection phase. For example, a
"defect detection rate of 0.2 per 100 requirements defects at the implementation phase· means that one defect
in the requirements is detected, on average, when implementing a set of 500 requirements . Figure 9.3 shows
an example project in which these data have been collected. It also shows the longevity of defects, phase of
injection vs. phase of detection. For the sake of simplicity, we have omitted the test and post.dclivety pha.ses,
which would complete the picture.
Let's focus on the detailed requJrements part of Figure 9.3. It shows that two defects per 100 were
detected during the requirements phase (assessed by means of inspections). This compares favorably with the
organization's norm of 5 per I00. looking across the "detailed requirements" row, we observe that our process
detected fewer than the normal rate of requirements ddects during subsequent phases. This seems to toll uS
that our project, and possibly the process we are using, is comparatively effective when it comes to producing
quality requirements. However, it is also possible that our detection process is worse than usuali This bears
investigation . To complete the table, we would include similar defect data collected during testing, and
during a specific rime (e.g., three months) after product delivety.
The results for d(Sign defects in Figure 9.3 are as follows . We detected more than the usual number of
design defects during inspections at the time they were injected, but recognized fewer design defects at later
PROJECT MElldCS 217

Defects detected,
-
Phase in whic h defect was detec ted
Per 100 requirements/per . •
in the design/per KLoC. etc. Detailed
This project/llonn requirements Design Implementation Deployment

Phase in which Detailed


defect was •
reqUirements 215 0 .5/ 15 O. I/O.l 3/ 1
- -
in jected
Design 3/ 1 IIJ 3/2
- - -
Implementation 212 sh
- -
Deployment 3/ 12
-
Figure 9.3 Examples of defect count-injection phase VS. detection phase

stages. Since it is more expe nsive to detect and repair a defect lalcr in the process, Ih, s indicates that ou r
project seems to be superior to the o rganization norms. Figure 9 .3 also con",ins Information abo ut defects
detected after deploymenl to customers , whic h is surely the most Im portant metnc In the end .

Defect Resolution
Tracking defect detectio n tells us the rate at which we arc fi nding defects. giving an indication of the qualtty
of the evolving product. Equally important is the met ric d,Jrcl rtSollllioll . wh ich measures the rate at which
defects are being resolved. Defect detection and defect closure arc complimentary . Fo r example . even If
defect detectio n is meeting o r beating the plan. if the defect resolution rate is bel ow plan . the backlog of ope n
defects increases and the qualiry and schedule of the project suffer.

9.2.2 Planning

Once the set of merrics to be collected is identified. a plan is t'Stablished with targets for each metTic. The be'St way
to derive targets is to use the metrics collected during previous projects as a baseline. adjusted as neces<;ary
Without projections based o n prc-vious projects, it is very difficult for project managers to kn ow whether a project
is meeting expectations. An example of a plan used to track dcf,rt d,lrclloll and d,Jtrt mollifioll is shown in Figure 9 4.
Figure 9.4 tracks the number of defects submirted and resolved weekl y versus the plan . Each week the
actual number of defects discovered is fi lled in and compa red wi th the plan . In this example. note that the
number of open defects for the first three weeks is g reater t han what had been anlicipated. At the e nd of week
3/ 10-3/ 16, 103 defects are open vs. a plan of 66 . Armed with thi s knowledge . th e prOject manager can take
appropriate corrective action Similar plans are c reated for each of the other melnes collected .

9.2.3 Monitor and Review

DUTlng the Ide of a proJecl it is a good Idea for key members of the project team to revlcw the metn cs
On a regu lar basiS, usually week ly . One good way to do this is for the prOject mana ge r to c reate a pa ke t
of IOformatlon co ntall"ng metfl cs c harts as shown In Figure 9.4 T h IS helps pre se nt th e info rmat IOn In a
GonClse format for eaSie r review . H owever, JUSt presenting lhe se oVervIew e h art 111 a nOt be enollg h
For example, in additIon to th e defec t pl a n ~hown In Figure 94 . ,ddillonal'llfo rm a ll o n ~lI h a detailed
218 CHAPTER 9 QUAUTY AND METRICS IN PROJECT MANAGEMENT

Build
44
45
46
47
48
49
50 20 TROUBLE!
51 10

5
o

Figure 9.4 Example of tracKing defect resolution-recognizing problems with defects remaining open

defect re ports ma y be Incl uded to better uncie"tanci the ou ree of the probl e m bei ng d is ove red If thIS
I ~ done fo r each of the mc-tn S Incl ud ed In the report , the amoun t of i nforrnalion Ciln become
ovcrw hclnlln g Al lh ough it I S sti li a good Idea to Include It all , I t is common to crC<ltc a umrn<lry,
so me t,me s ,n the form o f a pro),rt dn ,I,/'onrJ . A dashboard pre Cllt a co ncise , g raphical summary of
esse nti al InfOrmal lo n re ga rding the ge neral health of J project. Th is IS analogo l1 ~ t'o an automobile
d ashboard . wh ich co ntains gauge.:; slic h as fue l leve l, odometer, and engine temperature , (0 quickl y J
a crta ln th e ge neral S1aru and hc alth of a cor F'g ure 9 .5 shows an examp le dashbca rd from the

PROGRESS
PRODUCTIVITY

E... , 1 ~ V~
(8CWP)
s 10 •
COMPLETION
Adual'-'
tACWPI
StD>*
T••' ' '....
Coo,Qlr"lJ uu"
COh;:'.U ~ On T..,...
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 219

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<ure co nsiste ncy.)

2 To as..ess ou r manage me nt of th" flrojc~ t


For exa mple, if our defc t rate< arc lower than th e OmflJn y'< no mls for 111 0st pha<e< '" far, tlll'n we
arc probably mana!!inK our prole t w -II . A Anal Judgment on th l< ,yo uld depend o n th d Ie - f rate of the
delivered prole I Cl)m[1ar d With the no rm
220 CHAPTER 9 QUAUTY AND METRICS IN PROJECT MANAGEMENT


Table 9.2 Data on actMties relating to document creation and error rates

Research Meeting DraftlngTO RevlewlngT1 Finalizing" post·mortelll TOTAL


Timet' 120 30 210 130 140 30 660

% Time 18% 5% 32% 15% 21% 10% NlA

(Average % tlme)l2 - 14% - 7% - 15% - 30% - 16% - 18% N/ A

Quantity'" N/ A N/ A 22 N/ A N/ A N/ A 28

Productivity TBO" TBOll 6.3 TBO" TBO" N/A 2.512 -•

I
(Average procuctMty) TBO" TaO ' TBO" TBO" TBO" TBO" 18.3"

Self·assessed Quality" 3 S 2 1 5 9 N/ A

Defect rate LS N/ A N/ A 1.513 N/ A TBO" N/ A N/ A

(Average defect rate) N/ A N/ A (1 .1) N/A TBO N/ A N/A

Process Improvement (1) (2) (3) (4) ,-,


note #


The informatio n in T able 9 2 is examined, co lumn by column, identifying data that are different from
par. For cach datum below par, we de vise concrete actions that the team will perform differently for the
next phase . For each datum above par, we look for beneficial techniques that may be applied in future
phases. "Self-assessments" arc comparat ive, subjecti ve scores that the team assigns Various activities . One "..
way to collect the m for four actiV iti es, le t us say, is to ask each team member to allocate 5 x 4 = 20 points
among the fou r activities, each score being betwee n 0 and 10. The averages indicate how well the team as a
whole th inks it performed o n each activity. Th is i a subjecti ve measure that can be profitably compared
with other metrics .
Here IS an explanation of the superscripts in Table 9.2.

Left-Hand Column
II Spent by entire tcam , in person -hours

Ll The average amount of time spent on these acti vi ties in one of the following (select one), entire
organization o n all projects, e ntire orga nization on si milar projects (the ideal ), this department on all
t
projects, this department o n similar projects, this team o n prior phases.
U For documents, to tal number of pages produced in the case of documents. For code, X 1000 lines of
no n-commented code. A line of non- commented code is de fi ned as < A precise definition is provided
here. perhaps showi ng examples of how to count lines for common constructs such as for loops.>
L' This is a judgment that the team makes about the quality of the activity's product It is subjective but
ca n be very useful. A good way to obtain self-critiCism is to force the average of these numbers to be
five on a scale of 0 to t O.
USING METRICS FOR IMPROVEMENT 221

This I a key metri . It i necessary to deAne the following :


• What severity of defects will be counted (usually any besides trivial)
• When in the proccs thesc are counted (so as to be consistent for the sake of comparison)

Top Row

1'0 Spent b>, team members preparing the an ifact to the best of their ability; before submitting anifac! to
the rest of the team for review
TI I nc Iudes inspectIOns
' .

T:l After review; responding to comments from the rest of the team

In~rior of Table

II Measuring productivity for these activities is a more advanced concept and is covered later.
12 Pages per hour = (total pages)*60/{ total time in minutes)
13 Found during the "finalizing" stage
1< This metric is determined by the end of the project or even during maintenance-when defects are
detected that were injected during th is phase.

The following notes correspond to the last row in Table 9.2 and are examples of speCific process
• •
Improvement actions.

I. Our self·assessed quality measure on rmarch was 3. The team spent a percentage of time on this actlviry
that is close to the norm, so the remed y is not to spend more time on research . If there were know n
reasons why research was on the poor side (e.g., a new procedure or very unfamiliar type of application)
then the data here may not be a cause for alarm . O therwise . the team would discuss how to improve the
research process in the future .
2. The drajliHg of the artifact was poo r in several respects. It too k more than twice as lo ng to draft a page than
is usual; the product of drafting was significantly poo rer than the self·assessed average of nve; and the
defect rate was significant ly higher Ihan the norm. The table by itself proVIdes no explanations or trade ·
offs to deal with this, it merely indicates the problem . The tcam con iders the particular circumstances of
the activity and deci des what went wrong and how to fix it. For example, perhaps the main reviewer wa
Ed and his mother became ill during the actIvity The team may conclude that there was not enough
backup for lead writers, for example .
3. The next problematical activity was ,rui,wing, where the score waS lowe<t· I. ince the team spent 20
percent of its tIme reviewing compared WIth the no rm of 30 per ent , the team's first co nclusio n is
pr.obably to spend mo rc time revieWIng. ThIS has to comc at the ex pen,.., of another activity. The team
would probably take the time from the po, 'mo,'r", activity, where ItS sco re was very high, and finn/iz l"g,
where it spent more th an the usual amount of time
4 To capture benefic .. 1 prac tices for the future , the team notes area where It performed well . This applle
to the poslmorUm activit y, wh 're it performed IlIShl y to It< \OtISf. ti o n and used less time than is u,ua!. T he
team must Identify the r · a~on~ . An example is any unusu~1 actIVIty, <u h as team members btlllg ing t th
postmoncm prepared statements of prOLe" IIYlprove mcnt.
222 CHAPTER 9 QUAUlY AND MEIRICS IN PROJECT MANAGEMENT

Our self·evaluatio n gIve S o rcs of 3 to review and 8 to resea rch o ut of a forced average of 5. We spent
15% of our time o n revi ew and 25 % o n resea rch . We will spend 20% on each of these activIties for the
next pha e ,,
O ur ddect rate decl ined steadily except fo r thi s phase , when it rose. This seemed to be due to a lack of
commo n vi sion prio r to divid ing the writing. In past phases, we succeeded in establishi ng a common vision
of what we wanted to do before beginning to write our parts. Before begi nning to write the next document
we will conflnn a shared vision .

The ratio of requirements time to design time was 1.2, which is lower than this ratio from past successful
projects in the compan y. O ur design self·eva luatio n was 6, more than average . On our next project, we ,

plan to spend 10% more time on requirements analysis at the expense of design time.

Figure 9.6 Using project metries to improve software development processes


Teams set aside time at the end of each phase to assess the conclusions drawn from me tries, and to write down
how it will improve its process during the next phase. Figure 9.6 shows examples of improvement conclusions.

9.3.2 Improvement across projects

Companies strive to improve their perfomlance from project to project. No matler how efficient they are, the
be l orga nizations know th ey can always improve. Th ey iden tify area s for improvement and specify actions
that w"l lead to the desi red improvements in those areas o n subsequent projects.
Ste ps that can be taken to achieve these improvements are as fo ll ows,

1. Ide nti fy several areas for Im provement that arc important to the company. Examples include ~uality,
,cb,dul, prrdiclahility. and ,fficorncy.
2. Identify and coll ect metnes ,hat measure perfo rmance in each of ,hese areas. These metrics arc used as
baselines for setting goa ls in future projec ts.

3. As part of project planning fo r a future project, establi sh goals for improvement in each of the identified
areas, usi ng melrics from prior proj ects as a base line.

4. Identify speCific actions to implement that will support achievement of the goals.

As an example, Figure 9.7 Ii51 fo ur arcas ,hat have been identified for improvement, S<'brdul,. prrdiClahilily.
cIficimcy, and timt-lo-mn,kcL A metnc is identiflcd fO accurately measure project performance i n each area. Note
that the re may be severa l appropriate metrics to usc in each area, but fo r simp licity we are only identifying
one. An improvement goal is identified for each category, and speCific ac tions arc defined to bc implemenl<d ,
in the next project in o rder lO reach the targe ted improve ment goa l.
Figure 9.8 contains a ge neric set of actions to be implemented in order to reach the first quality
improvement goal Ii ted in Fi gure 9 .7, redu cing dqrc/,IKLOC by 10 percent. Note that in this example we ar<
I
o nl y fOCUSi ng o n the d'frc15IKLOC as a measure of quality, in practice there arc othe,-,; we would focu on as well.
The first of the improvement steps is to identify those parts of the software that contained the mas'
defects during the pno r release. The areas are then targe ted for additional design and code reviews to
understand why they contained a high number of defccts, and a plan is devised to rdactor those areas durin8
the subsequent project to improve their quality- Provisions are made in the planning of the subsequent projrct
to incorporate these action .
SOFlWARE VERIFICATION AND VAUDAnON PLAN 223

Improvement
Metric Description Coal
Quality Defect KLOC New defects fo und dunng 10 %
forma l QA testing , per
c hurned KLOC

~diCtability % schedu Ie accuracy % improvement across releases 5%


.
Improvement
- - - -
Efficiency MMlKLOC Pre -QA deve lopme nt effo rt 10 %
per c hurned KLOC

Time to Market Cale nda r rim elKLOC Pre -QA ca le ndar time per 15%
c hurned KLOC

Figure 9.7 Improvi ng projects across the organization examples of Improvement goals

9.4 SOFTWARE VERIFICATION AND VALIDATION PLAN

Recall that "(rificalio" respo nds mainl y to the question "Are we correctly building th ose artifacts in the present
phase that were specified in t he previo us phases7" Validalion res po nds to the q uestion "Do rhe artifac ts JUSt
completed in the prese nt phase sat isfy their speciRcations from previo us phasesi'
IEEE 10 12-2004 Softwa re Ve rificatio n a nd Validati o n Pla n. whose hea din gs are reprodu ed in Figu re
9.9, provides a framework for expressing the manner in w h ich V&V is to be carried o ut. Th is specificatio n is
writte n during in itia l p roject pla nn ing , a nd complime nts the Software Q uali ty Assurance Plan covered in
Chapter 6 and the case study in C hapte r 8.
The annexes to IEEE V &V S tandard 10 12- 1998 are as fo llows ,

Annex

A. Mapping of ISO/ IEC 12207 V&V requirem e nts to IEEE Std 10 12 V&V activities a nd tasks

B_ A software integrity level sc he me

C. De~nition of independent verification a nd va lidatio n ( IV&V)

Improveme nt Category: Quality

Actions,

I. Identify compone nts o f so ftware that o ntaine d most dekc ts.

2 Plan to conduc t de"lI n a nd Lode reviews in these areas.

3. Plan to re fac to r seve ra l o f these are as during slIhscqucnt projec t

FIgure 9.8 Example Improvement plan


22' CHAPIER 9 QUALITY AND METRICS IN PROJECT MANAGEMENT

I Purpase
5.4 Opera tian V&V
2 Referenced da cuments 5.5 Maintenance V&V
DcRni tlans 6. V&V repartlng requirements
4. V&V 'Overview 6. I Reparti ng
4.1 OrganIzatIOn' 6 .2 Administrative
4 .2 Ma ter c hedule 6 .3 Documentatian
4 .3 Saftware integrity level scheme 7. V&.V administrative requirements
4.4 Resaurce summary 7. 1 Anomaly reparti ng and resalution
4.5 R~ponsibi l i t ies 7 .2 Task iteratian palicy
4 .6 T 0'01 , techniques, and me thodologies 7 .3 Deviatian palocy
5. V&. V pracesses 7 .4 Standards, practic~ , and canventions
5.1 Management 'Of V&V 8. V&V dacumentation requirements
5 .2 Acq uISi tIo n V&V
5 .3 Development V&V 'Subheadings arc typical examples (IEEE )

Figure 9.9 tEEE 1012·2004 Software Verification and Validation Plan-table of contents
Source IEEE Std 1012·2004

C I Technical Independence
C2 Managerial independence
C3 Fi nanCIal independe nce
C4 Farms of independence
C4 . t Classical IV&V
C 4.2 Modified IV&V

C4.3 InternallV&V
C4.4 Embedded V&V
D. V&V 'Of rcusab le saftware

E. V&. V metrics
E. ! Metrics for evaluati ng saftwar< develapment processes and products
E.2 Metrics for evaluating V&.V tasks and for Improvi ng the quality and coverage of V&.V tasks
F. Example 'Of V&V organizatia nal re latianship to other praject res pa nsibilities
G. Optional V~.v task descriptions
H. Other r<ferenc~
I. Definitians from existing standards (na rmative)
Copyright IEEE 2003
An ideal pracedure is for an outside group to perform V&V. This is ca lled '.d,Jontdtttt Vtnjk.rio. ""d
V.lid.riml (IV&V).
CASE STUDY: SOFTWARE VERIFICATION AND VALIDATION PLAN FOR ENCOUNTER 225

TI,e next s~ tion in the hapter gives an example of a VVP case stlldy .

9.5 CASE STUDY: SOFTWARE VERIFICATION AND VALIDATION PLAN FOR ENCOUNTER

4.3 Resource Summary


Note to the SlUdent,
This ~ction shows an example of Software
This section describes the person-hours re-
Veritlcation and Validation Plan for the Encoun-
quired for V&V or the amount required to
ter vicko game project, organized in accordance
fund an external organization for IV&V.
with IEEE 1012-2004. In the interests of space.
various ~tions have been omitted.
Verification will be perfonmed Internally. Valida ·
tio n will be perfonmed partly by project e ngineers. The
costs of this IOternal work are built into the SPMP.
1. purpose
Validation will also be perfonmed by one 01ernal QA
engineer. This person will consume four perso n.months.
This document provides the verification and valida-
tion procedures that will be followed for the devel ·
opment of the Encounter video game . 4.4 Software Integrity Level Scheme

2. Referenced Documents The integrity level of software expresses how


critical it is. Software components that potentially
Software Project Management Plan threaten safety have the highest integrity level.
Software Configuration Management Plan The IEEE standard describes four levels, high,
major, moderate, and low. A tool supporting
infonmal research, for example, would probably
3. Definitions
be required to have only a low integrity level.

The Encounter application is required to ha ve


4. V&V Overview moderate integrity.

4.1 Organization 4.5 Responsibilities

The development team members will


This section describes how the V&V effort will
be organized (i n terms of roles) and how it
• Perform verifica ti on ac tivities throughout the proj·
relates to the development pha es.
ect, including Inspecti o ns within all pha ~cs

• Perform and doc ument all unit testi ng uSing )Unit


The verification and validation of Encounter IS
roordinated with eac h phase of every ite ration . • Validate requirements d ocuments with the market-
I• ng mCl nagcr
4.2 Master Schedule
The QA e ngineer will
Because of the orgamUllon of V&V "' de\ c rlbed "'
Section 4. 1, the VI!< V schedul e loll ow< directly to the • Verify that the teal11 h.\ lo llo wed lIs docume nted
Ploject schedule as defined In th e SPMI' procedures, ln iudins tho. e cie< ribedil1thbd ume nt
226 CHAPTER 9 QUAUTY AND METRICS IN PROJECT MANAGEMENT

• Perform all post -unit te tin g • Arc all cntlca l marketing factors identified?

• Report the =ults to the team and management • Docs any conce pt Imply a SIi!nificant risk to pro~Ct
completion) If so, should that concept be mitigated?
• Maintain this document

,
5.3.2 Requirements V&V
4.5 Tools, techniques, and methodologies The Encounter SRS WIll be verified by answenng the
follOWin g questions,
To be supp hed
• Are all critical requirements that were identified
5. life Cycle V&V during the concept phase speCified)

• Is the SRS organized In a way that facilitates


5.1 Management of V&V traceability )

The V&V dforton Encounter (i ntemal and external) will • Does the SRS account for all required interf.ces
be supervised by the manager of Quality Assurance. with other systems?

• Does any requirement imply a significant risk to


Each of the following sections describes how project completion) If so, sho uld that requirement
V&.V of every process will be conducted. be mitiga ted )
When this is to be performed internally, it
can be included in the corresponding docu· The Encounter SRS will be validated by expos·
ment (SPMP, SRS, etc.), and this V&V docu· Ing it to the marketing department and to a sample of
ment can refer to those. 30 game players.

5.3.3 Design V&V


The Encounter SOD WIll be verified by answering
5.2 Acquisition V&V the fo ll owi ng question ,

' Acquisition" is the process by which an orga- • Arc all requirements accommodated by the design)
nization obtains software. Using third·party
software relieves the development organiza · 5.3.4 Implementation V&V
tion of having to reinve nt the wheel. However, The Implementation of Encounter will be verified by
it places a burden on the organization to answering the follOWIng qu('Stions,
certify the Quality of such software. Many
disasters have been expenenced because this • Are all requirements fully verified)
step was avoided.
• Is the code organized in a way that faCilitates
traceability back to deSIgn and req uirements)
Each vendor·supplied tool used for the develop-
• I all code documented according to standards
ment of Encounter will be valIdated by the QA engineer.
• Is all code thoroughly documented )
5.3 Development V&V
5.3.2 Test V&V
5.3.1 concept V&V The test documentatIon of Encounter will be verified
Conceptual work on the Encounter game concept by answering the follOWing verifiCJIIOn Questions,
will be verified by answering the following questions. and the .ahdation questions that follo,,'_
CASE STUDY: SOFTWARE VERIFICATION AND VAUDATION PlAN FOR ENCOUNTER 227

• Are ~II critical cequ",:mcnlS in tended to be fu ll y 6.1 Reporting


rested at every level of det~iI (e .g ., human safe IY) ~
The QA person attached to the prOject reports the
• I the test phdo ophy adequate for the
sta lus of V&V weekly to the manager of QA and
requirements'
copies the team leader.
• Are the test plans complete a specined in the test
philosophy 6.2 Administrative
• Are the test cas~s complele as specified in the test
philosophy This describes who is responsible for the V&V
reporting effort.
For the test plans and procedures, th e reader is
referred to the Softwa re Test Documentation. These
plans and procedu res are deSIgned to accommodate The project leader is respo nsib le for ensuring
the following validatio n questions. that all V&V reporting is performed.

• Do the defect cou nt . defeCl rate, outsta nding 6.3 Documentation


defects, and defec t seve rity anest 10 an acce ptable
product? A single repon that includc'S all version of the result of
the tasks described in this document is maintained.
• If not, what success rate wi ll be required to allain
acccptabi Iity7
7. V&V Administrative Requirements
• Do they account fo r all of the metri s peciRed in
the SQAP ~ This describes who is respo nsible for the V&V
effort.
5.8 Operation V&V

This part verines that the application is appro· 7.1 Anomaly Reporting and Resolution
priately supported after deployment to users .
The QA engIneer attached to the Encounter prOject
wi ll mainta in th e current state and the history of each
To be supplied defect fo und . T he QA enginee r will rnai ntalll all
metrics identi fie d in the SQAP o n a Web site and
WIll e·mail a list of all anomalies (including defects)
5.9 Maintenance V&V
Ih at he or she deem to have excessive repa ir time·
TI,e maintenance plan hall be veri ned agai nst corn · Iones. This includes defecls with no repair duration
pany mamtenanee crite ria , specified in the com· es timates and tho e that have exceeded their planned
pany's mai ntena nce requirements and procedures, compictl on date . The Bugzil la fa cility will be used.
documenl 890.23.
7.2 Task Iteration Policy
6. Reporting Requirements
Th ,s seclion explains the circumstance under
Th,s includes who reports the resu lts of the whi h VsN tasks are repea led be au C 01
V.. V effort and to whom do they provi de results obta Ined o r because of changes in
thcie report~, the project.
228 CHAPTER 9 QUALITY AND METRICS IN PROJECT MANAGEMENT

v V tasks wlil be ropea ted at the discretIon of Any pro posal to deVIate from this plan requires
the QA repre e ntatl ve, but these wlil Include the th e approval 0 1 the QA manager and the project
f 1I 0"'lng c riteria . manager

• A n inspectio n w hose defects count is more than 20 7.4 Standards, Practices, and Conventions
percent greater than the norm
These arc set down for all company prOjects at http://
• A test whose defects count IS more than 20 percent
• •
grea ter than the norm
8. V&V Documentation Requirements
• An entire phase ,f the previous phase c han ge by
mo re than 20 percent.
Section 6 de cribed what should be reponed.
7.3 Deviation policy Section 8 covers the means for noting in
writing the results of V&V. It specifics the
form that all V&V documentation must take.
Describes the procedures required to deviate For example, it could be organized as an
from this plan . appendix to this document.

9.6 SUMMARY

Quality In project manage ment begins by cultivating a quality culture within the project team . Members
develo p a shared r.spon Iblilty and pride . Many projects designate team members with speCific responsibili.
tICS, and each actIvity leader promotes an attitude of qua lity for h is activity.
En unng quality reqUIres carefu l planning and mo nIto rin g throughout. Metrics arc collec ted and
analyzed, providing means of concretely assessing how well a project is executing . There are many useful
,,,1
metrics, some of the most ba IC arc projecl mtl,,'oHr plaIH"d '" fulfillrd , drJecl rOIlHI" and ",rruIIOH .
After identifying the metries to be collected, a plan is created with goals for each . Targets are created by
analyzing previous projec ts and using metrics fro m tho e a a baseline. If targets aren't established, project
managers will not know whether a prOject IS o n track.
During the course of a project, the team meets regu larl y to review the metrics. In addition to the detailed
data , a grap h ical summary often known as a projrrl dasl,board is c reated. The dashboard presents the key metries
in a clear, conCIse manner, allowing the team to quickly ascertain how each is aspect of the project is
perfom"ng against the plan.
Successful companies strive to improve the overa ll quality of their performance, both during the course
of a project and between successive projects. Metrics are analyzed in each case to identify areas requiring the
most improvement. SpeciRc actions arc then enacted, and metrics objectively measure whether the
improvements arc providing {he anticipated results .
The Sol-tware Verification and Validation Plan is an important part of project quality. It specifies a plan
for generati ng artifacts based on specificatioAs of previous phases (otrifiralion), and for building software that
meets customers wants and needs (validalloH) . IEEE to t2 · 2004 provides a framework for this document.

9.7 EXERCISES

I . In your own words, define · proJect metrics" and explain how they are used in managing a projcct.
2. The defect pl.n in Figure 9.3 shows the number of open defects falling behind plan st.ning in week
I . Assuming you are the project m.nager, at what point would you start taking corrective aclton'
BIBUOGRAPHY 229

Would it be aftcr the Arst week, or would you wait a number of weeks to see whether the situation
Impro v Arc there any other metrics you might collect to help you deci de? Write a paragraph to
e):pl~ in Ollr an wer.

3 D~cribc in your own words how a project manager could utilize a project dashboa rd in managing
a project.

4. What metrics related to software testing mi ght you include in a weekly project metrics report to
provide insIgh t into the status of the te ting process? Explain your choices.
5. For each of the remaining ca tegories in Figure 9.7 (predictability, efAciency, time to market),
Clcate an acti on plan to reac h th e stated improvement goals. Use Figure 9 .8 as a template for your
plans. Include a minimum of three actio ns to take for each ca tegory .

I EAM EXERCISE

V&V Plan
TI. Produce the relevant parts of a V&V plan usi ng IEEE standard 10 12 · 1986. Measure and report o n
the metrics described in Team Exercise TI in C hapter 6.
Criteria:

1 Practicality: H ow well does the plan ensure that the work will be adequately veriRed and validated?
(A = completely practicable in the environment of the project)
2 SpeciRcs: H ow speciRc is the plan in terms o( sui tably naming places and participants? (A = spell s
out exactly how V& V will be performed in the e nvi ronment o( the development)
3 Team participa·nt pe rce pt io n: T o what degree are partici pants likel y to perceive your plan as a help
to them ? (A = written in a way that respects the time and efforts of engi neers)

SQAP
T2 . Produce a rea list IC softwa re qua lity assu rance plan for your project. Measure the time spen l o n thi s
dlort by indivi dual mcmbers and by the complete team . Provide the corresponding metric data and
self-assessment for this assign me nt , as described in Team Exercise in Chap ter S.

Critcna: as (or Team Exerci se in C hapter 8.

BIBUOGRAPHY
I la ird, unda M . Ind M rol Srerman, hware Mea suremen t and E~ um;ulon A Practica l Appro') h/' W"ry- I'IIUlC"IOKt, 1006,
P9 181- 192
1 SohwJr~ P,oKram ManDQl'!l1 Nl"two r'k (S PM N) hup Ilwww ~ nl1ln com.
I

principles of Requirements
Analysis

Planning • Why the term requirements "analysis?-

• What is the value 0' written requIrements?


Maintenance
• Where do requirements come from?

The Software • What is the difference between high·level


Development and detailed requirements?
LIfe Cycle
• What is the difference between functional
and nonfunctional requirements?

• How do you document requirements?

• What does traceability mean?

• How do agile teams handle requirements?

• How can student teams gather


reQuirements?

Figure 10.1 The context and learning goals for this chapter

Bdore a software system is deSIgned and implemented, one needs to understand what that system .s
intended to do. This intended functionality is referred to as the rc4""",,,,,t5, and the process of gai ning the
necessary understanding of this is col lled rrqulrrmrnts ,malYSIS. An application for Video store management , for
example, could mean different things to different people, each a somewhat differing set of require ments. One
intop",r3tion could be an application that track. employee t.me and outputS paychecks; another, an e·m.,J
SOURCES OF REQUIREMENTS 231

• The proce of underst4ndinl! wh4t's wanted and needed in an apph ation For exa mpl e, yo u may know
that you U'.,.'
a colo nia l hou e in New England, bUI you may no t know that you will pro babl y ""d a
baseme nt for it .

• W e exp re require me nts in writing to comp le te our understand ing a nd to create a contract betwee n
develo per and custo me r.

FIgure 10.2 The meaning of requirements analysis

appl ication that processes Customer ren ta l req uests; a third , an a pplicatio n th at records rented vi deos and
computes charges; and so o n. As in mOst busi ness endeavors, the reliable and professio nal way to specify what
IS agreed upo n i to ex press it in writi ng. Therefore the o utput of requirements analysis is a software
requirements speciReatio n (SRS). T hese po ints are ummarized in Figure 10.2.
A requirement specioes wha l the customer wants. Th is no rmall y docs no t include any th ing about how the
applicatio n is d esig ned o r programmed . Specifyin g a req uireme nt is like tell ing a cont racto r lhat you wa nt a
12 foot by 15 foot roo m added to yo ur house . You gene rally do no t specify how yo u wa nt the contracto r to
build the additio n thai is a desig n a nd const ructio n issue.

10.1 THE VALUE OF REQUIREMENTS ANALYSIS

A dd ective requirement (i.e., o ne not re paired before the requirements document is fina lI zed ) turns o ut to be
very expensive. It i·s an estimated 20 to 100 times mo re ex pensive to re pair if allowed to slip thro ug h the
develo pment process compared with re pairing it soo n afte r it is incurred, In Anancia l term s, if the cost of
Rnding and repairing a defec t at requ irements time is $1 , then the cost of Rnding and fixing that same defect at
the end of the deve lo pme nt process is $20 to $1 00. The damage that re ults fro m the custo mer's poo r
experience with the appl icatio n is a fa cto r addit io nal to the expense involved.
G iven the trem endous be neRt of detecting and re pairing defec ts at requirements time, "' hy are so many
projects damaged by poor o r no nexiste nt requ irements anal ysis) A princ ipal reason is tha t custo mers usually
do no t know at the beg inning o f a projec t all that they want o r need . Instead , they learn to understand what
they themselves want o nl y while th e project progresses. Th e Encounter case stud y is an example of th is
uncertainty; it has a purpose, but o ne whose de ta ils are still in fo rma tio n. Thi s book emphasizes ite rative
develo pm ent and the close alig nm ent be tween the requirements, deSig n, and implem entation Agi le method s
are a prime exampl e. Engi neers usi ng a well ·orga nized ite ra tive process gathe r requirement , desig n for those
requi reme nts, and impl eme nt for them in coordinated ite rati o n ~ .

10.2 SOURCES OF REQUIREMENTS

We usually th ink of cu,'omm as the source of requirements since a ppli at,o n. are bUIlt fo r them. In p ractice,
matters are ra rely sim ple here because t he people paying for an applica tio n, the peo pl e who will be u ing the
appllcallon, and the people de<ig natcd to wo rk o ut the requ ireme nts may be differen t. It is wisest to conSIder
the WIshes and nee d~ of a spec trum of people. All of the people wi th on interest in an a ppli Ci'l tlo n' o utcome Jre
known as its .lQlctholdm To simplify matters In till' c hap te r, ho wever, we wi ll usuall y use th e tern, "c usto mer,"
There are two mai n requireme nts analysis challe nge , F" , t, a< already men tio ned , ustomers ro rel
know exactly wha t they want whe n a proJcct begi ns. TI,C co mplexi ty 01 mo dern appt. atio n, Ill akc~ ,u h
com pleteness all but impOSSIb le. ccond, <.Usto mc,.,. rare ly know all that they !I"d , either o metim", . th ey are
noteqUlpped to know it To relUrn to thc hou< add itiun ana logy. It may take tllne for a ho meow ner to ...:ollz,·
lI,at for the addit Ion he wants. he wi ll deS ire wi ndow_ o n 0 11 wa ll s. H e may have III be cdu atl·d to unders tand
that he n eed~ u> >uPP') rt the addI ti o n wi th p,ers ra ther than WIth a reg ular fou nela tion,
232 CHAPTER 10 PRINCIPLES OF REQUIREMENTS ANALYSIS

t
Unconstra/n«J
Doclslon support system lor mlillary IBeIICS

Encountor video game •

• Corpora Ie payroll system

Type 01 • Factory control system


application
• Enhancemenllo corporate payroll system

• Flight CDntrol system for airliner

Highly • Missile guidance system


constrained

I •
Relatively ApproxImate % of requirements
low gstheled from people

Figure 10.3 Source of reQuirements people and other sources


Source" AMpted Irom ..Software Reqwem€I1ts-SEI Cumculum MOdule SEI·CM· 19-1 2 ,. by JOhn W Brackett copyright ," 2009 call1Egie Mt'Oon ~ WI!!,
spec'al pel I i iksJon from Its SOftware Engineering InsUtute.

Requirement arise fro m mult iple sources, mostly from stakeholders, but also from documents and even
from books As shown in Figure to.3, Brackett [ I ) has plotted severa l types of applications to illustrate the
degree to which requirements are gathered from people, as opposed to other sources such as written material
Figure 10.3 classifIes applications by the degree to which they are constrained by nature restrictions on the
application that cannot be altered. For example, an appl ication that describes the trajectory of a ball is constrained
by graVity; chemICal reactions arc constrained by physical laws. Generally speaking, the less constrained a
problem , the morc its requirements must be obtained fTom people. At one constraint extreme, for example, is our
Video game case study. Being the product of pure imagination, it relies on people for most of its requirement.<.

10.3 HIGH-LEVEL VS . DETAILED REQUIREMENTS

A typical reqUirements document is large A detailed description of every requirement, although nccessary in
some fonn or other, can be mlnd · numbing to read. Imagine, for example, a document that spells out evety
detail of every property of MICrosoft Word™ . It would certainly no t read like a novell For thIS reason, we
often divide requ iremen ts documents into two parts, "igl>-fro" and d,tai/,d ,
The first part of a requITements documen, is an overview, which is relatively readable and is wdl suited to
customers Its contents are referred to as the high-ltvd or hSlSI:1t'Ss requirements . Anyone wanting to get an idea of
what the application IS all about read the high-level requirements. In many organizations, the mark<ting
department p~pares this material based on market research and conversations \~i th customers Although not
fonnally necessary, the hi gh -level requirements often Include a de cri ption of why the application is being
built, and they state the benents to both the developing organization and the customer [2). In some
organization s the: hlgh .level requirements fonn a separate document such as a -market requirements-
document In thiS book we will include the high-level requirements In the SRS. As an example, the video
tore application high-level reqUirements might contain sentences like the following ,
NONFUNCTIONAL REQUIREMENTS 233

The V,deo tore .ppl. at,on sh.1I enable clerks to che k DVDs in and out
The followIOg hows a ketch f the maIO u er ,nterface. . . .

The second part of a o mpl ete requirements do um ent con is ts of the complete particulars. They are
espeCially u ,,"11 for developers, who need to know precisely what they have to build . These arc the d.l.i/.d
rrquiJtm(IJts. Although de ta iled requirements are used frequently by developers, the y should be understandable
10 the u IOmer, and hou ld not conta in developer Jargon wh ere possi ble . Here are o rne examples from the
",deo slOre applicatio n.

The dail y late charge o n a DVD shall be computed at half the regular two·day rental rate, up to
the value of the DVD listed in the "Interga lactic Video Ca talog." '\>Vhen the amo unt owed reaches
this value, the to tal late charge is computed as this amount plus $5 .

When the "comm it" butto n is pressed o n CU I 37, the CUI shall diS3PP('ar and CUI 15 shall
appear with a superimposed g ree n bo rder (RC B = 6, 32 , 8) and the name and address 6elds Riled
with the data for the custo mer.

One challenge of writing the hig h·l cvel and detail ed requirements is to ensure that they remam
consistent over time. Thi s is facili tated by kee ping the hi g h. level requirement at a hi g h enough level-for
example , "Clerk can enter customer particulars." Thi klOd of statement te nds no t to change very much O n
the other hand, the details are provided in full in the detailed requirements and are much more liable to
evolve. A corresponding examp le is, "Clerks ca n enter th e customer's Rrst name of I to 10 alphabe tical
characters in the text neld shown in ngure 34 , a second name of I to 15 alphabetical characte rs . .."

10.4 TYPES OF REQUIREMENTS

Requir-ements are commonly cla.ssiRed as either i""" ioll.' o r "o"i"""io,,.1. Thi s classiRcari o n applies to both
high. level and detailed requ irements. Each type IS described in the sectio ns that fo ll ow.

10.4.1 Functional Requirements

Fu.d,o•• ' rtquirrmtnls, also known as beh.viora' reqUirements, spec,fy serv, ces that the application mus t provide
(e.g., 'The appltcation shall compute the va lue of the lIse r's stock po rt fo liO ."). An appltcation all ows entities
Interacting with it (ty pica ll y users) 10 accomplish tasks. Such an enti ty IS fTequent1 y a perso n, but it ca n also be
a machine o r eve n ano the r program . Ai""elio,,,,1 "q"i,,",",' speCifies something specinc thatlhe applica tion
allows such an entity to accomplish . In o ur video store application , fo r example, the fo ll OWing are fun ctio nal
requin:ments .

The appli ca tion allows clerks to check o ut DVDs


The applicatio n allows clerks to di splay the cu\to me r's ac ount tatus

10.5 NONFUNCTIONAL REQUIREMENTS

Any requirement that docs no t ~pcc ify fu nct,ona llty prOVided by tht· app lt atlo n I< "0..j"",,,0,,,,1 For cxarnri~ ,
• requJrement such ., "the ap plica tio n shall dl<pla y a custo mer\ a Ollnl >latll< In ics> th an two seco nd • "no t
functional , b ·c.ausc ,t does nnt <pc Ify a <pcc ,f, ,crvlCe Instea d, ,t q"al, 1(5 a service or erv, es « pe ,nts
23<1 CHAPTER 10 PRINCIPLES OF REQUIREMENTS ANALYSIS

somcthlnfl abou t th m). No nfun tio na I req uirements need to be , pc iAc, quantit.able, and testable. Consider
a nonfun tlo nal requirement that read,

The systcm shall ret neve user informatio n qui kly.

This reqUirement is vague (e.g., what docs reln"It mcan l), no t quantifiable (e .g , how fast i quicidy7), and
therefore no t able to be tested. An imp roved versIOn of the requirement would be as follows

Once the OK butlon is pressed o n the "Retrieve Account In formation " sc reen, the user's account
info rmati o n shall be displayed in less than 3 seco nds.

This requirement IS specific (because it identi fies a specific button o n a specific screen), '1uantiAable
(because of the specific response time), and testable . The documentatio n shou ld make it clear exactly what
"the O K bUlton" refers to.
Major no nfunct ional categories are· qua/il'" (e.g., reliability, availability, maintainability, etc.), Co", I'<li. l,
(o n the applicatio n or its deve lopment )' ",',mal i" '"jam (hardware , software , communication) and mor
COrtdJliolls. The se are summanzed in Figure 10.4 and elaborated upon in succeeding sec tions.

10.5.1 Quality Attributes

Rdlabllity "4u""",,,I, specify "the ability of the software to behave consistently in a user· acceptable manner
when subjected to an environment in which It was intended to be used." [ 3]. In other words, it is the extent to
which defects wi ll be detected by users dUring no rmal operation . This kind of requirement recogn izes that
applications are unli ke ly to bc perfect , but limits the extent of imperfection in quantified terms. The following
is an example , and assumes that a definition of 'kve l o ne faults" has been provided.

The Airport Radar Application (ARA) shall experience no more than two level-one fau lts per
mo nth .

• Quality attributes
• Reliability and availability (observed fau lts, ave rage uptime)
• Performance (speed, throughput, storage)
• Security (maliciOUS and non malicious compromi se of data o r functionality )
• Maintainability (cost to maint.,n)
• Portability (move to a different operating environment)
• Constraints on the applicatio n or it developm ent

• Extemal interfaces th.t the application "talks to"


• Hardware
• Other software
• Communication with external agents

• User interfaces
• Error handling
Figure 10.4 NOnfunctJonal requirement categories
NONFUNCTIONAl REQUIREMENTS 235

A"",labi/ity losdy rdated 10 re"abllity. quantifie< Ihe degree to which the application is to be ava lable
to lIS u el'5 The followlllg i an example .

ARA shall be avaIlable at level one on eIther the primary or the backup computer 100% of the
l1mc.

ARA hall be unavailable on one of thcse computers at level o ne or two for no more than 2% of
the time in any 30-day period.

Often . high-availability requiremcnts are specified in terms of "the nincs." For example , Ave-nines, or
99999% availability, means that a sy tern ca n o nl y have a yea rl y downtime of 5.256 minutes. This type of
requirement might be documented as fo llows.

The system shall support "nve-nines" availability.

Ptr/o"",,",, rrqui,,,,,,,,', specIfy timing constrai nts that the application must observe. These include
elapsed time for computat ions (speed), throughput, and storage (e.g., RAM usage, secondary storage usage,
etc)_ The follOWing i an example .

The Stress Analyzer shall produce a stress report of type five in less than a minute of elapsed time .

Performance requirements are a critica l part of ,wl-,im, applications , where actions must complete within
specified time lim its. Examples include collision avoidance software. Aight control applications, and antilock
brake controls. The follOWing is an example .

The computation of brake Auid pressure shall complete within o ne millisecond .

Stcurity "qui",,,,,,,, co ncem mal icious Intent toward a system. Th is makes security different from other
requirements, which specify application behavior when used by well-intentioned people. One can specify
requi rements that contribute towa rds security. These call for concrete measures, such as login procedures,
password lengths, and so on, that contribute to making the product more secure. On the o ther hand, imp"cit
security requirements are far more di fficu lt to deal with . Implicitly, no o ne wants an application that is vulnerable
to attack. so the requirement exists in the abstract. H owever, the nature of many future attacks is not predictable,
and so there is no way to specify a requi rement for their defense exccpt In genera l tcrms that are of little value.
Mainlainability rrqu"""",', specify how easy or difncult it i to modify the softwa re. as a result of fixing a
defect or implementing an en hancement. For exa mple , the easier it i to understand the software, the easier it
is to maintain . Maintainability can be measured by th e time it takes to repair defects. The f-ollowing is an
e.ample of a maintainability requirement.

The average time fo r a maintenance engineer 10 repair a sevcrity ·2 defect shall be no greate r than
8 person -hou rs .

Portabil,IY rrqu",mtnl' Identify those parts o f the sohwarc that may need to run in dilferent operating
environments, as well a ~ ho w ea<y o r difncult It is fo r those part~ to be ported. The following is an example.

The graph,cs subsystem shall be desig ned so it an run in bo th the Window< and U nllx operatin!;
~ys tem .
236 CHAPTel 10 PRINCIPLES OF REQUIREMENTS ANALYSIS

• Platform

• E.xample: The application must execute on any I CH Linux computer .


• Development Media

• Example: Tl,e applicatIon must be implemented in Java.


• Example. Rational Rose must be used for the design .

Figure 10.5 Examples of constraints

Tl,e maximum amount of effort to port the graphics subsystem from Windows to Linux shall not
exceed 2 person · months.

10.5.2 Constraints

A COll s/ralll/ o n an applicatIOn is a requirement that limits the available options for developing it. Recall that
requirements are genera lly "what" statements. '"How" is usually left to the design . Constraints can be thought
of as exceptions to this. Figure I 0.5 shows some examples.
Design or implementation constraints describe limits or conditions on how the application is to be
designed or implemented. These (nonfunctional ) requirements arc not intended to replace the design
process they merely specify conditions imposed upon the project by the customer, the environment, or
other CIrcumstances. They Include accuracy , as in the following example.

The damage computations of the Automobile Impact Facility (AEF) shall be accurate to within
one centimeter.

Tool alld lallguag< cOlls lra ;II /S are often imposed. These include historical practices within the organization,
compat ibility , and programmer expenence. Here is an example.

The AEF is to be Implemented in Java and developed on the Eclipse platform .

D",gll cOlls/ra ;II/' arc imposed on the project because stakeholders require them . They can be speciAed in
the requirements document or the design document. Such constraints restrict the design freedom of
developers. The fo llowing requirement IS an example .

1he AEF shall utilize the Universal Crunch Fom, to dIsplay impact results.

The constraint of having to follow certain , /alldards is often determined by company or customer
policies. Here are examples.

Documentation for AEF shall confom, to Federal Cuideline 1234.56.

The AEF code is to be documented using company code documentation guidelines version 5.2.

Projects arc frequently constnined by the hardware platforms they must use The following is an
example.

AEF shall run on Ajax 999 model 12345 computers with at least 128 megabytes of RAM and 12
Gigabytes of disk space.
NONFUNCTIONAl REQUIREMENTS 237

• Hardwa~

• Example: "The application must Inte rface with a mode l 1234 bar code reader."
• Software

• Example: "The application sha ll usc the compan y's payro ll system to retrieve sa lary Inlormatio n."
• Example: 'The application shall use version 1. 1 of the Apache server."
• Communications

• Example : 'The application shall communica te with human resources application via the company
.
Ifltranel. "
• Example: "The fonnat u cd to transmit "article expected" messages to cooperating shipping companie
shall usc XML standard 18 3.34 publ is hed at http :// .... ..

Figure 10.6 '!)'pes of external interface requirement for an application. with examples

10.5.3 Extemallnterface Requirements

Applications are frequently required to interface with other systems . The Internet is a commo n example of
such an external system. Interface requirements describe the format with whic h the application commu·
nicates with its environme nt. Figure 10 .6 shows the common types. with examp les 01 each .

10.5.4 User Interface Requirements: prinCiples

User interlace design is sometimes included with the "design" phase of software develo pment , but it ca n more
properly be considered part of the requirements phase . This book takes the latter perspec tive . including o nl y
sofllDare design in the "design" phase, and not grap hi c desig n.
Customers commonly conceive of an application by visualizing its graphical user interface (C UI ), so a good
way to help thelll describe the application is to develop draft CU ls. Our goal here is to provide some of the
essentials of userinterlace design. This is quire different fro m the I,elm lra! design of the application, w hi ch is covered
in Part IV. The latter includes considerations of what C UI c lasses to se lect and how to relate the m to other classes.
In developing user interfaces for app lications, it is ideal to work with a professional de ig ner, who is
trained In user behavio r. co lo r usa ge , and tec hniques of la yout desig n. Fo r many proje ts, however, especially
smaller ones, software engineers must design use r interfaces with no such aSSIsta n e . Thus, we lis t some
guidelines for user interface design .
Calitz [4] provides eleven s teps fo r develo ping user Interfaces. We have adapted these. as s how n
in Figure 10.7. Each o f these steps is applicable to the high · level req uire ments process andlor the detailed
reqUirements processes. Steps I and 2 are described in C hapter II. Steps 3- 11 arc explored in C hapter 12.

10.5.5 Error-Handling Requirements

Rtquiremcnt\ a nalySiS dea ls with two kinds of erro r~ . The first arc th ose that actors make (e ntit ks '"terac tillg
with the application suc h as a user or ot he r syste m ), the Sc o nd consi,ts of errors that developers make Error-
handling rcqu"cment~ 'pecify how the applic ation responds to diffe rent· type< of errors. Figure 10.81i ts some
of the ways of dealing With errors
~garding the flrs t kind of e rror. error-handling requirements explain h o w the application mli't re'pond
to anoma lies In I[S enviro nm e nt For e xam ple. whal ,liould the application do if It rc e lves a m,-,,,asc fro lll
238 CHAPTel 10 PRINCIPLES OF REQUIREMENTS ANALYSIS

'rp f:Know your user (Hl )


'rp1 : Under.tand the bUSlne<s funct.on in que t.on (H )
',pJ Apply prinCIples of good creen design (H , 0 ')
S"P' Scl«:t the appropriate kind of window< (H, O)
Itp s: Develop system me nus (H ,O)
Sirp 6 Sclect the appropriate device-based contro ls (H)
SI,P 7: Choose the appropriate screen-ba cd contro l (H )
SI,P 8' Organize and layout windows (H , D)
S'rp 9 : Choose app rop riate color. (0 )
SI'P 10: Create meaningful .cons (H , O)
S" P f f : Provide effective me sage, feedback , and gu.dance (0 )
Figure 10.7 Steps for constructing user interfaces
Sourte" "'rlatll!!d from Gafttz. w~ '!he Bsentlal Guide to user mter13Ct' Deslgl'l Arl lntroductoo to GUI Prind oleS and Techniques," .JOhn WIJef So Sons, 1996.

• Ignore

• Warn user

• Allow unlimited retries

• Log and proceed anyway

• Substitute default values

• Shut down

Figure 10.8 Options for error-handling requirements

another applicatio n that is not in an agreed-upon format l lt is preferable to specify th is in the requirements
document r.uhcr than leave the cou~e of action to programmers alo ne.
The second bnd of error refer. to actions that the application sh ould take if it nnds il,d! having
comm.tted an error-that is, becau e of a defect in its constructio n. This kind of error requirement is applied
very selectively, because our aim is to produce defect-free applications in the fir.t place rather than cover our
mistakes with a large set of error- handlmg requirements. In particular, when a functio n is ca lled with improper
parameters, we program a continuation of the application onl y if such an erroneous continuation is prdcrablc
to the actual cessat.on of the application. As an example, suppose that we have to specify the requireme nts for
a device that automatically applies doses of intravenous drugs. U ser. arc entitled to assume that the
application .s thoroughly specified, designed, implemented, and inspected, so that the drug composition and
dosage computations arc correct. Nevertheless, it would be wise in a case like this to specify a n independent
check of the composition and do age of the drugs before administering them , and to specIfy error handli ng
accordingly_Error-processing requlTemenlS in this case may consist of a comple te stop of the application, or.
temporary halt and a notincation to the operator of the device indic.ting the problem.

10_6 DOCUMENTING REQUIREMENTS

The output of requirements analysis is what the IEEE calls the software requirements specification (SRS)-
There are several ways In which an SRS can be organized. As we will sec in C hapter I I and beyond, the
Ecl,pse open source prOject is organized around three "subprojects." Within each, requiI'Cment are orgamud
AGILE METHOOS AND REQUIREMENTS 239

I. InlOoduction 2 I 6. Memory constraint.


1.1. Purpo>c 2 I 7. Operations
1.2. op 2 1.8. Site adap tation requirement'
1.3 Definition , acronyms, and abbreviations 2.2 . Product functions
IA . References 2.3. User characteristics
1.5 Overvi~w 2.4. onstraints
2. Overall description 2.5. Assumptions and dependencies
2. 1. Produ t perspectiv~ 2.6 . Apportioning of requirements
2 . 1.1. System in terface 3. Specific req uireme nts
2. 1.2. U ser interfaces
(sec Figure 9)
2. 1.3. H ardware interface
2. 1.4 . Software interfaces
Appendixes
2. 1.5. Communications interface

Figure 10.9 IEEE 830-1998 Software Requirement Specifications table of contents. 1 of 2


SA ' ~~ IEEE Std 830-1998

around several "themes ." The OpenOfflce open source project organizes its requirements III four main pans, a
word processor, a sp readshee t, a presentation faCility , and an illustration 100i.
In this book we will ofte" use and modify IEEE tandard 830 · 1998 [6 ], ,hown In Figures 10 .9
and 10. 10. The IEEE sta ndard was developed and maintai ne d by a committee of very experienced
software engineers . It is very helpful , but it requires mo difi ca li o n and tailoring 10 respond to changes In
tools, languages, and p ractices . The Arst two sections of the landard , "In troduction" and "Overa ll
desc ription ," correspond to the high. leve l requirement s and arc cove red in C hapter 11 . Section 3 of the
standard, the "SpeCific requirements," corresponds to the detailed requirements . It is expanded and
applied in Chapter 12 .
ext we turn our attention to the essential links of the SRS to the resl of the projecl.

10.7 TRACEABILITY

Tractability is the abilrty to readily understand how the parts of eparate project artifacts relate to ea h other.
In particular, it links indiVidual requirements With other project artifacts. (Sec, fo r examp le, [7 ]). A detailed
requirement is traceable if there arc clear links between it, the design c lement that accommodates II , the ode
that implements it , the inspection that verifies it, and the test that validates It. Figure 10 . 1 I shows
relationships between the artifacts, based on a si ng le requirement.
Table 10. 1 is an example of how a c hange in a requirement for DVDs in the video stOft application
causes c hanges in the remaining artifacts.
Hyperlrnking is a c onven ie nt way to transitIOn easrl y between art ifac ts. In particular, the requirements
document can be placed on the Internet or an intranet, Jnd dependent artifac t can be connected v ••
hyperlinks

10.8 AGilE METHODS AND REQUIREMENTS

Agile prOCesses specify requirements analys" by " t e\labli<hlnl! a .hared v'Slnn of the apl) li atlon Th •• "
dOl\(! v.a d,S(;uss.on~ amon~ the learn members and th ... CU~lOmcr After that the requlremenl' are gathered In
relatively small .. talle .. The v,,;on stage i. Intended 10 form a Lon cpt of the ullllll~le prod"ct that r< >lmpie
240 CHAPTER 10 PRINCIPLES OF REQUIREMENTS ANALYSIS

3. I External interlaces

3.2 Functional requireme nts


-organized by feature , o bject, user class, etc .

3 .3 Performance requirements

3.4 Logical database requirements

3.5 Design constraints


3.5 . I Standards compl ia nce

3.6 Software sys tem attributes


3.6 . I Rehability
3.6 .2 Availability
3.6 .3 Secunty
3.6.4 Maln tai nabil ity
3.6 .5 Portability

3.7 Organizing the specific requirements


3.7. I System mode - or
3.7.2 U ser class - o r
3.7 .3 Objects (see right ) - or
3.7 .4 Feature - or
3.7 .5 Stimulus - or
3.7 .6 Response - o r
3.7 .7 Functional h ierarchy - or

3.8 Additiona l comments

Figure 10 .10 IEEE 830-1998 Software Requirement Specifications table of contents, 2 of 2-detailed requirements
SOtIrre IEEE SUi 8JO.1998

and clear enough for all stakeholders to understand and relate to. This vision is kept as concise as possible
without compro miSing the shared vision itself. Examples arc as follows,

An appl ication that allows VIdeo store personnel to manage DVD re ntals

A Web-based calendar program fo r individuals and depalllllents


A system that analyzes individual. suscep ,ibility to d isease based o n the ir gene tic infonnation

The vision stage is followed by multiple iterations that are typically 2-4 weeks in duration. Such an
iterative style ha the advantage of kee ping misunderstandings to a minimum and allowing all concerned to
grapple with the requiroments being considered. The requirements for each cycle are gat herod by means of
lISt' ,writs narratives, always told from the us"-s perspective, of how the application is to be used. This
process is summarized in Figure 10. 12 and described in more detail in the sections ,hat follow.
UPOAnNG THE PROJECT TO REflECT REQUIREMENTS ANALYSIS 241

Requirement 1---- accommodates-- Design Element

implements relales 10
relales 10 implements

Test '<- validales ---: --- Code

verifies verifies verities verifies

Inspection

FIgure 10.11 Traceability among project artifacts

Table 10.1 How a change in a requirement for OVOs in a video store application causes changes in other artifacts
Onginal version Revised version
Requirement The title of a OVO shall consist of between 1 The title of a OVO shall consist of between 1
and 15 English characters. and 15 characters, available in English,
French, and Russian.

Design element

~ing
OVO ..QYQ.
title: String

Code class OVO class OVO


( (
String title • • • • Title title • • • •
) )

class TItle ...

Inspection report InspeC1ion # 672: Inspection # 935:

4 defects; follow-up Inspection #684. 1 defect; no follow-up Inspection required.

Test report Test N 8920 . . . Test # 15084 ...

10,9 UPDATING THE PROJECT TO REFLECT REQUIREMENTS ANALYSIS

A project's document sct is a liVing e ntity It has to be "fed and cared for" at regu lar intervals thrOullhOlIl the
life o( the project TYPically, when a pha e IS executed, severa l documenl must be updated
For very large projects, the proce" of analYZlnR the customer's requirements IS (ormal and or~anl zl'd ,
Forexampie, the U.S_Department of Defense (000) ohe n publ"hcs a requesl for propo<al. (RFP) to develop
2~2 CHAPTER 10 PRINCIPLES OF REQUIREMENTS ANALYSIS

Develop
common
vision

Specify user slories Each cycle:


and lests beginning

Write tests lor Each

Each cycle:
end Code

Figure 10.12 Agile requirements analysis

an SRS alone. Such an RFP contains a very hi g h level descripti o n of th e project. The RFP can be thought of as
specifying the hig h . level requi re me nts. Contrac to rs res pond to the RFP, and a winner is chosen who creates
dctailed require ments. To en ure that th e requirements are sa ti sfac tory, numerous meetiF'lgs are held. These
involve contracto r perso nn el , civi l serva nt specialists and managers, unifo rm ed ofRcers of the Navy or Air
Force, and o th ers. The rcsu ltlrlg RS ca n be th ousands of pa ges lo ng. The winning contractor mayor may not
be c hose n to perform the actual design and development of the application .
Once h' gh · level requirements have been ga thered, the SPMP CJn be updated as shown in Figure 10. 13.
Such upd a ting occ urs through ou t the' li fe cycle of an application.
The result ing schedule wou ld rypica ll y be like that show n in Figure 10 . 14, containing more detail than
th e schedule show n when th e SPMP was o n gi nall y drafted (C hapter 8) but still not ve ry detailed. In

Status after Status after Obtaining


Initial Draft High-Level Requirements

,WI"lo"" Initial More milesto nes; more specific

Risks Ide nti fy initia l risks Reti re risks ide nti Red previously, identify more risks
now th at more is known about the project

Sc/xdwl, Very rough Preliminary project schedul e


.-
Desig nate h ig h -level Designated e ngi neers fo r derailed requirements
requ irement' engineers analysis I

Cosl EsI;""'lio" Very rough First estimates based o n job conte nt

Figure 10.13 updating project plans after obtaining high-level requirements


.3 ...... '.1& 1' [ . ...1
(~a"t'b
~~4S.S

L AlcHed\le
~ 0eI7' 7 ~de,.."

1 '" '! ICC

,...
'.EYote

e ........ rele.u .....2 ! - _._------


-0et0
- 0, --
C~rec:,.MemerlS
- 00.1 tS$b ISO
- I
- -
I
Figure 10.14 Typical schedule after obtaining high-level requirements

particular, we may know that release 0.0 .2 shou ld be made on November 13, but It may be too early to deCide
other parts of the schedule .
Cost estimation ca n be improved once hi gh -level requirement have been analyzed. Th e main
Improvement stems from the increased understandlOS that developers gain concerning the scope and nature
of the application _ Func tion pOLn! estimates (described in C h apter 8) can be made more comp lete , and 0 ca n
the estimates derived from them for schedule and labor. Direct bOllom -up e timates can be improved as well.
Another factor limiting rhe number of Iterations of the requirements IS the hi g h degree of coord lOatio n
required to keep the project documents and th e ource code coordinated . 1111 is o ne reason that hi ghly
iterative development techniques such a agile meth ods do not rea ll y atrempt to wnte detailed requirements
documents.

10,10 SUMMARY

Requirement analysis IS the process of unde rstanding whal ', ,"anted a nd needed 10 an application . The
output of requirements analysis IS a software req uireme nts spe Ihcation ( R ), whi h serves as IOput IOtO the
design process. The R document used in thi s book is IEEE standard 830 - 1998
ReqUirements arc divided into hig h -leve l a nd detailed rcqlliremen ... Hi gh -level reqUlrement< arc al 0
called business requlfcments These deSCribe why the app li ation IS belOS built and <tate Ihe benefits to both
the developing organization and the Ql<tOlller Detailed requlfement, provide omplete speciC, < about the
requirements that developer must know 10 o rder to implement the appli ation .
ProJcct requirements often change and evolve throllghou tthc life of a project. \Xfhcn the do, other prOject
anlfacts such as the de~18n al1d Impleme ntallon mil t c hange accordingly Trnrrnbi/lly allows for mallll,lIl1lng
a~lalJon between IndiVidual requirements and other prOJe t artifocts to faCilitatc IIpdatlOA the m
Both high -level and detatlcd requirement' are ciasslted "' either fun tl o nal or nonfunctional Fun lIonal
requir 'ments 'PC ify 5ervicc~ th at the app" allon mu t proV ide 10 the II c r. N o nfunctional reqUIrement
specify qual,tles, <.en slrainh, Interfa os, and errur h a ndlln ~ of the application ,
Agtle reqUirements analys" ,tart, by deOnlng a o n I<C v", on <tateme nt ahollt the Intended application .
ext , 2- 4 week development y I ', are excUited , With the R,." 'IeI' of eaL h dchnlO~ the reqllirel11cnh f(lf that
2« CHAPTER 10 PRINCIPLES OF REQUIREMENTS ANALYSIS

Iter.ttlon Each requirement IS u.ually ba cd on a """lory along with an explicit acceptance test. A uscrStory IS
a hig h . level piC e of req uired runctional iry a seen by the antiCipated user. Detailed reqUirements arc usually
expressed in terms of unit te ts r.tther than being wrinen explic itly .
After requ irements analysis IS completed (or after each iteration," an Iterative process), the project plan
I updated to reflect the new details known about the application . The more requirements that are known, the
closer the schedule omes to being fina lized .

10.11 EXERCISES

I Explain wh y a defective requirement could be 100 times more expensive to fix after software is
deployed ve rsus being fixed during requirements analysis .
2. Give an examrle or a so rtware application in which the customer is the sa me as the end user. Give
an example in which they are different. In each case . identify the customer and end user.
3. In your own words, explain the difference between hi gh.level and detailed requirements. Give an
example of a h igh -level and detailed rcq'Jirement for a typical word rrocessi ng application.
4. In your own words , describe the difference between functional and nonfunctional requirements.
5. Explain wh y the foll owing requirement is not sufficient. How would you amend it(
" The o rder e ntry system shall not crash more than 5 times per year. The system shall recover
from each crash as quickly as possible to avoid down time."
6. Bracken makes the po int that the more constrained an arrlication , the less reliance we have on
people as the source of requ irement . (Refer to his graph in Figure 10.3 comparing "approximate
percent o f requirements gathered from people" with "type of application.") Can you think of any
applications that do not rail on the graph's diago nal )
7. Agile requirement; ga theri ng calls for a customer representative to work continually with the
development team generating requirements . Describe a scenario in which this type of arrangement
may produce poor requirementS .

8. What are three major advantages and disadvantages of describing detailed requirements with unit
testsi

BIBLIOGRAPHY

1. Brackett , ] "Softw3R' Rcqulrt~mC'nls SEI CU rriculum Module SE I· CM · 19- 1.2: January 1990. hupJlwww sc: ,.cmu.~dul1lbr.uy1
r
absrracw rcpof'tsl9OcmO19 dm 3cc~srd N ov('m~r 1S, 2009 J.
Mort Abcwr SO/llNrr RC4I1'ttM",fJ. Mic lO<ioh p~S\. 2006, P 5
2. W iegers, Kl.rl E., W
3. Davis. AIVl M ., NSoJlll'IJrt RtqvlrtWlm lj Ob"trlt F"",ho"). a"J Staid", Prentice: Hall, 1993 , p 310
4 Callt'Z, W .• "11.1( EJsmlldl ~wJ( to Uw Irs'tr/act 00'9" k ,,,troJlI( llI1II !D CUI Pmlclp~ amJ Trcbrsrqllt)," John Wilcy & Son .., 1996
S. Alexander, lan , ;tnd Ncoll Malden (Ed itors), ~Sc",,"nos, Siono. US( Cam.. nr~h IIx Systmls Drotloplfln" Llt-Cyru" (pJ.pc'm;u:k), John
WIley & Sons. 200 ..
6. ~I EEE Rccomme:ndC'd Pri)c~icc: (or $o(IWolr'C Rc:quJre:me:nts pc:-cl t\ca tions,· IEEE SrJ !JG- I90S, June: 1998
7 Wle:gert, K;ul E. ~Sof'1l)Q rr Rcqllll'CMnfb," Microsoft Prc:ss. 2003.
Analyzing High-Level
Requirements

• What are examples of customer wants?


Planning
• What does stakeholder VISion mean?
Maintenance
• How do you mtervlew for and document
requirements?
The Software
Development .-___ '___ • How does one write an "overview"
Lifeeyele requ irements section?
Require,i.e"t•
• ".iysls
• How do you write -mcun functions" and
lion use cases?

• What agile methods are there lor dealing


Design with high-revel requirements?

• How do you SpeClty user Interfaces at a


high level?

• How does one frame secunty


requirements?

• How do you use dIagrams for h,gh·levet


requ Irements?

• What are examples 01 high· level


requirements In practice?

FIgure 11 .1 The context and learning goals for this chapter


2.6 CHAPTER 11 ANAL YlING HIGH· LEVEL REQUIREMENTS

Hi g h . level reqUire men ts descnbe the purpo e o( an appl.cation and ilS Intended functiona lity. They can
al a descnbe the app lication's beneRts to both th e cu>tomer and the dcveloplng organization. This chapter
de cnbe th e process w hereby we collect, ana lyze, and specify the requirements at a hi g h level . It is help(ul to
express hi gh . level requ irements usi ng both text and dia grams, in o rder to convey a complete understanding
of the intended application . Hig h . leve l requirements arc of great interest to all stakeholders, particularly
eu to mers, who purchase and ult imately usc the applicati o n based on it require ments .

11.1 EXAMPLES OF CUSTOMER WANTS

T y pically , at the time that requirements analysis com me nces, the customer is still (orming concepts of what
he o r she wants and needs. ThIS is an.logou< to the requirements·ga thering ph.se between an architect and a
client . Fo r ex. mpl"" a client may want a house with (our bedroom s and a large li vi ng room , but nevertheless
rel ic o n th e architect to help clarify what he wants .nd needs (e .g ., a ranch house with a living roo m with
ealing (or ten ).
As an example , consider the Encounter case study. The (allowing is a fragment of customer thinking
obta ined by a myt h ica l marketing depal tlllcnt.

Encounter is to be a role -playing ga me that simulates all or pan o( the player's lifetime. It should
be of interest to bo th male and (emale ga me players.

Figur<'S I 1.2 and I 1.3 summarize the hi gh.level requirements (or the Encounter case srudy. The complete
descnptlon of Enco unt er hi g h -level reqUirements is contained in Section 2 of the SRS, Overall Description. The
requ irements sta tements In Figures 11 .2 and 11 .3 arc at a very high level with detail purposely omitted. For
exa mple, th e requ irement "Each quality has a value" does not specify what those values are. SpeCific values are
documented in the deta iled req uirements o( Section 3 of the SRS.

• Ro le·pla yi ng ga me that si mulates all or part of the lifetime of the player's character.
• Ca me chacac ters no t und er the player's control called "fo reig n" c haracters.
• Ca me cha rac ters ha ve a number of <llIalirits such as strmglh , spud, pa tirncr , etc.
• Each quality ha a value.
• C haracters ""ncounter" each other when in th e same area, and may then "engage" each other.

Figure 11.2 High·level requirements for Encounter, 1 of 2

• The result of the engagement depe nds on the va lues o( their qualities and o n the arca in which the
engagement takes place_
• Player characters may reallocate their qualities, except while a foreign character IS present.
• Realloca tion takes dfect aftcr a dela y, during which the player may be forced to engage .
• Success is measured ...
o by the "life points" maximum attained by the player - o r -
o by living as long as possibl e.

Figure 11.3 High·level requirements for Encounter, 2 of 2


STAKEHOLDER VISION 247

At thiS rag~ requlI"cmcnrs analysis, there are usually unrcsolved bsues such as whether there is to be
In
onc or several h.ra ters under the control of the player, what should occur when two character; Interact, and
w~fher thc same an be played over the Internet. It IS the task of the development team to work With
customers to clarify their wants and needs_ A common pro ess is to interview the customer, which is
d~bed III Section 11 .3.
Customer nccds can be Subt ler to las ify than their lV.n'" since customers arc typically less conscious of
them . For example, a cu tomer may W.II' a musi application that allows computer novices to write music but
may "ltd a periodic auto-save function to avoid lOSing work. Whether such a feature i a requirement or part of
thc design dcpends on what is agreed between the developer and the customer. If the customer. having
underilood auto-saving, wants this feature , thcn it becomes a requirement_ The customer may be content ,
however, to Icave it to the designer as to how to accommodate the computing needs of novice users. In that
case, auto -saving would not be a requirement, but a desig n element.

11_2 STAKEHOLDER VISION

The people who have some interest III the Outcome of the product are ca ll ed its ".ktl,old"s. As an example,
consider the creation of an c-commerce W'cb SIte. One set of stakeholders consists of the site's Visi tors .
Typically, their primary requirement is the ease with which they can And and purchase needed items . Thc
company's owners are stakeholders, too. Their primary requirement may be proflt, sho rt - or long-term . For
this reason, they may want the si te to emphasize high -margin items. Marketing, another gTOUp of stake -
holders, may rcquire the Web site to track visitors . The application's developers are stakeholders, 100. For
example they may want 10 use new development tec hnology to keep up to date.
In the case of packaged (shrink-wrapped) applications such as word processors, spreadsheets, and
development environments, as well as their equivalents (such a do,vnloaded applications ), the deve lopment
team pays a gTeat deal of attention to the acceptability of the application by as many users as possible.
Although this can be a difncult marketing problem , it is clear that the users arc the most signincant
stakeholders_ For many large projects, identifying the most imponant stakeho lders is complex. n,e
·customer" is often the pany paying to have the application developed, but even this is not clear-cut
For example, the Navy may be paying for an application , but the developers' day -to- day customer may be a
civil servant rather than a naval ofncer. Then again , arc not the taxpayers the "customers," since they arc
actually paying for the application] The customer of a subco ntractor is the prime contractor. The Ctl tomer
for shrink -wrapped applications is a composite of potential customers established by the marketi ng
depaltlllenl. WRen an application is intended for Internal company usc, such as claims processing within
an insurance company, the customer i~ an IIlternal organization .
ConAicting takcholder interests ca n ea<i/y result in inconSistent requirements_ An example of this
occurs when two different groups Within a company, with different motivations, apparently want the "samc"
application built. When requirements ca nno t be reconciled, project tend to flounder and are frequently
canceled. Even when stake ho lders' requirements are co n,i tent, they may be toO expensive to sa ti sfy entirely.
Developers yet anot her stakeholder com munity- are subject to professional respon<lbilities, which can
profoundly affect reqUirements. uppo. e, for example , that developers arc asked to build software for a medica l
<k-viGe With a fixed budget , but they come to understand that the reqUired fearures ca nno t all be adequately tt-' ted
'.'Hh'n that budget. Unless the budget" changed , they would need to dim lnate feature for professional reason,
A good deal 01 stakeholder identiAcatlon and management involves Ill.naging the <cope of the
rC'luorcments to make them bUildable within give n bud!!etary and scheduk con~ trailH~ . The go d prole t
leader ~rmounh these ddf,cultlcs a pro c ,t hat require, manaHcnal , personal , bu<lnc", alld politi al,klll'
Customcf\ develop a Vision somct lm c~ ulle nsclous or IIlLomplet e of how thelf al plication "'ill
operate_This Vls)on IS sometime<; referred to a ~ the applica ti o n', modd or COfl«P' of oprr.,Ii.II I "'crellt peorle
248 CHAPT€R 11 ANALYlING HIGH-LEVEL REQUIREMENTS

may hold differing co ncep ts of what a software application enta,ls_ For exa mple, th e poss ible concept of
operations for ' a weather syste m" could be

• a facility for {"urning raw weather service information ,nto graphica l form
or
• a real -tim e system fo r forecasting the weather
or
• af.\ application for alerting users to weather anomalies

These diffe rin g co ncepts of operations lead to very d iffe rent applicationSi
The project manager o r requirements engineer helps the stakeholders to clarify their concept of
operatio ns , ince custo mers usua ll y lack the means with which to express such concepts, engineers can
propose appropriate techn,que uc h a usc cases, data flow d iag rams, or Slate transit io ns, w h ich are described
below These tec hni ques are also used for desi g n , as sh own in Part IV.

11.3 THE INTERVIEW AND DOCUMENTATION PROCESS

Much of the analysis of requirements IS a person -to-person activity , organized to produce an application
satisfyi ng the customer_ Figure 11.4 summarizes the process of preparing for and interviewi ng the customer to
ehcit their require ments.
ince there are ryp lcally several stakeholders who want to provide th eir input, the Hrst issue is deciding
whom to interview. Recall that requirements co m ing from different stakeholders may be contradictory. It is
often effective to Interview a small number of primary stakeholders, and then solicit co mments from other key
stake ho lders. Two interviewers at each session arc preferable to one, since a typica l interviewer tends to miss
POIn[ . Bringing a recorder can help. with permission requested in advance. The most sig nifica nt person to
Interview IS ofte n the most difficult to chcdule time with , so perseverance is called for. Interviewi ng the wrong

Befo're interview:
1. list and prioritize "customer" Interviewees
• most likely to delenninc project's success.
2. Schedule interview with fixed sta rt and end times.
• at least twO from development team should attend .
• prepare to recordi
At interview :
3 _ Concentrate o n listening .
Don't be passive, probe and encourage.
• persi t in undt'rstandlng wants and exploring "tcds.
• walk through use cases, also data flow ) state diagram s)
Take 'horough nOles.
4 . Schedule follow -up mee' lng for validation .
After interview :
5 . Draft SRS hi g h -level requirements using a tandard.
6 . Contact customer for commen t'S.

Figure 11_4 One way to handle Interviews with the customer


DESCRIBING MAIN FUNCTIONS AND USE CASES 249

ptOI'le can I.. sult III wa>ted o me and dfort. The e",,,, ' 8 ,1e process in particular tn, ist' that the customer
communlt. supply ju<t o ne rcpr.,,;c ntatl ve for reqUI re ments. Th is puts the o nu o n the stakeholders to provIde
con n ent requiremen t'; ra ther than havll1g develo pers adjudicate amo ng d, ffering custo mer communities.
Altho ug h It IS Im portant to listen carefu lly to the CUsto mer at the mtervi ew, o ne usuall y ca nno t obtai n
requ,,..ments b o ne·way listening alo ne. T ypically, the cu to mer fo rmulate some of the requirement a he
goes alo ng , and need - help. Altho ug h Ihe VI ion crealed is pri marily the custo mers, the intervIewer and the
cuSlo mer develop a visio n Jointly to an ex te nt. usto mers usuall y require some pro mptong to fi ll out thci r
VIsion, a I,ttie (but nOI too muchl) like a witness o n Ihe stand . Denni [ I] suggesls askIng three ty pes o f
questio ns: close·ended, o pen-ended, and pro bing. Close-e nded que ti o ns, such as, "H ow man y videos do yo u
expect to keep in stock " prov,de ,mpo rtant de tai led ,nfo rmation about the system. O pen .ended que tio ns,
such as, "What are the sho n comings of yo ur current vi deo sto re system]" allow the intervi ewee to elabo rate
on his requirem ents. Pro bing qu.,,;tio ns , such a "Ca n you give me an exampl e of why the use r interface is
dif6cult to use?" are fo ll o w·up questions desig ned to ga ther mo re detail ed info rmatio n.
U e cases, described in Section I 1.5 are an effective way to obtain and express requirements fo r a wide
variety of appl icatio n Some requirement need to be diagra mmed, and ways to do Ih is are described In Sectio n
11.9. To validate the requirements as written out, Ihe II1terviewers follow up via e· mai l, holding a subsequent
meeting if necessary. Recall that the dtlnikd requirements have ye t to be gathered and require additional meeung
time
After the meeting , the hig h . level requirements are draft ed on a fo rm at such as the IEEE tandard. The
draft should be provided to the customer communi ty fo r co",ments, and successive interviews arc conducled
unt" there is sati sfactio n \vith the high · lcvel requirements.
The great challe nge we fa ce is expressin g clearly wh at custo mers wa nt and need. W o rd alone ca n be
appropriate, but for many applicati o ns, narrative text needs to be supplement ed by Rgllrcs of van ous k,nds.
The following sectio ns describe how to express hig h· level requ irements.

11 .4 WRITING AN OVERVIEW

An overview is inte nded to all ow readers to quickly understand the mai n purpose o ( the ,ntended applocation.
O therwise, it sho uld be as sho rt as possible and should seldo m need alteration whe n projec t deta" s change
The ch allenge o f writing a good ove rview is usuall y underesum ated. pro bably becau e it is often thoug ht that
,f one knows what a subject is about then summariz ing it sho uld no t be d ifficult
The follOWi ng is an example for the video sto re appltcation, in th is ase, a songle se nte nce suffices

V to re is inte nded to help video sto res manage DVD inve ntory and rentals.

II IS tempt ing to add mo re details to thi s, but good requirements document< arc organtzed to provide
detaI ls 111 o rderl y sta ges, so add ing mo re detai ls hcre wo uld result on dup lica ti o n and could reduce readabil, ty .
"Manage D VD onvc ntory and re ntals" prOVIdes substantive info rmat io n but 's genera l enouglt so that changes
on requirements detai l< are unl ikely to fo rce ,t to change .

11.5 DESCRIBING MAIN FUNCTIONS AND USE CASES

FollOWi ng an overview sectio n, h, gh · level req uorement s u<ually li« the majo r (un t,o n such a< "e nter new
Video" and "re nt vIdeo " Since users ty pi ca ll y lI UIt ZC ap plt auo ," through a rel atively , ma ll nllm ber of
common ba~k . a n d . rort h on teract,o ns, t his can be a good way to summartze functi o naltty 11 dfe t, ve wa to
document Ih.,.e In teract ions 15 th ro ugh wri ti ng li St cn<rS , o nl(i nally co,ned by Jacob o n [21 U ease de, nbc
the lyp,ca l .equence of ,nterac t,O", betwee n u<e r 0 1 an "Pplt auo n J IlO th e appl! a ll n 't,ell , and proVide a
250 CHAPTER l' ANAL ¥ZING HIGH-LEVEL REQUIREMENTS

narrative of how Ihe application is used [3) . They have become a very effcclive way to express many
fun tional high-Icvel reqUIrements. As an exa mple , when using J word processor, we usually ( 1) relrieve a fllc,
(2 ) cha nge and add teX! , and Ihe n ( 3) store the resull. Functional hi g h -level requirement. are often naturally
cxpre sed as an inleraCli o n belween th e applicalion and agencies eXlernal 10 it, suc h as the user.
Agile projects rend 10 employ Ihe idea of IISer slo';t!. TI,esc are si mdar to usc cases but arc broader in
scope and have dis llnc t c rileria . U scr stories are de cribed in Sect Ion I J .6.
A use case IS ide ntified by its name and by Ihe Iype of u erof the applIcation, called theaclor. The main part
of a usc case documcn a typical inleraction bctween an actor and the application , often called a scmario. A
scenario consists of a numbered list of steps. Each step should be simply described and include who is carrying out
the SlCp. A good way 10 start wriling a usc case is to list the tnai" sllcem sct"nrio, which is the sequence of steps that
lead 10 a succt'Ssful o ul come. A single use case should nOI attemprto accouni for a significant number of branches.
Other scenarios of Ihe usc case , such as error conditions, are ty pically documented as ext""j""s . For example,
Rrlnroc n File would be a typical use case for a \\lord processor, with the user as actor. The main success scenario
contains Ihe following seq ue nce of seven steps. NOle Ihal each step stans with Ihe entity Ihal execules Ihe slep. ln
Ihe case of an error in ope ning the selected file . an alternalive is doc umenled in the Extensions secllon ,

RetTieve a File

Main Success Scenano

I. User clicks File menu

2_ Syslem displays op lions new and open

3. U ser clicks open

4. Sy lem displays Ale WIndow

5_ User enters directory and file name

6. User hits open button

7. System retrieves referenced file into word processor window Extensions

7a5ystem dISplays error ind icati ng file could no t be opened

It is possible for a single person to use a system in several differenl ways, adopling Ihe roles of differenl actors.
In UML, a usc case diagram shows Ihe actors, the use cases, and Ihe relalionship between Ihem. A use case diagram
is a useful 1001 for d iagrammatically summarizing Ihe sel of aCIOrs and usc cases without having to show allihe
delails of Ihe usc cases. Figure J 1.5 is an example of a use case dia gra m, wilh Ihe names of Ihe use cases shown in Ihe
ovals, and the actors drawn outside the rectangle with lines connecting Ih<'TTl 10 the use cases Ihey inleract with.
As furlher examples of use cases, Figures 11 .6 and 11 .7 contain examples of lise case scenarios for the
I"ilialit< and E"ga9' Forcigll ChMaclcr use cases for lhe Encounler case ludy.
The aclor in each of Ihese usc cases is the player of Encounter. Each use case is a sequence of aClions laken
by the player and Ihe Encounter game, as shown for Ihe IniJializt lise ease. The Engag, Forrigll Charnelrr use case is a
typical sequence of actions by Encountcr and Ihe player, whenever Ihe player's main characler and a fo",ign
charaCier arc in the same area .1 the same lime. The aClor in the 5" Rub usc case is a game designer. The actor
describes Ihe ability of Encounler 10 support the ediling of rule forcharacler interaction. The Trawl 10 Adjomol
Arta usc case is explained in the case srudy accompanying this book. The Stl Rules use case is nOI included in t~
case ludy ",quiremcnts.
DeSCRIBING MAIN FUNCTIONS AND USE CASES 251

ActOG
Initialize )

/ Travel 10
adjacent
area
Player "- /

Engage
foreign
"'-
character
"-
Designe r Set rules

figure 11.5 Use cases for Encounter-a UML use case diagram

Initializ~

I. Systtm displays player's main character in the dressing room .


2. Sysltm displays a window for semng his character's qualities.
3. P/Qytr allocates the qualities of his main character.
4. P/Qy" chooses an exit from the dressing room .
5. Systtm moves player's main character into the area on the other si de of the exi t.

Figure 11.6 Initialize Use case

Engag~ Foreign Character


I. Sysrtm displays the foreign character in the same arca as the player's.
2 Sys/tm exc hanges quality values between the two characters.
3. Systtm displays the re ults of the cngagement.
4. Sysltm displays player's character In a random area .

Agure 11.7 Engage Foreign Character use case

The actor need not be a human role- It ca n he another syste m th at lIses the application. For example, if
the application under development I a robot con trol y.tent, then the actor cou ld be a fa tory au tomation
system that uses the robot contro l sy~tcm
Use cases can handle limi ted branching, but .r there is more than one leve l of bran h,ng, the exte n"on
Idea. dc~cnDcd above, ca n be tned Ot herw l e the ",. ca," should probably he decomposed Into other lise
cases Even a slOgle branch in a lise cas lead to an awkward description . Forcxample, the follOWing ould be
a usc case for a personal budgeting aprl,cation

f User selects "add checks' or ' reconcl lr a count"

2 If ' add che<.k. selected ,


252 CHAPrER 11 ANAl YZl NG HIGH-LEVEL REQUIREMENTS

3 ne .et lo n happen>

not her a lio n happe ns


5 • . (one o r more stcps)
6 . If ' reconclle account" selected:
7 One action happens

S. Another actIon happens

9 • •

Th is would be better decomposed '"to "select o ptio ns," "add c hecks: ' and "reco nci le accoun t" use cases.
Use case are like tones and so they provide excellent insight into applications. They can be expressed
at d.ffe nng level of generality. The Uni Red Software Development Process [4] reco mmends using detailed
use cases to specIfy a large fractIo n of the requirements.
A usc C35e that is si milar to an existing o ne yields li((le addit io nal value . Usc cases sho uld be stq"mlial,
or el e orlhogollal to eac h other. T wo usc cases are sequentia l if o ne can follow the o ther. Orrhogo"al is not a
preCISely deli ned term , but o rthogonal use cases take completely different views o r options. For example,
in a warehouse appl,catio n, usc cases based o n a fo reman actor and a Rnancial anal ys t actor would typIcally
be o rth ogonal. In the Encounter case study, Sri Rul" is o rth ogo nal to £"gag, Forrig" Cbaraeltr. Chapter 14
shows how use cases are combined to produce new usc cases; it also introduces inheritance among usC'
ca cs.
Jacobson's [2 ] inspiration fo r the idea of use cases was that, despite the huge number of potential
executIon . mos t applIca ti o ns are conceive d of in term s of a relat ively small number of typical interactions.
He suggests starting application desig n by writing usc cases, then usi ng them to drive class selection. This
technique is demo nstrated in C hapte r 12. Use cases are also the basis for system·level test plans.
Many established documentation standards, including the IEEE's, predate use cases and they must be
augmented to accom modate them. The Encounter case study describes them in Section 2.2 ' Product Functions'
of the SRS, as th IS IS the sect Io n that describes the functi o nal high -level requirements. Although use cases arc
often identified with object-o riented methods, they can be used with any development methodology.

11,6 AGilE METHODS FOR HIGH-lEVEL REQUIREMENTS

HIgh -level reqUIrements fo r ag de projects arc collected and understood in a manner si milar to that for non-agile
methods except that the requirements process operates ," pieces and continues continuously through most of
the li fe of the project. Non-agi le processes requi re a time when requirements are frozen (,.e , beyond which the
customer has no right to change them). Agile processes, o n the other hand, accept frequent chang~ in
require ment as a necessity How can one of these be a valid approach without the other being invalid] Th ..
difference lies in the level of truSt e ngendered by very close customer contact. If the customer's trusted
represe ntative works continuall y as part of the development team , it is unlikely that he will suddenly ask fOf
un reaso nable requirements In agile processes, selected h igh-level requirements arc elaborated upon within
each iteration. Each is usuall y based on a ",,,slory or slori", each accompanied by an explici t acceptance teSt A
uscr story is a high-level piece of required functionality as seen by the antlcipaled user. According to B~k and
West [5] a use r story must be discrete, estImable, teStable, and prioritized, as described in Figure 11.8.
Compared with use ca es, us"r stories are described less by their form than by these qualities. Having to be
estImable is o ne d ifference, and this is ill ustrated in the example below. User stories can al a be more utens;ve
than usc' cases.
AGILE METHOOS FOR HIGH·LEVEL REQUIREMENTS 253

I. From US.,'S P"l"$pcctive


2. Dlscret.,
• Single functionality, feature , o r expectation .
• Not neees anly precise.
3. Estimable
• Developers can estimate required effort.
4. Testable
5. Priori tized
• By customer, in consultation .
6. Can be Ilt in a Single cycle.

Figure 11.8 Required qualities of a user story

Beck and West [5J give an example of how to ga ther user stories. Thc custo mer starts wi th the fo ll owi ng
story.

0.0 Will outpeifom1 all other u",dill9 machilles

This is fine cxcept that it's no t estimable-there is no way to esti mate th e effoft reqll1red to carry out th is
job. Consequently , the developer probes fo r more speCific stories to o btain estimable ones, a process known
as splitfing.

1.0 Payment. Will accept all killds oj paym"'t'

2.0 Freshness. Will sell 110 stale or ou tdaled mcrchalldise


3.0 Restocking. Will auton,atically request rcstockill9 oj iteltls selli1l9 best ill tl" arm

4.0 Communication . Will (omm lm icntt with tht cus lonur 10 prtvw l tran sactio" (rrars

This is an improvement, but these are still not estimable, so further splitting is required. Recall that
prioritization is also ca lled for . The agilc programmcr the n requests more speCtfics concernin g the highest
priority story. If this were ' .0 Pay",,,,t , the uscr mi ght provide the following :

I. t Accept coins

1.2 Accept ('''''"ey


1.3 Accept debit card

1.4 Accept mdit card

1.5 Acapt debIt or mdit card Uta W,b Irallsaclioll


1.6 Accept Jortlg'rl coilts {HId ( UfralC)', at least C'IH 0 5 Jar snits III Europt

1.7 OHVCrl ("ur(tHeirs

1.8 Ellsu" Ihal pay",,,,t m"IS or t')(",ds tb, cosl oj th, "ltCled /Jrod" I

1. 9 Makr chall9'
254 CHAPTER 1 1 ANALVZING HIGH·LEVEL REQUIREMENTS

0 .0 WI/I
Spill
outperform all
o/h8r wmding
1.0 P8ymen~ Accspt
machines Spill
all kinds 01 psyments
2.0 Freshness. Sell
NOI eSlim able no stale or outdated 1. t Accept coins
merchandise
t 2 Accept currency
3.0 Restocking.
Automatically request
t .3 Accept debit card
restocking 01 Items 1.4 Accept credit card
sell/ng best In tha
area 1.5 Accept debit or credit
card via Web transaction
4 .0 . ...
1.6 Accept loreign coins
NOl eSlim2ble
••••
Needs prioritlzalion

Figure 11 .9 SplItting user stones

The plrlling process is Illustrated in Fi gu re 11.9.

11.7 SPECIFYING USER INTERFACES: HIGH lEVEL

Th e speCIficat Io n of a user iNerface at a hi gh leve l is often included rn the high . level requirements. Recall
fro m SectIo n 106.4 rhe fo ll OWi ng steps in specifyi ng user interfaces.

Step I . Know your user

Step 2 . U nderstand the busrness function rn questio n

Step 3. Apply pnnClples of good screen desig n

Step 4 . •

W e wrll discu s Steps 1 and 2 in thi c hapte r as the y app ly o nl y to h ig h · level requirements. The
rem ai ning sleps arc described the nex t chapter, on dctcu led requirements.

11.7.1 Step 1: Know Your User

ThIS step invo lves understandin g the narure of th e applicatio n's eve ntual u ers. Figure 11 . 10 outlines ome of
the fac tors Involved The c heck lis t IS a way of ensunn g that we know the ba IC c haracteristics of the
anticipated u ers, and that we documen t our as: umptions. These characteristics determine the nature of the
user interface. In genera l, users with less educa ti on, trainin g. skill , and moti va tion rcquir~ grca t~r simplicity,
more explanation , and more help. This may have to be traded o ff against ef~de ncy and speed. It is 011<11
desirable to provide several levels of uscr interface, dependin g o n th e leve l 01 the user.

11.7.2 Step 2: Understand the Business Function

ThIs Slep requires the d esig ner to understand th e purpo e of the particula r proposed u or interface in I.nms of
the application's overall purpose. For example, If th e busines purpose is the stocki ng of. warehouse, we may
SPECIFYING USER INTERFACES: HIGH lEVEl 255

• u,vd of knowledge and experience


• Computer literacy (high; moderate, low)
• 5) tem expenence (h igh; moderate, low)
• Experien e with Imdar application (h,gh , mode ra te; low)
• Education (h igh school; college; adva nced degree)
• Read,ng level (> 12 years schoolmg, 5- 12; < 5)
• T yp ing skd l ( 135 wpm; 55 wpm; 10 wp m )
• Characteristics of the user's tasks and jobs
• Type of use of this ap plication (mandatory, dIScretio nary )
• Frequency of u e (co ntinual; fTcque nt, occasional, o nce .in .a-lifclIme)
• T umover rate for employees (h, gh , moderate; low)
• Impo rtance of task (h igh , moderate; low)
• Repetitiveness of task (hig h; moderate; low)
• Training antici pated (extensive, self-trainin g through manuals; no ne )
• Job category (executive; manage r; pro feSSio nal; secreta ry; clerk, etc. )
• Psychological characteristics of the user
• Probable anitude towa rd job (posi tive; neutral; negative )
• Probable motivatio n (hig h , mo de rate, low)
• Cognitive style (verbal vs. spatial , analytic vs. intuitive, concrete vs. abstract)
• Physical characteristics of the user
• Age (young; middle aged, elderly )
• Gender (male, female )
• Handedness (left, ri ght, ambidextrous )
• Physical handi caps (blind, defective vision ; deaf, mOlOr handicap)

Figure 11 .10 KnOw your user when developing requirements


Sot.rce: Adapted from GaUtz. w.. '''Tl'Ie fsse"t~1 Guide to User Interlace Oestgn: Ar11nvoauClJon to GUI pnno ples and technIQues: ' John Wiley & sons, 1996

want the user interface to reflect the layout of the warehouse floor. The seque nce of screens that appear
typica lly reAects the manne r in which use rs no rmall y carry out their tasks for thc business at hand.
Sometimes the execut ion of a program ca n b e e nvisaged by displayi ng a se ries of C UI images .
For exam pic , OAe could provi de a fair co ncep tion o f Encounter by di splayi ng a seq ue nce of scrcen sh o ts.
Figures 11. 11 a nd 11.12 arc exa mpl es of preliminary C UI sketches forsc lling the qua lities of an Encou nter
character.
Upon being show n C Uls, the customer typicall y realize that he needs more or wants o meth ing
different. In the exa mple how n in Figure 11.11 , it could well occur to the cus to mer tha tthc C UI for c hangi ng

Ouallbes Value chosen

11.11 Preliminary sketch of user Interface for setting game character qualities
256 CHAPTER 11 ANALYZING HIGH·lEVEL REQUIREMENTS

Name 01 Name 01
adjacenl area adjacent 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.

cricJc An event
Indicates 'slock OVO" (usually a
slart stale / ___- - - - - - - - - - . - - . . ., 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 257

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
"commit-
button
~~~~. ____________•__~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
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 259

o ConAd~ntiality "C'
o D.t3 passed not vi,Ible to the unauthorized.
o Nonr~pudi.tion

• Pani~ can prove the eXistence of agreement!:..


o Integrity "I"
Ability to alidate no tlaltered in transit.
o
o Auth~ntication "A"

o Ability to vahdate user's ident Ity .

o Authorization

• P~rmi sion to deal with the subject .


• Availability
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 <c'
~onc _ ' me ,nal rules for <eco m ty protect the confldc nlla loty , IIl1 egri ty, and av.i1abd, ty of In livldual he. lth
information and ""II prov,de a sta ndard level of proteellon on an environmen t wher ' he.lth ,nfoml. tio n
260 CHAPTER 11 ANAL YlING HIGH·LEVEL REQUIREMENTS

• n,e H ea lth Insur.ln cl' Po rt abilIty and A counl abiltl y Ac t passed


In 2000 a nd 2002 ; 2003 compha" e
• Regu lales health information c rea ted o r mallltalned by health
care providers
• U Department of H calth and Human rrvlces rc< po nslble fo r
Im plementin g and enfo rCi ng
• lalll thrust· Ensure th at an IndI vIdual's hea llh In fo ml . tl o n IS used
only for health pu rpo<cs

• En urcs conAdentiality, integrity, and availability


• Ma nda les safeguards fo r phYS Ica l to rage, ma Inte nance , trons·
. ,
ml lon, ana acccc;;s

Figure 11 .21 MaIn poInts of HIPAA


Source HIPAA Act of 1996

pertaini ng to an indi Vidua l is housed (·Iectron icall y an d/or is rrtm mitted over telecommunicati o ns system s!
netwo rks. The standard mandate safeguards for ph ysical stora ge and maintenance, transmission, and access to
IIldividua l health info rmat io n. EntitIes reqUIred to co mpl y with the standard include any health care provider,
hea lth care clearing house, o r health plan that electronicall y maintaIns o r tronsmils health information pt'Ttaining
to an in divi dual · Figure II 2 1 ummarizes these poi nts.

11.9 USING DIAGRAMS FOR HIGH-LEVEL REQUIREMENTS

Acc o rd ing to D avi [6 ) and WIegers [7 ), no SIngle VIew o f requirem ents gives a complete understanding, and
It IS o h en hel pfu l to represent hig h ·leve l req uire me nts usi ng dIag rams. What IS o ften needed is a combination
of text and dIa g rams to convey a complete pic ture of the Inte nded apphcatlon . We introduce two types of
dI agram used to descnbe hI g h . level reqUIre men ts: da ln flow and ' Ialt lra tl,illotl dia grams. We are using them
he re to express requ irement . Thcy arc often used to ex press deSIg ns as wdl , and this can be confusing. The
dIffere nce to watc h fo r IS not so much th e fo rm of ex pressio n as whe ther th e attempt IS to express ' what"
(requ ireme nts) o r "how' (desig n)

11.9.1 Data Flow Diagrams

Some requirements are na turoll y described as th e flo w of data am o ng processi ng e leme nts. Fo rexample, imagllle
that our customer is tryin g to explalll what he want fro m an ATM banking applicatIo n, startm g with depo It
and affecting accounts at several locations In a Jain flow dlagra .. , the Hod" , sho wn as CIrcles or rectangles,
represent processing Untts. ThearrolDS between nodes deno te th e Ao w of data . The arrows are annotated wilh the
data's type . Dalll , to,rs-places where data reside, such as databases arc den o ted by a pair of honzontallincs
enclosing the name of the data store. ExIt""" a9C>1CtCs such as the user and printers arc represented by rectangles.
For the ATM application , the dtpo,il functi o nality mig ht get the deposit from the user and check tht
deposit tronsawon to ensure that It IS legitimate. These '"nnions arc represented by clfcles In Figure I I n .
Next , the type of data Rowing between the functions is noted on the figure- the account number and the
depOSit amount. The user IS involved. too, and so IS represented A function to create a ~lI",mary of account'S,
10 give another example', requires input from a store, as shown .
A more complete data flow diagram for the ATM requirement would be as shown in Figure II 23.
UStNG DtAGRAMS FOR HtGH'lfVEt REQUtREMEPlTS 261

Processing
81811.801 Input
Get
deposit i-----UIIr

ACCOUnt no.
and deposff Outout
Direction
of data now Dala type Prtnlet

•• • •••
I
Balance
Validate
query
deposit Create
I
Account __ dala
Account
account
summary
Data store database

figure 11.22 Data flow diagram explanation of symbols

The complete diagram of Figure 11 .23 includes the "member banks" data score , which is a list of banks
allowing a deposit at this ATM. It also shows the data Aow for the response to a query, in which details about
an account are displayed. ExpreSSi ng these requirements in text form only would be marc difRclllr than using a
data Row diagram to help describe them . Notice that data Aow diagrams do not show COnlroi. For example,
the ATM application does not indicate what function occurs first . Standards used for the symbols differ
among organizations (e .g ., rectangles ca n be used for the processi ng elements rather than circl",,).
Whether or not data flow diagrams are helpful for expressing requirements depends upon the
application . For example, the ATM data Aow diagram in Figure 11. 23 clarifies for many re.ders what
behavior the application is mcant to exhibit, whereas video game requirements would probably not be

Member
banks Get User Get
deposit Inquiry
I
Bank
Error
nDtnB Account j Error
Account II
..-
account
& deposll display

Validate Validate
Inquiry
deposit
Account II
Display Make
account Inquiry
Account II
& deposir Prfm'

Account BaIanC6
dar. query

Do
deposit 06po!U Account
'\J
"'"""unl
Create
account
transaction summary
1,.n08elion _.- _. database -- 00/8

11 ,23 partial data flow diagram lor ATM application


262 CHAPTER 11 ANAL ¥ZING HIGH-lEVEL REQUIREMENTS

descnbed well uSin g a data now diagram . When usinM these dia gra m' for require ment s , peClnc.tlon, there i~ a
"snlAcant dan ge r of hpp inl! into perfo n"in g desig n ,"stead o f analyzlnB reqUirements. For example, If an
appitcatio n IS reqUired to tra ck the now o f o rders within a compan y, then a data now diagra m (DFD) shOwing
thl proces at a h ig h level would be an appro priate form for hi g h-level reqUi re me nts because the DFD "
nceded to ex press the o utcomes O n the other hand, consider an application that is required to apply a
complex formula . A DFD explain,"!! the calculation process would be part of the design , but nOt the
req Ui re me n15- the fomlula would be uffi cient for expressing the requirement . We will r<-vislt data Aow
d iagra ms in Pan IV, the de ig n ectlon of the book.

11.9.2 State Transition Diagrams

Sometimes, an application, or pan thereof, is best th o ught of a being in one of several slalrs. The Sta te of an
application is its si tuati o n o r s tatus. States are sometimes called "phases" or "stages ." Although a state often
correspo nds to a CU I and vice versa, the state concept is more general than C Uls_The idea is to divide the
applrcatlon into sta tes so that the application is always in o ne of these states. Note that the states we arc
de fi ning arc based o n the requirements of the appl,c.ation-not its software design . For example, it might be
useful to think of an o nlrne sho pper at a bookselling si te as being either in "browsing" state (looking at book
info rmati o n) or in "purchasing" state (providing credit card information , etc.). A diagram that depicts the
different states and the transitions between states is ca lled a sial, lrallsilion diagram .
There arc several pOSSible Enco unter states,

• 5,l/mg up· the stare during which the game is being set up
• P"ilOring. equipping th e players character with qualities such as "strength" and "intelligence" can be
performed as lo ng as no foreign c haracter is present

• Wa iliHg. noth ing is happe ning in the ga me th at is experienced by the user


• Engaging the state in which the player's character and the foreign c haracter arc exchanging quality va.lucs

The e sta tes arc sh own in a UML state transi ti o n diag ram," Figure 11 .24. For eve nt -driven applications,
diagrams Irke this can be an effective way for the custo mer and developer to obtain a shared concept of how
the: application IS meant to work .
After identi fyi ng the states, the Imn silions between states are added. TranSitions, denoted by arrows, arc
each labeled with th e name of t he ro," 1 that causes the object to change from one state to another. Events arc

,
_~ Setting up Preparing
,••
(initial state) I
Player I
clicks I
Complete quaNties ,I
setup menu
• ,,
(final

, state)
ForBign
,
character __--j
Wailing ' - - - - enters Engaging
8f8a

Figure 11 .24 Partial Encounter state transition diagram


USING DIAGRAMS FOR HIGH-LEVEL REQUIREMENTS 263

Stale
EY..~
Player Coodilioo
moves to
adjacent ~ {foreign
8rea character
present]

{foreign
character
absent] Engaging

Condition SIal9

Figure 11_25 Using conditions In Slate transilion diagrams

occurrences that can cause a c han ge in the object's state . A t)'pical eve nl on a CUI is a mo use c lick. The soli d
circle denotes the startin g state. The final state IS d e pic ted by the solid circle inside another ci rcle.
States and transitions ca n apply 10 entitic at many levels. For example, a ship ca n be in one of several
stales, such as Sailing , Docking , or Dock,d . Parts of the shi p ca n be in evera l states, For example , a cabin can be
in Occupied or Unoccup"d state.
Sometimes, when an objec t is in a give n state and an eve nt occurs, the object can tran itlOn to one of
several states, depending on a condition . For exa mple, when thl- player decides to move h er character 10 an
adjacent area, the ga me tranSItions rTOm th e Waitillg state into one of two states. O ne possi bili ty is to
transition back to Waili"g state (if the foreign c haracter is absent from the e ntered area ); th e o ther is to
transition to the Engaging state (if the fo reign c hara c ter is prese nt in th e entered area ). In UML, co nditi o ns arc
de noted b y square bra cke ts, as sh ow n in Figure 11 .25 .
The complete state transition d iag ra m for Encounter is sh ow n ID Figure I 1.26 O nce the player has fi n ish ed
scumg up the Encounter ga me , the latter transitions from s,lIillg Up state into Waiting state. If Encounter IS in

Ptayer Reporting
Se\1Ing up dismIsses Setting
report qualltle$
Player window
completes
setup

Player
set requasts Player
qualities status requests to
window __- set qualities

enters area
Foreign
chartJcter
Player enters area
moves to
adjacent area Engaging
Playor
quits
{foreign choracter ~-===
pro.ent]


Fleur. 11 _26 Encounter sUite transilion diagram
264 CHAPTER 11 ANAL VZING HIGH·LEVEL REQUIREMENTS

\\fmfl"9 ,tatc and a forc l!!1l harac ter e llterl, the n Ellco""ler trln,itlo n, IIlto E1I9a91119 sta tc F,gurc 11.26 ,nd,catc,
th.t th c pro c-; . of setlll1g qual ity va luc< .nd the pro e» of repOrllllg the re,ldts of an e ncounter ca n b<:
int el1\Jpted by thc amv.1 of the foreI g n c haracte r The laller allse< a new encounte r to commence Immcdiately.
A sta te Iransltio n 1110 del is a good way to explaIn the o llce pt of opera tI o ns of Encounter State
tran Itio n model arc commo nl y used as de Ig n 100is a well (sec hapter 16 ) Whe ther o r no t they should b<:
used to exprcss 11Ig h . level reqUlremellts, as we are dOlllg here , depends o n the apphcation in questIon and
h ow helpful doi ng so IS fo r the custo mer. Tim ma y require ome edu cati o n of the cu tomer.
For man y app1.catl oIlS, each tate correspo nds to a C UI H owever, there .. a wide variety III what we may
de Rne as a state . ll,e tate d iag",m in Figure 11 .26 corre po nds rOll ghl y to the pre cnce of VIsua l artifacts on the
mo nito r, but thcsc are no t C Uls. Fo r example, when the foreign ch.",ctcr FreddIe appear o n the monitor, the
app1.catlOn t",nsltio ns to E1I9n91119 tate, but rreddie is Just an additio nal g",ph,ca l clement, not a scpa"'te CUI.

11.10 CASE STUDY: HIGH-lEVEL SOFTWARE REQUIREMENTS SPECIFICATION (SRS) FOR


THE ENCOUNTER VIDEO GAME

2/ 1/98 Hal Furness: Entire document reviewed


Note to the Student:
for small improvements
Using a standard 10 write the SRS helps one to
cover all of the aspecrs of requirements that 2/ 19/98 Karen Peters: Document reviewed and
readers need to know about, and provides a suggestio ns made
recognized structure. Seve",1 standards are avail·
2/29/98 Karen Peters: Moved use ca.ses to
able , but we WIll concen""te on the IEEE Stan·
Section 2.2
dard. The complete IEEE 830·1998 standard can
be found in [8). Most organizations allow modi · 3/ 1/98 Hal Furness, Improved wording
fkation of the standard to tailor it for their own thro ughout; sense not changed
use In fact, the template used below modi Res the
5/20/04 Enc B","n, Updated to 830·1998
standard by omitting some less important sec·
standard
lions and by addlllg sections on concept of
ope",lions and use cases. The reader can com· 14/ 20/08 Eric Brannen, Edited to improve as·
pare the case study headings with the standards sorted clarifications
shown III Figures 8 and 9 of Chapter 10.
In the case study portion of this chapter,
1. Introduction
Sections I and 2 cover the high .level require ·
ments. The remainder of the document, Sections
3 and 4, containing the detailed requircillents, IS
1.1 Purpose
provided in the case study at the end of Chapter
12 . Recall that customer requirements are not The purpose of this entire document (not the
intended to be detailed enough to develop the purpose of the application ).
design and implementation thi is the purpose
of rhe detailed reqUIrements.
This document provides all of the reqlliren1cn~
fo r the Encounter video game Parts 1 and 2 are
History of versions of thIS document,
II1tended pnman ly for customers of the ,pplicatlOn,
but will al<o be of interest to soft" 'are enginee~
1/ 19/98 Hal Furness Initial draft
buiJding or maintaining the sohwarc. Part .. is in·
1/29/9 8 Karen Peters: Reviewed for technical tended primarily for <oftware engineers, but will ,Iso
accu",cy, changes made throughout be 01 mtcrt: t to ustomers.
CASE STUDY: HIGH-LEVEL SOFlWARE REQUIREMENTS SPECIFICATION (SRS) FOR THE ENCOUNTER VIDEO GAME 265

1.2 SCOpe
Encounter is to be a role-playing game that simu-
lates the lifetime of the player's main character. It should
(The Iospccts of the application this document be of interest to both men and women. The measure of
is intended to cover.) 'success' in playing Encounter is up to the player.
Typically. success will be measured by the ' life points'
maxImum attaoned by the player or by the ability of the
Thi document covers the requirements for player to live as long a life as possible.
release 0.0. I of Encounter. Me ntion will be made Some game characters arc to be under the
throughout thIS document of sele ted probable fea . contro l of the player. The rest. called "foreign"
rures of furure relea es. The purpose of this is to characters. are to be under the application's control.
guide devdopers in se lecting a design that will be Came characters will have a fixed total number of
able to accommodate the full ·scale application . points allocated amo ng qualities such as strength.
stamina, patience, and so o n. C harac ters encounter
1.3 Definitions. Acronyms. and Abbreviations each other when they are in the same area at the
same time. and may then engage each orher. The
See Table 3.3 . result of the engagement depends on the values of
(heir qualities and on the environ ment in which the
1.4 References
engagement takes place. Engagements are not nec-
essarily violent or adversa nal. Players have restricted
Software ConHguration Management Plan (SCMP)
opportu nities to reallocate their qualities . One of the
for Encounter version 1.0
player-controlled characters will be referred to as the
Software Design Description (SDD ) fo r Encounter "main" player character.
version 1.2 In early versions of this game. there wi ll be only
Software Project Management Plan (SPMP) for o ne player·controlled character and one foreign
Encounter version 1.2 c haracrer.
Software Quality Assurance Plan (SQAP) for The eventual nature of the characters is 10 be
Encounter version 1.0 determined fro m insights gained from surveys and
Software User Documentation Plan (SUDP) fo r locus groups. It is expected that initial releases will
Encounter version 1.0 not have anionation Encounter should eventua ll y be
Software Test Documentation (STD ) for Encounter hig hl y customl zable. so that users can eit her start
version 1.0 with predefined games . substitute predesig ned char·
acte rs and rules of engagement. or devise their own
1.5 Overview characters and ndes of engageme nt.
The design shou ld support expansio n into a
Intentionally omitted.
fa mily of games. including Intemet ·based multiple -
playoc versions.
The author of this document felt no need for
this section. and ontends to cover the overview 2.1 Product Perspective
in Section 2.

In this secti on. Encounter is com pared with


2. OVerall Description other related or competing product . This os a
useful way to prOVide perspective on the ap-
MAke this !leneral enough so that it oS unlikely plication . Subheading 2. 1. 1 of thos section h.s
to chanllC much in future versions. Avoid been changed from the IEEE standard to ac-
tC&lelllcn" that are repeated on later sections. commodate "concept of operattons."
266 CHAPTfR 11 ANAL Y2ING HIGH·LEVEL REQUIREMENTS

· n OUnter IS Intended to tu lAIl the need (or


the sta ndard IEEE head lOg ' u.>er in terfaces" 10
prog",mme'" to have a g rea ter IOnuen c OVer the
empha ize Ihal the«: arc not the detailed C Uls
ntent o( video ga mes with additiona l program ·
ming It IS al 0 intended for a somewha t mature
clientele Encounter is IOtended to appea l to bo th 2 .1 .2 .1 Area User Interface Concept The areas
ge nders . The de iBn and documentation (or Encoun · In whic h encounters take place sha ll have an appear·
ter will make it convellient to expand and modify the ance very ro ug hl y like that shown in Figure 11. 12.
ga me. It IS anticipated that Encounter will be used as
a legacy application for expansion IOtO applications 2 .1 .2 .2 User Interface Concept for Setting
such as o ffice Interaction simulati o ns . Quality Values When sctti ng the values o( game
characters under his control, the player uses an In terface
2.1.1 Concept of operations o( the form sketched approximately in Figure 11 . 11.
The scroll box i u cd to identify the qua lity to be SCt,
and the tex t box IS used (or setting the value.
This section conveys the overall concept of
the application by whatever mea ns are most
2.1.3 Hardware Interfaces
natural for doing so. In the case of Encounter,
None. Future releases wi ll uti lize a joy tick.
the requirements developers deci ded that
state/transitions best convey the concept.
2.1.4 Software Interfaces
No ne .
Encounter can be 10 o ne o( the (oll owing states
(also shown 10 Figure 11 .26), 2. 1.5 Communications Interfaces
No ne . Future releases wi ll Inte rface wi th the Internet
• Setting up. The state 10 which the game is bei ng
via a modem.
set up by the playe r

• Reporting. The system is displayi ng a window 2.1.6 MemoryConstraints


sh owi ng the sta tus of the players character(s). Encounter sha ll require no more than 16 MB of RAM
and 20 MB of secondary storage (see test plan < test
• Se tting qualities. EquipPing the players character
refere nce to be supplied ».
With qualities. Thi s process consumes arbitrilry
amounts o( time, and can be perfo rmed as long 2. 1.7 Operations
as no torelgn character i pre cnt

• Engagi ng . The state that app lies whenever a for·


No rmal and special operatio ns required by the
cign character and the player's main character are
use r, uch as modes of operatio n, da ta proc·
present in an area 3t the same time .
essing support functio n , a nd back up and re·
• Waiting. The: player and the (oreign character(s) covery operations .

are not actIve.

This state/transit Ion is tested by integration test It shall be possible to ave and re trieve a game.
< to be supplied> .
2.1.8 Site Adaptation Requirements
2.1.2 User Interface Concepts

The followlOg figu,..,. are preliminary sketches of Req uiremen ts for execution o n a particular
key I'ser i nl~c(s o nly , used to proVIde PCISPCC· installat ion; versions in various la"B"lIcs
live o n the producl. All lhe user int., laces are (e.g., French, Japa nese, panish ).
~pccifi.ed in derail in Section 3. We have modified
No ne.
CAse STUDY: HIGH·LEVEL SOFlWARE REQUIREMENTS SPECIFICAnON (SRS) FOR THE ENCOUNTER VIDEO GAME 267

2.2 Product Functions I. Player h its hyperlink connecling displayed area


to adjaccnI area
Summary or the major funcltons of the applica. 2. Syslcm di plays (he indIcated adjacent arca
tion. This section is more detailed than Section Including player's c haracter
' .5, but does notattemptto supply all details, as
doM in Section 3. The writers of this SRS 2.2.3 Encounter Foreign Character Use case
ckcided that use cases are an appropriate man. ActOr: Player of Encounter
ner in which to specify the overall functionality U sc case:
of Encounter.
I. System moves a foreign game character into the
area occupied by the player, or Player moves
This section specifies Ihe required overall func . into an area containing a foreign character
tionality of the applicalion, but is nOI Inlended to 2. Syslem causes the two c haraclers to engage
provide the complele specifications. Sectio n 3 pro.
vides the requirements in complele detail 3. Syslem displays the result of the engagemenl

4. If eilher the player's characler or the foreign


2.2.1 Initialize Use Case charac ler has no pOinls, the game terminates
Actor: Player of Encounter
Use case: Figure I 1.27 gives the lexl of Ihe 5. O therWise, Syste m moves the player's character
JnitJalizt use ca e. The use case is shown in con text to a random area different from that in which Ihe
with the Eneo"nl" foreign ebameltr use case and the Sri encounier tOok place, and displays it there
",It, use case. Initialize is Ihe typica l sequence users
execule at the beginning of a session. 2.3 User Characteristics
This use case cOfT~ponds to test < Iesl referen e
to be supplied> in the Software T eSI D ocumeOia tion.
Indicate what kind of people the typical users
are likely 10 be. Examples: novice, software
2.2.2 Travel to Adjacent Area Use Case professional , accoumant with five years of
Actor: Player of Encounlcr computer usage, etc.
U se case:

Actors
Initialize
Initialize - - 1. Syslem displays playefs
main character In the
dressing room.
Travel 10 2. Syslem displays a window
adjacenl 'or setting his charactefs
Player area
qual~les.
3. Player allocates the
Encounler character.
0'
qualities his main
foreign 4. Player ohooses an exit
charaCler
'rom the dressing room.
5. System moves playefs
Sal rulos main character Into the a_
Designer
on Ihe other side of the .xlt.

11 .27 Initialize use case (or Encounter


268 CHAPTER 11 ANAL VZING HIGH·LEVEL REQUIREMENTS

The u cr IS expected to be approXImately 20- the devel o pers. It IS antIcIpated that they WIll be part
3 ye.n; o( age o( a futurc release "OptIonal" requITement. will be
Impleme nted at the dI scret io n o( the developers.
2.4 Constraints
11.11 CASE STUDY: HIGH-LEVEL
REQUIREM.ENTS FOR ECLIPSE
These are all conditions that may limit the
developer's options. They can onginale from
many sources. Note to the Student:
This section discusses published requirements for
Eclipse. There is no single requirements docu·
Encounter shall operate o n PCs nlnning
ment (or Eclipse the requirements arc spread
Windows XP or later at a minimum peed o( 500
over multiple documents. The authors have
1Hz. Java shall be the implementation language.
reconstructed a partial requirements document
from thesesourcesata single pointin time, p.lacing
2.5 Assumptions and Dependencies them roughly in IEEE fonnat for the sake of
comparison. The result is necessarily incomplete,
(Any assumptions being made (or example, and illustrates a shortcoming of many 0 pen source
future hardware.) projects. Most of the material below is quoted
directly (but selectively, of course) from the
Eclipse documentation online at the time.
o ne

'The Eclipse Project is an open source software


2.6 Apportioning of Requirements
development project dedicated to providing a robust,
full.featured, commercial ·quality, industry platfonn (or
(Order in which requirements are to be the development of highly integrated tools. The mis·
implemented .) 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
The requirements described In SeC1ions I and 2
eclipse as an industry platfonn is realized: '
of this document are referred to as "customer require-
'The Eclipse workbench consists o( lOim/olDS. Each
me nts"·, those in Section 3 are referred to as "detailed window contains part,. Each part can be a vittD or an
requirements ,f The primary audience for customer
wilo,. A pmPte/iv< is a physical conRguration o( pans.
requirement is the customer community, and the Figure I 1.28 shows a typIcal Eclipse screenshot: ' This
secondary audience is the developer commu nity.
example is a Java perspective (as indicated in the
The reven;e IS true (or the detailed requirements shortcut bar). This pen;pective consists o( a Windows
These two levels o( requirements are intended to be
Explorer-type of view, an editor, and other parts,
consistent. Inconsistencies arc [0 be logged as de- including the console view.
fects . 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 This panicular window is used merely as an
the detailed requirement version since it is more example, to make the speci6cation more un-
detailed . derstandable not as a detailed spedRcalion-
'"Essential'" requirements (rdefred to in Section
3) are to be implemented (or this ven;ion of Encoun ·
ter. "Desirable' requirements are to be implemented , From http://www.eclips• .orWp.oJcc.slindex.h.ml.
in this release i( possible, but are not committed to by • Ibid.
ECUPSE PLATFORM SUBPROJECT (FIRSl OF THREE! 269

.., P .... 'ucth •

.. . ... l ~.r 1u,,11



: WHY' . , Pr.,faaac: ' J...
.. To Ch&l\ir ql.u 9"eT. t'ld ~ _ , 'JO t .o
C E bit:T. t ~ ca,.cod " aDI1 "
. ~_ ••
J

~::~1 )Mo • • ••. \\
,.y...
...... .El....
ueut ..
C""' 1109 ..

. . .. 7 l S part. )."tuI "log bordC1" ..


. . , 7 )"otu ,U " ."port , •••••• 1 l1'9 . . ... l ..
.. "'It •

#-.o.Q
~ .P.£ SF«
Ho,90'tuLt

, lb..,lIctJ ..)
5 1"'091 1 hllll Lc_ • _ . S tr t"9l
SUuri J e!ht,lt.c-.• • aew S t r\lr9{
-1
!.J( -u....,......•
_._" . •

- Cu , ' ---
_.erE

0Copf
c .... r ( I hId "tcu' .
c ....r l J eo:hlS!:. :n:t cu t a '
II
Z
'0'
J ·c
..
n

lotu.h""

Agure 11 .28 Eclipse GUI


SOUrce: Edlpse, flttp :JIWWW e<:lrpse org/articlesJAttic~UI-GoidellneslJndex.hltnl.

The Eclip e Platfo rm provIde. the fun dam ental


The following three sections are quoted from building blo ks of the Eclip e projects Plan tasks arc
Eclipse documenration WIth some adaptanon . new features of the Ec hpse Platfo rm o r igmhcan t
reworking of exi tlng feature lany of the hanges
under con. iderallo n for the next release of the Echpse
11 .12 ECLIPSE PLATFORM SUBPROJECT Platform addre s three majo r themes, a follows ·
(FIRST OF THREE) • U ser experience theme. ImprOVIn g Eclipse from
the poin! of vIew of the e nd u e r

Note to the Student: • Responsive UI theme . Making it easIer 10 wnte


Since Eclipse IS organized around three sub· EcI ,p e plug· ,ns that keep the UI re ·pon"ve
projects, it is natural to org.nize the summary
• Rich client platform theme. Ce nera hzl ng Echl',e
requirements in the same way . With l ~ each
into a platform fo r building no n. ID E appJ.ca tlo ns
project, summary requirements are organized
ilround """,,cral "themes." Th,s IS a way to orga· In addtno n, there are Impo nant E itp<e PI.tfoml
nize the (high· level ) reqUIrements and allow Improvement, that do not natu rally ht IntO a ny of the
latitude at the samc tIme The the mes do pro · above themes The<£: are a tegori:ed as f 1I0w<
vide content , but they avoid pecifying d etails.
• ther E IIp e PI . tfo m1 IIems
270 CHAP I ER 11 ANAL YlING HIGH -LEVEL REQUIREMENTS

too lbars, and le ng thy nat l, sts of preferences Th ..


Belo w a", examples elaborating upo n these . pro blem IS aCllte In large Eclipse-based produ cts. The
Plat fo rm sho uld provi de add itI o nal ways fo r control _
ling wo rkben h clutter, such as funher menu and
User EXperience Theme toolbar custo ml za bil ity, d isting UIshing be tween nov-
Ice and ad va nced func tio ns, suppanln!! d.rfc rent de·
Th, the me incl ude, Imp rovi ng bo th the "o ut o f the veloper roles. and ma rc speci fic o bject contributions
box" experience 0 th at new users arc producti ve fo r panicular me ty pes ., ( 37929)"
fas te r, and fi nd ing bellc r ways to scalc up to large
num bers of plug .ins witho ut overwh e lmin g the user.
The number given above in parentheses is a link
Committed Items (Eclipse Platform subproject, to the following bug cntc",d in Eclipse's BUgzilia
User Experience theme) bug database, https/ /bugs.eciipse.orglbugsl
show_ bug.cgi7id =37929. This and other require-
ments are managed in the same way as defects
The requ irements h ere arc grouped by prior- The reason is that both deRne work to be done on
ity. ' Commltted" IS the highest priority. The an existing application. Each Bugzilla location
o thers are · proposed" and "deferred." Comple- contains extensive discussion about the requi~ .
tion of a requirement is denoted with a green ment and the progress made imple",enting it.
c heck mark. This amounts t'O the detailed specification.
common way of specifying detailed requirements
in open source projects. The begiAning of Bug-
Improve UI scalability zilla Item 37929 is shown in Figure 11.29 and
"Des pIte dfo n s to e nsure UI scalabili ty WIth a large Figure 11.30. We w;1I rerum to the subject of
base of avai lab le tools, the Ecli pse wo rkben c h still requirements tools in Chapter 12.
Intim idates ma ny user'S wi th long menus, wide

II_pm· ht l7nf r;-.. ....,!mp:tO'l' m.... '.)


&.aLiK &:It.!!IIcn.~ ... .. ,...., ~ ¢'«nt.,. w.... t .

• C' .f!! .."


~

r."': , "' "'" ee•

.. ,~ • ;: ' .., ~'" 1t'~I:DI'·'"


"''''"It:hI I

Figure" .29 USing Bugzilla in Eclipse to track bugs and detailed requ irements, 1 of 2
ECUPSE PLATFORM SUBPROJECT (F(RSf OF THREE) 271

t:'Leaw as RESOt VB» m Rn


(' a.opmbvj
r Marie. bua as VERn I F I)
(" Mark hue as CLOSEn

Vltw Due Acdvll)' I Format For Pabidn&

Description:

- - AdduJCnaJ CO" ....'" !!l. Prom.hm.us RN..,.s200J..Oj.21 1/.·/ 8 - -


•••

--AddlhOnaJ Co,.""", !!l. From MorPMus 200J·Q6.08 14..40 - -

I ~ olad af ter ceadlDO the [cllp3e Pr o) e c ~ Dratt 3.0 pIon tha t 1n ecl l ~e
3.0 that tble bUQ q01QO to be a4dre3~ed , but I a130 V&nt tbe peo ple who 13
going to eusdce~5 t.h13 bUQ to pc ovld.e Cop 1 ' ~ t o do ~bC' lIICnu and t. oo lbar
cU3t.D:lll ECot i o n ( 1 ,e, 01108 u.s to remove WlVDJlt.ed IIICQ\,I 1tc....., peoor" "Q~ l c ally ) • It
.,..... .. a .. a ~" ...... r .... '; .... ~ ... ,.. r _ ... .. . ; ... . . . ...... " .... .-.-. . .. .. _ _ .. ......... r ,..,. . ........ _ "'_,.v
FIgure 11.30 USing Bugzifla in Eclipse to track bugs and detailed requirements. 2 of 2

Improve initial user experience proposed Items (Eclipse Platform subproject,


User Experience theme)
Users who are new to a n Eclipse·based product ca n
find the ir first experiences with it overwhelming ,
even dauntin g. The initial experie nce would be The ' proposed" category is the second most im ·
improved if a product cou ld preconfigu rc the work · portant priority. Note that these requirements are
bench to show o nl y the subset of function that a new expressed in an exploratory, less specific, manner.
user really needs; welcome pages could be personal . Requirements analysis still has to be performed to
ized for part icular use rs roles or levels o f ex perience . transform these into commil1ed items.
. " (37664 )
Th e fo ll owi ng work items are being ac tively
Improve U/ affordances Investi gated , but we arc no t yet ab le to promise any
. , . (3767 1) "Work romp/tId solutIOn for th is rolea c .

Allow editors to open files outside workspace


This is a way of tracking the status of A ommo n reque t is to be able to use Ecil psc to open a
requirements. fi le that i not part of the workspace, or " erhap' even
o ne o n a remote ys tc m, In add ilion, appli ation
272 CHAPTER 11 ANAl VZING HIGH-LEVEL REQUIREMENTS

would like to provide fi le exte nsion associa tio n so (. recently deferred item) Provide a general
that doub le -cl icking o n a Ale in th e 0 de kto p would purpose navigator (36961) ...
open th e assoc iated Ecli pse edi tor. The o perat io ns
and capabi lities ava dab le o n th ese 'outsi d~ of the
These arc just a few examples Ihat illustrate the
workspace" Ales wo uld need to be deA ned . (37935 )
organiza tion o f th ese documents.
Improve workspace synchronization with file
system . ... Other Eclipse Platform Items

De tails o mitted The foll o wing are examples from the Eclipse
Platform subprojec t within this "theme."
Content-type-based editor lookup. ...
Design Constraints: Compatibility of Release
Details o mitted 3. 0 with 2.0 and 2.1

Thissecti o n is qlloted from note'. It consists of


Deferred Items (Eclipse Platform subproject, no nfunctional requirements, and one example
User Experience theme) is expanded here. A "breaking" change is one
that preve nts some applications from execut-
The Ecl ipse project t racks requ ire ments that ing on the new version that did execute on the
may never be imple me nted. This enables them old one. N o te also that this paragraph contains
to be revived , provides history, and discour- po licy elements for requirements rather than
ages th e m fro m bei ng pro po ed again. It helps requirements themselves.
to clarify th e project's directi o n.
' Ecl ipse 3.0will be compatible with Eclipse 2.0and
These items are next In line fo r chis release. As 2. 1 to the greatest extent possi ble. The nature and sco pc
comm ltters complete th eir assigned tasks or add i· of some of the key plan ilems are such that the only
tiona l help becomes available , some of Ih csc items feasi ble solutio ns wo uld break compatibility. Since
may be comm ilted for Ih is release: breaki ng changes are a di nlption to the Eclipse com-
mun ity, they ca nno t be taken lig htly. We (the Eclipse
Add table of contents support to wizards PMC) wi ll have an opcn d i cussio n with the community
(36947) .. . before approving a proposed breaking change for inclu-
sion in 3.0. In other regards, Eclipse 3.0 will be compati-
ble with 2.0 and 2. 1. W e also aim to minimize the effort
D etails omitted
requi red 10 po rt an existing plug-in to Ihe 3.0 APls. We
wi ll provi de a comprehensive EeU"" 3 .0 Port"'9 Guide that
Add project templates (36960) . .. J covers all areas of breaking AP I c hanges and describes
- .. how to po rt eXisling 2. I plug-ins to 3.0. Up-to-date drafts
of Ihe Eclipse 3.0 Porting Guide will be included with
(. recently de-committed item) Aid ongoing miic-slo ne builds so that It'S possible to climb .baaed
learning (37666) the 3.0 rel eu e wago n at th e earl y stages. o r to estimate
the amou nt of effort Ihat wi ll be involved in eventually
porting exisling plug-ins 10 3.0'-
More tracking the status of requirementS. "De-
committed" means, dfectiv¢ly. "dropped' • hu pJ/www ecl ipse oeg/e Ilpse/developmen t!
cc hps<-proje l_pl.n_L0..20040 130.htm l.
CASE ST1.JOY: HIGH-LEva REQUIREMEIflS FOR OPENOFFICE 273

11.13 CASE STUDY: HIGH-lEVEL


REQUIREMEN I S FOR OPENOFFICE nather than to SpeCify its requirements. The
follOWing is found at http jlwww.openofflce
This s«tion is intended to give the reade r an Idea of org/productlwriter.html _
the O~nOfflce requirements.

"WRITER ha everything you would expect


No~ 10 the Student, from a modem, fu ll y equipped word processor. It's
The prose below has been adapted by the si mple enough for a qUic k memo, powerful enough
iUlhol'5 from httpJlwww.openofflce.org/prod _ to creale comple te books with conte nt , d iagra ms,
uaJ which was written with a partially market- i ndexes. elc. You're fTee to conce ntrate o n your
il18 Ravor. For example, we have replaced message, while WRITER makes It look great
"WRITER is a powerful tool _. _" with The Auio-Pllol takes all the hassle out of prodUCing
"WRITER is a tool . _ ... "You can easily inte- sta ndard documents such as letters, faxes, agendas, min-
grate images" has been replaced by "It facilitates utes. You arc of course iree to create your own templates.
integrating images.' OpenOffice requirements The SIyI,SI puts the power of srylc sheets IntO
are decomposed at this top level as shown next . the hands of every user.
You're free to add words and phrases to the
Aulo Corrcc1 dlClionary, which can c heck your spelling
OpenOfflce consists of the following , as yo u type
Aulo ompltlt suggests com mo n word_ and
• WRITER is a 1001 for creating profeSSional docu -
phrases to complete what YOll are ty ping
ments, report , newsletters, and brochures. It facil -
Ali loFormal takes care of lhe fo rmatting as you
itates integrating images and c harts in doc uments,
write, leavi ng you fTee to concentrate o n your message.
creating everything from business letters to com -
Trxl fram" and linking mean you arc free to lay
plete books with professional layo uts , as well as o ut newsle tters, Ayers, etc. exactly the wa y you want
creating and publish Web content. them to be.
• CALC is a spreadsheet that facilitates the absorpti o n of Increase the usefulnes of your lo ng, complex
numerical information . It e nables users to calculate, docume nts by generatmg a table of contents o r mdex-
analyze, and visually communicate data. Advanced ing terms, bibliographical references, dl uslr.! tl ons, ta -
spreadsheet functions and decision making facilitate bles, and o ther objects. You are free to choose yourow n
sophisticated data analysis. C harting tools ge ne..,te email sofrware-","' RITER offers direc t connection to
20 and 3D charts. email sohware . Make your documents freely available
with WRITER's HTML expo rt to the Web, o r publish
• IMPRESS is used for the creation of multim edia in Portable Document Format (. pd to g uarantee that
presentatio ns. It allows specia l effects, animation , what YOli write IS what you r reader sees Of cour;.c, you
and drawing tools. are free to u e old Microsoft W ord docume nts, o r save
your work in W o rd format fo r end ing to people who
• DRAW faCilitates the pro duc tio n of everything -
are still locked int o Microsoft product>.'
from si mple dia gra ms to d y nam ic 3D il·lustratlo ns
and special e ffetts.

• The Da tabase User Tools faci litatt'S day to day We would ex press these mo re like the
database work in a Simple preadsheet-like form following .
Th<-y su ppo rt dBASE databases and ODSC or JDBC

High-Level Requirements for WRITER WRITER s hall be a fu ll -feot ured word proce, ·
or It hall all ow Ihe crea ti on o f "nlple d
It appears that th e: o nl y hi g h -level desCription and complete books With o nte nl " d,.gr>n" Ifl -
of WRITER IS wntten in a style to attract users dexe , e tc An e.amplc IS sh o wn In FI~lIre I I , I
27. CHAPTER 11 ANAl YlING HIGH-LEVEL REQUIREMENTS

""""'-.4.
..
.... " ....
t..

.~
1'10
~

M "urn.", (,,, t M"'~


'1lI0I'I''.
,• •
6: =rlo. d IN
,.I m!"~ ",om CDs, Of
""" ........ rtd I ~om,,.nch.
collO", ~(.
T"t'II!' o,eftO'!U.OI" fP1'\"\hEl)'
h.I~ bat,.. WI tt..IMdb .. d:,
bed Ibn bu, IdOI~ . .an' ••
"oud WI _ _ c. ~" L l
Ow 1IICII1' dltU ,..' ~ !MeDte
""".$ "'" ~ ,.06:. t:JCIi,,..... Ltd ... _
~UII'P LJ
~G)e ' . _ ...
.
I\u 001_n btoUt '
...
aM .f~ u l

Hi g'" IsIh Is
fl. MI kI _ o8lcw RA y.A/'.... IttJOI."",, ·ou
.....,."7 ... Ja" todqMfd~Itt . . . h fir £N.'
bllJ_rsMWIplluavws.rs . . . J.,,_I'I( ~~f'>fI fo,,,.,.
Mfl& COI$ "U' H>,dIMtOWltl1ls 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 , requirem e nts in an app licatio n coiled (rather
agendas, mimHes. The ry/is l featu re shall allow th e unpoe tically ) /,,"tzilla . Issuezi lla consists of
user to easdy vary th e sryle of a docume nt. The "issues ." An issue could be a bug but it could
Aulo omel dieliollQr), feature shall check spell ing duro also be a task . This is similar to Eclipse's
ing or afte r te t entry The AuloComp/crt feature shall use of Bugzilla . Some Ope nOfnce projects
uggests common words and phrases to comple te a have created more careful requirements
partia ll y typed sentence The A"loForma l feature shall documents. For example, the OpcnOffice
handk formattmg while th e u er e nters text. Tht lext PROJECT Management Toolset (draft a, ')
fram es and /ill/UII9 feature shall all ow the user to and the OpenOfflce Bibliographic module
Ae xi bl y fo ml at newslellers, Oyers, etc. (draft at .) .
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
, h"plloopm openofll e o rgiR lesldocument 171/
I S43100PM_Requoremen"_D"cu,,,on_DraftJ\ I. pdf os
We will skip addItional reqUIrements for of 2005.
O~nOffice . It carries man y of its detailed 6h t t p J1wv..'W .gCOCII jC'S.com/ma nI ;;h_k.....1grJwaVBi blio_
rtq h'ml a of 2005
EXERCISES 275

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

l. JoooI>wn. Iv... · Ol,od 0M0"" So!..,." E.gl• .m,,/' A U.. C." On·... App,..cb." (Addison. W«ley Obj<C1 Technology sma). Add,..,n·
W<Slcy. 1994 .
3. Fowki . Manin. "UML IMblW n.,nI EJ;r.... A 8ri<f C.wl, .. oM S",.wJ",J Obj«i MoJd;"g lA.gug,: Addison.Wcsley. p. 99. lOOo4.
4 Jacobson. Iv••. C,.dy Booch ond Jomos Rumbauwh. "Th U•.j1rJ So/''''''' Orodop.", Pr.",," (Addison· Wesley Objoct Tcr:hnology
$cries). Addison.Wesley. 1999.
5. A1exonde<. I... ond Ncn Maiden (Editors). "x...ri... 5'.ri". Us< C ."" Througb ,lor 5Y'.... , O""lop"",,'li/,.Cy,k", John Wiley 0 Sons.
lOOo4.
6. Invis, A1.n, "20. """"'pits 0/ So/...,,, &'9,.. ,,;.g." MeC.. w HIli, 1995
7. WicQCh. ~rl. "SofbNrt Rrqlffmtmb." Microsoft Press, pp. 193-4 . 1003.
8. -IEFF Recommended Prxtitt for Software- Requirements Spttifications," IEEE Sid 830· 1998, June 1998
Analyzing Detailed
Requirements

• What ways are there to organize detailed


requirements?

~-- Matntanence • How do you express user interfaces in


detail?

The Software • How do you express security requirements


Development in detail?
Ufecycle
• What kinds of error conditions can be
specified?

• What is traceability and why Is It important?

• What ways are there to prioritize


requirements?

• Why associate requirements with tests?

• How do agile methods relate to detailed


requiremen1s?

• How do you use tools for requirements


analysis?

Rgure 12.1 The context and learning goals for this chapter
THE MEANING OF DETAILED REQUIREMENTS 279

ft~r luSh -level requIrement are spe Ifled , tYPI ally (or an iteration , the next ste p in rcquorcments
i is to define the deraIled req uirements. The purpose 01 de taIled requirements is to provide the reader
WIth absolutel y .lIth.t's requored of the application . W,th o ne exce pti o n, the re i no where cI e fo r the team
to state <XiI Ily what thIS conSIsts of. For e ample, if we do no t state here that the title of a VIdeo mu.t appear In
• t6-poont font on th e mo no tor, then we aSSume that thos will no t appear In the produ ct
The "exception" mentio ned above refers ro the pOSSIbility 01 eother stat Ing each detail ed requ irem ent as
a comment In the so urce code or of expecting source code and its unit tests to effectively specify the
requirement. Thi tends to be the approa h oI agile projects, which we discus ed previous ly. Ag ole projects do
not rule out the kind of documentation char we di scus In this c hapter, but they value working code ahead of
Sll h separa te documentation.
This chapter concenrratcs on wriue n deta iled reqUireme nts. However, whe ther o ne writes down
d~tailed requirement in these ways o r not , there is no c hOICe but to eventua ll y think them thro ug h. In fact ,
they fo rm a common currency of app licatio ns, as it were Detail ed requirements arc usuall y d ivi ded on to
sectIons, including funct io nal requirements, no nfunc ti o nal requirem e nts, and CUI deta ols

12,1 THE MEANING OF DETAILED REQUIREMENTS

Detailed requorements provide software e nginee" with a ba is lo r deSIg n and Implementatio n. n,ey are
sometimes called "specific requirements," "functi o nal speCificat io ns," o r "developer requirements." Detail ed
requirements consist of a complete liS! of specific prope rtI es and functionality th a t th e application must
possess, expres ed In complete detail. Eac h of these requ irements is labe led, and tracked thro ug h imple·
mentation . Detailed requirements a re consistent wit h, and e laborate upon , the h Ig h -level req uireme nts _They
ar< inte nded to be read primarily by developers -h owever, customers are inte rested in the m as we ll , and
should be able to understand and commen t on them wi th few exceptions. Recall that the primary aud ie nce fo r
the h ig h ·level re.q uire m ents consists of customers.
As the case studies in this book demonstrate, when it comes to software e ngineeri ng, "the deVIl is In the
deta,ls: For example, in 1999 NASA lost a weather sa te ll ite wo rth a rep o rt ed I $125 mill,o n, reportedl y
because control data they had assumed to be in metric fo m, was no t [ I J

.. the root cause for the loss of the M eO spacecraft was the failure 10 usc metric unit s in the
coding of a ground software file , "Small Forces," used in trajectory mo de ls. SpeCIficall y , thruster
performa nce data in English units instead of me tric units was u ed in the software app loc.toon
code titled SMJORCES (s mall forces). A fi le ca lled Angular M o me ntum Desaturation (AMD )
contained the o utput dara from the SM JO R ES so ftware. The data In the AMD fi le wa<
require d to be III me tric units pe r existing o ltw.re Intwface docume ntatI o n, and the trajectory
modelers assumed the data was provided in metric unIts per the requireme nts.'

This descri ptIo n ,mpl,es that the req uireme nts stated the need for metnc un Its but the oftw.rc d id no t
Implement the requi re me nts correc tly A fascinating fact os that thIS defe twas Ide nti ,ed with", mere day, afler
the d,saste r. Th, s mea ns thai it may not be hard to loc.te a defect o nce we kn ow it I present. The pro llcm is often
OUr Ignorance o( liS presence The d etailed requi rements lo rm the first lone 01dde nse agilln tthe corruption r
OmIssion of dcta ofs Far fro m beIng the mindless ac ti VIty that it mig ht flrs t appear, !;e tlln g all the requ Irement'
down In complete detaIl Inv'Jlves the d ifficu lt tasks 01 orga ni zo ng people and the " th u"ht proce" . To
understand this challcng~ , Imag Ine the task of or)(anlz lng a 20-volume req uo re me nt< document (' t , " c1lectlve

I nllp jinc"" bbc en uk/ l /hJ", ,"cd"5 14 76~ tm


, hp j/ltp hq no .. 80y/ puiJ/paoircpIlrt<l 1999/IvICO-,cl'orl pdf
280 CHAPTER 12 ANALYliNG DETAILED REQUIREMENTS

that a N A englOeer, for example, would know cxa tly where to add o r look (or a <pccific reqUirement Storing
and malOtalnlng these requireme nts In a ""a rchable database helps a great deal , but the task remains difficult
Indeed.

12.2 ORGANIZING DETAILED REQUIREMENTS


Requirements c hange constantly, and so written reqUIrements should be well ·orga nized a nd easy to update
To apprec Iate th e value of carefu ll y o rga nizi ng de taIled req uire me nts, consi de r the following rather random
attempt at wrillng detaIled reqUire ments for the Encounter game. No te that these requireme nts are still raw
and arc no t in pected .

Every c haracte r in the Encounter video game shall have a name.


Every game c haracter has the same set of qualities, each with a floating po int value .
Encounter shall take less than a seco nd to ~omput e the results of an engagement.
Each area has a speCIfic set of "qualities nceded." For example, combat areas require strength and
lamina ; li ving rooms require sensi tivity and intellect.

Whe n two Encounter game characters are in the same area at the same time they may either choose or
be obliged by the game to e ngage each other.
Every game ch arac te r shall have an amount of life points.
The sum of the values of qualities of a game character relevant to the area in question shall be referred to
as the character's area value. In an engagement, the sys tem compares the area values of the characters
and computes the result of the e ngagement .
The name of any c haracte r in Encounter shall have no more than 15 letters.

A It grows, an uno rganized list hke the o ne above quickly becomes unmanageable.

• Its very size makes It hard to understand as a unit even before it grows into the hundreds, if not thousands.
• The reqUIrementS arc of mixed types, performance requirements must be dealt with differently from
functiona l requireme nts , (or example.

• Some reqUIrements naturally belong with related o nes.


• It is d ifficult to loca te a speCific reqUIrement.

Functional detailed requirements can be organized acconding to several claSSifications, including by


feature , use case, CUI , state, and class. We describe each method in more detail in subseque nt sections. Tools for
managing requirements can help a great deal. Nevertheless, the decision as to how to organize detailed
requirements 111 the first place is important because teams reler to them continually if the document is well done.
The IEEE standard 830-1998 provides document templates for several ways to classify the detailed
requirements. Figure 12.2 shows the conventional and the object,oriented classification templates of the IEEE
830. 1998 standard. The object-oriented claSSIfication uses classes/objects as a me thod of organizing the
functional requirements. The SRS is often tailored to corporate or team needs by adding or modifying
sections as appropriate. For example, the 00 organization lacks a section equivalent to 3.4 in the non-OO
organization 10gical database requirements." The Encounter case study uses a modi Red form of the IEEE 00
ORGANIZING DETAILED REQUIREMEIfTS 211

3. Specific ""quirements (non-OO)


3 . I External interfaces
3.2 Functional ...,quirements
3. Specific requirements (00)
3.3 Performance ""quirements
3. 1 External interface requirements
3.4 Logical database requirements
3. 1. 1 User Interfaces
35 Design constraints
3. 1 2 Hardware interfaces
3.5 . I Standards compliance
3. 1.3 Software Interfaces
3.6 Software system attributes
3. 1.4 Communtcations interface
3.6. I Reliability
3.2 ClasseS/Objects
3.6.2 Availability
3.2. I Class/Object I
3.6.3 Security
3.2. 1. 1 Attributes
3.6.4 Maintainability
3.2. 1.2 functional reQutrcmen ts
3.6.5 Portability
3.2. 13 Events .
3.7 Organizing specific req u irements
• ••
3.7. I System mode - or
3.3 Performance requirements
3.7.2 User class - or 3.4 Design constraints
3.7.3 Objects (sec right ) - or 3.5 Software system attributes
3.7.4 Feature - or 3 6 Other requirements
3.7.5 Stimulus - or
3.7.6 Response - or
3.7.7 Functional hierarchy - or
3.8 Additional comments

Figure 12.2 IEEE 830-1998-specific requ irements, 00 and non-OO organizations


SOUtce: IEEE Std 830-1998.

style and includes a sectIon for usc cases. Fi gure 12 .3 maps the detatled requirements section o( Sect Ion 3 to
the requirtments ca tegory it describes.
It may be advisable to o rga nize detailed reqUIrements int o a comb",.lio" of lasslficatlons For example, a
feature· based organization could be used within the co"figllring, txcculmg , and backing liP tates of an accou ntIn g
application . The requirements for a factory automation system cou ld be orga ntzed at the h, gh. t levd by
function (i ntake, part manufacturing, and assembly), they co uld then be o rga ni zed by clas withIn eac h.
This means the metho d o( organizing detailed requirements is somellmes related to the probable
architecture or implementation of the appitcation For example, if the deSIgn is :0 be object-onented, detailed
requirements organtzed by use case or class should be considered because they faclittatt traceabtlity. If the
application lends itself to an obvious functional breakdown, then o rga ni ztng the requirement by (.>lUre hIerarchy
may be appropriate.

12,2,1 Organizing Detailed Requjrements by Feature

The oldest manner of orga nt ZII11( detaIled reQ Ulrement< IS by feature . This amount to prOVIding a SImple Itst
of functional,ty such a< the fo ll OW Ing , f'Or th e Encounter VIdeo game Many (eatures are defined bv J IImulus .
and-response pa", as for requirement 12 7.
282 O1APTER 12 ANALYZING DETAILED REQUIREMENTS

3. Specillc requlremenlS
3.1. EXie mal inlerlaee - - - - - - - Inlerface requ lrome nts
requ irements
3.1.1. User inlerlaces
3.1.2. Hardwa re inlerfaces

3.1.4. Communications Funct10nal requirements


interlaces
3.2. ClassesiObjecls
-see section tbd-
3.3. Performance requirements ...
3.4. Oesign constraints ~ Othe r n? nrUnclionai
3.5. Sofiware syslem altribules ~l requirements
3.6. Other requirements

Figure 12.3 IEEE 830· 1998-specific requ irements, 00 style interpreted as functional and nonfunctional detailed
requirements
SOUrce. IEEE Std 8JO. 199S .

125 . The re shall be a SCI of hy perlinked locat io ns at eve ry exi t to every area.

126. The fo reig n c harac te r shall move fro m area to adjacent area at ra nd o m times, with an average of
three seconds

127. Whe n the use r clicks o n th e "Set qual ities" butto n, the window in fig ure xx appears on Ihe mo nitOr.

Arra ngi ng req uire me n ts by fea ture has Ihe advanta ge o f simpli ciry but the di sadvantage of in·
accessibi lity ; th is is because it all ows jumpin g fro m a feature in o ne pan o f th e applicat io n to a feature
In a com pletely d iffe re nt pa rt. For example , if we wa nted to c han ge the manne r in w hich the fo rei g n character
moves about, we wo uld have to de termin e tha t th e relevant requirement is number 12 6. H ow would we kn ow
w h at o t her req uire me nts are affec te d] Searc h tOo ls can help a g reat deal. Ano th er disadvantag e is the lack of
traceabi lity. For examp le , what pa rt (s) o f th e cod e does requirem e nt 12 5 map ta l
One wa y ro im pose o rd er o n fun c tio nal feature lisls is to arran ge them in a fun c tio n hitrnrcby (i .e., by
dec o mposing the ap plicati o n into a set of h ig h . level fun c tio ns, and th e n Ihese into subfunc ti o ns, etc.). For
exa m ple, the requ ireme nts fo r a ho me b ud get program could be d ecomposed into ( I) dJeckill9 functi o ns, (2)
sa viN9s func ti o ns, and (3) i"" " 'm,,,t fu nc ti o ns. The required ChlCkill9 fu nc tio nality co uld be furth er decomposed
into checkbook fu nctions, reconcilwtio" . and rcporlj"g, and so on.

12,2.2 Organizing Detailed Requirements by Use Case

US( cam (Intro duced in C ha pte r I I) ex ploi t th e o bservati o n that many requ irem e nts occur naturally in
o perati o nal seq ue nces. Fo r exa mple , an ind ividual requ ireme nt suc h as "a video sto re applicat io n shall allow
ente nn g th e title of a new vid eo" ty picall y takes place as pan of a seqll,"cr o f transactio ns . A usc case diagram
sh OWing a collectio n of usc cases fo r a vi deo store applicat io n is illus trated in Figu re 12.4 .
The auth o rs ad vocate provid ing use cases fo r hi g h · level req uire ments . O ne may have the o ption of
usi ng this same organi zing p rin ciple fo r d eta iled requ ire men ts. In this case we would gTOUp the detailed
requireme n ts acco rd ing to eac h use case, Aes hin g out the ste ps o f each use c ase in complete detai l. The
fo llo w ing is an exa mple of how o ne suc h groupin g o f req uire me nts wo uld appea r in the SRS.

3.7. I C hecking in DVDs


Th is is a deta iled versio n o f sec tio n xx. (N o te I, <cc th e "N o te" ex pl ana tio ns o n the next ~gel
ORGANIZING DETAILED REQUIREMENTS 33

1. User hits arry key


Activate }---
9 2. System displays main menu

1. User swipes bar code


/'
Clerls
Check in DVD - 2. Sysr... II displays due dala
3 . .,.

Check out DVD )


,.. . . .
2.
Y
-( Stock DVD 1. User obtains ·slocl( screen
"
2. User enters name of DVD
Buyer ( ........ .) 3 . . ..
IL

Figure 12.4 Organizing requirements by use case for the video store example

The applicatio n shall provide the following capabil ity to interact wIth store clerks. These
requirements assume that the main scree n is on the mo nitor (Note 2)
3.7. 1.1 Step I , Chtck III button (Note 3)
The clerk shall be able to hit the Chrck III bulton , whereupon the (b,ck In screen WIll appear
(described in section xx above).
3.7.1.2 Step 2, Filling in fields (Note 4)
The clerk shall be able to fill in the following text fields In the (b, k In s rcen •

3.7. 1.2. 1 Video name field


This field shall allow for 30 alphanumeric characters, including blanks.
• • •

Note I , This paragraph corresponds to the Chrd:in9 in DIID usc case described in the hlgh. level
requirements .
Note 2, This section introduces the usc case and states prrcondlrions. if any. A preco ndition I a fact
assumed true at the inception of the usc case.
Note 3, This corre ponds to the nrst step of the use case.
Note 4, Since these are the detailed requirements, they must specify the requirements completel y. The
details will not be speCified elsewhere.

The Unified Software Development Process favors orga ni ZIng all requirements by u e ca e . Aglie
methods de ·emphasize detailed requirements in favor o( workong code , but they emphaSIze organization of
requirements by user tory.

12.2.3 Organizing Detailed Requirement by GUI


ApplicatIons display CUI , and thes" are the means by whIch users think o( them, 0 It ca n be natural to
prOVIde requaremcnts organIzed In thIS way . Using thI S style , rhe requaremcnt (or the Encountt"r video g"me
would be ,omethonll like the followIOIl ·
284 CHAPTfR 12 ANALVZlNG DETAILED REQUIREMENTS

I Are. CUI ,
Arca C Uls shall have Ihe appe.rance shown in figure xx. When the user clicks o n the ' Set qual,ties"
button , the wi ndow in figure xx appears o n the monitor. When the user clicks o n ... .
2. Dungeon C UI . . .
3. Living Room C UI • • •

4. et Qua lity C UI ....


5 Vicw Q ualities Window • • •

The advdntagc of organizi ng requirements by CUI is its direct connectio n with the usc of the application .
Anot her advantage is traceability, we have a good chance of tracking the requirements associ ated with a given
CU I class. One disadvantage of rhis means of o rganizatio n is that it ofren fail s to cover all of the requirements. ln
the Encounter example, we need to describe the requirements for the interaction of the player's character and
the foreign character. No C UI paragraph is a natural container for this. Perhaps the closest is "Area CUls:
However, this is not a uitable place for specifyi ng the manner in which characters exchange points. Another
disadvantage IS rhat given functionality is often associated with several CUls.
As an example , Figure 12 .5 illustrates an organization of the video store requirements by CUI.
Specificatio n of individual CUls is discussed further iA Section 12.3.

3.1 Sslecting Procedures S'ock oVo


The GUI for selecting procedures shall be as shown in
Agure 1. 1\ shall be possible to select from the I Figure 2
following procedures by clicking on a radio button. Nl.nIber 01 roc: .,
followed by the "go· button ....
1 :1 '--'
I ~~-

Select Proc edure


3.3 Checking out DYDs
Slock OW @
Af95 '" CUSIOmef' @ The GUI for checking oUl DVDs shall be as
Cte " ous DVD @ Figure 1 shown in Figure 3. 1\ shall be possible to ...
Choc:II. In OVD @

9 Checl< DIJ. DVo


avo """'"
1 Figure 3
i ........ _
, ,
-- .'-

3.2 Stocking DVDs


The GUI for stocking DVDs shall be as shown in 3.4 Registering Customers
Figure 2. 1\ shall !>e possible to enter a DVD Into the
... -.
systelll using the GUlln figure ... The application
shall save the title expressed In up to 30
aJphanumeric characters and the number of copies. Regtster Customer
The laner shall range between 1 and 100. inclusive. Fw.tnl me

•• • 1 I
Figure 4

Figure 12.5 organizing requirements by GUf, for the video store example
ORGANIZING DETAILED REQUIREMENTS 285

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 )
286 CHAPTER 1i ANAL YlING DElAILED REQUIREMENTS

1. Obtain domain classes and objec18 Irom use ca,., and high. level
requirements diagram,
r ,
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 217

Player (') flSl


le.son'Ne
"vel)' IForeign Character I
IExit II Combat I you
candidal" closs IGame Character I
can think of
IEncounter I (this 11s1), then IPlayer Window I
IMap II Result I down
(2) drastically cut IExit Choice Window I
to a lew
IRoolI' I ~ essential classes. IQuality I IGame I
IScore I IConnection Hype~ink 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).
288 CHAPTER 12 ANAL YlING DETAILED REQUIREMENTS

Pia cr: Plny,r barnelrr IS a preferable name (mo re speciAc to the domain ).

Foreign 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., IS still wllhin the domain
of the app lic.tion )

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 ConnectionHyperlink

PlayerCharacte, ForeignCharacter (1) list every


reasonable
candidate class
I Playe!OuaJltyWindow I you can think 01
then (2) drastJ.
IEngagement I I EncountelGame I cs1ly CUI do .. " 10
~~~
I EngagementDisplay I
B few 8ss&ntiBl
e'e ..ss (Ih/s /1st).

ICey IA ...." ., d r, ';>. &I'd code, b&ank:a I t! I'W\IIIfd I


Figure 12,8 crasse-; for the Encounter video game, showing only Inheritance relationships
ORGANIZING DETAn ED REQUIREMENTS 2"

Th~ classes in Figure 12.8 may relate in ways besides inh~ritance. For CJGImple, EHCo"nler Arc. ConHeclion
will probably .ggreg~te two Arta objects. However, our concern here is only wilh the core application classo<,
using them to organ .ze the requirements . Relat.onsh lps among classe, arc , hown where necessary. Using
Inheritan e enables some degree of leverage. For example, after 51ating the requirement' for EHCO"nllr Characler
we do not need to repeat these requirement' in describing Player Cbaraeler and Forti9n Characler. The Eneo"Hlrr
QaracltT class is shown in italics in Figure 12.8 becau,e it i, abstract- thi, declare, that there will be no actual
characters beside player·controlled and foreig n c haracters.
The IEEE 830· 1998 SRS standard designates a place where the purpose of each class is stated,
together with its key attributes and fu nctio ns. The stan dard ca lls for uSIng the decimal numbe ring system
fro m each class (e .g ., 3.2.5) to eac h of its attribute requirements (e.g ., 3.2.5 . 1) and each of its function
requirements (e.g ., 3.2.5.2). In stead, we will arrange classes alphabetically to make it easier to add and
~move classes. Such insertions are necessary as the applicatio n grows. It is important to number
requirement.s, however, in order to be able to manage the m, so we do this within each class as show n
in the case study.
Sometimes, only "essential" requirements are numbered since onl y they mllSt be tTaced for now. A good
reference for this style of organizing specific requirements is Jordan , Smilan, a nd Wilkinson [2]. T o assist in
trac;ng detailed requirements it can he lp to give a name to each o ne, a in the case stud y. For example ·

3.2.A. 7 Preferred qualities

[essential] Each area shall favor a set of qualities.

Including "desirable" and "optio nal" detailed requireme nts is beneRcial for several reasons. First, the
scope of the application can be co ntrolled by implementing the requ irements in a planned order. Second ,
~tati ng future requirements provi des directi o n to designers, helping them to create designs that can
accommodate fuiure features . One technique for indicating which requirements have actually been designed
for and implemented is to start by including a disclai mer with each , as in the follow ing exa mple.
When organizing deraile d requirements by class, .t's sometimes a c hall enging issue to decide under
what class to state the requirement. Consider the following require me nt example,

Every Encounter character shall have a name ...

This requirement shou ld be classified with "Encounter C harac ters," We wi ll explain below the relarion
of this with a CUI requireme nt. The following require me nt «quires more consi deration.

Whenever the player's main cha rac ter en ters an area , rhat arca and all the characters in it shall be
displayed o n the mo nitor,

Class candidates to classify this function are Playrr haraelrr and Arro . TI,e requirement effectively calls
for an event h an dl er A na tura It n'gger'lng c lass fo r handling the entry event would be lhe area e ntered . because
.
.It IS aware 0 f W' h Ie h c h aracters .'" h ab 1't I' t. The area entered could display itself and the c harac ters It contaons,
\0 the requirement stated above could rea o nabl y be classified under Arm . .
0 d '
W eo ften lin It necessary
to dcal with /I.diu;d""/s. 099"9al;0Ils , and GUis ce ntered o.n a SIng le theme. For
example, for a video tore manageme nt application , we need to deal with the followon!! .

• ' d I V.' dual D VDs7 For exa mple, what are the l en~ th lim.tallons of lhel r
Wh ilt are the reqUire d properr'1e~ 0 f on
titlc\7
290 CHAPIER 12 ANALYllNG DETAILED REQUIREMENTS

• What are the required propertie of the co llecti o n of DVDs? For example, what is the requirement for
stocking new CUls?

• What are the specincations of a CUI that displays info nnauon about DVDs? For example, what are the
limitations on the text shown? (CUI speCifica tions often change Frequently.)

TI,inking ahead, we recognize that the e will be separate classes when we come to design time, so we
organize the requirements document paragraphs to anticipate this. It is u ually best to begin with lhe
paragraph that describe the requirements o n the ",JiviJuals: in thi case, DVD . This speCifies the required
degree of detail that the application is required to store . It is referenced by other paragraphs.

3.2.DV DVDs

• • •

3.2.DV. t Attributes of DVDs


3.2.DV. I.X Director's Name The application shall retain the name of the director of
each DVD . This shall consist of the director's la t name, in a fonn of between I and
30 characters, which can consist of a·z, A·Z, and a hyphen . In the case of multiple
directors, only the first alphabetically shall be retained.
• • •

3.2.DC DVD CUI


The CUI displaying a DVD shall have the appearance of figure xx.
• • •

3.2.DC. 1 Attributes of DVDs


• • •

3.2.DC. I.X Director's Name Appearance The director's name shall be dispiayed in
the location shown in figure xx , in accordance with requirement 3.2.DV. I.X, but
limited to the first 20 characters. . ..
• •

3.2.DC.3 Events Pertaining to the DVD CUI


• • •

3.2.DC.3.X OK Button When the "OK" button is pressed • • •

• • •

3.2.DI DVD Inventory


• • •

3.2.01.2 Functionality of DVD Inventory


• • •

3.2.D1.2.x Stocking a DVD The application shall allow new DVDs to be added to
[he inventory, up to a maximum of one million . ...

• • •
USER INTERFACES: DETAILED REQUIREMENTS 291

rgaOlzmg
pnncipl. Advontage< ))1Sadva11lage<
By Feature © Mops well to why we ore ® Docs not map well to 00 code
bUIlding the appl,ca ti on
© Easy to understand ® Hard to locate random requirement
By U se Case © Easy to understand ® U c cases may overlap
® Hard to trace to deSIgn and code
® Coverage IS hmited
By CUI © Easy to understand ® Not every function appears in a CUI
® Functionaliry of C Uls overlap
® Hard to trace to design and code
By State © Easy to understand ® ClaSSification can be unclear to the
© Design th Inkin g begins early cus tomer
® H ard to allocate requirements to state
By Class © Easy to trace to code ® C1assi 1catlon can be unclear to the
© Easy to locate random cu)tomcr
requirement
© Design thinking begins early

Figure 12.9 ways to organize detailed requirements advantages and disadvantages

12.2.6 Classification Methods: Advantages and Disadvantages

Figure 12.9 ummanzes the d iffe rent way to organize fu nc tio nal detailed requirements that we discussed In

the previous: sections, along with th eir relative advflntagcs and disadvantages

12.3 USER INTERFACES: DETAILED REQUIREMENTS

Recall the follOWing ste p in specifyi ng user IOterfaces.

Step 1 Kn ow your u er

Step 2, Understa nd th e bu<inc" fu nc ti on 10 question

Step 3, Apply pnnClple of good scrcen dC<1gn

Step 4 Select the appropnate kInd of windows

Step 5. Develop system menus

Step 6 elect th e appropriate devlce ·b.,cd contr I

Slep 7: 0100se the appropriate s rcen -ba<ed control,

Step 8 rganize and layout w lndow<

Sl<:p 9 hoO\e appropnate colors

Step 10 rcate meanIngful Icons


"llId"n~c
Step 11 J) rovlde c (fclive me>sage, fe" dl" , k, alld D
292 CHAPTER 12 ANALYZING DETAILED REQUIREMENTS

• En~ure consl ten cy amo ng the Screen. of d es l ~ n a tcd "PPloc.t lons, and among <crcc n< w,th,n cach
• conventIo ns, procedures, look .and . fecl , loca ti ons
• Anticipate w here the user wi ll usua ll y s tart
• freque ntl y uppe r left-place "Ars t" clement th e re
• lake navigation a si mple as possi ble
• align like clements
• gro up like c lem ents
• o nsl der borders aro und like cleme nts
• App ly a hierarchy to emphasize orde r of imparlance
• Apply principles 01 pleasing visuals u uall y:
• balance, ymmetry, regul arity, predIctability
• simpliCIty; unity: proportion, econom y
• Provide captions

Figure 12.10 Principles of good SCfeen deSign


Source GaJItz. W • • :"e E.ssenbal GOlde to user Interlace DeslgJ1 An IntroouctlOO 10 GUt Prindp~ and TechniQues," JOhn Wiley ~ Sons, 1996

Steps I and 2 were descnbed in the previous C ha pter I I since they apply primarily to hi g h ·level
requ irements We now describe the remai nin g steps fo r specifyi ng detailed user interlace requirements,
whIch are esse ntiall y a detailed descriptIOn of each C UI screen.

step 3: Apply the principles of good screen design


Figure 12 . I 0 li sts some majo r clements of good scree n design. The figure includes several lac tors that often
app ly to mak In g an interface pleasing Alth o ug h these serve o nl y to introduce the subject of visual effects,
th ey arc nevertheless usa ble by the average software e ngi nee r.
As an example, we app ly some of th ese principles to an example o f a sClcen used to input information about
customers and the ir accounts. An ini tial attempt at a C Ul,s show n in Figure 12 . 1 I. To improve the interface, we
start at the to p left . placing the most impo rtant clements firs t, and grouping like elements. Figure 12. 12 illustrates

Type: checking 0 savings 0 mml o CO o

Branch: Main SI. 0 Elm SI. 0 High SI. 0

Privileges newsletter 0 discounts 0 quick loans 0

First name I I
Middle name I I
Last name I I
Street I I
City I I
State/county I I
,
4 _ ...........

-'~

-
. ~
•.
.. ~

..

Figure 12.11 Applying principles of good screen deslgr>-"Before"


scuu: GaDa. W • ''lne ESS 'ltial G'oOt to user Interface ~ All introduction to GVi PPrIInIt<~' ' l anct Ted~." JOI't, 'Mtey 3; SOns.. 1996
USER INTERFACES: DETAILED REQUIREMENTS 293

New Customers ,--, -.



. -. - ' . •

- Branch r Account type r Privileges


0 Main St. 0 checking
0 newslener
0 Elm 5 1. 0 savIngs
0 discounts
0 mmf
0 High 51. 0 quick loans
o CD

Figure 12.12 Applying prinCiples of good screen design-" After"

the improvement that the applicarion or th ese p n nciples can bring. Figu re 12 13 shows where so me of rhe
principles of good screen des ig n were applied.

Step 4: Select the appropriate kind of windows


Each user interface purpose can be served most effectively by o ne ortwo panicular types of windows Figures 12. 14
and 12. I Slisr five common CU I purposes and a window type thai sarisfies each olthem The Window types employ
Windows™ terminology, but are typical.

------
·~w..Qustomers ""' - dl!~~a EXQBCted position

- Name ----- ~dOre~ -


p '- ---
--4
First I I SI,eet
~~e.J<9~tmJq ::::J
M ~hg,a li~~ ~/(l.rl1~!1t~ -:r ~ City I I
I r~ StatQ/co

Last I Border around like elemenrs

Branch - Use capr/ons Account type r Privileges

o Main 51. o checking o newsletter


o (. '- -
o Elm SI. SvmmQUJ! o diso 6il1~
o I .. , . ..
o High SI. o quick loans
o CD
GfOUQ
J/kBRIBroeOIS ProQOoioo

Fl&ure 12.13 How principles of good screen design were applied


294 CHAPTER 12 ANALYZING DETAILED REQUIREMENTS

I . Purpose: display properties of an enllly


- property window
Propertie s u f autumobile 18g

Brand
Model
~ID=----_ _ 893·8913·789014

2. Purpose: obtain additional information so as 10 carry


out a particular task or command
•. dialog window
Help
Word
This screen 0 All screens 0

Figure 12.14 Types of windows, 1 of 2

Step 5: Develop system menus


Some rules for the creation of main menus, provided by Calitz [ 3], arc shown in Figure 12. 16.
Users require a stable, comprehensible anchor for applications, hence the need for a constant main
menu The number of Item on thIS menu sho uld usua lly be between r,ve and nine, because most of us feel
comfortable with chOICes of thi size. For example, the word proce sor with which this book is being typed
ha nrne m.rn menu items F,lr, Edit , \I"",, III Strl , Fonnat , Tools , Tahir , Willdo"" and Hrlp . The number of items
could have been far higher, Since there IS plenty of space for more . However, we would probably have to

3. Purpose: ABC alerl message


provide information Caution: "age" must be < 120
- message window
~

4. Purpose:
present a set of controls
- paleNe window

5. Purpose: This Is • pop-up


amplify infonnation window, designed to
- pop·up window provide on·t/le-fty
am~ification

Figure 12.15 Types of windows, 2 of 2

• Provide a main meflU


• Display all relevant alternative (only)
• March the menu structure to the tructure of (he application's task
• Mmimize the number of menu levels

Figure 12.16 Developing system windows


USER INTERFACES: DETAILED REQUIREMENTS 29S

continually search the l1sl for the option we require, and this outweighs the benefit of increasing the choICes.
The main menu items arc determined by the bUSIness at hand-in this case the processi ng of texL Thus, for
example, gTaphics command are placed o n a secondary menu.

Step 6: Select the appropriate device-based controls


"Device· based contro ls· are the physical means by which users communicate their desires to the application.
They include joysticks, trackballs, graphics tablets, touch screens, mice, microphones, and keyboards.

Step 7: Select the appropriate screen-based controls


"Screen· based controls" are symbo ls that appear o n th e mOOIto r, by mea ns of which the user no tiRes the
application of his or her input and intentions n1CSC include Icons , buttons. text boxes, select ions, and rad io
buttons. The rule for arranging screen· based cont ro ls in a Window arc Virtuall y the same as those for screen
design in general (see Figure 12 . 10. Their numbe r is, agai n, ryp lca ll y berween five and nine. Th is number can
be increased, however, when a hierarchy is used . For example, In Figure 12. 13 th ere are rwc nry o ptions to
select from , but the interface is manageable because th ese Iwen ty items arc orga ni zed 1010 SIX grou ps.

Step 8: Organize and layout windows


The rules for layi ng out multiple windo ws are si mil ar 10 Ihose for ind iVidua l screm desig n (involvIOg
symmetry, proportion, ctc.) as in Figure 12. 10, but Ihey IOvo lve arrangemen ts such as til ing and cascading.
The latter terms 3re illustrated in Figure 12. 17.

Step 9: Choose appropriate colors


When used with skill and taste, color ca n enhance displa ys. Colors do no t aUlo malicall y make a user inlcrface
more uschll or more attractive, however, and they can ca ily worsen It. According to ren owned designer Paul

~C~a~s~c~agdrrm~guw~m~d~O~w~S! --------lcon
,-
Tiled New Customer I
t - windows --I
I
- Name Screen
Text bOX - - - . &
First I I I .....a<d
-.:J
Last I I boc'

Account type · Privileges


Radio __ checking o newsletter
button 0 savings q. discounts
o mml - " IJ.QIr
Button - - - r - - +\ CIInceII ~AAIIY... C1J.~k

Acure 12,17 COmmon GUI terms


~ rnc;u teproGuced WIth pe4iiifS31()n It om corel
296 CHAPTI:R 12 ANALYZING DETAILED REQUIREMENTS

r
Rand , ·co lor is comple. ity person, ,cd" 4) oftware e ng,nc"" who do not have a profe'slonal desIgner with
whom to work .hould be very panng aod On<ervallve about the u c of co lor. Try black and white ~r<t If
there" a lear purpose to ,t , ""roduce one color Make sure th t th,s help' the u,cr Th,nk seriously before
addIng more olor'S.
Takong note of well .e<tablished applocat,ons, suc h as w,dely u ed wo rd processors, ca n suggest how to
usc colors well. You Ca n be assured that experienced pro fe« ,onals desig ned thcsc onterfaces, and the
untrained software engoneer can beneRt from im,tat,ng them . n,e color blue ,s common ,n real · world scruns
of all kinds. Symmetry of colors 's often recommended, and th,. symmetry c an be of severa l varieties. For
example, the author's word processor uscs mainl y three d,ffere nt , hades of blue, which occur in a symmetrical
pattern on the standard color pa lette. The other two colors u cd arc yellow and , to a lesser extent, green.
These are used on small quantities, accentong additional functionaloty o nl y, and they do not compete with the
major Item , which arc in b lack and gray.

12.4 DETAILED SECURITY REQUIREMENTS

\'qriting the detailed requirements for security measu res is a maftcr of being entirely speciRc about the n«ded
secunty measures. Some of these are shown in Figures 12. 18 a nd 12. 19 When II comes to security logolls, for
example, we may want to requITe that if there is no keystroke o n the application for ten minutes, it logs off
auto matically. Audit tra,ls for security breaches arc important. Some of these requITements are easy enough to
specify but difflcult to implement. For example, how would an application know that it has experienced a
security breach)

12.5 ERROR CONDITIONS

For each requirement, we ask what would happen if ,t were to take place under erroneous circ umstances. As an
example, let's take a requirement example put forward by Myers [5]. as shown in Figure 12.20.

1. U ser id entification capabi lities


• Rules on IDs, name clashes, restnctions, etc
2 . Person or entity au the ntication capabilities
• Exact requirements permitting acces to resources
3. Security logoff
• Measures to prevent unattended or unusual usage
4 . Aud it trails of security. related events
• Type, outcome, state at the time , date and lime, Source

Figure 12.18 oetalled security requirements. I of 2

5. Password speciRcations
• length , composition, allows characters, etc.
6 . Controls to en ur. data integrity
7 . Retrievable record of encryption methods
8. Information on security attributes of the system

Figure 12.19 oetalled security requirements. 2 of 2


TRACEABILITY OF DETAILED REQUIREMENTS 297

AjtnCclto" lballtlls w!xlbtr Ihr,. "","bm produCt all equilalerallriangle (all sides equal), an i,osceles I'ia ngle (exactly
!wo sid~ equal), or a sca/en, lriangl, (all sides different),

fIIu1'e 12,20 Requirement example, without necessary erro,s

A junclion lI,al Idls wh,lI", a lriplel oj nu",bm prodllc" ,


1. an ,qui/alera/lriangl, (whose ,id" are all 9rea ler Ihan zero and etlllOl). in which cast .1 oll lpul, 'f' al Ih, prompl, or

2, an isoscel" lIian9 /' (whoSt ,id" are grealer Ihall uro, exaclly Iwo oj which are eqllal, and Ihaljorm a lriangl,), in which
cast il oUlpul, '/' al Ih, ,ysltm, or
3, a sealen, Iriangl, (whoSt ,id" are all grealer IIJan zero, which jorm a lri,,'g/r, m.d Ihal is n,ilh,ttquilaleral nort,o,etl,,). ill
which caSt il ollipuis '5' al Ib, prompl. or
4. no Irian91" ill wbich caSt il oulpuls 'N' a l Ih, prompl.

, FIgure 12.21 A more complete version, accounting for errors

This requirements specification is not complete because it does not account' for error conditions. The
version in Figure 12.21 is more complete . A lack of error conditions in requi rements specifications becomes
especially g laring when the function is tes ted, si nce the tester forces error co nd iti o ns and needs to know ,,,hat
the required output is.
Sound requirements analysis does not tum a blind eye to "illegal" input: it deals with th em directly. For
example, it IS tempting to assume that a C UI for the triangle requirement d oes nOt perm it th e input of negative
nUiTlbers, and so the function docs not have to deal with erroneous data . Such an assumption is unwise because it
transfers the "legality" part of the triangle require ment to reqUirements o n code clients of ou r triangle htnction ,
- This increas~ the dependence among parts of the applicatio n, whereas we always try to obta in independent
parts. Although it i, good practice to trap invalid user input at the CU I leve l and to o blige the user to e nter o nl y
legal va lues, this does not subsl'itute for good requirements and error recognitio n elsewhere . The auth ors
recommend requiring the trapping of incorrect data at many , if no t all . possible points. Th is is equivale nt to a
long-established engineering practice of practicin g redundancy to pro mo te safety,

12.6 TRACEABILITY OF DETAILED REQUIREMENTS

Chapter 13 di scusse the qualities that we want requirements to possess , an d metrics fo r meas"ring them .
We will call out o ne property he re because it is fundamental to how we think about req uirement<'
IraClabtlily .
Imagone an application with 1,000 speC ific requirement , Without, clean tTa ce fro m each requirement
through the deSIgn o f the app li cat.o n to th e actual code that Implement s it, it IS very dlmcult to e n ure that
such an application remains In compliance wHh th e requirements , When th e reqUIrements change, wh ich i
safe to assum e , this becomes eve n mo ,e dtfficult The capaci ty to map each detailed requirement to .tS
rtl<:vam pan ts) of the design and implemen tat Io n is called Ira ea btli ty . We Rrst di cuss the tra eab.h ty of
functional requirements, th en nonfu nc ti o nal req uire me nt<.
One way to help a ompllSh traceabi lity IS to map ea~ h functIona l d e tailed req UIreme nt to a Specl
function o f the target language Th .. t 'c hn.qu e is used III th e Encounter a e stud y. FIgure 12 22 .ho" '$ rart<
/
298 HAPTER 12 ANALYZING DETAILED R QU IR~M ENTS

Design

Code Implementing MY-D-Aequireme:=n:::t :..----=--=----::---:0


Code

Test plan My-D-Aequirement

Test plan inspec1ion r,.:e~po~rt:,=i~~~~=~':":':===::....J


Test report
= - key Iraces
•• 0 - ; delailed

Figure 12.22 A thorough trace of an invidivual detailed requ irement

of the project that we would like to keep linked to have comple te traceability. Achieving and maintaining this
deg ree of tra ceabili ty durin g devel o pment is a major c hallenge .
As an exa mpl e, co nsider the fo llo win g functional require ment for th e Encounler video game case srudy

\'(Ihen a foreIgn ga me c haracter e nters an area co ntaining th e player's main c haracte r, or vIce
versa, they engage each o ther.

The m ea nin g of this stateme nt is clear. What re mains to be seen , however, is what part or parts of the
desig n and code will be respo nsi ble for implementin g this requireme n t. Whe n usi ng thc 00 paradigm we
can link this requi rement to a speCific function of a speCific class. The issue of w ha t class is responsible fo r a
function is not trivial , and it ari ses repeatedl y when usin g the 00 ty le . For the above example, ArrD
objects would be able to recognI ze that an engagement i to take p.1ace s ince the y would presumabl y be
aware of th ei r inhabitants. In particular, th IS requireme nt wtll be traceable to peclhe event-handling code
for th e Arra class.
As the project proceeds, the requ irements d ocument hou ld be kept consistent with the d esig n and the
implementation . When requirements are hard to trace through desig n and code , however, d evelopers tend to
avoid updating the requirements d ocument when mak ing c han ges to the ource code becau. e of the extens,,'e
effor! required . Ultimately , such a deteri o rati o n of documents result in escalatin g development and
mainte nance expenses. ThIS pheno menon is illustrated by th e following example.

Dnxloptr Bill j, ask,d 10 make cbang" 10 1/" implemnllallon /.Jill find, il difficlIlt to COlln,, ' Ih, cod, b, j modifyin!J
to 'he corrtspondiJlg pflrts oj tht rtqu;rrmtttis documtnt l cotlStqurnl/y. ht flllls to "pdale rlx dOCUmN1111110Pl

Devtloper CD n"," i, task,d 10 m"k, "CU, modific,, 'ions. Sh,


imp'''"'"1s 'I(", cod•. Irsl, il. "nd b,gi", Updali"!J lbe
rt4uirtmrnls documrnl. Howrotr, rtltryOtlt Itlls htr "0110 botbtr, 1>0lnting oul IIl(lltht rrqUlrt'"rtt ts dOClfn't"rtt is out oj
dal, in ,ever. I pltlCCl affd no Oil' lrusls il"ery milch They ,,1/
ber il makes "0 Sm,' 10 lake II" I,m, 10 ptrJ«1 her pm'
w/"" /10 01/' will "tid Ih, Jocumenl ."y",ay So Carmnl mo"" Oil 10 do 011", programmill!J n,. '/I<",,,,,"nrs
b(hocttl fht rt4U1rmttJIls JocufTItn' find the codt ('O" ';"U( 10 Wldttl
TRACEABIUlY OF DETAILED REQUIREMENTS 299

Module 1 Module 2 Module 3


Regu,,,,,,,ent
1783 getimerestO computeSa lO showNameO
178 4 showAccountO showAddressO showNameO

FIgure 12.23 Example of a requirements traceability matrix

When a requirements document as a whole is untrustworthy. even the most conscientious developer
balks at properly updating his or her particular part. On the other hand , when the documents are clearly
crosS' referenced, and management makes documentation a job performance requirement, engineer< do keep
them in very good professional shape. In other words, the system used to match detailed requirements with
the designs, and code thaI imp lement them , must be very clear and co ncrete.
When the code implementing a requirement needs to exist in several parts of the implementation,
tracing is achieved by means of a requirements lracmbi!ily ",alrix of which Figure 12.23 is an example. Here,
requirement I 783 is implemented by the action of fun cti o ns 9rll"lm,10 in module I , compIII,Ba!O in module 2,
and ,howNa"" O in module 3. A change in this requiremenl necessi tates a change on o ne or more of these
functions. This must be carefull y managed because Ihese func tions may participate in satisfying other
requirements (e .g .. ,bowNa",,() is used to implement requirement 1784 as well ). As a result, changes made to
satisfy one ",quirement may compromise another. Since many· to· many relationships are difficult to manage ,
we try to make the mapping between requirem ent and function one-to-onc.
We want each detailed requirement to be traceable forward and backward . The preceding discussion
concerns forward traceabiliry of functional requirements from detailed requirement to implementation.
Backward traceability of a detailed requirement means that the requirement is a clear conseq uence 01 one
or more high .level requ irements. For example, the detailed requirement

Foreign characters should move fTO m area to area at intervals averaging 5 seconds

can Ix: traced back to the fo ll o wing hi g h . level requirement, which was part 01 Section 2.0 in the SRS .

The rest [of the c haracters), called "foreign " character<, arc to be under the application's control.

This backward traceabiliry is a basis for the inspectio n o f detailed requirements. Compiete traceability is
Obtaoned when each detailed requirement is Ionked to a spedRc ekment of design , and to a unit test, as suggested
by F'gure 12.22 . lt indicates the advantage of a ti ght trace (correspondence) between each individual functional
requ' reme nt, the part of the design Inte nded to handle the requ irement , and the pan of the code that implements
it. These are coupled with the focused tcst lor the requtreme nt , ca ll ed a 1..,;llrsl. Unit tests are the subject of
Chapter 26.
The preceding discussion concerned functional req uireme nt , but how do we trace nonfun ctional
requireme nts1 This ca n be dimcu ll because more than o ne pari 01 th e design .nd implementation may
contribute to satisfyi ng a nonlun tiona I rcqutremcnl. For example, a req uireme nt that every En Olonter
t n!!"gem"nt com plete In less than o ne second could involve ode in an Ellgagr",ml class, .neVor a Gill'" b.,mcl"
class, . "eVor an A"a clas<. ur oblccti ve at requlremen ls tllne is 10 specify nonlun tlo nal require ments.
clearly as possi ble . In o rd er to larify nonl"nctlor.. 1 requ ireme nt , we will al,o lo uch o n des,s n and
tmplementafion issues.
300 CHAPTER 12 ANALYZING OEl AI LEO R(QUII1EMENTS

InspOCI

- - - - -••......1,mPlemenlatlon l
,,-/ t
,/ I
,/ I
,/ I
,/ I
,/

Implemented by tests ...


Relevant whole application I

components ,/
.- I
I
,/ I
,/ I
,/ I
,/
Nonlunctional Requirement · - - - tested by - - - - • System Test

Figure 12.24 Tracing and testing lunctional vs. nonfunctional requirements

O ne goa l of the design phase is to isolate each no nfunctio nal requirement In a se parate design clement
In the case of performance reqUirements , an iutempl IS made to isolate time -enrical processing units
Appropriate , inspectab le, nonfunctional comme nts accompany each function that is aHected by performance
requirements. Preferably, these are quantitative, as in "must complete in less than one mollisecond In the worst
case ." Simila rl y , in cases where storage constraints arc spec lfled , we identify functions that generate the most
stora ge.
Expenence shows that a relatively small percentage of function s in an application account for most of
the processing, so searching for a few principal time ·consuming ones can be fruitful. Let's return to the "one·
seco nd" performance requirement example for Encounter engagements mentioned above . At design and
implementation time, we seek typica l rime-consuming components in the computation of engagements
These components include loops, graphics displays, and netwo rk communication . Loops and commUnication
arc not involved in computing engagements, and a test is implemented to ensure that the graphics and CUls
required for an engagement execute f.. st enough . Probably, the function that consumes most of the time is
either the function to "e ngage a foreign character" of the E"9a9"""'1 class, or the function to dISplay
engagement results.
To validate nonfunctional requirements we therefore tic each ohhem to a test plan, preferably at the time of
writing the requirement . Figure 12.24 illustrates the typical relationship of functional and nonfunctional
requirements to implementation and testing, discussed above. It illustrates the fact that several elements
may contribute to nonfunctional requirements, and that system or integration testing is typically required to
validate nonfunctional requirements because verifying them (i.e ., prior to execution) can be dimcult.

12.7 USING DETAILED REQUIREMENTS TO MANAGE PROJECTS

Detailed requirements can be considered the "currency" of 3 project because they track the amount that' been
accomplished. For example, a project manager can track the project as in Table 12 1 Recall that It's import.nt
for developers to qUickly Rnd rclevant requirements sections to enable them to easily keep a requircll1.-nts
document up-to-date. In the IEEE requirements format, functional requirements arc III ection 2. If we ,,'ere
to number the paragraphs 3.2. 1, 3.2.2, ... , It would be time-consuming to locate the paragraph pertaonlfl/.!
to a CU51.",,, class, for example. For this reason , the authors usc an alphanumeric labcll n8 uch 3 2. U for
Customers, 3.2.DV for DVD<, ct .
PRIORfTlZJNG REQUIREMENTS 301

Table 12.1 Example of a table that facilitates the tracing of a rCQulrement

with video

12.8 PRIORITIZING REQUIREMENTS

It is usuall y diffic ult- if not impossible-to imp le ment oil desired fun c tio nah ty of an appiocat lo n o n sc hedule
and within budge t. As discussed in C hapte r 8 , one may trade o ff copabilily , schedll le , qual.ty level , a nd COS I. Thus, .r
the schedule , budget , and quality leve l can no t be chan ged, the o nl y alternative is to vary ca pabd ity-th at I ,

to reduce the:: requirements that are implemented . Thi s reduct ion prace S IS perfo rm ed in a planned manner.
One techniqu e IS to prioritize the specific requirem ents. Rank ing all requirements is usually a waste of time
Instead, many organizatio ns classify requirements in to three (sometime fo ur) catego nes. \'I/e wi ll ca ll th em
-essential ," udesirable," and "optio nal." The usc of three categories IS an applicati on of triage des nbed In
Chapter 5. We fi rst implement all of the esse ntial requirements. The de irable and o pllo nal req uirem en ts
indicate the direction in which the app licatio n is headed and thus inAuence th e des.g n F.gure 1225 gives an
example of req uirements prioritization .
Some specul ate that as muc h as 80 percent of the real benents of man y appiocatio ns accrue fro m as fe w as
20 percent of the requireme nts. Thus, if prioritization is perfo rmed well (e.g., calhng ro ughl y 20 percent-no
mo re- "essential"), o ne can possibly achieve most of an appl.catio n's be ne fit with o nl y a frac tio n of the wo rk.
Th is is a useful point to keep in mind if the project begins to run o ut o f time.
The preliminary draft of a n SRS sho w n in Figure 12.26 co nrains so me pri o rnized deta.led requiremen ts fo r
the first release of Encounter. They are provided here, "warts" and all , to g .ve the reader a feel fo r i<sues that mu t
be dealt with. Some of the "desirables" wi ll become "esse nt ials" in future releases. The requirements are in dr.l ft
form and are clearly in need of reorg anization. They arc improved upon later In this chapter and in the ca e Stud y
The prioritizallon of requirements usually re lat es to the itCr.llio n that wi ll .mpl ement them Fo r
",<ample, if we arc not ab le to impl ement the "optio nal " rcqUirement "Enco unter shatl take less than a second

[essentia l] Every gnme cho,"el" ',as II" sam' " , of qual.,irs .


[deSirable] Each ar(Q hns 0 5<1 of preferred qllal"irs
[optional ] Th, play,,'s characler sholl o!l' w.lh tv'ry nlCou"ler. Th((lge rale call bt " , 01 5<IUP lim, lis d,faull is olle ymr Pt,
t'hCoultkr

FIgure 12.25 Exa mple of prioritization of detailed requirements


302 CHAPTER 12 ANALYZING DETAILED REQUIREMENTS

PREUt>.IINARY I RAFr I FnUlU I11c r de laried rcqulI'c ,n e nt'


(n,e , e ~re no t e l (lrHJ nlzed , , ce th e ca e , wci y (IIr an lIl1proved form ,)
(no t rn'pcucd ll c, se nl ml l Every ga me c h.l rac te r In th c Encounler video I!amc <ha ll have a name
[ no lll1Spcc tcd l[es,e l1tl alj Every game c hara ler ha' th e ,all' e se t 0 1 "ual,ti es. ca h ha vlnl! a Ao. tln g pOInt
va lue
[ I10 t "'<pe ted )(c,se ntl all En o Ullter takes pl ace in areas, co h of whIc h IS o nne ted to ol her areas by eXIts
(no t In< pecred )( e se nt ia l] Whenever ~n EI1 o unter ga me c haracte r e nle " an arca cont.,nrng anot her game
c ha racter and o ne of them is pla yer- o nlro ll ed, th e c hara te" may c lthe r c hoo<c, o r be oblrged by rhe
ga me, to e ngage eac h ot her.
[ no t inspccted ][e< e nt ial] Whenever ~ player-co ntro lled ga mc c hara ter IS a lo ne , the playe r ca n change
th c va lue, of ItS q ual it ie"
[ not rn pe red ][ desirable} The na me of eve;y c haracter in Encounter shall ha ve no mo re than J 5 c harac tc"
[no t inspected ][desira ble] Ar any give n time, every ga mc c harac te r shall possess a number 01 livIng pornrs,
The e are the sum of rhe values of irs qualities,
[ no t inspe ted ](dcsi rabl e} Each area has a ser o f preferred qualities,
(no t rnspe ted][ desi rable ] Combat arcas require stre ng th a nd stami na; livIng room areas require listening
abriity and intellect.
[ not inspected]( de irable) The sum of the values 01 qualities of a ga me c haracter rel eva nt to the arca ,n
q uestion shall be referred to as the character's area value, In an engagement, th e syste m compares the area
values of the c haracters and transfers to the stro nge r half the poi nts of the weaker, Fo r example , suppose
th e player engages a (orei gn character in an area reqUirin g stamina and attention to detail , and ps IS th e
value 01 the player's stamllla , Assumin g p, + p, > f, + f" we wou ld ha ve p: = p, + f/ 2, p; = p. + fJ2, f: =
1/2, Ia' = f/ 2 where x' de no tes the value of x after th e transaction ,
[ no t inspected][optiona l] Encountershall take less than a second ro compute the resuits of an engagement.
[ not inspected ][ o pti o nal ] The player's c haracter shall age with every e ngagement. The age rate can be sel
at e rup rim e , Its default is one year per engagement.
[ no t II1spected](o ptio nal ] Playe r-controlled c haracte rs lose o r gai n th e values of their c ha racters at the end
o f every engagement at the rate 01 +2% when und e r 30 and - 2% when ove r 30_

Figure 12,26 Preliminary SRS fragment showing prioritization and status of deta iled requirements

ro compute th e resul ts o f an engagement" in rhe second iteration , it could appear with h ig her priority in a
subsequent iterati on. Th e requirements for an iteration arc maintained in an identi fi able manner. TI'1 helps In
unders tandin g subsequent requirements.

12_9 ASSOCIATING REQUIREMENTS WITH TESTS

As each de tailed requirement is written , tesrs for the rcq urrement <ha uld be developed There a~ e erol
advantages to wnting tests Si multaneo usly with the requirement. Fi"'t, dOIng so helps to lan ly thc <pt'C1 11<-
requirement. Second, it shifts SOme work Irom the testin g ~ha e of th e project to the requIrements phase, Thi<
relI eves some of th e pressure on the latter half of the project when rhere IS less tlexlb.lrt III the use of timc
Agiic pro esse 110 o ne slep brther, and If>'ClJy each detailed requirement by mean of a test
AGILE METHODS FOR DElAll ED REQUIReMENTS 303

T est input for Requir<:ment NNN Ex pected o utput


Harry
H arry
X X
" " (bl ank) ,. (bl ank)
1234567890 12345 1234567890 12 345
1234567890 123456 1234567890 12345
. . ' "
. ...

Figure 12.27 Example of association between detailed requirements and their tests

To rake an e xam pi c, o ne of Our req uire ments is as follows,

Requ irem e nt N N N . Every ga mc c haracter in the Encounte r video game shall have a unique name
containin g be tween I and 15 c haracters.

Requirements of th e attnbute type like th is rea ll y specify get- and set · fu nctions, so that Figure 12 27
constitu tes the begi nn ings of a test plan fo r th is requirement Part VII covers these teSts In detail.

12.10 AGILE METHODS



FOR DETAILED REQUIREMENTS

In an agile project, th e de ta il ed requ ire me nts arc u uall y expressed In terms of in ·code comments and '"11t
tests rat her than be ing writt c n ex pl ici tl y in a se parate docume nt. For examp le , conside r a traditiona l
requ irem e nt such as th e fo llOW ing .

Customers sh all be able to e nte r th e name of a D VD in th e text box, up 10 20 alphanumeric


characters. The appl icatio n shall check th is, wll h punctua lio n marks replaced by blanks, Wllh the
DVD inventory , a nd d isplay accordin gly "Sorry , we don't stock thIS DVD" or "Added to your Ii t."

Th is is replaced with o nc o r mo rc lests as show n in lisling I , aug mented by code comments and eqUivalent
data e ntry in the correspo ndi ng CUI. Assume that the se tu p code in the unit test contains the followIOg

1: Example of JUnit testing. typically used in agile methods


DVDSearch dVD Se a rch = n ew DVDSe a rch() ;

public void t est Lookup ( )


{
/1 "Gone Wi th Th e Wi nd ' , should be present
dVDS e arc h . d oSearch ( " Gone With Th e Win d " ) ;
a sse r t Eq uals ( dVDSear ch , searchResu 1t , true) ;
a sse r tE q uals( dVDSearch . outputMessage , " Added to your list " ) ;
II " War a nd Peace ' , should be absent
dVDSeaICh . doSearch( " War and Peace " ) ;
a ssertE quals ( dVDSealch . sealchResult , false) I
304 CHAPTER 12 ANALYZING DEl AiLED REQUIREMENTS

assertE qual s( dVD Searc h.outpu t Message , " Sorry , we don ' t stock
this OVO' , ) ;

• • • • • •
}

Fi gure 12.28 "lImmarizcs lhls discuss ion.


The adva nt" g~ o f uSing tes ts as a requirement is that thi s i concre tc , th e d Isad va ntage is th at It IS not
complete. There i. nothin g to sto p us from including th o ro ug h d eta iled req uirements with the un it tcst.
ho wever, thereby gainin g agi le and, to some ex ten t, no n.agile ad va nla gcs Thi i show n in Figure 12.29

-.-
OJ
CD
C ust o mer shall be able to enter rhe name of a OVO ,n rhe tex t box , up to 20 alphanumenc
«• c harac ters. The app hcation shall check rhi s. wi th punc tuati o n marks replaced by blanks, with
c: the OVO inve ntory , and display accordingly "Sorry, we d o n't stock this OVO" o r "Added to
o
Z your liSt." (Excerpt from requirements d ocument. )

public void testLookup( ) {


I I ' 'Gone with The Wind" should be present
-.-
OJ

CD dVDSearch. doSearch ( .. Gone With The Wind" );


«
• • •
I I ' 'War and Peace' , should be absent
dVDSearch.doSearch( "War and Peace" );
• • •

Figure 12.28 Unit tests and code comments as detailed requirements in agile processes

I· Requirement 3.4.2: Customer s shall be able to enter the name of a DVO in


the text box, up to 20 alphanumer ic char acter s . The app licat ion shall
check this, with punctuat ion marks repla ce d by blanks, wi th the DVD in-
ventory, and display accordingly' 'S orry , we d o n't stock this DVD" or
, 'Add ed to your list. ' , -I

public void testLookup() {


II ' 'Gon e With The Wind" should be pres e n t
dVDSearch. doSearch ( .. Gone With The IHnd" ) ;
• • •

I I ' 'War and Peace' , should be absent


dVDSearch. doSearch ( "War and Peace" );
• • •

Figure 12.29 Comblnlng agile and non·aglle methods In handling delalled requirements
USING TOOLS AND THE WEe FOR REQUIREMENTS ANAl. YSIS 305

, . Understand next
requirement

5. Refeetor 2. Refactor
o. Understand code 10 clean code base 10
high-level uP. ele. prepare for Ihe
requirements requirement, jf
necessary

4. Modify code
base 10 pass
3. Write tests
Ihe test
validating the

F'tgUre 12.30 The agile programming cycle

When unit tests arc used as detailed requirements, [hey are some times written btJort the code is written
This style is known a !<sf-dn"nl drur/opmtnl. It bui lds upon the existi ng code base, and IS ca rried out in the
following sequence.

I. Understand the required new or modified functiona lr ty.

2. If needed, refact o r the code to prepare it for the new func ti onality. Rdactoring preserves the code's
functio nal ity, ne ither increaSIng nor dec reasi ng its actual h'llcti o na lity. It IS discussed in detar! In Chapter 24

3. Write test code that would test thIS functiona lity If It eX Isted . This is usuall y done with a tool slIch a
J U nit This te t will fa d initIall y beca use the functiona lity it tests does no t ye t eXIS t

4. Add to the code base until th e test pa ses.

5. If necessary, refactor the code base to make it clear and coherent.

Test ·driven development IS described funher in C hapter 27.


Recall that agile development co nsists of the cycle shown "' F,gure 12 30. Refact o ring, de cribed In
Chapter 24 , IS esse ntia l to the pro ess In two ways. It IS u<cd to c han ge th e fom, (not the funcllonal,ty ) of the
code base to prepare for the addillon of new fun c t,onal,t y It" al,o used to make the resultIn g addit Ion r.t
,moothly WIthin the app lication as a who le

12.11 USING TOOLS AND THE WEB FOR REQUIREMENTS ANALYSIS

Tool, can htlp th e process o f ca ptunng and managIng r ·q urrcment<- for example , hy >o""n~ , ,ltegon z; n!:.
p"oritizlng, asslgnlns , and tracklnu them One be neA t o f >uc h tool, i> to kn o w who" worklllg on what
requirement at what tIme Ton" <.a n also help to o nt",1 '·fea ture crce p'· -the pr t" by w h, c h leatur~s that
ire not r.ally nece.sary are add ed to th e app lrca tron W,th th e approprI"te t 0 1<. a projec t !tader can more
eaSIly asseos the tatu, "f r.qUlrt·ments a nal y", I or exa mpl e , th e leacler an N" ly d e tcII'lIOl' the percenl"!!"
306 CHAPTER 12 ANALYZING DETAILED REQUIREM ENTS

j:ilatuB
F,oC'tJon wmplOIO Roady lor Ooa.gned Imogr••lon
aQlllOOlllllWl edPd1¥ No.
lor
QUmb.or Essontlol OpUonol slor1od 213 'nopoction UN' 'I liad
' /3
"T tested
Ooslroble Inspoetod

8&§PQQsible
QDgIO~Q[
T
-t

Figure 12.31 Example spreadsheet lor tracking ;equlrements

of essenti al deta iled reqUire ments implemented and full y tested by QA. Bugz ill a (someti mes in a version with
the unappealing name "Issue zi ll a"), an open sou rce too l for manag ing reqUi re men ts, was descnbed In .he
Ecl ipse hig h· level requi reme nts case <rudy This cc tlo n also d iscusses the management of requ ire ments for
si mple projects, as wel l as IBM's comme rcial ReqUl sllei' ro ' 001

12.11.1 Simple projects

For simple project , much of this can be performed usi ng a si mple Web ·bascd spread sheet, as illustrated In
Fi gure 12.3 1. Howeve r, fo r most reasonabl y sized projec ts a req Uire men ts tool is esse ntial. The "deSigned for"
desi gnati o n in Figure 12.3 1 ind ica.es that the require me nt is accounted for in the desig n. "Un it tested" means
that the code implementing the req uireme nt has unde rgo ne testi ng in stand·alo ne fash ion . "IntegratIOn
testing" means that the application has bee n tested to verify that it impl ements the requ irement. A table such
as .hat in Figure 12.3 1 is mai ntai ned as part o f a project s'atus document that can be attached to the SPMP
The e lls in th is marri x could be hyperlinked to releva nt parts of the project's documents, thereby
preserving slngle·source documen.atio n for detailed req uirements (i.e., e liminating duplication ). For example,

,.. ____ _ Hvpedink from Jaya Source


I to CorresQonding 0 • Reauirement Using /ava doc

ro ,.I t
<a href="RequAnaM EngaglngForeignCharacter ">
Engagement Requirement 1
("Engaging a foreign character")
<la>
. ... Implementallon commenls ... .

"' The purpose of this melflod Is stated in SRS.


The purpose is not repealed with the source!'!'fIe.
.,.
public engageForelgnCharacter( ... )
(
• • • • •
)

FllUre 12.32 Hyperllnk from Java source to corresponding detailed requirement using Javadoc
USING TOOLS AND THE WEB FOR REQUIREMENTS ANALYSIS 307

h)'JlCrlinks from the ourcecode to the corresponding detailed requirement can be accompli hed with toolssuch
a Javadoc.J.""doc converts certain Java source code comments into an HTMLdocumcnt describing thc classes
and Iheirmethods (sec, for example , [6 ]). By insening hyperlinks to the SRS within the e commenlS, the HTML
document produced by Javadoc hyperllnks to the SRS. This IS illumated In Figure 12.32 , where the detailed
requirement corresponding to the method CllgagtForrig. Characttrf) is hyperlinked from the document that
Javadoc produces from the ouree code. The usc of dodtts make thIS process increasingly convenient.
The trend is for continual improvements in the process by which prog rammers will be able to more
easily go back and forth between the SRS , the deSi g n, the graphical user interfaces, and the source code.

12.11.2 IBM's Requisitepro™

For substantial projects, professional tool s are needed to track reqUIrements. The shee r number of detailed
requirements usually make this necessary. One example is IBM's Requ is llePro™ product. The fo llowing figures,
describing it, are taken from hllp.//www.lbm.com/deve lo perwo rk ra tio nailli braryl53 47 html F,gure 12.33
shows a window for sClling the properties o f an Individual detai led req uirement
RequisitePro allows various views o f the requ ireme nts as a who le This helps projec t managers and
software engineers to manage and track their progress FI gure 12.34 is o ne example .

W •• I As&! I
...
t U !lr: '0, I ned", I Cb f.
I
-- -
....."or
I
T,..·
\It
r,IT;.~h~E.'---------------~iJ J
Ic :' :a::

.
,
:
U 11

c ..

Figure 12.33 Setting properties of a requirement In IBM'S RequisitePro""


SlraoonaVliDra1y!S247 htmt

rM
Figure 12.34 A view of a collection of reqUIrements In RequlsltePro
SoI¥ck IBM, hUDHYMW_iDm comIde~eIoptNo'Of'tslrttiOMlllibrbfYJ'5.247 htrnl
308 CHAPTER 12 ANALYZING DEl All D 11EQUIREMENTS

't ,'2'

- •
1$9 •
, 0 _II/ll,,.d,.
t

1.0. J m

- -
erell-"I ~I

Figure 12.35 History of a requirement In RequisitePrc™


Source 18M, hupJ/www Ibm cOlTVde\IeloperworkSlrotlonaVllbraryl S247111mJ

It is possi ble to query this requ irements database-ill other words, to obtain all requirements satisfying a
desired criterion , su h as those pertaining to security As individual requirements are wo rked on by softwar~
engineers, tools hke RequisitePro,.M .IIow the "history" to be tracked, a sho wn in F,gure 12.35 . H,story refers
to an account of the work perfomlcd to sa ti sfy th e requirement at various points in time .

12.12 THE EFFECTS ON PROJECTS OF THE DETAILED REQUIREMENTS PROCESS

Once detailed reqUIrements have been coll ected, the project documents can be updated to reflect the
improved project knowledge. We w"l take as an example the reqUIred updates to the SPMP , which can be
updated as sh own In Figure 12.36.
Detailed requ irements are placed under conA guratl o ll control. One issue to be addressed is what level of
detaIl should be counted as a software conn gura tion item (CI ). ertainly , Section 3 as a whole ("SpecIfic
requ"ements") of the SRS (using the IEEE standard ) could be a CI Each class could be a CI. Individual
requ"ements are typIcally too nne· grai ned to be Cis.
\'qhe n the list of requIrements grows into the hundred , i"cotfSIsttHCltS Can easily arise . Oassifying
requirements by classes, classe; by packages, and packages by subpackages, and the like becomes a necesSIty.
The packages typically correspond to subsystems in the ove rall organizatIon of the application.
Although rompl","css is a goal for which we strive In collecting requirement , it i usually an elusive goal
For substantial applications, there is seldom a natural "last" requirement-just the last one before requirements
freeze . For th is reason , we strive for self·complctcncss: ensuri ng that all of the requirement!' necessary to
accompany each requirement arc present.
Large ·scale projects require increasi ng organizational fomlality (not to be confused WIth formal method» .
The SRS may have to be divided into separa te volumes. A single section on Our (tiny ) case rudy could <"xpand
IntO a 700· page volume. Extensive management work is required to schedule the development and onspection of
detailed requirements. PrOjects WIth hundreds of spednc requ"ements need requIrement manallement tool
The suecc<sful WIdespread usa~e or thdava package< ha shown, however, that I.rge collections of reqlllrementlo
are manageable when the functionality IS organized by well·deRned po kalles, oubpa kag.: and la c>
The rewards of good requirement< analY>ls arc sub tantlal onvcrsely, the penaltl<'S or poor
requirements are substa ntial too. For examp le, Faulk [7], repom on • Covernment A counting Of c study
of the C heyenne Mountain Upgrade project on wh,ch "reqllirements· related problems· ulted on. 600
STUDENT PROJECT GUIDE: REQUIREMENTS FOR THE ENCOUNTER CASE STUDY 309

R"ull of updating
- latus after afltr higl!.lrod Result of updating .fter detailed
Initlol draft rtq,Hrrmt"'S •
reqUirements

Milestones Initial Mort d,'ai/,d More detailed


Risks Idenl ify Relire t'isks idrn· Retire risks identiAed. ide ntify more ri sks
lijI,d P,roio",/y,
serk mort risks
Schedule Very h ig h Prtlinmwry pro)- Mo re det.ailed, shows c1.ss and method
level ,el leh,d,,/, development ta,klng
Personnel D esignate C- £"9111(((S dcslg . DeSig nate softwa re architects
requirements "a I,d fo, D·
engin~ers rrqu irrmrols
mUllySIS

Cost Crude Firs! csritlln l(s Improve d cSlimalc using more specific
Estimation eStimates baltd 0" job function points and/or past experience
CO ll 1(")1 1 with similar requirement

Figure 12.36 updating a project upon completion of detailed requirements ana lYSIS

million cost overrun . an eight ·yea r delay , and dimin IS hed capabilit y. Debates continue abo ut the perce nta ge
of large projectS that turn ou t badly versus the percentage that turn out well. Many large projects do a fi ne job
of requirements anal ysic;. Th e author can arrest to thi s fro m persona l experience

12.1 3 STUDENT PROJECT GUIDE: REQUIREMENTS FOR THE ENCOUNTER CASE STUDY

This section illustrates how the requirements princi ple . covered III this book arc translated into practice, by u ing
the video game case stud y as an exa mple It use the o bJec t-o ncntcd sty le of expresslll!: reqUirements Recall that
thiS organiZing style has the advantage of improved tra cea bil ity and the disadvJnta ge o f diminished readability
compared with o ther organizations such a. by use casco11,e ca« study IS continued III <ub equent hapters

1. Preparing
Hal Furness, haVi ng bee n elected the requirements leader. wa< re<po nsi blc for o rgan izing the anal y<is o f the
reqUirements. As per th e prOject o rgani za tio n, Hal was bocked up by Karen Peter,_ They d eCid ed to ga th er
reqUireme nts in two stages. The Ar<t would be primarily from th e customer, perspec tive (hi g h . level
reqUireme nts ), and th e seco nd primarily for d evelo pers (detailed requlremt'n,, )
Hal and K.lren prepared to Ka th e r metnCS on th e req uirement, proce<s 11,ey c1as<ifled the <tage of th e
pr(')Ct:ss by preparati o n Interview, WfllC · Up, and review The I1l clrics they chose were dl tJtcd mo,t1 y b
l

company policy. and were a< follows

• Time taken

• Pagei of hlgh . level req uirement> wn ll e n


310 CHAPTER lZ ANALYZI NG DETAILED REQUIREMENTS

• - eif ,. " c"I1lCIH o f Ih · artlfa t, On a < ale 01 I- I! (nut rn anJuted by ,,",pa ny po litY)

• Dele tS lound dunn" ""pc tioll' . a, appli~:tble

The ~a dcr IS referred to SectIo n 4 01 thi s guide to ,cc the,e metfl (' arran Ke d In tabu la r fo rm
a~n made ,ure that the sy<tcm for IOKl(ing and trac kIng delco, wa , In p la<..c . a nd that Hal was
equipped WIth the docume ntati On of how to usc It
The o mpa ny', "'W t o~ onsldered video ga mes a promISIng area . and were wrll ing 10 provIde seed mont'}'
fo r requireme nt< anal y;i and a prototype It wa, now H al and Karen', t3>k 10 cietern"ne WIth whom to speak 10
get hlg lNevcl rcqu l ~l1lenl . Hal unde~l ood Ihal no ne of the team knew muc h aboul Video gam<.,.. He deCIded 1.0
Interview people who fTeq uc ntl y play ga mes and are intereSlcd In g ivi ng Iherr tIIn e lor a modest fee . H e made
o ntact with Betty Si ms, President of Amaleur Ga mers Intern all o nal, an enthu lastl game player who saw a
bnght luture for VIdeo ga mes as vehIcles lor fun , community involvement , a nd educat Ion Betty also knl"W man y
ga rn ers. H al and Karen decided to wnle up requirements speclfica llons based o n BellY's "'put and then show the
spc ificd tl o ns to others. The rest o f the team was to inv{"sti ga le oth er avc nue~ for input at the sa me: t lm ~ .
At a weekly meelin!!, H al prese nted a plan for requ rrements analysis, as fo llows,

Week 1,

Hal and Karen , Interview Betty, begi n draft ing h ig h · level requirements .

Fern and AI: Seck o lhe r candidates fo r requrrem ents input

Week 2 :

Fern and AI: Report candidates 10 weekly mee ting .

T ea m, Selec l o ne o r two addil ional people 10 supply requirements.

Hal and Karen, Complete draft of high . level requiremenlS, e ·mail to Betty for comments; arrange to
interview the deSig nated additional people; c· mail existi ng specifica tion to them; c reate a complele
requireme nrs docume nt fo r iteration t ; place under conAglirat io n comro l.

Week 3 :
T eam , Approve the SRS for iteration I.

H al and Karen: Interview deSignated people. edit and expa nd the specification; c·mail to all
interviewees; collate respo nses, edit docume nt, leaVi ng selected issues for team resoluti o n; plan detailed
requirements analysis (sec the Part V 01 this book).

Week . :

T eam, Provide input on the draft SRS; approve plan fo rdetailed req uirements analysis (see Part Vol Ihisbook)
Hal and Karen, Write up SRS and e·mail to all interviewees.

Week 5 ,
Hal and Karen: Resolve issues raised by interviewees, write up results; e ' ma,1 to team, begIn
impleme nting detailed requirements process (sec C hapter 13).
Team : I~ spect h'lIh . levei requirement•.
STUDENT PROJECT GUIDE: REQUIREMENTS FOR THE ENCOUNTER CASE STUDY 311

Despite the expense, Hal felt .t impon.nt to have the cntlfe team inspect the high . level requirements
because of the do ument's importa nce In general , the team planned to use thrce·perso n inspection teams.
Hal heduled the first interv.ew with Betty .n Room 1428 of the Stewan Building from 10,00 a.m. to
11 :30 o.m. He .·moiled h er a bnef write ·up of the project's history, and created the foilowoog very simple
agenda.

10:00 a.m.-l0: 15 a.m. Hal : motives for the project

10: 15 a.m.-l 1,30 a.m. Interview of Beny: customer requirement

Hal decided not to introduce more details because he wanted BellY's requirement to influence the rcst
of the meeting.

2. Interviewing the Customer


Hal and Karen arrived at the interview with Betty, equipped with good sound recordoog equ.pment. Betty could
not understand why anyone would want to build a video game unless it competed with the best available. Hal
explained that this was just a firs t step. to provide the team with expenence in this kood of programming, to get an
idea of the scope of work required, and to show the investors what could be accompli shed with a given amount
of funding . Other motives were to dctermine whether there was any merit to the ideas that v.deo ga mes have
potentially wide appeal , and arc applicable to educatio n. Aftcr this, the meeting became more focused The tape
recorder was turncd on and Hal and Karen began to take detaded notes.
Betty's contention was that role·playing games (not action games) held the most promise for broadening
the playcr community . She disc ussed the minimum capability that a prototype would need . Th i in luded
areas where the game characters would engage , ways to get from one area to the ot her. ways to cause
intoractions among characters, and what wo uld happen when ,he c haracters engaged . Hal and Karen ,ned to
separ.te the issues and features as they arose . into "c rucial for the first itera tion," "can be post poned ." and
' other (Le., they used a triage method). The importance of the requirements lis,ed in "other" would be
determined later.
Given the script.like nature of ,he requirements Beny described, Hal focused on ob,a'OIng use coses
fro m her. He asked her to describe typical scenari os for the game. Be'ty de cribed wha, happens ,vhen two
characters interact Kare n took no 'es and expressed thi s as a use case-a sequence of action 13ken by the
player and/or the game-a nd then read it back to Beuy .
Beny couldn't- think of any o ,her scenarios . Hal felt that there IOU t be more, and a_ked how the ga me gets
staned. This resulted .n a second use ase. The third use case th.t they recognized explained how the pla)'cr
mOves his character from one area to another. These three use cases seemed '0 be a satisfactory begin ning. Hal
and Karen felt that there mig ht be additional essential use cases, but 'hey would have to gather ,hcm la,er.
Berty , Kare n , and Hal sketc hed a few screens together. One showed a typ.cal encoun,er, .nd another
showed a screen for en teri ng the qualities of ga me ch arac'crs. The re was considerable d i cussion of the
perspect.ve that the player wou ld have. Betty wanted a player perspec'ive where the vicw shown on the mon i,or
is the v.ew seen by the player. Karen felt ,hat 'he reqUITed complexi ty for ,h .. view would rake ,hc proJec, well
beyond their modes, initial budget . It was agreed ,ha' a modified fro m·above view would be adequate for the
prototype. The screen sketches reflected ,his. TI,ey agreed ,h>! conSIderable re lIlement of the user .n,erface
would be required
Because of the in,erfaces that ,hey sketched, Karen fel ' that 'he go me could reall y be underst od an i b),
meaM of states Betty was not famoliar with th. tem" but she was comfortab le describing ,vha' he called ,he
'0
"mode<;" of a typica l role . play.ng game, wh.ch ,urned o ut be the sa me oncept. Karen ond Hal ,hen ,ke t hed
out the requ.red ,ratc' of the gome, and rev.ewed w.th Kare n h ow ,he Rame golS from One s'a'e to all ,11 r
312 CHAPTER 12 ANALYZING DETAILED REQUIREMENTS

H ~ I bro II ctll",d 'n:d cI~rofy ", !! the gJl1le lurther by analyz ing lhe lI"w ,, ( data, but , oon (cal,~d that
the data Ilow I CI" lll'C live added httle va lue
Karen I" vlewed he r no tes with the o ther, A (ew pOlOt ' nceded carre tl ng, but th ' re wa, lIene ral
:lgrecmcn l on the de~ ripti n.

3. Writing Up the software Requirements Specification


Hal and Karen diVided the task o f WfltIOg up the RS by ,ec tio ns They used the IEEE R standard, $cctlons I
and 2 ( eetlo n can I>t> o f the detJded requirements, the proce s (or whic h" d, >cus,ed In the Stude nt Project
C",de for h ~pter 4). T o avoid onOicling wri te·ups, they made ,ure that their sect io ns wc re as Independent as
possible. Hal remembered IllS previous project, where the team pe nt sa muc h time reconciling pieces written by
different people that It would have been quicker for one perso n to pe rfo rm the entire tas k alo ne
They disclls<ed how to proorotl ze the req",rement" becau Cit wa, becomin g lear that o therwise the list
of requirements would become fa r larger than the team could handl e. Hal ,.anted to rank the m all , but Kare n
pointed out th at the effort Invo lved would be large ly wasted- most of the top -ranking reqUirements would
ge t done anyway , so the ir exact order would not be important. Almost none o f the botto m ones wo uld get
done , a the lime spent ra nk ing them also would be wa red . They deCided to use a tTiage method to rank
requirement into essential at o ne extreme, optio nal a t th e other, and desirable for the middle category
(which simply means neither essential no r optional) . They felt that it might be necessary to rank the deSirable
reqUireme nts later. Th IS saved a grea t dea l of useless debating time. They de cribed their claSSification
scheme 10 ectio n 2.6 of the SRS ("Apportioning of reqUi rements") .
Section 2. 1. I (concept of operation , containing the sta te diagram fo r the game) took Hal the longest time to
write because he had to translate Berty's info rmal comme nts into a concrete fDim . They tried to cross-reference
appropria te sections of the SRS with correspo nding ,,'Sts even though the teStS we re still sketchy This helped to
clarify the requirements themselves. however. When Betty looked at the test for Section 2. 1. 1, she recognized that
Hal and Karen did not understand some of the issues. In particular, whe n the game is in Reporting state and the
foreign character enters the area contai ning the player's character, the tcst did not expect anything to happen
Betty saw thi< as detrimental and as a way for the player to effectively halt the game. The defect was added to the
list of defects wi th a "major" categorizatio n.
nt
Karen sketc hed the user inte rfaces using PowcrPoint a a draWing tool , rather than building them
wit h Java, the target lan guage. She considered PowerPolnt adequate because the Uls in thi s part of the SRS
are meant to be sketches-the de tailed Uls are specificd in Section 3- and, in any casc, they wcre liable to be
c hanged a g reat deal ThIS helped Hal and Karen to show the sketches to Betty and the o thers, obtain
feedback , and then specify the Uls exactly for the de tai led req ui re ments.

4. Following Up
The SRS Sections I and 2 we re .·mailed to Betty. She realized that Hal and Karen had included o nl y twO o f
the three lise cases, and the third use case describing moveme nt of the player's character was absent. Thi
defect was logged with a high priority.
Betty was surprised to see that the SRS did not reAect several is ue that she thought he had made clear
were importa nt , and was humbled to see that the SR reflected ' requirements" that he had offhandedl
me ntioned but now realized would be a waste of time. The latter IOciuded the ability of the player to change
outfits while an engagement is progressing. She had numerous comme nt , mOSt of which Hal and Kanen
responded to, and some of which were added to the list of defects, Hal e ·mailed the R cction I and 2 to
the team to e nable the m to prepare for an inspection .
Team leader Ed had learned about Arlan Howard , a market ing executive who wa very familiar With the
video game industry The financial backers were willing to fund fun her requirements analysis at the customer
I ~d, and Hal and Karen pre pared to mee t with How~rd The I~tt er wa. no t able to ~r.nr them more th. n half
STUDENT PROJECT GUIDE: REQUIREMENTS FOR THE ENCOUNTER CASE STUDY 313

-
thiS projcct II Writ,,·up
organization (results 01
norm Preparation I ntervi"w insp"ction) Review TOIllI
TIme spent 200 minutes 170 minutes 270 minutes 250 minutes 14.8 hours
(minuteS)

... TIm" sp"nt 250/ 890 = 170/ 890 = 270/ 890 = 200/ 890 =
28 %1120% 19%1123% 30%1127% 22 %112 9%

Quantity 15 pages
procluced
Productivity 15/ 14.8 =
(= TIme! 1.01 pgs/hrll
qldntity) 0 .9 5

xlf·assessed 9 5 9 2
quality
( 1-10)

IXI<ct rate 1.3 per pagel/


1.0 I oer page

Process Spend ~20% Spread inter· Check mate · Spend ±30%



improvement less rime vIew time rial morc (hor· more time

prepanng more evenly o ug hly priorto revIewing
among people inspection

F"lgUre 12.37 Example of postmortem data and analysis

an hour since he was very busy. Karen developed a prioritized list of questions and topics and mailed them
and the existing draft 01 SRS Chapters I and 2 to H oward . They planned to wrap up the high . level
requiremenlS with Howard. The team also planned the process of developing the detailed requiremenrs .

5. Metrics and Postmortem for High-Level Requirements


The high. level requirements were ubjected 10 an inspection by the enri re team and the defects were
recorded. For the next weekly meeting, Hal and Karen sum mari zed the metrics as shown in Figure 12.37 . The
team agreed on the postmortem ob ervatlons shown .

6. Preparing for Detailed Requirements


Hal and Karen had completed their write · up 01 lhe hi g h .level reqUIrements, ba ed o n di cussion and
Intervlcws with Betry Sims and Arlan Howard. Th ey used the IEEE standard, whose headings prompted them
lor the nonfunctional requirements such as CUls, performance, and hardware platfol'lllS Now they had to
Identify the manner In which they would organize the fun tiona I Detailed Require me nts. They antiCIpated
haVing to revisit and update Ihe S R many tim es, coordi nating the de<lgn and code with it : they wanted this
prOCcs, to be as si mple as possible . As a result, th eir major criteroon wa, the ability to easily maint.,n
consIstency between the R$, lhe deSig n, and the code.
314 CHAPTER 12 ANALVZING DETAILED REQUIREMENTS

11, y 11,; , dis lIs' cd orHa", z i n ~ ,he de,ail ed rC'1uorcmcn" by ,late< and a~ '''H'' , bJ,cd on the "at ·
"anSlllon d1J81-:lm de,c nbed "' ,he h'/lh .!cvc! requiremcn» Thl< or/oCallizatlon me thod would <-" nmt o( al.\t
I,he .K,ions that a player would take, , uc h as hck,nl! an eX it hyperhnk o n an area , (o llowed by the effects o(
th" a tI n They both agreed thai till wou ld be an undef\tandable organization, bu, dec ided that It would
no t 'nce to the nnplemcn,ati on a, well as rhey wanted They began ,earch,ng (or other way' In whic h to
rganize ,he detailed requiremcn,s.
Hal wa- ,n (avor of organ lzi n!! the funct ional detailed reqlllre men ,s by use ase, especia ll y Since he
wan ted to loll ow the Llnl ,ed Software Devciopment Process H e sa id ,hat , at tillSstage, the Video game could
most cas d be thought of In terms of the srlth'9 up u~c cas.e, th e ,"OVfI19 lUHOIIg tlJt ga mt OfClU u~c case, and the
MI9"9"'9 thtJortigll bflraclrr lise case . He point'cd out how co nvcnit:nl ll would be to use JUSt these three use cases
as the to tal e"ent of rhe (unctiona l requirement . He was also ex Ited about the prospect o( perhaps being
able ' 0 reuse these u e ca e, for specifying future games
Karen agreed tha, the requirements would be qui te easy to understand if orga nized by use case , but she
had several 01 jections. The first wa that some requirements would be pan of more lhan one use case. An
example is what happe ns when an exit fro m a room is clicked . T hi s could be pan of a ll of the three use cases
they had ide"tined, and so it would nOt be clear where to look lor i, Karen's ot her o bjection was the fact that
mapping from the usc cases ' 0 the code would not be as clean a ,he orgaOlza,ion she had ,n mind. Finally, she
pointed out that the organization was no t yet equipped to properly archive use cases for future reu e.
Karen wanted to orga nize functional use cases by class, which , she aid, faCi litated traceabiliry (rom
requirements to implementatio n. She wanted to pick ,hem ca refully enough to ensure that they would be used as
part o( the design (and Implementation). Hal pointed out a disadvantage of thi approach · the fact that it (oFCed
them to deCide very carl yon some o( the classes tha, they would u e II11mpie mentIOg the application . He was
worried about the pOSSibility ,hat they ma y later c hange their minds about the selection . After further
discussion , they deci ded that o rgani zi ng the detai!cd requircmenls by class had more benents lhan drawbacks,
and they committed to this method . They decided ' 0 be very co nse rvative about class se lection , however.

7. Classifying the Detailed Requirements


Hal and Karen firs t took each usc case, and identified what object o( what class In"iated the action and what
object has the responsibi lity (or carrying out the action . This process prompted them to create andlor identify
classes. They fou nd it necessary to ca ll Betty and Arlan several times to clarify use case steps they thought
they had understood but really didn't.
Hal listed the classes and objects mentioned in the usc cases. They then brainstormed , couring every
aspect of Encounter they cou ld reasonable ima gi ne for additional po sible classcs. As a Rnal step in the class
selection process, they dras'ically cut the list down to an essenl i. 1 few , but taking care to pre erve all of the
clas es referred to in the use cases. The final list consisted o( Arra, E"COIIMI,rCharn I", En co"nlrrGam" En9a9"'I(>11
E"9a9rnomlDisplay , Con",elio"Hyprrl;"k , Forri9"CJ,ara clrr, Play,rCl,ara Irr, and PlayrrQ"alily Window.
They now Rnalized the headings of the SRS in Section 3.2 ("SpeciRc requITements"). They collected the
delailed requirements related to areas in Subsection 3.2.A, corresponding to th<' Area class. They ordered these
subsectio ns alphabetically because they anticipated adding classes later. They sumllSed that if they were to have
ordered topics by number (e.g., PlayrrCbara I" being 3.2. 14), then locating an individual rcqll1rement would
have been more difficult, because the user of the SRS would have to search many of ,he 3.2.N subsections be(ore
Rnding the one applicable. The next class being EncolonlrrArra 0" "relion , they numbered the next . ubsecl10n ' .2.
EAC, and so on . W ithin each cla.ssiRcat·ion, they crea ted subsection$ for al/rib"I" , nltiti",].IM lionlll,ly, and n.... l$ .

8. Writing the Detailed Requirements


Karen and Hal wrote Section 3. 1 on uscr interfaces by Riling in derail, On the sketches the had made forth. h.gh.
level requirements, then aski ng Oelty, as well as the human factors dep.nment, to rev iew them. Know,"s that thiS
would be the Anal document from which the<" were to be bUilt, the>' hod ,he Cll tomer .g"-'" on e"ery detoll
CASE STUDY: DelAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME 31 5

Thcy checked their interview notes with Betry and Arlan as to the properties ("attributes) of each
classification (cia s). For ex~mplc , thcy asked what propenlcs we re required for the connections between
cwo Encounter areas. (One property of such co nnec tio ns was "the first area" connected , and another was
' the second area.") For each class , they asked themselves what entities (instances of the class) were
required for thc game . For exa mple, there would ha ve to be a dressi ng room arca and a courtyard arca They
then asked what functionality the class had to possess . For exa mpl e, a functionality of each Encounter
character is the ability to configure the values of it·s qualities (requirement 3.2.EC.3 .2). Finally, they listed
all of the events that In tances of the class were req uired to rcspond to (fo r example , clicking on an exit
from an area l.
Onc aspect that di turbed them was the time reqUired for new va lues to take effect. They realized that
this wa a key aspec t to the ga me, if no time were to e lapse , the playe r would si mpl y set the qualities
pertaining to the current area to a maxi mum , and little skill would be required to play the ga me 11,e delay
made the game interesting , but the problem was, h ow much delay should there be) 11,cy con ide red stati ng
"to be decided" for the durat io n, but finally concluded that th is would no t help. They deCided to specify fo ur
seconds, feelin g that changing this amount should be straightforwa rd .
Karen was concerned about the iml'recision of some of the requirements, espeCially those co ncerning
the manner in which qualiry poi nts shoul<l be exchanged when two characters engage each other he felt
that programmers could easily misunderstand the requirements. ThIS would wa te time on defects a~d
produce a defective ga me. She suggested usi ng Z·specifications. Hal made the poi nt thai ~ o o ne excepl Kare n
would understand them ,,'ell enough , ince Ihe rest of Ihe leam dId not have Ihe required edu call o n .
They compromised by agreeing 10 use appro priale mathemall cs In specifying Ihis requirement , bUI no t the
Z·specificalion format. Karen made a menia l nOle Ihal if she ever taughl sohware e ngi neerin g, he would
insist th ai all students to be comp le le ly comfo rtable ,.ith Z ·speciRca lions.
Prom pled by the section headings in the IEEE SRS standard , Karen and H al made sure to cove r all of the
performance requireme nts and c h ecked them With Betty and Arlan , mostl y penalning 10 the peed Ihat Ihe
game would have to possess 10 be inleresting . They a lso Ih oughl Ihrough the memory reqUIrements (RAM
and disk). They the n completed Ihe document.

9. Following Up: Metrics and postmortem on Detailed Requirements


The requirements analysis team asked Be lty, Arlan, and Ihe res I of the team to Ins pect Ihe detaded requirements.
They performed thIS inspeclion primarily agai nsllhe 11Igh -level reqUIreme nts by ensuring Ihat every part of Ihe
high-level requiremen t were elaboraled upo n by delai led reqUire me nts. They also e mployed a c heckli Ilike the
one described in Table 13.3 of Chapler 13. Several defecls were fo und, whi ch H al and Kare n recorded and
repa"ed . The resu lts of thiS proces were Similar to Ihose de c ribed In Figure 12 37.

12,14 CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME

Th,s seclion compleles the requirem e ntS sjJeclRca · 3.1 Exte rn a l Interface Re qu iremen ts
tlon of the Encounter vid eo ga me in IEEE format.
3.1.1 User Interfaces

3, Detailed Requirements
Section 2. 1.2 in the SR for the En ounlcr VIdeo
lIame showed o nly ketc hes of u cr interfa In
Note to the Student. order 10 proVide product p<!T'Sp<Cl1ve It Ia ked
The IEEE term u.ed in this hcadJllg IS ·speclfic" delailsand , ha uld not be rega rded as the last word.
requirements We have substituted the te rm If u er Interfaces are not o mple leIY ' p<CI-
'ck~lled" to be ~onslstenl with the lext Aed later In Ih ls docume nt , Ihe~ all delall. ,holJd
316 CHAPTEI! 12 ANALYZING DETAILED IlEQUIREMENTS

Note : Each part


of Ihls Ilgure Is
s pecifi ed
- - - sepa rately In
COURTYARD Section 3.

dressing living
room room
Elena Current hfe
points: 56.38

(SelQU....... ) Value
16.18
1~'2i·1

Figure 12.38 Detailed requirement for Encounter courtyard GUI


Source. Gtaptbcs reproduCed WIth pcrmlssK>n from Corel.

same lIser interface is used to ho w the statuS


be given in this section. Since we are using the of the player's c haracter.
object style of specification in this case study, the
details of each window arc packaged with their An interface of ty pe a above will alwa ys be present on
classes In Section 3.2.2 in the SRS. In any case, the monitor. When called for by these requ irements,
this section should explain the physical relation· inte rfaces of type b o r c will be superimposed .
ships among graphical elements (e.g ., cascading, This requirement i teSted in Software Test Docu ·
tiled, superimposed). 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 ,
The hardware that Encounter (which is a
with a player.contro lled character, a foreign charac ·
software application) deals with
ter, and the results at an engagement. This interface
takes up the ent ire monitor scree n. Areas have
connections to adjacent areas, labeled by hyperlinks. None
Clicking o n one of these hyperlinks moves the (I n a fUlur~ release, Encounter will be control·
player's character into the corresponding area. lable by a joystick.)
The entire sct of '"te rfaces is as follows :
3.1.3 Software Interfaces
a. One user interface for each area, specified in
Section 3.2AR below .
b. A uscr interface for <ctting the qua lity values of the Other software with which Encountler must
player's character, sp<eiRed in Section 3.2.PQ. '"tlerface: an enmplle would be a prin~r drwct
c. A user interface for displaying the results of an
e~8a8ement, speCified in S"ction 3.2.ED. The None
CASE STUDY; DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME 317

(In a futu~ ~Iease , Encounter wtll be playable


from IntergalactIC Internet Gaming Slle .) referred to elsewhere in the project, could not
be disrurbed. TI,e requirements would not be
alphabetically ordered. As a ~sult, one would
3.1.4 communication Interfaces have to go through the requirements one by
one one to locate a particular one.
(In a future release, Encounter shall Interface
with the Internet via a modem with at lea t 56 Kb/s.)
3.2.AR Areas
3.2 Detailed Requirements by Category
F,rst, we de cribe what the class (i .e., this
classification of requirements) refers to.
The IEEE uses the heading "Classes/objects" for
Section 3.2. Th,s assumes an audience that
knows object orientation. It is necessary to An area IS a place viewab le on the monitor. All
untkrstand 00 to create this section but it is aCllvities of Encounter (I ncluding engagements) take
not necessary in ordeno read and understand it. place in areas. Rooms, gardens, and courtyard are
examples of areas.

3.2.AR.1 Attributes of Areas


Since we ane classifying the detailed require-
ments by class, we first list the classes that we
have (very carefullyl ) chosen . These are not all Here we tell what properties each object
of the classes that will be used by the applica- (specific entity) of the class must possess.
tion merely the core classes pertainmg to the
domain of the application , which arc adequate
3.2.AR.1.1 Area Name (essential; not yet
for organizing all of the requirements. In this
case, for example, all of them are aspects of the
implemented)
Encounter video game.
The statement above in parentheses indicatcs
the priority and the sta tus of the requirement.
Categories for the Encounter video game suffi -
Once the requirement is coded and tested, the
cient for expres.ing the requirements arc Area,
statement "not yet implemented" is either de-
EncounterCharactcr, EncounterCame , Engagement,
leted or changed to "implemented." "Essential"
EngagementDisplay, ForeignCharactcr, PlayerChar.
requ;rements are implemented first. Once a
acter, and PlayerQualityWindo,,, .
requirement has been designed for and Imple-
mented, "essential" can be removed. This is
The nunlbering "3.2.Area.N .N ... :' etc. u ed one technique for tracking the state of the
in Section 3.2 makes it easier for us to insert, application and its relationship WIth this SRS.
remoye, and locate nequirements by organiz- Another technique is to specify the iteration to
ing alphabetically the classes that contaIn whIch the requirement applies.
them. ThInk in terms of hundreds of require ·
menls. If we were 10 number the classes usong Every n ounter area \yill have a lIfl1quc nJme
-'3.2, 1 .. ""'3.2.2 . . ,If elc. , then in crting
,o j
con"sting of I to 15 chara tcrs . Acceptable hara -
nh' classes would have to be done at the end te" ,hall onSl<t of blank<, 0 thro ugh 9. a thro ugh z ,
of the I'$!, sincc exlslln8 numbenng, already and A through Z on ly.
318 CHAPTER 12 ANALYZING DETAILED REQUIREM ENTS

TC~l plan < Idcrcn C 1'0 t(' ..,1 goe, he re >


alternative would have becn to express these
requirement a, (un lio ns: for example,
E. l13ttnbute.type requirement map5 to a pairof "Encounter <hall be c.apable of displaYIIlg
get· and set· fun lions. TI,i. document suggests XYZ area With the (allOWing charaCterIStiCS'
how ea h requirement can be hyperlinked to a
lIllIt test in the Software Test Documentallon.
3.2.AR .2.1 Courtyard Area (essential; not yet
3.2.AR.1 .2 Area Image (essentia l; not yet implemented) There sha ll be an Area object
implemented) There ,h.1I be an image to display with the name "courtya rd" requiring the quailtlcs
eac h Area object on th e enllre momtor. The image stamina and strmgth . The preilmlna ry courtyard
,hall fill the enllre mo nitor Image hown III Figure 12.39 IOcludt·s a map of
nearby arca5 .
3.2.AR.1.3 Area·Specific Qual ities (essential;
not yet implemented) O nly some game character 3.2.AR .2 .2 Dressing Room Area (essentia l; not
quali"e shall be applicable in each area. The spec i~c yet implemented) There hall be an area With
qualities required for cach area are spcci~ed in Section nam<.' "dressing room" requirin g no qualities. Its
3.2.AR.2 . preliminary image, shown in Figure 12 .40, include
a map of ncarby areas.
3.2.AR .2 Area Entities
3 .2.AR .2.3 Dungeon Area (essential; not yet
We designate specific area objects that muSI implemented) Th ere shall be an area with name
exist wi th in the appl ication. This section has "dungeon" reqllirin g the qualities stam ina and pa -
been added to the IEEE standard. The tience. Its preliminary image shown in Figure 1241
includes a map of nearby areas.

kitchen

COURTYARD

dressing living
room room

--I
IGot "*"11 ,

I".-1 0" 'lQ


"",""""
""'"
fOOOItO

lEnd ....1
fOOo"
Doj~ I i)I'I .....
Figure 12.39 Encounter courtyard Image
CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUi'lTERVIDEO GAME 319

DRESSING ROOM I<Ql!marn

ID1ngflQn

... IOktoIrt

eo..,...
....,
10'0Wl1

'" 1'1\)
IOJIIi
CUIoI:lfl
....,
Figure 12.40 Encounter dressing room image
E. J. Staude• ..IOhn \\Iiley & Sons. 2001

3.2.AR.2.4 Kitchen Area (essentia l; not yet 3 .2.AR.2.S Living Room Area (essential; not yet
implemented) There shall be an arca with name implemented) There shall be an area Wllh name
"kitchen" requi ring the quality concenrrati on. The "hv i ng room" rcquiri ng the quali ti es co ncen tra ti o n and
preliminary kitchen image shown in Figure 12.42 stam ina Its prelim inary image show n In Figure 1243
Includes a map of nearby areas. includes a map of nea rby area

DUNGEON

dressing
stl!d v
room

'00'''
IClUih

Figure 12.41 Encounter dungeon Image


320 CHAPreR 12 ANALYZ1NG OETA1LEO REQUIREMENTS

KITCHEN

...
I GoUla... I Courtyard
I'C«IWI

ISelqt"~ I """"'~. ""'"


.oom

lEnd gem. I
,-
Drou '''IQ

01.1 'IQ' t;II ,


""""
Figure 12.42 Encounter kitchen image
Source COpyright, E. J Braude, John WHey & Sons, 200 1

3.2.AR.2.6 Study Area (essential; not yet imple- 3.2.AR.3 Area Functionality
mented) There shall be an area with the nam e
"study" requinng (he quality concentrati on. Its pre -
This is the required functionaliry that pertains
liminary image shown in Figure 12.44 includes a map
specifically to areas. Every functional
of nearby areas.

LIVING ROOM

courtyard

study
00 , ' ... .
('o ' .... 7~ u PI
..
-
'-.

00. 0 M - , 'I)

Figure 12.43 Encounter Illiing room Image


CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME 321

Living
room

STUDY

DUDgfOD

-
00
eo..n,..!
'0 1-- -
.....

Figure 12.44 Encounter study Image

3.2.AR.4.3 Interrupting Engagements (op-


capability of the application should belong to
tional; not yet implemented) Players are able
one of these sections. to interrup t e ngagements on a rando m basis. On
ave ra ge, the playe r ca n stop o ne of every te n e ngage·
No ne nlents by executing the proced ure to set qualities.
The u er tries to inte rrupt an e ngageme nt by at ·
3.2.AR.4 Events Pertaining to Areas te mpting to set the pl ayer's qualities. If the ga me doe
no t all o w th iS, no indi catio n is give n; th e ga me
proceeds as if the attc mpt had not been made.
We separate the events that pertain to are as
from the attributes, objects, and metho ds. An 3.2 .AR.4.4 Pressing the Set qualities Button
event is an action that occurs to the applica-
(essential; not yet implemented) W he n the
user presses the S{I q,wlilirs bUllo n, a w,"dow for selling
tion and is instigated from outside of the
the va lues of qualities a ppears superimposed o n the
application.
area, provi ded th at the re is no fo reign c harac te r in th e
arca. Sec 3.2.PQ fo r the speciHcat ion of th is wondow.
3.2.AR.4.1 Display on Entry of Player Character
(essential; not yet implemented) Whe nevcr the 3.2.AR.4.S Pressing the End game Button (op-
player's main c hara te r e nte rs a n arca , that a rea and
tional; not yet implemented) W hen the user
presses the £ull g(Jmt butto n, the gil mc [c ml inalCS.
the characters in ,t ha ll be displayed on the mo nitor.
No add itio nal scree ns a ppear.
fIlli ng the mo nito r.

3.2.AR.4.2 Handling Engagements (essential; The previous sentenct, an inverse require·


not yet implemented) W he n a fore ,g n ga me me nt, was fe lt to be necessary because games
character e nters an a rea conta ,n, ng the p layer', o ftc n do display a summary o f • se slon.
maon ch.aracter, or Vice versa, th ey engage co h o ther.
322 CHAPTER 12 ANALYZING DETAILED REQUIREMENTS

3 .2.AR .4 .6 Pressing the Get status Button (op- Kitchen


t ion al; not yet implemented) When the user
prc" cs the Gti sla/us bUllo n, In engagement display living
courtyard room
willdow appears shoWIIl8 thc Statu< of thE player'>
haracter before and aftcr the last cnllage menl. 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 Key I . """"""'"
I S connected
Figure 12.45 Encounter area configuration reqUirement

3.2.CH .1 Attributes of Connections Hyperlinks


3.2.CO .2 Connec tion s Entities
3.2.CH .1.1 Connection (essential; not yet
implemented) Each connection hype rl ink corrc-
3.2 .CO .2. 1 Dressing Room-<:ourtyard (essen-
sponds to an area connect ion
tial; not yet implemented) The,. shall be a con -
necrion between the dreSSi ng room and the courtyard
3 .2.CH.2 Connection Hyperlink Entities (essen-
tial; not yet implemented) Thc re are two co n- 3.2.CO.2.2 Dungeon-Study (essential ; not yet
nectio n hyperl inks corresponding to each are. implemented) There shall be a connection be-
connection, one in each area of the co nnec ti o n. twee n the dungeon and the srudy.

3.2 .CH .3 Functionality of Connection 3.2.CO .2 .3 Study-Living Room (essential; not


Hyperlinks None yet implemented) T here shall be a connection
between the study and the living room .
3.2.CH.4 Events pertaining to Connection
Hyperlinks 3.2.CO.2.4 Courtyard-Living Room (essential;
not yet implemented) There sha ll be a connec-
3.2 .CH.4.1 User Clicks on a Connection Hyper- tion between the courtyard and the living room.
link The effect of clicki ng a connection hyperli nk
3.2 .CO .2.S Dressing Room-Dungeon (essen-
is th.t th e player's character is displayed i n the area
tial ; not yet implemented) There shall be a con-
on the other si de of- the area connectio n.
nection between the dreSSing room and the dungeon

3.2.CO Connections between Areas 3.2.CO.2.6 Courtyard- Kitchen (essential; not


Characters travel from area to adjacent area by means of yet implemented) There shall be a connection
connections. Each of these connects two areas. Fig- between the courtyard and the kitchen
ure 12.45 shows the required connections among the
areas. 3.2.CO .3 Functionality of Area
Connections None
3.2.CO.1 Attributes of connections between
Areas 3.2.CO.4 Events pertaining to Area
Connections
3 .2.CO.1.1 First and Second Areas (essential;
not yet implemented) Each connection shall 3.2.CO .4.1 Moving a Character throug h a Con-
connect a pai r of areas, which we Will ca ll the "first" nection (essential; not ye t implemented) on-
and "second" areas. neetlons are disp layed J< h perlink, .t the borders 01
CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME 323

areas whenever the player's charactcr i in thc area . Elena Cunenllile


When the user cI.ck such a hypcrlink, the linked points: 56.68
.re. is displayed with thc character in this area.

3.2.EC Encounter Characters


Value
16.18
3.2.EC.1 Attributes of Encounter Characters
Palience
3.2.EC.1.1 Names of Encounter Characters
(essential; not yet implemented) Every game Figure 12.46 Required user Interface for status
character in the Encounter video game shall have a SOU/ceoCraphlcs reproduced with permiSSJon from COre(
unique name . The speciRca ti o~s for names shall be
the same as those for Area names, speCified in 3.2. equal to the sum of the quality values. The values of
AR.I. the remainin g qualities are automatica lly adjusted 0
as to maintain their mutual proportions, except (or
3.2.EC.1 .2 Qualities of Encounter Characters resultin g quant ities less than one, wh.ch are replaced
(essential; not yet implemented) Every gome by quality values of zero
character has the same set of qualities. Each quality
sha ll be a nonnegative floating po.nt number wit h at 3.2.ED Engagement Displays (essential; not
least one decimal of precision. These arc all init.al · yet implemented)
ized equally so that the sum of their values is 100. There shall be a window displaying the re ult of
The value of a quaiory ca nnot be both greater than 0 engage ments. The format IS shown .n Fib",re 12.46 .
and less than 0.5.
For the first release the qualities shall be concen· 3.2.ED.4 Engagement Display Events
tration, intelligence, patience, stamina, and strength.
3.2.ED.4.1 Dismissing the Display (essentia l;
3.2.EC.1 .2 Image of Encounter Characters not yet implemented) When the user hits OK,
(essential; not yet implemented) Every game the display disappears.
character shaH have an image.
3.2.EG The Encounter Game
3.2.EC.2 Encounter Character Entities The The requirements in thi s secti o n penaln to the ga me
characters of the game arc described among the as a whol e.
types of Encounter characters.
3.2.EG .1 Attributes of the Encounter Game
3.2.EC.3 Functionality of Encounter
Characters 3.2.EG .1.1 Duration (optional; not yet imple-
mented) A record shall be kept of the durat.on of
3.2.EC.3.1 Living points (essential; not yet tach game, timed from when the playcrbegi ns the game.
implemented) The Encounter game shall be 3.2.EG.2 Entities of the Encounter Game
able to produce the sum of the va lues of any charac·
tds qualities, ca lled its livinS pointS. 3.2.EG.2.1 Single Game (essential; not yet
implemented) There shall be a .ngle s,me
3.2.EC.3.2 Configurability of Encounter Char-
acter Quality Values (essential; not yet imple-
mented) Whenever an Encou nter character .s Future rdea es will allow several ver<.ons of
alone in an area, the value of any of .t qu.iotlCs the game to run at the same t.me
m.ay be set The va lue chosen mu' t he le<> than or
324 CHAPTER 12 ANALYZING DETAILED REQUIREM NTS

3.2.EN Engagements To take .. nU111e n al exam pl of a n cngllg ment


All c nfotJ ~(" m 'nlh Ih(' II1l cra<.tion between J p:a nlC in tim area If the pl. ye r\ ,tam.na w.lue " 7 and
h3"Ct r o ntrollcd by the rla yer and , fo rc.w. ConCe f1lra110n value" 19. and Fredd . - the fnr ' I!ncr'~
hJra ter <tamll' • •s I 1 and co n~c ntra11 0 n 0 6 , then Ihe player
"<lro llgcr The re,uil of the cngage me nl would be
3 .2.EN.1 Attributes of Engagements No ne
Playe r, , tanllna 7 + I 112 = 12 .5 ; co nce ntrat.o n
3 .2 .EN .2 Engagement Entities There arc no 19 + (0.6 )/2 ~ 19 3[0 ]
pemlancnt cng"semcn l ent iti es .

3 .2 .EN .3 Functionality of Engagements 1 1/ 2 = 5.5; co ncentral10n 0 because (06)/2 .5


less Ihan 0.5
3 .2.EN .3.1 Engaging a Foreign Character
(essential; not yet implemented)
3.2.FC Foreign Characters
A fo reig n charac ter .s an Encounter characler not
This particular requireml'nt is mathematical in under the players control
nature and so Ihere is no attempt to replace the
mathematics with natural language, which 3.2.FC.1 Attributes of Foreign Characters Sec
would risk compromising it~ precision . The Encounter character requirements. These are initial ~
use of natural language to explain the mathe- ized to be equal.
matics is a good practice, however.

In future releases, foreign characters may mu -


When an engagement takes place, the "slro nger tate into new forms.
of the two c haracters is the o ne whose values of area-
_reciAc qual ities sum to the greater amount. The
system transfers half the values of each area -speCIfic 3 .2 .FC.2 Foreign Character Entities
quality of the weaker to the stronger No transfer of
points takes place if neither character is stronger.
This section tells that there is only one foreign
If ei ther c haracler has no poi nts after the value
character.
reallocations arc made, the game ends. If the game
docs nOI e nd, Ihe player's c haracler is moved to a
rando m area and the results of the engagemenl arc 3 .2 .FC.2 .1 Freddie Foreign Character (essen-
d.splayed . tial; not yet implemented) Therc shall be a
As an example of the value reallocalions, suppose forc.gn character named "Freddie: who e image IS
that the player engages a fore ign character in an area shown in Figure 1247. Th.s character shall i01lially
preferring stamina and concentration . If p~ is the value have a total of 100 POlOts that arc d1<tribulcd equally
of the player's stamina , and assuming p, + p~ > J. + fe. among Its qualities.
we would have p: =p. + i/ 2, P: =P. + i/ 2.1: = i/ 2, andi:
= i) 2.
3 .2 .FC.3 Functionality of Foreign Characters

The reader will recognize th. delect in the last 3 .2.FC .3.1 Foreign Character Movement
equation, which should be i:
= // 2. We will (essential; not yet implemented) A long as It
is alive, a forc.g n character should move from area to
leave the defeci Inlact as an example.
adjacent Mea '" rand om interval'\ J,vt:ragins t~·o
seconds. After being present in an area for J rando m
CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME 325

called the "main" character. The nature of this con·


trol is subject to the restrictions peclned in the
/' remaining requirements. ThIS character shal l initially
,. ,I have a lotal of 100 POints that are dislnbuted equa lly
,!
among its quailtie

3.2.PC .2.2 Additional Characters under the


Control of the Player (optional; not yet imple-
mented) The player shall be able to introduce
characters other than the main cha racter that the
player con trols. Detads are to be decided

3.2.PC .3 Player Character Functionality

3.2.PC.3 .1 Configurability of the Player Char-


acter Quality Values (essential; not yet imple-
mented) Whenever all fortlgn players are absent
from the a·rea containIng th e player'" main character,
the player may set the value of any quality of the
main character uSing the Player Quality Window
shown In Figure 12.49 The value chosen must be
less than or equal to the sum of the qua lity va lue
Th e values of th e remaining qualities are automat i-
ca lly adjusted 0 as to maintain their mutual propor·
tions , except for resulting quantities It:ss than 05 ,
wh ich arc replaced by quailty value of zero
Figure 12.47 Foreign character Freddie image
requirement
3.2.PC.3.2 ConfigurabiJity of the Player Char·
SOUrce Grapnlcs reproduceo with peofmlSSlQn from corel.
acter Images (desirable; not yet imple·
mented) The 1>layer shall have the option to
amount of time averaging o ne seco nd , all of the choose the image represenllng hiS or her maio
character's life pOint are divided among the quail ties charac ter fro m at least two Images These o ptions
relevant to the area , such Ihat the va lues of each are shown III Figure 11 48 .
quality arc as close to equa l as po Sib le
3.2.PC.3.3 Aging of the Player Character 1m·
3.2.PC Player Characters ages (optional; not yet implemented) The main
These are Encounter characters under Ihe conrrol of player character hall automatica lly IIlcrcase each
the play("!" quality b), a percentage for the Irst half of hi or her
hfe, then decrease each qua llt)' by the same percent ·
3.2.PC.1 Attributes of Player Characters ee age for the second half Delails arc to be deCided
EncOUnter characLCr aunbutts Player character Im age
Un be sdected from one of the Images in Figure 1248 3.2.PQ The Player Quality Window
Thl ... I a Window from ,,,h leh the pl ay er Ill') JlloCJtt"
3.2.PC .2 Player Character Entities the va lue< of hI> or her h,racte"

3.2.PC.2. 1 Player' s Main Character The playt'r 3.2.PQ.1 Attributes of the Player Quality
shall have (.ontr,,1 over a parll lIlar U3me (. haracttr window The wlndnw for ,ett"'~ the qllahtlC> 01
326 CHAPTER 12 ANALYZING 0[1 AILED REQUIREMENTS

Elena Sean Boris

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 displayi ng four of the qualities at a time . Cltck.,ng on
• typical example in Figure 12.49. The g.me charac· one of these qualities allows the player to sdect a
ler icon appears In the center, and Its name appears at va lue for It in the text box o n the right. An explan ·
the left top of the screen. The character's life poi nts ation of how the arlthmelic IS performed IS shown 10

.ppt.r in the center. On the left center is a li st box a pale yellow box in the lower part of the screen

Shawn Currenllile points; 100.0

Choose the quality _ _ Image Choose Ihe value 01 _-,


you wish 10 set 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 :r 26.66

Figure 12,49 User Interface required GUI for setting quality values
sour" GraphlCl reprOduCed wllJ'I pe.,nlssb'l Irom Corel
CASE STUDY: DETAILED REQUIREMENTS FOR THE ENCOUNTER VIDEO GAME 327

Color backgrounds for the name, life points, and 3 .3 Performance Requirements
value boxes are to be pale turquoise.

3.2.PQ .2 Player Quality Window Entity Pcrfom,ance reqUIrements include required


speeds andlor tIme to complete. Unless docu ·
3.2.PQ.2.1 Window for Allocating Qualities mented in a different section of the SRS, they
(essential; not yet implemented) A window may also include memory usage (RAM andlor
hall be avai lable under the conditIOns de cribed disk), noted either statically or dynamically
above to all ocate the value of the player character. (i.e., memory required at runtime).
The willdow 'hall have the appea rance of the C UI
hown in SectIon 3. 1. 1 2 of this specificatIon. TI,e applicatIon shall load and di play the
Initial image In less than a minute.
3.2.PQ.3 Player Quality Functionality Engageme nts shou ld execute III less than one
second.
3.2.PQ.3.1 Initiating the Display (essential; not TI,ese requirements are te ted In STD < refe r·
yet implemented) The player quality menu shall ence to lest goes here >.
be able to display it elf.
3 .4 Design Constraints
3.2.PQ.4 Player Quality Window Events

3.2.PQ .4.1 Displaying the Value of a Quality This section speCifics restnctions on design . If
(essential; not yet implemented) When the there is no material in [his section , designers
player clicks on a quality in the li st box on the are free to create any (good) desig n that
left. the value of that quality sha ll be disp layed in satisnes the requirements. For example, we
the text box on the right. can add the design constraint "one·story" to
the fo ll owi ng: "A house with four bedrooms.
3.2.PQ.4.2 Setting the Value of a Quality all of which are less than a thirtY·second walk
(essential; not yet implemented) When the from the fami ly room ."
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 Encounter shall be desi gned using UML and
window shall appear stating "invalid value: try again ." objec t·ori ented design It shall be implemented in
Java . The software shall run a a Java application on
3.2.PQ.4 .3 Dismissing the Window (essential; tI'
Window 95. lt shall be designed a way that makes it
not yet implemented) When the user hits the relatively easy to chan ge the n.tles under whIch the
OK button , a time of four seconds elapse , after game operates so that o r-hers can customize the game.
which the window disappea r . At th e end of this time
period (i .e., if there arc nO interruptIons) the va lue 3.5 Software System Attributes
allOCations are made .
3.5. 1 Reliability
3.2.PQ.4.4 Interruption (essentia l; not yet Encounter shall fatl not more than o nce III every
implemented) Upo n Interruption of the dl play 1,000 encounter< T est documentatio n < reference
of the quality value window, the window van l hes to te t goe here >
Note that interruption s , hall be aused by a
forei~n character entering the arca . Note also in thi s 3.5.2 Availability
case that the qualtty value are not hanged and th at En ou nter hall be ava tl able for play on an I
an engagement takes place. n.tn ni nR \'(11ndows 95 onI (i.e ., no ot her appl icOl lo n
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 Characters and Areas
(a ) Sample VO formats, deSCflp110nS of
(essential) It <hall be str<lIghtforward to change
characters and areas.
COSt analysis stud ies, or results of
user surveys
(b) Supporting or background Informa-
3.5.4.2 Globally Altering Styles (desirable) It
shall be straI ghtforwa rd to globally alter the style of tion that ca n help the readers of the
the areas and connectIOns (Style changes reAect dif, SRS
ferent levels of game play in the same environment. ) (c ) A description of the problem to be
solved by the software
3.5.4.3 Altering Rules of Engagement (oP- (d ) Special packaging instructions for
tional) Rules of engagement should be relativel y the code and the media to meet
easy to c hange. security, export, initial loading, or
other requirements
State explicitly whether or not each appendix
3.6 Other Requirements
is to be an official part of the SRS .
None

12.1S SUMMARY

Detailed requirements ("developer" or "detailed" rcquirements) arc written primarily with designers and
developers in mind. They are created from hi g h · level req uirements, as well as from conti nued customer
Interac tio n . Detaded requirements must be testable, traceable , and consiste nt. Since they become numerous
they must be classified systematically. There are severa l ways to orga nize de tailed requirements including b
featu re , use case , CUI , state , and domain class.
Agile projects tend not to create documents separate from the code and tests with detailed requirements
Detailed req uirements must be traceable to the desi g n and implementation that realize them and to the
tests that vahdate them. Without a clean trace from each reqUIrement through the design of the appli atlon to
the actual code that Implements it, it is very difficult to en ure that such an app(,catlon remains in compliance
with the requirements When the requirements change, which i safe to a sume, this become< even more
difficult. Detailed requirements must also be traceable in the o ther direction , to the 11Igh-level reqUIrements
they arc derived from , fa ensure that all arc fully specified.
Since it is difficult to Implement all desi red functi o nality, requ irement are often prionllzed . Jtegones
such as ",roliol, d"irablt . and opilo""1 are used to deSl gn.:e pnOrities. OrganizatI o n, ommit to dd,vc ring
essential functionality, and if there is time they Implement desirable and then o ptional feJtu,,:
EXERCISES 329

Once detailed "'qulrements have been collec ted, the project documents are updated to reAect the
improved project knowledge . For example, schedules are updated with more accurate dates and risks arc
,..,tired and more info rmation is learned.

12.16 EXERCISES

I. To what audience arc detailed requirements primaril y targeted,


2. Name five wa ys of o rganizing derailed requirements.

3. What is wro ng wirh rhe fo llo wing Derail ed requirement , Ex pl aIn how you wo uld fi x them.
a. HomtBudgtf shall di splay a co nve nient interface fo r entering personal data.
b. SalCoHlro' shall compute the predicted tim e it takes to c ircl e the Earth o n the current orbit,
and the actual time taken to circle the Earth o n the previous orbit.
c. /II v<sIKin9 shall determine the best investment stra tegy .

4. What are three advantages and three disadva ntages of o rgani zing delailed req uirements by class
rather than by feature,

5. Suppose that you are definin g the requirem ents fo r an applicatio n that simulates the movement of
customers in a bank. list fi ve classe, that can be used to o rganize the req uire ments.
6. Provide detailed requirements fo r each class identi fie d in Exe rcise 3 by describong o ne attribu te and
one function corresponding to each class.
7. When identifyin g do main classes (as in Fi gure i 2.8), wh y is it usefu l to denote the rel atI o nship
between them (i.e., inheritance, aggregatio n),
8. Applying the principle of goo d screen desig n outl ined in Step 3 of Section 12.3 sketch good C UI
screens fo r a ho me finan ce applicatio n that ,
a. displays a summary of a user's fi nanc ial ho ldings, o rganized by ty pe of ho ld,ng, and
b. allows a user to input rhe details fo r a new ho ldi ng

9. For cac h d etal'1e d requorcmen


. r I'sted
I 'In Exerc ise 6 , assign a priority (e .g., essential , desi rable,
o ptional ) and explain wh y you chose th em.
· '1ar t 0 F'19u re 12.27 Ihat spccines test input and output fo r o ne o f the attribute
10. C reate a c h art SImI
identified in Exercise 6.

IEAM EXERCISE

SRS
, t h e SRS fo r your a p pl 'lca rio n · Use o r mod ify the IEEE
W rotc .standard
" . If YOll are u In s an iterative
apprQac h , try to .In d 'Ica te what requirement< arc to be Impl emented In each itera tIo n.
330 CHAPTER 12 ANALYZING DETAILED REQUIR EMENTS

Tra k the t me SpCIlI o n thi' by individuals a nd by the "roup Hrcak thl ~ tIme Into appro prtate
o tl vi ties Measu re the effec tivene, o f you r effort. (Feci free to develop yo ur o wn mctrics, sec also
tea m exercises III previou< c hapters ,) Indi ate ho w the pro CS5 yo u u<cd to de ve lop the RS c;ould
have been lin proved.
Evaluation cri teria:

( I ) Degree of clarity
(2) Exte nt to which the plan includes all relevant del'ai ls and excl ude, irrelevan t materia l
(3) EffectIveness o f your <elf· measurement and process imp roveme nt descrtption

BIBLIOGRAPHY

I Booch. C r.:ady . "Ob} ,-Qnt'll lcd APlIII)'lls (mJ Dwgtl Ull ih ApplicaIlOrtJ,"Add lso n. Wc",lcy , 1994
1 Jordan, R. hard, Ruth Smllan, .lnd Alex Wilkinso n, -Sut'am IIll1n8 the: Project Cycle with O bJect-Onc nted ReqUIrements,· OOPSLA
Co"JruPlcr PfOCttil'"9s ( 1994), pp. 287-300.
3 Cahtz, W , "The ES).t'rl hul Glmle 10 Uw Irt,nfaa Df1j9" At! '"'rOdUf flon 10 CLiI PnrtnplN arlll Tcconufuf1," John Wiley Sons, 1996
<t . lUnd, Paul , "A D~.g""'s ArC YJlc Uni'Vcr'SIlY Press, 1985
S M YCN, C le nfo rd. J., 'Th An oj SoJtwart Tnli"g." John Wiley & Son~ . 1979
6. Jav.,™ SE 6 PI3tfonn Documentatio n, 2006.
7 , Faulk , Slua rt ,"Soft ..... are Requ i reme nlS ; A T ulOria I." 1997, hit p:llww ..... .c ~ . umd , (' d ulcl3 o;: o;:/s pri ng2004/c msc8 38plRC'Qu l rC!mC!n lsl
F3ul~ReQ _Tul , pdf [accessed Novcrnbc:r 29, 2009 ].
8. ,,tars Clim3tc! O rbiter M'shap Investigation B03rd Phase I Repo rt , N ovembc:r 1999 , hpJlltp hq nit..Q .gov/puhlpaolreponsll9991
MCO_ rc:port pdf [accessed Novc:mbC'r 29, 2009] ,
uality and Metrics

Planning • What is meant by the accessibility


01 requirements?

• Comprehensiveness?
• Understandability?

The Software • How do you assess the degree of


Development ambiguity of requirements?
Lile Cycle Requlr.II,ents • Consistency?
.RIIIy'"
• Prioritization?
• What is meant by the degree of security
in requirements?

• In what sense can requ irements be complete?

• Teslable?

• Traceable?

• What melrics are suitable for these qualities?

Figure 13.1 The context and learning goals for this chapter

This chapter deSCribes measures of q uality In requirements The mo re a requireme nts docume nt
expresses what the customer wantS and needs, the h ighe r Its quality \Vle u uall y think of de tails as being far
less Important than the "bl!! pic ture ," but a misSing requirements de tail ca n se n ously affect projects , a
numerous case studlcs show Recall , fo r example, th ove rlooked de ta il o f metnc-to- no nme tnc dl>tance
COnversion that dispatched a $ 125 million spa ecraft to obli Vio n
332 f tAPTER 13 QUALITY AND M ETRICS IN REQUIREM ENTS ANAL VSIS

Hm a ccssible I ~ ca h rcqum.~ rn c nl '


o mprc he nslve I, the SR )
unders tandable I> caLh req Ui rement )
• unambiguous IS each reqUIrem en t?
onsistent "the R )
• · effec ti vely prioritized arc the reqUirem e nl<)
· .. secure IS the requirement'
· self·co mplete IS the SR )
· testable is each req uirement (
• traceable I S ell h requirement ]

Figure 13.2 Attributes of requirements analysis that promote Quality

To he lp e nsure that the requ irem e nts are indeed covered, we foclls on qual ll Ie, that requirem ent< should
po oss They sho uld be complete and consiste nt; eac h one should be capab le of being traced through to the
design and impl eme ntatio n , tested for valid,ty, and implemented accord,ng to a rational pri omy, Figure 132
Iosts these attribu tes and tells what we sho uld look for in good requireme nts. We can systematically revIew
and inspect req uire ments based o n thi s li st . For example , a set of co nsistent requi rements is fa r more Iokel y to
express wha t stakeho lders want and need than a se t with contradic tions.
Th is c hapter disc usses ho w each of these qualities ca n be mea.sllred . "Targe t va lues" refers to the numerical
goa ls set in the project relative to various metrics. Metrics are most useful when their target values arc pecihed i.
advancr. For exampl e , we could state in advance that , based o n experie nce o n past projects, requirement will be
considered ' complete" whco the rate of modinca tio n and addition is less than t percent per week.
Projects are greatl y improved when the QA organization is Involved in rhe requirements a nalySIS stage.
In particular, QA ve rifies that the intended development process is being execu ted in accordance with plans
QA sho uld participate in inspec ti o ns o f requirements docume nts. They tend to have a healthy perspective
bec ause they lInderstand rhat they will ha ve (0 validare the product based on the requirements. In poorly
o rganized projects, QA may be handed an appl ication with little or no req uire ment documentation and
asked to test it Th is begs the question , "what is the application supposed to do)"

13.1 QUALITY OF REQUIREMENTS FOR AGILE PROJECTS

Before d,scussi ng the attributes of req uireme nts analysis qualoty lIS ted above, let us discuss the quality of
reqUirements for agile processes. Th e primary process for requirements here consists of el iciting user stories
from th e customer, along with acceptance te ts, and then subjecti ng the imp le mentatIon to th ose te t upon
completion. In addition , the custo m.er must feel satisRed with the result. Thi s mayo r may no t be supported b
significant documentatI o n. Quality has to be assessed , if not measured acco rdon g to th is sta ndard. Th,s entaIl
computing the fraction of acceptance te sts passed and making an assessme nt of th e custo mer' rcaclIon.
possible via a que stionnaire . Si nce the customer-usually in the foml of a team member rcpre entatlVC' ISo
part of the developme nt effort, requirements assessment include the performance of the customer Given the
nature of req uireme nts analysis, this is all to the good .

13,2 ACCESSIBILITY OF REQUIREMENTS

To deal with a set of req ui rements, we should be ab le to access the o nes we want, when we want them ThIS IS til.<-
quality ofaCCtssibility. The first property we need in this respect is a means of identifyinj,1 the detaIled reqllircm('nt<
COMPREHENSIVENESS OF REQUIREME~S 333

• Ea" of getting to statement of detailcd requirements .

• Metric:

0, tX'III.tly /o,,!/ aotrag, access Ii",' (compand ",ilb Ih, orga Hizalion, Horm)
to: aOtfagc acctss rime as fasf as Ca H be rxptC'tJ

flCUre 13.3 The accessibility of requirements

We do this by num bering them in same way . A good numbering system allows uS to kn ow whe the r the
requireme nt has bee n imp le mented , for example, and to trace it to the code that actually carries it out.
A projcct's requirements change continually throughout itS life cycle. For example, when a programmer tries
without success to implement a requirement and explains this to the customer, the latter freq ue ntl y Rnds mi sing
pam in the requirement . The SRS must then be accessed to ascertain whether these mi sing requirements were
present, and included if they were not. Taking an example from the video store case study, the CUSfOmer (i n this
case, the video store) may question why a DVD's play time does not appear o n the mo nitor. The developers and
the customer will want to know whet her this wasspecified in the SRS. Where in that docume nt should they look to
determinc this7 Rummaging through poorly organized documents is time ·co nsuming and therefore expensive .
H cre is a c hecklist for improving the accessibility of requirements:

• Do you know where the h igh -level requirements arc stated7

• Do you know w here t he detailed requirements are lis ted?

• Arc the detailed requirements o rganized in groups, preferably with each gTOUp correspondin g [0 a hi gh -
level requirement7
• Are all of the detailed require ments orga nized infO a list, o r a clearly understood Ii t of list 7

• Can you look up requirements by keyword7 By subject matteO By use case7 By G UI ? By uscr type7

• Can you look up requirements by other cri teria relevant to the particular app licatio n o r pfOJec t7

One accessibility metric is the avtragt time ,aken '0 access (J dtta il('d mtuim11M1t. To measure {hi . a sampJt:
would be taken of exi ting and missi ng requirem e nts, and severa l people would be timed fi nding these or
ascertaining that they are absent. Statistica ll y speaking , 150 is a good sa mple size . Smaller sample sizes are
unreliable but are probably better than nothi ng . In selecting a sample , one uses a process that is as rand o m as
time allows. For example, o ne could ask eac h of a group of people fa miliar with the pro posed appli catio n to
contribute ten potential detai led requ ireme nts, then pick at random fro m the combined hst to obtain samples
to seek. AcceSSibili ty IS summarized in Figure 13.3.

13.3 COMPREHENSIVENESS OF REQUIREMENTS


A quality SRS e xpresses all of the require ments fo r a produc t. By co",p"hrns,.""",, we mean the exte nt to ",h i h
the customer's wants and needs arc included. An appropriate metric would thus be pcrccIJI"9c oj Ihc cli slomc,S
rcq.irrmtllis aPPtJlriHg iHIb, SRS. An o bvio us way to e nsure thi S i to have the ustOl1lcrvalidate it , but th i i not a
simple matte r, as the poi nt in Figure 13.4 sugges t.
The comprehe nsiveness of requi rements fo rms an elusive and vague goal , and ye t the co",pl e~enc<~ of
requirements is key to the successful o mplc tion of a pro lcct and the Ira king of progrc ' Each Itcra tlo n
334 CHAPTER 13 QUALITY AND METRICS IN REQUIREMeNTS ANALYSIS

• Not cnotl ~ h resources LO ~a t isf cvC".'ry c.. u\lumer wl.; h


• Prlonll zc '0 Ihal cOl11prehenslve within each bat h of reqUirement,
• ustolllcr can ttlwon't read en tire RS
• I\bkc R J< to lollow
• U sc a ,tandard
• "Read" SR to custo mer
• limitations of self.inspectlons
• lIbject to peer Inspe ti o n
• Con tradictory s takeholder requirements need to be s. ,isfted
• Apply diplomatic kills and expec t compronll<e

Figure 13.4 Issues in attaining comprehensive requirements

make the requirement mo re comprehensive. One way to deal with the evolVing set of require ments is to
Include requirements of h,turc iterations and of all priorities In measuring comp leteness. An example IS s hown
In Table 13. 1. Thi s perspective helps us to assess how close our plans arc to sa tisfyi ng the customer's wants

and needs.
A mo re tractable measure is stij.compl","tSS, in which the requ irements contain all materials th at its partS
reference. However, this is somewhat different , and is discussed bel ow.
Here is a checkltst for improving the comp rehensive ness of requirements:

• Summarize, or give a very short preliminary description of needed requirements that have not been
included yet.

• Is the customer satisfied that the requirement' reAect all of his or her needs and wishes

• What fraction of the listed requirements are slated for implementation in the current release Future
releases )

Figure 13.5 shows two useh, I comprehensiveness metrics .


The IEEE define a rather complex measure of completeness in 982 2· 1988 A3S. 1. This is a fonnul.
involving 18 observed quantities (e.g ., "number of condition optio~s without processing") and 10 weights
(e .g., the relat ive importance of "defined functions used") . It measures the degree to which there are loose
ends within a set of detailed requirements.

Table 13.1 Including future requirements


Requirement

NO. Description Priortty ~


1780 Every DVD record shall contain the title. up to 60 alphanumeric characters 2 3

781 Every customer record shall include the customer's credit card number, consisting of 1 2
16 digits.

782 , ..
UNAMBIGUITY OF REQUIREMENTS 335

Lrt T = total numb~r of documented derailed r~quir~ments


(all priorities, all iteration )

ME [RIC: % Requir~ments ;mpl em~nted =


100 .. [no. of requirements Implemented]
T
METRIC: % R~quirements Curr<ntly Targeted =
*
100 [( no. of requirements implemented)+
(no. of top priority reqUIrements in current iteration )]
T
Ftgure 13.5 lWo useful comprehensiveness metrics

13.4 UNDERSTANDABILITY OF REQUIREMENTS

Understandabi lity appears to be a hi g hl y subjective qua lity because it depends o n peoples' o pIni o n.
However, it can be measured . For example, a random set of people from an appropriate population can be
asked to express on a form their opinio n 01 a requirements docum ent Table 13.2 is an example of an
opinion form-in this case applied to a u or interface . Here is a c hecklist fo r imp roving the compreh en ·
siveness of requirement s.

• Are the requirements written in language that its ty pical reader would understand7

• Do they use the vocabulary of the cl ient problem domain 7

• Do the requirements describe only external behavi o r-that is, as seen from the user's POlOt of view l ("U ser"
can include external sys tems rather than just people .)

• Do the requirements avoid stating ',010 the problem is to be solved, what tec hniques are to be used, o r ho'" the
application is to be designed7 (The except io ns to this are when such peCl fica tio n are indeed req uited up front .)

13.5 UNAMBIGUITY OF REQUIREMENTS


Unless a derailed require m e nt is written cl earl y and unambig uo usl y , we wo,,'t be able to detcmllnc whether It
has been properly implemented . Figure 13.6 illustrate an e xa mple of an ambiguous requ lte ment , fo llowed by
an Improved version . The o ri ginal requirement seems to allow the player to c hange the qualitIes 01 a ga me
character at any time durin g the game This would take the hlO o ut of the ga me , because the player would
simply set quality va lues to their larges t possi ble re levant values and there wo uld 1><: little room for tryIng

various strategics_
Here is a ch eckl iSt fo r improving the no nambi guity of rcqL1lremcntS

• For each reqUIreme nt, IS there o nl y o ne way that 0 ty pica l reader would IOterpre t "

• Fo r each requ irem e nt , arc terms aVOIded that could be underswod 10 mo re than o ne way7

F,gure 13.7 shows a me tric for ambi g uity that de pe nds o n a trioge meas ureme nt deCIde whether the
d.:talled reqUIrement ha e xac tl y o ne clear meo ning (score of 2 ), o r mony mca n1l1gs ( corc 0 ), o the " vl<c g,ve"
• 'COre of I .
336 CHAPTtR 13 QUAUTY AND METRICS IN REQUIREMENTS ANALYSIS

TIlt ~lu rr ",m "(lilt lilt. qurr/lll N of Ell OUl.ltr d)arntl(~

X At all tim e) Prol>,bl


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

Better vers ion .

Wb",w" all /orei911 playm are ab,,"1 fro", II" arM


Olll(1j'II"19 rh( play,,) ItWit I Iwrt, lu, flu pfaYfr may
cballg, Ib, q"al,ly "til,,,, 0/ 'h" 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 337

Means: No contradiction , in whole or in part

Example: ..... The DVD


~ classificatlon order
., ... shall be the order of
OVOS shall be classified preference of the
alphabetically as drama. customer. ...
comedy, ho"or .....

Metric: Percentage of contradicted requirements

Figure 13.9 Consistency in requirements

The object·oriented style of organization of requirements helps to avoid inconsislenCle by classifying


detailed requirements by class and by decomposing the m in,o a si mpl e form This IS not a guarantee of
consistency, however, and so requirement inspections include a c heck for consi ,ency. H ere I a checkli , for
improving the consistency of requirements,

• For each requ iremen" are there olher requirements that could lea d '0 co ntradicting or annulhng i,)
• For each requirement , are there other requ irements that arc very similar and so can reate Inconsislencles?

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

A consistency metric is Ih, prrc,"lag, oj d,lail,d rrq llir",,,,lIs partly or wholly cOlllmd,clcd r/5<whrrr. T o ob,ai n such
a metric, one would consider a sample of de ,ailed requirements - I 50 would be appropria,e-and investiga,e
each one in tum '0
determine whether i, is co ntradicted elsewhere in ,he document.lllis en,ad, comparing"
to all of the remaining detailed requirements . Figure 13.9 prOVides ano,her example.
This measure is imperfect because it accounts on ly for pairs of Inco nSIS tent reqUIrements A Figure I 8
illustrates, inconsistency can fesult (-rom a se t of requirements

13.7 PRIORITIZATION OF REQUIREMENTS

Since qua lily is ultim ate ly de Aned by customer sa lisfacllon, the re qUirements ana lysIS proce, "con tinuall y
directed toward the customer's conce pl of sa ti sfacll o n . T eams 'YP lca ll y show stake holders Interim a com·
plishments, and stakeho lders then IIlnutnce lhe course of the work accord ing ly . Be ausc of thIS. ,h,' priority
of requ ireme nlS and thus the order In which requirements arc Im plemented , as de cnbed III hapter 12-
makes a SlgniAcant d iffere nce in the custo mer's sa ll sfa tion In math ematical lan guage, ,hi IS a non ·
commutat ive operation si nce the SRS seque nce

impttP1m1f rcquirrmrll l A (hen pllHf fa Implnllcnl frqUlrCII1(Ht B

may well produce a dilferent produc t from


irnplrmOl I rrquJrcmtnf H then pi,," 10 ,,"plnnrll' rC'qulf('moll A
338 CHAPTER 13 QUALITY AND METRICS IN REQUIREMENTS ANALYSIS

-''>lIme three prioml zatl o n . IJlgIJ, In,Jium , and low

Me tn Vanatl o n fro m . IJi!lb = • ,"til""" = • IOlv


Let T = to tal number of de tail ed requl ,cmems

100. [T -IT / 3 - l1I gh l - IT / 3 - nledium l-IT /3 - lowl]


T
o= worst; 100 = best

Figure 13.10 A metric for measuring the quality of prioritization

There are effective and ineffective prio riti za tio ns. Fo r example, g iVing most req uirements the hIghest
pn o rity Indicates poor planning. Ranking low . prio rity requiremenlS IS usuall y a waste of time because they are
unl ikely to be all im plemented. As me ntio ned , when stake ho lde rs see the Impl eme ntatio n of reqUIrements, they
tend to change subsequent requirements. An effective priori tizat ion tries to account fo r these faccars
H ere is a c hecklist fo r improvi ng the prioritization of re q uirements.

• Is it clear what requirement sho uld be worked o n (irst] Seco nd )

• Arc the prio rit ies at a hi gh level consistent with th ose at the detai led leve l)

• Is there a pnoritlzation process in place such that it will remain clear what is the ne xt importan t requ irement
that sho uld be wo rked o n)

• Is the prioritization appropriately matched with customer expectations?

• Is the prioritization appropriately matc hed with project risks?

As ume that each req uirement is in o ne of three priorities. H ow would we measure the quality of the
prioritizationr A good quality prioritization categorizes requirements into equal parts, indicating that no
category has been neglected. Figure 13. 10 sho ws a metric fo r this.
For example, if 900 requirements arc very well prio riti zed, each category would contain 300 requirements
and the fo rmula would g ive 100 . [900 - 0 - 0 - 0 V900 = 100%. O n the o ther hand, if 700 were classified as
h igh priority, 100 as medium and 100 as low, the me tric would yield

100. [900 -1300 - 7001-1 300 - 1001-1300 - 100111900 = 100' 100/900 = 11.1 %

Th e low percentage indicates poor prioritization.

13.8 SECURITY AND HIGH-LEVEL REQUIREMENTS

Security ca n be dea lt with a an actual (explicit ) requirement or as on at~ributo of require ments. For example.
"All passwords shall be unavailable except to the system administrato." I on explicit requirement of an
application. On the other hand . 'The requirements in our SRS will cause (ewer than 10 security brea hos of
level I or greater (defined elsewhere) in a century of COntinuous operation under the threat e nvII'Onmcnt of
2009" is not a requirement in the ordinary sense. It is an attribute of the requirements.
Security In requirements is a special case in that It deal s with deliberate explOIts o n the p.ln of o the l'S to
misuse It. Traditional requirements, after aH, are intended to specify what an application sbowlJ do, and have not
SEl.F·COMPLEI ENESS OF REQUIREMENTS 339

.ddJtssed misuse. This i changing . To an increasing extent, requirements documeOls are addressing the security
~ by including such content as misus< casts. These arc similar to the idea , me ntioned earlier, of inverse
requirements. The following are examples of misuse cases use cases that the system is required to disallow.
An automated user of the application eMters a known user ID and more than 10 password per second.
A user accesses more than 30 customer records in a si ngle si tting and transmits these to another
address within 10 seconds of accessi ng the m.

Here is a checklist for improving the security aspects of req uirements,

• Consider the places in the pro posed application where intrusion appears to be possib le. Are concrete
security requ irements stated fo r those places]

• Has the conRdentiali ty of data, where applicable, been specificall y required]


• Has the security of user identiry been speCified]

• Has the security of passwords been ex plicitly call ed for]

• Has the ownership of Rles or access been speciRed ]

• Has encryption been called for when appropriate l

• Have speCific, known security exploits ("hac ks") been speCified aga insO An example is "SQL Injection shall
be prevented." (SQL injection is a mea ns of unautho ri zed database access.)

Ha ve speCific and po tential exploits been speciRed against vi a misuse cases]

13.9 SELF-COMPLETENESS OF REQUIREMENTS

TypiCally, a requirement depends o n o ther requirem e nts. A set o f requirements is " If·com plttt If it contai ns
every part whose inclusion is necessi tated by parts already present. Figure 13 II illustrates an incomplete et
of «quirements. Without the speci Rcatio n of how a video is to be "displ ayed," thi s se t of requi rements is
incomplete as a unit.
As anothe r example, suppose that the SRS for a ca le ndar application contai ns the fo llowi ng requi rement.

Th, applicalioll ,hall rttain all ",jormatioll t>ltrrrd by tht "'" jor tach appoilltmtllt.

REQUIREMENTS
I. Tht applicalion lhall di,play a DVD ill slock Ivbtll a
lilk i, mtrrrd at Iht prompt, ot""wi" il ,IJall di,play
"OUT OF STOCK. "
2. Tht applica llon shall display all oj Iht ,10"" DVD,
by any dirtclor whost las t namt i, ", Iurd at Iht promp t
Thts< ,hall bt di,playtd Ollt by 001t Advall ill9 tlJrollgh Iht
DVDs ,hall bt con lrolltd by Iht lorward artOI/1 kry

I'..:o",pktt: Lacks s pcc ,f, atl on o n how to display a videol


Fi&ure13.11 An example of self·lncompleteness In requirements
340 CHAPTER 13 QUALITY AND METRICS IN REQUIREMENTS ANALYSIS

'\ h~n J rc"QlIIrCI1lCnt I~ pre se nt, ,n mu~l tJlI tho~c


nc e'SllJled h y II, pre'en e

A mcln (0 = best, I poor, no theoretical upper li mi t)

[number of mi ssing necessa ry associated requirement s]


Inumber 01 detailed requirements present]

Figure 13.12 A metric for self·completeness

The prese n e of th is requirement ncce sita tcs a requirement describing means forentcnng apPointment
information It also necessitates a reqUirement explaining means (or displaying this Information . TI,is IS the
meaning 01 "sell-completion ." Here is a c hecklist lor improVing the sell-completeness 01 requ iremcnts

• For eac h requirement stated, are all th e requirements prese nt that it rclers to]

• For each requirement stated , arc all the requirem e nts present that It depends on ]

To measure sell·completen ess, we look a t each detailed requirement and note any necessary associated
reqUirement that is missing . An appropriate metric is shown in Figure 13. 12 .
The number 01 miSSing requirements is determined by sampling.

13,10 TESTABILITY OF REQUIREMENTS

Each detailed requirement must be leslablt; that is, it must be possible 10 definitely validate that the
requirement is operative in the finished app lication by testing lor it. Figure 13. 13 provides an example
01 a non testable requirement, and sh ows what it would take to make the requirement testable.

TI" sysl,", shall display Ibt differolCt ill salary


b,lw,," Ib, clioll mid 1/" worldwidt aocra9' for Ih,
snmt Jradt.

X ca n't be tested because the average mentioned


cannot be determi ned (even th oug h it exist ).

Better;

Th, syslt'" sl,a/J display 1/" d,f}","" ill salary


b,lwtrll Ih, eli",1 alld II" "Iimaltd loorldwid, .",ragt
for Ih, ,am, Irad, as ~"blishtd by Iht Ulliltd Nalloll'
Oil {IS Web ,ilt www.tbd al th, limt of Ih, display . •

Figure 13,13 An example of testability


TESTABIUTY OF REQUIREMENTS 341

Table 13.2 Example of a user satisfaction questionnaire


User satisfaction
o = of no value; 5 = average satisfaction; 10 = a pleasure to use
Quality Score
1. OVerall appearance

2. Layout of text areas

3. Layout of buttons

4. Readability

5. Ease of entering data

6. Degree to which erroneous data entry is prevented

• • • • • •

Requirements that are no t testable arc of negligi ble va lue. It would be impossible to assess whether such a
requirement has been attained. This is an all·or.no th ing property. The re is lit tle value in the "degree of
testability" of a requirement.
Testability can sometimes be used to specify a detailed C UI requirement. Fo r example , instead of
specifying a CUI in complete detail we may prefer to provide a test suc h a the following ,

The CUI for entering DVDs shall ha ve the Rclds and butto ns listed in figu re xx, and its deSign
shall score an average of at least 8.5 out of l Oon the user satisfactio n questionnaire In Table 13.1 .

An effective way to ensure testability and to ensure the clari ry of a requ irement at the sa me time is to
include tests with the requirement. Figures 13 . 14 and 13 . 15 illustrate an example.
Agile programming applies this test orientation but sho rt ·ci rc llit's the prose by e ncodin g the test up
front , usi ng it as a requirement, in effec t . A reasonable testabil ity me tric IS the fo ll owi ng,

The percentage oj dr,ailed requi"",en" ,ha' are accompanied by a '" ,

Even when a requirement is tes table , executing a test may be d ifficult o r time-co nsum ing. T o be
complete, we sometimes need to consider the cos, oj ',,'i"9
as part of the considerati o n. A very h igh cost

The video store app lication s hall impl eme nt a discount program as follows,

• One DVD , no di scount


• Two DVDs, 20% d isco unt fo r the second DVD
• Three DVDs: 40% di scount for the second and th ird DVD
• All videos beyond the th ird are dl counted at 40% .

13.14 Including tests witlh requirements, 1 of 2- the requirement


342 CHAPTER 13 QUAUTY AND METRICS IN REQUIREMENTS ANALYSIS

I U\lo me r we" Jo nes re nt, o n ' OVO He b c hJrl(ed the rq!ul. r rc nt31 o( $ 5 00
2 ustomer T r re," Edward, re nts two OVO, he i, c h3rgcd th e rc~ul ar rel1t31 o( $5 .00 fo r the f,m and
$4 00 (20% d" ounl ) (o r the e o nd .
usto me r ll,eodo re L, sl renlS Ihree OVOs He, c harged the regul ar re ntal of $500 for the nrst, $4 00
(20% d,s ounl ) (o r the second , and $3.00 (40% d i ount ) (o r the thIrd .

4. usto me r Fred Harari rent < !lve OVOs. He IS c ha rged Ihe re~ul a r re ntal o ( $5.00 (o r the first, $4 00
(20% di s ount) for th ~ seco nd , and $3.00 (40% d, s o unt) (o r Ihe third. The fo urth and nfth OVOs are
harged at $3.00 (40% dlScot'"t ).

Figure 13.1 S Including tests with requirements 2 of 2- Ule tests

inAuences our c ho ,ce and pnoriry of requirements. For example, suppose that we cons,de r adding to our
online video service the follOWing requirement:

Fo r each movie entered by the customer, the appltcation shall di splay a number from 0 to 5 that
provides the ystem's estimate o( how much he will like the movie . This e t,mate 's based on the
, .. .
customers past viewing ratings .

ThIS can be tested, but the expense of doing so properly ma y d,ssuade us from making it a hi gh prio ri ry
Reco mmendation algorithms have become a competitive activity amo ng providers, with large rewards
provided fo r the creators o f the most (measurably) effective ones. like this one, many requirements are
strongly associated with business decisions.
Here i a c hecklist for improving the testability of requirements,

• Is Ihe requirement clear enough to devise inpu t/output data samples lhat exercise it) Specify the tests.
• Is there a set o f tests that, if passed. provides significant confidence that the requirement will have bee n
satisfied?
• If one reasonable person in the cuSlomer community proposed a set of tests for the reqUIrement, would
another probably agree that it tests the requirement?

13.11 TRACEABILITY OF REQUIREMENTS

T raceabiliry was defined in Chapter 10. Our concern here is how to measure a .et of requirements in th,
respect. A requirement is traceable if it maps in a completely clear manner to the design clement that
accommodate it. the code that implements it, and the tests that test ,t . \'(Ihen the 0 0 or "class"
organizat ion o( requirement writing is used, the mapping to the class within the des'gn and to the code
can be comple tely clear. It requires work and clear th"'king to mainta", such clariry, however. For e ample , a
Cuslolll" paragraph that speCifies the rentals that each customer can have could compromise traceabili ry The
design would probably have the clas«, C""O'"" , DVD, DVDRrtJlnl , and DVDRrnlnls. The requirementS
orgal1lzallon should reAect this.
Organizing cla.scs by funclIona lt ty, CU ls, use cases, and so on has vanous advantages, as dis u sed "'
Chapter 12 , but traceabiliry is 110t a strength for most o( them . One would have to pen,« cach deta,led
requirement and ask whe ther a will clearly map to a class.
METRICS FOR REQUIREMENTS ANAlYSIS 343

(Range: 0 to 100)

tOO' L: [traceability of each detailed requirement (0 - 2)J


2 . [number of detaIled reqUlrementsJ

0= untraceable, 2 = clearly traceable to a specific class

F1gUre 13.16 A traceability metric

Here is a checklist for improving the traceability of requirements:

• For each detailed requirement . is it clearly conceIvable that an ide ntifiabl e part of the code base will
Implement it? (It's ideal when a single method implements a SIngle deta ded requirement. )
• Is it clearly conceivable that a ing le, identifiable pan of a software design ..nd implementatio n could contain
itl (A detailed requirement that must be spread over several probable main modules is not easily traceable.

Traceability can be measured as in Figure 13. 16. Usi ng 2 as a measure allows the appl,catio n of triage for
a give requirement , where 0 = u,,'raccablt, 2 = Jldly 'ra ctablt , J othtnVlst .

13.12 ME I RjCS FOR REQUIREMENTS ANALYSIS

The previous sections of thi s chapter described metri cs for a number of requirements qualities , acceSSIbility,
comprehensiveness, understandability, unambiguousness, consistency, deg ree of pri omizatio n, secu rity, se lf-
completeness, testability , and traceabi lity_ Additio nal metrics ca n be considered .
The fo llowing li st of quality assurance metrics includes requirements analysis metrics in IEEE Standard
982.2-1988 ("IEEE Cuide for the Use of IEEE Standard Dictionary of Measure to Produce Reliable
Software"). Some measure the qualities we have already discussed in a different manner.

• Percentage of unambiguous speCIfic requirements (IEEE metric 6)

• Degree of completeness (IEEE metrics 23 and 35 )


• Percentage of misdassined detailed requirements (in the object. oriented sty le, thIS measures the percent·
age allocated to the wrong dass )

• Traceabil ity (IEEE me tric 7)


• Degree of atomIcity (indIvisible 1010 smaller parts)
• ConSistent with the re mai ning reqUIrem ents (IEEE metries 12 and 23 )

• Measures of the effectiveness of reqUIrements inspectIon


• Percentage of missIOI! or defec tI ve requirements found per hour of in spection

• Musures of the effectIveness of the requirements analy is proces

• Uxt per det-a ded reqUIre ment


• On a gross baSIS (!'Ota l lim e spen t/number o f dctoded ,.eq ulfe mcnt ~ )
344 CHAPTER 13 QUALITY AND METRICS IN REQUIREMENTS ANAL VSIS

• 0 " a In a"~ ,,,al b"" ( oq 10 He t one more)

reqlllrcrncnb arc

- rnodifled

- elimlnaled

- added
• 1easure of the degree of o mpl e tcncss of the requIrement, . ThIs can be e't lmated from the rate, after the
official "nd of dctarled requirements collectio n, a t whic h specIfic requrrem e nts are . ..

- mod ified

- added

13.13 INSPECTING DETAILED REQUIREMENTS

The reader is referred to C hapter 5 for a descriptio n o f the inspection process In general.
Detailed requirements are the Arst software process documents that ca n be inspected agarnst pnor
docum e ntatio n (the h igh.level requirements). Inspectors prepare For the inspection by reading over the hIgh .
level requirements and companng the detailed requirements with them. It ca n be very productive to Inspeci
requ ireme nts against each of the qua lities and metrics listed above .
The rest of thi s section proVides an example of a detailed requirements inspection. H e re is an un inspected
versio n of detailed require ments For the Encounter video game case study o n which we will perfo rm an example
inspec tion, entering the results in a table (see Tabl e 13.3 ). We empl oy the technique of auto mati cally adding the
"no t inspected yet" comment to each . It is removed when the inspectio n takes place. The Anal versio n of these
requirements, re sulting from the inspecti on, is shown in the accompanyi ng Encounter case study.

Arm R'4u ir"''''11 I ("Art. name"). (Not inspected ye t) Every area shall ha ve a name of up to t 5 characters.
Art. R'4uir"""11 2 ("Art. image") . (Not inspected ye t) There shall be an Image in gif fo rm to display each
Art. object.
Art. Rr4ui"'''''11 3 ("Display area method") . (Not inspected yet ) Whenevcr a player character enters an
arca, that area and the c harac te rs in it shall be displayed.

Art. Rr4uir"""11 , ("Courtyard object"). (Not inspected ye t) There shall be an Art. o bject with name
"courtyard: Its image shall be that shown in Figurc xx o n pagc xx.

Art. Rr4uirrmrnl 5 ("Dressing room object"). (Not inspected ye t) Therc shall be an Area object with name
"dr<ssing room" and blank background image. The dreSSing room shall be adjacent to the courtyard area.
Encou,,'er Rr4uirrmrr,' f ("Engaging a foreign character"). (No t inspected yet) When an engagement takes
place, the Following computation IS performed, The sum of the values of qualities of a game char.Jcter
relevant to the area in question shall be refcrred to as the characters area value. (In this release, all qualities
will cou nt as equal.) In an cngagement, the system compares the area values of the characters and ITan fer<
to the stronger, hal fofthe points of the weaker. For example, suppose the pl.yer cn!!ages a foreign character
In an area requiring stamina and attention span, and ps is the value of the player's stamrna, et . A Imlog p.,
+ p. > f, + f" wewould have p,' = P. + f/ 2, Po' = p. + f/2 , F,' = (,12 , fo' = f/2 where xl is the vallie 0 x.fter
the transaction.
Table 13.3 Example of a foml used for the Inspection of detailed requirements

Traceable
Requirement Traceable forward
NO. Description backward Comprehensive Consistent Feasible unambiguous Clear precise Modifiable Testable Note 14

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 NOle2 Yes Yes Yes Yes Yes Yes Nole 3 Yes Yes
Re.9ulrement ,
1007 Encountercharacter Yes NOle 1 Yes Yes No 1 Yes NO 1 N0 2 No 1, 2 Yes
Requirement 1
1008 EncounterCharacter Yes No 11 Yes Yes Yes NOl e Yes N06 Yes Note 9
Requirement 2 8
1009 Encountercharacter Yes Yes Yes Yes Yes Yes Yes Note 3 Yes Yes
R~ulrement 3

1010 EncounterCharacter NOle " Yes Yes Yes Yes NOle NOle 12 No 7 Yes Yes
R~ulrement 4 12
1011 EncounterGame Yes Yes Yes Yes Yes Yes Yes NOle 13 Yes Yes
Requirement 1
Yes Yes Yes Yes Yes NO8,9 Yes Yes Yes -z
1012 foreign Character Note 11 VI
."
Requirement 1 m
n
1013 Pla~er Character Yes Yes Yes Yes Yes NO Yes Note 15 Yes Yes :::t
10 z
Requirement, C>
NO 12 Yes 0
1014 Plaler Character Yes Yes Yes Yes No 12 NO NO 12 Nole 3
~
Requirement 2
Yes Yes Yes Yes NOle 10
12
Nole Yes Yes Yes Yes
...
~
m
1015 Pla~er Character 0
10
Requirement 3 '"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 ,",' I" Rrq,,;rrmn" ("Qua lities of !;,me charac lers''). (NOI Inspec led yel l Every game
1
c har. ler has lhe same scI of qual ,.lies, each having. floating pOlin value These arc In'tialized 10
1001n, where n is lhe Ilum ber of quali lies. The qua l'lie, are allentiOn 'pan , endurance , intelligence,
pa lie n C, and strenglh .
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 I ("Encounter game objec!"). (NOI In pecle d ye t) There shall be a Si ngle
Encou nterGa me objecl.
FOrtl911Charaeltr R,q"",m,"1 ("Freddie foreign characte r object") . (NOI inspecled yet ) There shall be a
I
foreig n c haracte r named "Freddie," all of whose qualities have equal values and whose Image is shown in
Figure 4.57.
PlaytrCh.,.eltr R,qlllrnllcIII
("Conngurability"). (NOI inspected ye ll Whenever all foreign players are
I

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
2
complele control over a part icu lar game character called the main c haracter.
PI.yrrCharaelrr R'4"irCltl"" ("liVing points") (Not inspected yet). Encounter shall produce lhe sum of the
J
values of lh e charac ler's qualities, ca lled its livi ng points.

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 347

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
348 CHAPTER 13 QUAUTY AND METRICS IN REQUIREMENTS ANALY IS

• L1nJ",bl ~u 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

• What are the goals of software


Planning design?
/: Maintenance • How do you use various design
models for a single application?
Testing
The Software • What are use case model ,
Development class models, data flow models,
Life Cycle RequIrements and state models?
IIfI8IWsIs • How are frameworks used in design?
Implemelltation
-.;::: • What are the IEEE standards for
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 351

only Ih~ code The beneAts of a fully detaIled desIg n arc balanced agai nst the time: required to document and
maintain detail~d designs. For large elfo"s, level s in between high level and detailed desIgn may be identified
This chapter introduce the concepts, needs, and terminology of software design. It sets the stage for
the ~m.jning chapters in thIS pa" of the book, whic h include various co nc rete examples.

15,1 THE GOALS OF SOFTWARE DESIGN

The first goal of a software design IS to be sufjimtll for atlsfying the requirements. U ually, software designs muSt
also anticipate changes in the requ irements, and so a se ond goal is jlrxibi/ily. Ano ther goal of software design IS
rohosllKSS: the ability of the pro duct to anticipate a broad variety of input. These and other goals are summarized in
Rgu~ 15.2.
These goals sometimes oppose o ne anot her. Fo r example , to make a de ign effiCIe nt il ma y be necessary
to combine modules in ways that limit Aexib di ty. In fac t, we trade off goals agai nst each other in ways that
depend on the project's priorities
A software design is sujlie;," 1 if it provi d es the compo ne nts for an Imple me nta tio n that satIsfies the
rcquirements . To assess such suffiCie ncy , o ne needs to be able to understand it. This fact is obvious, but it has
profound consequences. It can be d ifficult to create an understandable deSIg n for applications due to the large
number of optIons that are typically available . Open Office, for exa mple, is a ve ry comple x applicatio n when
viewed in complete detail. Yet Ope nOffke is simple when viewed a t a hI gh level, as consisting of a few
subapplications: word processing, spreadsheet, presentations, and database.
Modulnr;1y is thus a key to understandability . So ftware is modular when it is di VIded into separalely named
and addressable components. Modular software is muc h easier to understand than mo no lithic software, and
parts can be replaced without affecting othe r parts. It is easier to plan , develop, mod ify, document, and «-st .
\\:'hen software is modular you can more easily assign different people to work on differe nt part .
A design is a form of communication. In its most elementary form , it documents the res ult of a des igner's
thought process, and is used to communicate back to h imself thereafter when he needs to know wha t he
designed. Thi s IS fine if the designer is to be the o nl y person who has this need , but a projec t usuall y Involves
several people throughout its lifetime . If a design is not ulldm lolldnb/, fo r them, it IS of lim ited val ue, and the
project's health is at risk. Design implification , in particular, frequentl>' results in a better de ign .
Understandability is usuall y achieved by o rga nizing the design as a progression fro m a high level w ith a
manageable number of parts, then increasing the detail o n the parts.
A good software archItect and designer forms a clear mental mo de l o f h ow the appl icati on WIll work al
an ov"allievel , then develops a decomposi tion to match thI S mental mod e l. She firs t asks the key modularity

• Sufficiency: handles the requ irements


• UndersliJndability: can be understood by intended audience
• Modularity: divided into well -de n ned parts
• Cohesion: organized so like- minded clem e nts are grouped together
• Coupling: organized to minimize de pende nce between elements
• Robustness: can deal WIth WIde va ri ety of input
• Flexibility: can be r<:adiiy mo difie d to handle c ha nge in reqUIrements .
• Reusability: can u e parts of the desig n a nd implementation 111 o the r app ll ca ll o ns
• Information hiding: module interna ls are hIdde n from ~tl:ers
• EffiCiency: executes wi thin acceptable lime a nd <pace IlInlts
• Reliability; execute< WIth acceptable fa dure rate

15.2 Principal goals of software design


352 CHAPTER 15 PRINCIPLES OF SOFTWARE OE51GN

= Component

High cohesion Low coupling


(parts belong together) (mInimal contact)

Figure 15.3 High cohesion and low coupling-bridge example

question such as: What Rve or six modules shou ld we usc to decompose a personal nnance applicatIon) What
four or five modul e neat ly encompass a word processi ng application ? After decIding this, she turn ' 0
decomposing the components , and so on. This process is sometimes ca ll ed "recursive design " because i,
repeats the design process o n design compone nts at successively fine scales. Software decomposition itsel f
involves consideration of cohrsioll and couplillg.
Cohesion within a module is the degree 10 which the module's elements belong toge,her. In other
words, " is a measure of how focused a module is . The idea is no' just 10 diVide softwa re into arbitrary partS
(i.e., modularity ), but 10 keep related issues in the same pa rt. Coupling descnbes ,he degree to which modules
communicate with ot her mo dules. The higher the degree of coupling, the h arder it i 10 understand and
change the system . To modularize effectively, we maximiz, cobtsion and 111illimizr coupling . Th is principle helps to
decompose complex tasks inlO simpler o nes.
Software engineering uses Unified Modeling u.nguage (UML) as a principal means of explaining
desi gn. Understanding softwa re design concepts by means of analogous physical artifacts is helpful to orne,
and we will employ this mean on occasion . Figure 15.3, for example , suggests coupling/coheSIon goals by
showing an architecture for a bridge, in w hich each of the six components has a great deal of coheSion and
where the coupling betwee n them is low. The parts of each bridge component belong together (e.g., the
co ncrete and the embedded metal reinforcing it )-this is high cohesion . On the oth er hand, each component
depends on just. few o,her components two or ,hree , in fact. This is low coupling .
The "Steel truss" III F,gure 15.4, on 'he o,her hand , shows many component dependIng on each other at
o ne place. We would question this high degree of coupling.

Component

High coupling X

Figure 15.4 A Questionable architecture high coupling In a truss


lliE GOAl S OF SOFlWARE DESIGN 353

• Oblilinin.9 ,"Ort or ',,5 oJ wi,.,., alrtady prm,,'


Example: handle more kinds of accounts without nceding to change the existi ng design or code
• Adding "tw killd, oJ Jllllcliollalily
Example: add wilhdraw to existing dtposil function
• Cha"ging j""Cliollalily
Example: allow withdrawals to create an overdraft

fl&Ure 15.5 ASpects of flexibility: ways in which an application may be required to change

Low coupling and high cohesion are particularly important for software design because we rypica lly
need to modify applications on an ongoing basis. Compare the life cycle of a typical software application with
that of the bridge in Figure 15.3: the likelihood that the software will require mod ,Rcatlon is many time
greater. Low coupledlhigh cohesion architectures arc far easier to modify, since they tend to minimize the
effects of changes.
The number of top-level packages in an architecture should be small so that people can compre hend the
result. A range of "7 ± 2" is a useful gUideline , although specinc projects ca n vary greatly from tim range for
special reasons. As an example, OpenOfnce would be hard to understand if we decomposed it into 100 parts
instead of four as follows : "word processi ng, spreadsheet, presentations, and databa e." The mind has much
trouble thinking of 100 separate things at more or less the sa me time. The difference between small - and
large-scale projects (such as OpenOfnce) is the amount of nesting of modules or packages. Projects rypica ll y
decompose each top -level package into subpackages, these into subsubpackages, and so o n. The "7 ± 2"
guideline applies to each of these decompositions.
A design or implementation is robll" if it is able to handle miscellaneous and unusual conditions. These
include bad data , user error, programmer error, and e nviro nmental conditions. A design for the video sto re
application is robust if it deals with attempts to enter DVDs with wrong or inconsi tent information, or
customers who don't ex.ist or who have unusuall y long names, o r if it handles late rental situations of all kinds .
Robustness is an important consideration for applications that must handle commUnication .
The requirements of an application can change in many ways, and as a resu lt a design must bejl""blt to
accommodate these changes. Fi gure 15.5 illustrates ways in which an application may change.
A set of previously used drsi9" partm" is a useful resource for flexible designs. DeSign patterns are
discussed in Chapter 17. We design so t·hat parts of our own applications can be rr"ltd by others and ourselves _
Figure 15.6 lists the rypes of artifacts that often ca n be reused .

We can reuse ....

• Object code (or equivalent)


Example: sharing dlls between word processor and spreadsheet
• aas~s in sou rce code form
Example: Customer class used by several applications
Thus, we write gene ri c code w henever possible
• As~mblies of rdated classes
Example: the java.awt package
• Patterns of class assemblies

FIlii,. 15.6 Types of reuse


35' CHAPTtR 15 PRINCIPLES OF SOFTWARE DESIGN

A an example of I." reli'>c, o n<ldcr the cI"" DVDRe" I./ that ""oclat.s the I)VD and Ih customer
ren ting it u h " cia s " rcu ~ab l e on ly in ano lhe r application d al"'/I with the renta l 01 DVD<. wl-"eh "
li mited. II. however. we deslg ll a R", III/ class dea li ng wit h the rental o f an fi rm to a (", IOmer, and If /JVDRaiID/
Inherit fro m R"' lli/. then we wou ld be abk to reuse the Rall. / portion fo r other app licat ions due to ItS
genera lity . Design patterns faci litate the reu •• of assembli es o f related classe, rather than Indi Vidua l ones
'.Jonnalio" /"di"9 IS a deSig n pri nCiple "' wh, h the interna ls of a modul e arc dcilbe ratciy nOI usable by
code that docs not need to know th e detai ls. T h iS i. suppo rted 10 o bJcc t, oflented languages by declanng a
publ ic Interface throug h which user code accesses the ob)ec" 01 a class Pnva te me thods and annbu te\ are
o nl y accessibl e to the objects of the class itse lf. Informatio n hidin g all ows the Internal s of a module to be
modl Rcd without the use rs of the modul e haV ing to change . It also reduces compleXity because the module
interface is R~cd and we ll deR ned; usi ng code need not be co ncerned With Internal detai ls.
Efficinl ry refers to the use of ava il able mac hlOe cycles and memory . We create deSign s and Impleme nta .
tions that are as fas t as reqUi red . and that make use 01· no mo re tha" the reqUired amount of RAM and disk
EfRd e nt desig ns a, e o fte n ach ieved in stages as fo ll o ws. Fi rst. a dcsig n is conce ived Witho ut regard te
dRcie ncy; efRcie ncy bottle necks arc then identiRed. and ~na ll y the a ngi nal desig n IS modi fi ed As an
example , consider the usc of maps o n the W eb. When the user browses a map and wants to move to an
adjace nt area. earl y algorithms required a separate page fetc h. Algorithms were introduced . ho wever. to
automaticall y fetch appropriate adjacent maps aft er th e init ial fe tch . im provi ng efRciency and. with it, the
user's experience . It is ideal if cfRciency is considered at th e t,mc of initia l desig n. however.
It is unrealistic to expect that a real ·wo rld applicatio n be 100 perce nt defec t· r-ree. An application is
...Iiabl, if it fall s within a predetermined standard of fault occurrence. Met rics make t hi S precISe. such as the
average time between failures. Reliabili ty is related to but diffe re nt fro m ro bu t ness. Robustness is mostly a
design issue because o ne must spec i~call y accommodate erro neous data in ad vance-accommodating it does
not happen by accident or experience. O n the o th er hand . reliabili ty is mostl y a process issue. requinng
thorough inspect ion and testing of arti facts. Desig n affec ts reli abil ity in that clean deS ig ns make It easier for
developers to produce error· free applicatio ns. H owever. a wide range of o th er fac tors make for reliabi lity.
because an applicario n can fail fo r a wi de va riety of reasons.

15.2 INTEGRATING DESIGN MODELS

The architectural drawings o f an of~ce bUilding comprise th e fro nt eleva tio n, the si de elevation. the electrical
plan . the plumbing plan . and so o n. In o ther words. several diffe rent views are req uired to express a bUlldlng's
arch itecture. Similarly. several different views arc required to exp ress a software desig n. They are ca lled modds
Four important models are shown in Fi gure 15.7, and they are expl ai ned next. Several ideas here are
taken from the Un iRed Software Develo pment me thod o f Booch. Jacobson. and Rumbaugh. Figure 1-
includes an example fro m the Encounter video gam e case study to illustrate the four models and how the fi t
together.
The subseque nt sectio ns o f th is chapter elabo rate o n these mode ls so that they ca n be contra ted and
combined with each o ther. Subsequent chapters in th is parr of the book prOVide detailed examples of each

15.2.1 Use Case Model

This section describes several levels o f use cases and related concepts. The " , ClISt ",odd conSIStS of the
follOWing four parts:

I. The ,,", i"61 " SC CQStS : a narrati ve fon11 . suitable fo r devcl opcr. to ·cu to mer commun i ation, descnblng the
required basic sequences of ac tio ns
INTEGRATING DESIGN MODELS 355

To express requirements, architecture, and detailed design

Use case model Glass model


"00 this ... • "wffh objects of these classes .. .'
e.g.". engage foreign character e.g .. with Engagement .. . classes

Target
Application

Data flow model State model


"'in this way ... .. ~reac t;ng to these events ,.,.
e .g .. character scores flow e.g .. when foreign character enters
from .. . to ...
• Video game example

Figure 15.7 Models to express deSigns (and parts of requirements)

2. Their re fi nement into regu lar u" cam. descnbed in Chapter I I

3. Their transfo rma tio n into "qu"'ctdiagrallls (covered in Chapter 16). which in rurn ca n be in twO successive
stages of re fi ne me nt:

(a) With informal functionality desc riptio ns, at first lacking all details

(b) With specific functio n names and howing all details

4. SCOtarios: instances of use cases th at contain specifics. and that can be used for testing. For example . a
scenario of the use case step

( uslomtr cboosts accounl

would be something like

John Q Smilh choosts ch,eking acco",,' 1234 5 .

The usc case model e xpresses wha t the applicatio n is supposed to do. as suggested In FIgure 15.8.

15.2.2 Class Models

Classes are the building blocks -mo re preCisely, the ty pes of budding blocks of deSIgns Cia . mo dels
consist of paekagts (a groupi ng of clas es ) that decompose Into smaller packages. and 0 on. whIch dccompo c
Into classes. and these, in turn . decompose primarily into met hods. Thl IS shown in Figure 15 .9. We cover
doso;cs in more detail in Chapter 16

15.2.3 Data Flow Models


The class modd descnbes the kind, of objects Involved; It does not show a tual objects dalll jlo.' ,"oJd, o n n,C
the olher hand , shows specdi o bJcc t< and the type of data fl oWIn!! between them It IS related to the cia ,
356 CHAPTER 15 PRINCIPLES OF SOFTWARE DESIGN

Uso cue modol :

BUlin•••
u•• c••• ------------ U.. ce..
~ ;
~;
~;
~
~
~
~;
~
~

~~
~
e laborated by _.
~~
~~

Sequence
dl.gram r------------1 Scenario.
I

Target
Class model
Application
..
Data flow model State model '

Figure 15.8 The role of use case models in design

model , because the objects invo lved must belong 10 the classes III the class model. We discuss data flow
d,agrams in C hapter 16. Fi gure 15 . t 0 shows the parts of a data Aow model.

15.2.4 State Models

Sta te models reflec t react ions to eve nts. Events incl ude mOllse ac tions and c hanges in variable va lues. Events
arc no t described in class mo del s or component models, but they do occur in the state model. We in troduced
sta tes in Chapter 11 as o ne way to describe the requirements of an application . The states in that conte xl
describe the external behaVIOr of the application . The states we arc referring to here reAect the state of

Use case model Class model

I Package ~" ,,
Consists
of ...

Cla.s
Terget
Application

Data flow modol State model


'--

Figure 15.9 The role of class models In design


~ JIt(;U:l5on. lVII, "Object oriented SOltwMe Englneerlna: A I.M case DI'iven Approach," Addtson·wesley. 1992
FRAMEWORKS 357

Use case model 1 Class model

Target
Appllmlon

Data flow model State model

Processing eta"le"t ~----1


, Data type
I
,, ,,
organized ,, "
by ... , Data store
I
Subprocesslng eleonant

Figure 15.10 The role of component mOdels in design


$OUt't'e.: 1aCObson, IVar, " Object Oriented Software Engineering: A use case Driven Approach:' Ad<3!son·WesIcy, 1992.

Use case model Class model

Target
Application

Component model State model : "reacting to these events "

I States ~n------1
decompose
Substates
I
Into ...

I Transitions
I
Figure 15.11 The role of state mode ls in design
Sourt:e: Jacobson, rwr. "ObJect Or~nted SOftware Englneenng: A use case Driven Approach, " AOdrSOfl·Wesley, 1992.

elements in a software design . The role of stare mo del s is shown in F.gu re 15 . 11 . n,ey are described in more
detail in Chapter 16 .

15,3 FRAMEWORKS

As we have secn, the rruSt of compo ne nts is a major goa l in so ftware development . If an o rga nization ca n't
leverage its investments in the ski ll of it designers a nd programmers by usi ng their work severa l times over,
competitors who do so will be faster to market with superior produc ts. Th e parts of an application that are
particu lar to it and arc not reused arc often ca lled Its bus11ltsS log'c. Bus iness classes arc es ent.ally the doma.n
classes d.scussed In Chapter 12.
Where do we keep the lasses slated for reuse] H ow do we orgaOlze the m] Shou ld we build.n rela tlonsh.ps
among thesc classcs] Do they control the application or does the app ilca no n co ntro l lhem ] n , e computlOg
358 CHAPTER 15 PRINCIPLES OF SOFTWARE DE IGN

--;::"=.-::...=-:..-.., - . -., ,.-. - ~u._._

Aenloilioms Rontals
- -,

RenialCuslomer$

'-_. ..
- --.~-.- --- _...._ .. __ .R._~._

.- • '" • ---~
Figure 15.12 A framework for rental applications

community ha learned from experience that merely making a list of avadab le fun ctio nality docs nOI necessanly
result in reuse . We have learned . however, that arrangements like the Java AP I (co here nt se ts of classes) do
indeed lend themselves to highly successful reuse. The Java AP ls (3D, 20, SWing , etc.) arc Jramrworks .
A Jrm"rwork , sometimes ca lled a library, is a collection of software artifacts usable by several different
applications. These ani facts arc typically implemented as classes , together with the software reqUired to
utilize them . A framework is a kind of common denominator for a fami ly of applications. Progressive
development o rganizations designate selected classes as belonging to their framework . Typically. a
framework begins to emerge by the time a development o rganization develops its second to founh
application . As an example , consider the Renlal fra mework shown in Figure 15. 12 that our video store
application could use. This architecture divides th e clements into the items that can be rented (books, DVDs,
etc.), the people who can rent them , and the rental reco rds that associate members from the first two pans.
The individual classes in the fra mework will be suppl ied later. Frameworks like these are usually
obtained in a combin ed botto m·up and to p .down manner; boltom .up by examin ing the tructure of actual
application architectures such as the video store application, seeking more general forms; and top·down by
conceptualizing about the needs of a particular family of applications such as rentals.
Classes within a framework may be related. They may be abstract or co ncrete . Applications may use
them by means of inheritance, aggregation , o r dependency. Alternatively, as we wil l see below, a framework
may feel like a generic application that we customize by inserting our own pans.
Figure 15. 13 shows the relationship between framework classes, domain classes, and the remaining
design classes. The design for an application consists of ( I ) the domain classes (that are special to the

F•• hb.wortlcl•••••

,----------
I :
I I
I
I DMIgn cI8.... I
I
I I

1M dfJ,.,1ed "u/gn I "'1 I


I I I
I I I
I I I
/ I 1
The CI,•• Madl' .." I I
L _________ _I

Flpre 15.13 ClaSS model VI. architecture and detailed design


SUMMARY 359

1. Inb Oductlon ..' 4, Dependency description


1.1 Purpose 4.1 Intermodule dependencies
ArchltectUN
1.2 Scope ,• '" 4.2 Interprocess dependencies
1.3 Definitions, acronyms, f ' .'.
.... 4.3 Data dependencies
and abbreviations !
•• 5. Interlace description

2, ReleNnce.

3. Decomposition description

5.1 Modute Interface
5.1.1 Module 1 description
3.1 Module decomposition 5.1.2 Mod ule 2 description
3.1.1 Module 1 description 52 Process Interface
3.1.1 Module 2 description 5.2.1 Process 1 description
3.2 Concurrent process 5.2.2 Process 2 descri ption
decompoSition 6. Detailed design
3.2.1 Process 1 description 6.1 Module detailed design
3.2.2 Process 2 description 6.1.1 Module t detail
3.3 Data decomposition 6.2.2 Module 2 detail
3.3.1 Data entry 1 description 6.2 Data detailed design
3.3.2 Data entry 2 description 6.2.1 Data e ntity 1 deta il
6.2.2 Data entity 2 detail

figure 15.14 IEEE 1016·1998 SOD example table of contents

application ), (2 ) some of the fram ewo rk classes (generall y speaki ng, no t all are needed ), and ( 3) the remaini ng
classes needed to co mplete th e design , w h ic h we are call ing simpl y "desig n" classes. The design classes consist
ofthose required fo r the architecture and th ose that are not. The latte r a re effectIve ly the detai l design classes,
requ ired to comple te the d esig n. These three co nstitute th e class mo d e l fo r th e application . All of the domain
classes are in the de ta iled d esig n because th ey are very specinc. The fra mework classes used are part of the
application's architecture.
The framework classe s used in th e desig n a re part of an a ppl icati o n's arc h itecture , as show n in the figu re.
The domain classes are usuall y part of th e d e ta iled d esig n si nce they arc speCific to the ap pl ication and are not
architectural in nature .

15,4 IEEE STANDARDS FOR EXPRESSING DESIGNS

The IEEE So ftware D esig n Docum e n t (SO D ) sta ndard 10 16· 1998 provi des guid e lines for the documentation
of design. The table o f con ten ts is shown In Figu re 15. 14 . IEEE guideli ne explain how the SOD could be
organi zed fo r va n ous arc h itectural styles , most of w h ich are deSCribed above . The case study uses the IEEE
standard, WIth a few mo d ifica tio ns, to account fo r a n e mphas is o n th e o bject·on ented perspective As show n
In F'gu re 15 14, Sections I t hrough 5 ca n be co n id ered software arc h itecture , and Secllo n 6 ca n be

considered the detailed design, to be covered in th e next c hapter.

15.5 SUMMARY

Softwa re desig n 's a mo d el of the ,ntended oftware appllca " on , as spc , Aed by its req uire me nts A software
design is analogous to the b luepri nts of a house.
Good software designs should ex h,b,t the fo llowing c haracteri tI d; , u nders tandab diry, modu lar·
,ty, high cohesion , low coupl, n!!, robust ness, flcX lb d,ty, reu,abi l, ty, ",forma tio n I" di ng, err, ,en y , and re habll l!}',
Whe n expreSSI ng a software dcs l!!n, ill S he lpfu l to use evera l d iffe re nt conne ted VICW , or mo dels
use .. se model de nbes what the app hcatlon I< ,ntended to do from the po,nt of view of th ~ 11 er _ eql1en e
360 CHAPTeR 15 PRINCIPLES OF SOFTWARE DESIGN

d,agra m< arc de ri ved fro m u\e a es and de< rlbe ubJecl' and the <cq ue nce o f ",e th ud.. ca ll , between them
la,s model s arc a stati re l)rc<e ntall o n of the la,se, o f the de,,!! n and th e reia li o nslll p between them A data
tlo w model show, spcClRc o bjc t, and the types of data fl o wing be tween them A Sla tC mo del sh()w< deSIgn
cleme nts and th " " reactio n to events.
Fra mewo rk arc collec tio ns o f reusable software that Impleme nts a !!enc ral so lutio n to a uene ral
problem. For exampl e, C Ul s arc ohen des is ned via fra mewo rks .0 that new app lica ti o ns do no t have to
rewrite code to implement a C U I. T hey ca n instead leverage the eXIsting C UI code and just add the" Own
• •
<.:ustom tzal Ion.

1S.6 EXERCISES

I . Write a pa ragrap h deSCri bi ng what a "so hwa re de ig n" is, and why it IS impo rtant .

2. In YOllr o wn wo rds, defi ne th e goals of software desig n and ex plai n why each goal is important.

3. In yo ur own wo rds, de Ane the fo ll OWin g term s; nl odufnrily , coh" io" , and coupli"g. Why is each a
desirable property of software designs7

4. Ca n a design be cohesive and exhibit a high degree of coupling7 Explain your answer and provi de
an exam ple .
5. H ow might coupl ing and reusability be relatcd7 H o w might cohesion and re usabi lity be related7
Explain your answer and provide o ne example fo r each .

6. In your own wo rds, expla in what is meant by robus/II"' . Belo w is code fo r a meth od dioid,(). Make
the method mo re ro bust in at least two ways.

public double divide ( Double aNumerator, Double aDenominator )


{
return aNumerator. doubleValue ( ) / aDenominator. doubleValue () ;
}

7. U si ng the Internet, research o ne of the many Java API framewo rks (e .g., Sw ing, JMF, 20 , 3D ) In a
few paragraphs, describe the design of the framework and how it accommodates re u e.
8. Provide a modulari za tion fo r an appl icatio n that advises clients o n stock picks, and enables them to
tra nsfer funds am o ng vari ous stocks and savi ngs accounts. Expl ai n yo ur solu tio n. Hi" k One
reasonabl e solutio n employs fo ur packages.
Language

• Whal is Ihe UML notalion lor classes


Planning and packages of classes?
y - j Maintenance • How does UML represenl class
relahonships such as Int:lentance,
• aggregallon, and dependency?
The Software
Development • What IS a sequence diagram?
Life Cycle Requirements
analysis • How do UML achvily diagrams
relale 10 lIow charts?

088lgn

Figure 16.1 The context and learning goals for UliS chapter

Reca ll that a "software des,gn" I a reprc<cntat lo n. o r model , of th~ >olrw.re to be budt For many yea"
SOftware engineer rel.cd on a mi<cellany of >omewhalllnrc ialeci graphica l mca n for gc u",J.C acro" the pOint
of thcor designs Their prln Ipal mcans were data now diagrams, lIow har", and wa s to p'CILIre Ihe locallon
of phY\Jca l nics These wcr never vcry all,fac lory W,lh the adve nl and ""de accep lan c of obJect-onented
methods , leader"> 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<"" , lor exa mple , now needcd I" he rq I'l'<cnted "' de',!,!"
ftgures The Unlr,ed Modelln/! un!;lIa;:e (UM!.) " I!'" re",lt
In thl> chapter we ,"troelu e the UML, wh, h " now a Widely accepted , IM~ d y w.p h,Lal nOta lion lUI
CXpr SS ln!! "bJect.onentcd de"w" The lI t- IL standard" nu n'J.;cd by the nonproil l bleL t i\lanagcmcnt
362 CHAPTER i6 THE UNiFiED MODELING LANGUAGE

Canister ~-- Class name


st:e--rs-:7In"t- -
/ _- -..- n-u-rn""'C"'a- n-;l""'
- numWafers: int - - Anribute: type
.. :Vlsible . size: noat
Irom without .. dlsplayO
~_ _ Operations
, _ ' . getNumOpenSlotsO
.. setStatusO
ResponSibilities:
-- describes each Place for
~-- comments
canister unde rgoing
fabrication

Figure 16.2 Class details in UML

Croup consortium of compa nies (www.o mg .org ), and ta kes hundreds of pages 10 formally specify. As a result,
UML tends to be incl usive (some say too muc h so), incorporating da ta flow and , in effect , flowcharts; but It
contains much more that we do not have s pace in this book to include . The part> that we do cover, however
are adequate for m ost of o ur needs . UML is an excell ent ste p in the direction of imp roving software
engi neering, but wi ll probably be improved upo n as the d isc ipltne evolves.
The c hapter describes class relatio nships in UML, includin g inherita nce (Class Models, Section t 6.2 ) a
wa y to represent control among fu nc tio ns (Seque nce Diagrams, Sectio n 16 .5 ), diagrams of state , events, and
transitions (Section 16.6), its moderni zatio n o f fl ow c harts (Ac tiv ity Diagrams , Sec tion 16 .7 ), a nd finally data
flow diagrams (Sectio n 16 .8 ). Section 16 .9 shows an exampl e that combines these.

16.1 CLASSES IN UMl

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

16.2 CLASS RELATIONSHIPS IN UMl

This sectio n discusses the way In whIch UML collec t< cla«es and such In packages It .lso inllod" es
rel.tionships call ed associations.
CLASS RELAnONSHIPS IN UMl 363

" , and " '-

pllClulge of classes
-
myPackage -"
.. - class MyFIrstClass ( ... )

mySubPackage .
'w,, _

-• package myPackage.mySubPackage;

1
MyClass
I· .- ....,_ . . _.. class MyClass ( ... )

subpackage
/
- hidden- MyFlrslClass
-'
./
• public package
myPackage;
Bcccess/blllty of classes class MySecondClass ( .. .
from outside package )

-'--- -, ~
/
IC visible » 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 . Two-
way 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
364 CHAPTER 16 niE UNIFIED MODEUNG LANGUAGE

Employer

employs

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
Fi gure 165. The "1..3" next to
w ith 1-3 Instances of an Employ". Conversely , the " I. .• " next to E"p/oy" mean that each instance of an
I
Employer can be associated with a minimum of one Employtr (with no maximum ), In ocher words, the
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

1..3 employs ~ 1..•


Employer Employee
• is employed by

,
Personallnfo

Figure 16.5 Multiplicity of associations In UML



INHERITANCE 365

... and "'-

MyPack8ge
package MyPackage:
abstract I MyAbstractClass . . . .
MyAbslraclClass package MyPackage:
class MyDerivedClass MyAbstractClass
---I-~-
Inheritance
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 class MyClass imple,ents Mylnteriace
'------7\..------' ( ,,
-------- -----------------.-
• • • • • .
rsallzsllon )
I
I
I
MyClass
myMethod()

Fllllr. 14.7 Interfaces In UML and Java Implementation


366 CHAPTER t 6 THE UNIFIED M ODELING LANGUAGE

on<lder ag' ln Ihe app lica ti o n ,h., ass; ts Ihe user In d raw ing a simple r,gurc of a pcr<on Si nce il deals
wllh ""nou geo metric shapes. we may intro du ce a Gromr/nc5l,.pr class from wh ich Rr I(/nglr and ,uch In henl.
Th" save us fro m havi ng 10 rcpea l cod e commo n 10 Rr Ilmglc, G,elr , rna"glc, and so on , lhe reby promoti ng
modu larity , fleXi bility, and reusability in the deSig n. This exam ple i desc ribed as a w ho le in Secti o n 169.

16.4.1 Aggregation

Aggrr9alion IS a type of a soci al ion Ih al can be Iho ug hl of as a w ho le- part re lalio nshi p . It IS d e no led wi th an
ope n diam ond nexl 10 th e aggregat o r (wh o le ). Agg regalio n ind icates Ih e Slruc lU ra l Inclusio n of objects of
o ne cl ass by ano th er, and is usuall y imple me nted by mea ns of a cl ass (w ho le ) ha vi ng a n attribule whose
type is the Incilided class (part). Agg rega tio n is sho wn in Fig ure 16.8, w llh bo th Company and Employ-
"Dirrclory each co nsi der<d a "wh o le ," and eac h consisling of mull iple Employ"" th e "paris." Th e label "emp·
next 10 th e di amo nd d e no tes th e refe ren ce In Compa"y and Employ" 10 Ih e agg regate d Employ". The usc of
aggrega tion Im plies Ihal if a parli cular Em ploy" is bo th a pari of the Co mpa"y and parI o f the Employ-
"D" " ,ory, Ihen the IWO agg re ga lors "share" Ihe Empl oyee instance th aI is part of both . That is, if "Jane
Doc IS an Employ". the n o ne instance of her Employ« re cord IS c rea led . a nd bo th Compa ny and
EmployeeD " eclory refe rence that insta nce .
Rcrurn ing to th e applicat ion that assists the user in drawing a si mple figure o f a person, the associ ation
belween Fool and FoolSbapr probabl y turns OUI. mo re specificall y. 10 be an aggregatio n of FootShapt by FOOl. I
T h iS exa mple is descri bed as a who le in Sec ti o n 16.9
t
16.4.2 Composition

Compo' i/ion is a stro nge r fo rm of aggregati o n in wh ic h th e aggregated o bjecl exists o nl y duri ng the lifetim e
(and fo r the benefi t o f) th e composi ng object-n o o lher o bject may refe rence it. T he composed obJecl is I
created and destroyed whe neve r Ihe composi ng objecl is creal ed and de<tToyed. Compositi o n impl ies that I
the composed in ta nce is nOI shared. Fo r example , Figure 16.9 shows Ihat Employtt inslances are struc turall y I
pa rt of Compa"y and Em p/oyaDirtclory. Fo r any give n emp loyee suc h as "Jane D oc ," a separate instance of her
Employee o bject is crealed as pa rt of Comp""y and Emp/oyaDirtclory.

Company aggreglltlon
att: int
emp
-- -- • Employee
my Function()
----
1: ---- '\

aggreglltlon
"- --- ---
f.-.. /
~- -
dB'S
dass Company /\ amp
{ EmployeeDtr. "tory
Elhpk,yse amp; {
in! 811; Employee amp;
101 a1l; EmploveeOlrectory

,
• • • •
• • • • •
)
) att: int

/ " myFunctionO

fllu re 16.' UML representation of aggregation and Java Implementation


.

1
INHERITANCE 367

Company composition
att: int Employee
, ,,
myFunctionO , ,
, ,
, , •
, ,
, ,
composition
~

/
/ emp
/
/ "
dass Company
{ class EmployeeDirectory EmployeeDirectory
class Employee emp: { att: int
{ ...
} class Employee emp:
(. . .) myFunctionO
• • • • •
} • • • • •

}
/
/
/
/
"
Figure 16.9 UML representation of composition and Java implementation

16.4.3 Dependency

Drp",d",'Y, denoted with a d o tted line arrow, means t hat o ne class depends upon another In the sense that if
the class at arrow's end were to chan ge. then thi s would affect the dependent class Stnctly speaking,
dependency Includes association, aggregation . co mpositio n , and inheritance. However, these relati o nships
have their own notati o n , and we usuall y reserve dependen cy to indi cate that a metho d of o ne class utilizes
another class, and to relate packages. Thi s is shown in Figure 16. 10.

Dependence: UML Notation ... and ... Typical Implementation


MyDependentClass
att: int u u •• u •• _ u u u MyReferencedClass

f-------"";"
myFunctionO •
dependence
(reference to s class)
cl... MyDependentClass
(
• • • • •
void myFunctionl( MyAelerencedClass r)
( • •• ) •
I _ _ _ . _ _ __
I
paramete,

MyAel.rencedClass myFunction2( ... )


( . .. ) t. , -- - , - - -- -' or relum type
I
void myFuncUon3( ... )
I MyAeferencedClass m ...
) ·~I_______ ~~~ ~ or local variable type
)

Figure 16.10 UML reprcsentatlon and Java Implementation of dependence (excluding Inheritance and aggregation)
368 CHAPTER 16 THE UNIFIED MODEUNG lANGUAGE

CustomerMailAppllcatlon
goneraleMaliO customer 1 CuSfomor
getCuslomerTypeFromUser() eleateMallO
malnO
r ,,_
I ... - - _

I
I ',--
,
,
--- - - ---
I
I "" --- ---
I

DelinguentCustomer
""
MountalnCuslomer
--
RegularCu stomer
createMailO crealeMaliO creat.Mail()

Cus1omerMailApplication
generateMaliO customer 1 Customer
getCuslomerTypeFromUserO eleateMa/tO
malnO

Figure 16.1 1 Exa mple of a class diagram (class model) for a customer mall application

16 .4.4 Class Diagrams

Class diagrams help us to vi,ualize the des'gn of applicatio ns. They describe the ty lX"S of objects in the application,
thm amibutes and ope"'tions, and the sta tic rciatio nsh ips between them I l l. Co nSIder an applica tio n produCIng e·
mail text fo r various kinds of customers. A possi ble UML class diagram IS show n in Figure 16. 1 1. It says that the class
( uslommvlmlApp"Ca llo" has a variable named customer, which is of type Customer. Since ( £Islam" is abstract, the custom"
va nablc IS either a DclmqunltCuslomrr, MOttntainCU51omcr, or RtgularCuslom« When nUlomcr.ma frMnil() is called, o ne of
the three versions of crwfll\1ailO is called, depending o n the class that cu, 'omer belongs 10.
The stre ng th of class diagr.m s is that they help us to envisage th e buildtns blocks of an application .
Note , howeve r, that they do no t indicate the way in which the appli cari o n execu tes. In the C usto me r Mail
Appl ica tion class model , fo r exa mple, there is no way to tell w hat me th od execu tes after mai.t(). Sequence
dtagrams, d iscussed in Sectio n 16.5, prov,de this capabi lity .

16.4.5 Object Diagrams

An object diagram shows objec ts and th ei r relat ionships. A n objec t is a particular realization of a class , so
object models arc dCTlved from class model s There .re many possi ble o bject model s deriving from a class
model. Fo r example, let's retum to th e class mode l in Figure 16.4 . Figure 16 . 12 ho ws o ne objec t mo del that
derives from it . Wh c:: rc::as class models are compile -time rel atio nships, object model s are us ua ll y runtime:
relationships. Figu re 16. 12 shows that the o bject njaxCorp Co,"pa"y employ th e objects ,"c,Employ« .nd joe,
Employ« It .Iso sh ows that the o b ject ahcCorp·Compa"y employs th e objec t Joc.Em ploy«.

16.5 SEQUENCE DIAGRAMS

Use cases arc a good complement to classes because they de fi ne steps through wh,ch a use r and an ap pltcation
transi tion . To use them i n design, however. we refine them into a more:: technical fann So that class and
methods that enable them can be ident,fied. In .ddition , there arc many «que nce of 'C(,on ' th.t applications
SEQUENCE DIAGRAMS 369

Class Model

IEmployer I 1..3 t ..n


IEmployee I

One Particular Derived Object Model

sue:Employee
ajaxCorp:Employer

jjOe:Employee
abcCorp:Employer

Figure 16.12 Example of a class model and a particular object model in UML derived from it

need to be designed for but are not use cases. The number of possible sequences o( (unction ca ll s even
common ones-is very large, whereas the number of use cases is kept relativel y small (4- 20 (or small jobs and
at most hundreds for extremely large ones). Sequence diagrams are graphical represe ntati o ns o( control Aow,
and are particularly useful for describing executions that involve several object" as found tn the sce nario of a u e
case. Sequence diagrams rcquire us to think tn terms of objects and funct io ns. The lifctime of each object
involved is shown as a solid vertical line, with the name of the object and ItS class al Ihe top . Each tnl eraclio n
between objects is shown by means o( a horizontal arrow from the objecl initiatJng Ihe service to Ihe objecl
sup.plying the servicc. As an example we develop a sequence diagram (or Ihe Ch"k 0 141 use ca e for Ihe video
store appl ication. Figure 16. 13 shows a beginning sequence diagram (or Ihe usc case.

Note 2
Originates 'rom use case: NOle 1
Clerk :MainScreen :BarCodeReader 1. User swipes bar code
order
2. Applicalion prompls
doCheckoul0 for rental duration
3. User enters duration ...

:Checkoul0ptionDisplay
readO
Step 1 01 use case I
NOle 3 I
I
:Checkout I
, I
I I
Step 2 01 InltlaleO I
usecas8 ShowO I

Note 4

flcure 16.13 Beginning of a sequence diagram for Check Out use case In Video store design
I
370 CHAPTER 16 THE UNIFIED MODEUNG LANGUAGE

The (01l0w\I'8 no te explain the cOlTCspol1ding (ca tllrcs o ( the d,a grn rn '

a te I · In a <cquen c d'.8rn m, limc gocs In a downward direction. In th is cxample, doCheckou lO


a c ur< firs t, followed b ,,,,dO and thcn iHllililcO, and so o n
o tc 2 U sc cases Jrc 1Illtliltcd either by the use r, as thi S o nc IS, or by (In o bj ec t I nitiation
bcgin at the to p Icft of the dia g ram , a nd a solid verti ca l linc be neat h thIS sy mbo l IS drawn to
,nd,ca te that thc e ntit ), alread y eX ists W e ca n uppl y preconditions to specify assumpti o ns
that apply at the incep t ion of the ,equencc.

Note 3· cqllc ncc diagrams sho w the initia ti on and execution or il sequence or functions. The
obj ec t at th e be gi nning of each arrow {t1 ilra lC5 work , the objec t a l [h e en d of the arro w ca m(s Old the
wo rk 0 1 th e me th o d Ind icated . Eac h clo ogated recta ng le den o tes the execu tio n of a meth o d o (
the ccrrc~ pondlOg o bject

In o ur Ch,ek Q", seq uence diagra m, the clerk initiates the seco nd (un c tion by swipin g the bar code
reader over the VIdeo. \Vle then determ ine w ho o r what should execu te th e respo nd ing function . Since a
bar code reader recognizes a swipe, we may decide that a Bar od,Rtadcr o bject would be approp riate (or
d ealing With actions relat ing to the ph ys ical re ader, and th at th e requ ired fun ction o( Ba,Cod,R,adcr will be
nam ed "adO. There will be o nl y one BarCodcRcadcr objec t (or the entire application, so the no tat io n
",BarCodcRcadcr" to rep rese nt th is o bject is su(RcierH . There is no need to nome a BarCod,R,adcr object; we
ma y deCide la te r to make the "adO method o( 13a,Cod,R,adrr static, in whic h case no actua l BarCod,R,adrr
object would be invo lved

Note 4· We can ca pture the c h eckout process with a Grekoul class. The BarCoJ,Rcadrr o bject then
c reates a Grekoul o bject. We h ave used a fac tory meth od iHiliat' O here to create and initia lize the

User :MainScreen :BarCodeReader I :CheckoutOplionDisplay I


doCheekoutO

1.
I :Checkoul II :Account I I
2. t inlliateO

2.2 ereateO

2.3 showO

3. setDuralionO

This sequence diagram originates from Use case:


4. storeO
t. User swipes bar oode
2. AppllC8tion prompts lor rental duration
3. User enters duration
4. AppllcaUon stores record
5. Application prints C\Jstomer's account status
--
Figure 16.14 sequence diagram for Check Ouf use case In video store design
SEQUENCE DIAGRAMS 371

Player ncounter mainPlayer· Ireddie:


Game Character. ForeignCharact er
PlayerCharacter I
I I
I I
I
create and display I
I
move
I
I
create and display I
I

move
I U

figure 16.1 S A sequence diagram showing concurrence

Chtcko"t object. The method j"jtlat'() then creates a display for choosing checkout optio ns and
shows it on the co nsole . A comple le sequence diagram for the usc case is given "' Figure 16 t 4.

In the previous sequence diagrams, the solid arrow head indica te s)"I(I](ollo"s method ca ll s, meaning that
the caller receives control back when an operation is comple[c. Sequence diagra ms show aSYJlcbrollous
messages using either stick arrow heads o r half·arrows. An asynchronous message means that the caller does
not wait for an opera ti o n to complete. InSlead, control returns immediatd y back to the caller and th e result . if
any, is processed at a later time. The called method executes in a separate thread, either by spaw r.ing a new
thread or executing wi!hin an existing thread. The elongated recta ngle at the end of the arrow represents a
thread that executes in parallel. As an example , we migh t want the game characters of Encounter to move
independently from area to area during the action . This is shown in Figure 16. 15 with both a PlayrrClJaractrr
and ForrigilCharactrr runn ing in epa rate threads .
Figures 16. 16 and 16. 17 summarize the steps needed to create a sequence diagram .
When the initia to r is the user, a simple label at the to p suffkes, rather than a rectangle. Note that the
object responsi ble for executing the method named o n the arrow is at the O ld (no t the begin ning ) of the arrow.

1. Identify the use case whose sequence diagram you


will build (il applicable)
2. Identify which entity initiates the use case
- lne user, or
- an object 01 a class . ." . "... myObject
..
'
'

:M Class
• name thO ob;oct, if posSJb&e "
3. II not the user. draw a rectangle to represent
Ihls Initiating object at lelt toP .. ........ .. .. , •

- use UML ob/«l:C/sss notallon ~ ~ :


4. Draw an elongated rectangle beneath this to represent '
Ihe execullOn 01 the operation I n ~iating Ihe process •
5, Draw an arrow pointing right Irom it •


'.

Fl&ure 16.16 Steps for building a sequence Oiagram, 1 012


372 CtiAPTER 16 THE UNIFIED MODELING LANGUAGE

6. Identify which onilly handles tho myObJect myObJeC1 1


:MyClass ;MyClass l
operation initiated .
.... .. I
- an objOCI 01 a claM
I
• l'\llmo Ihe Cl.lss
ClPOra6onO I
• name tM OOIOC1

"
7. Labellhe arrow With the name of .

.•
the operation .... '" , .... ... •• .. ' • •

8. Show a process beginning. uSing


an elongated rectang le . ..... .. . .. . •

9 ...... ConUnue with each new


statement of the use case

Figure 16.17 Steps for building a seQuence diagram. 2 of 2

16.6 STATE DIAGRAMS

We intro du ced th e co ncepr of state and transi tion s In C hapte r 11 as a way lO some times express
requi reme nts A slale diagram shows the states of the objects of a class , the eve nts to which th e object arc
sensitive , and the resultin g transitio ns between rhem , State di ag ram s are also kn o wn as sfa lc-Iransihou
diagrams o r Slllftcharts .

16.6.1 States and Substates

In UML. sub>!ates of a statc arc Impl y show n as nested rounded rectangles. Figure 16. 18 sho ws the states and
su bstatcs th at ma y be present '" an O. /i",Shopprr class. It shows that while a sho ppe r is c hecking out , she can
be having her c redit valida ted .
The stall" 1l1complclt indIcates tha t the shopper has signaled a readiness to check out but has not yet subm itted
credIt card info nmation. The black dot and arrow ind icate that O"/"" S/JOpp,, objects are initiall y In the Browsi.9 statc.

16.6.2 Events

In the context of state models, an wrnl is somethin g whose occurrence affects o bjects of the c1uss in question,
Exa mples of eve nts arc a butto n click o n a Bultoll o bject or (], chJnge in the value of an o bject's variable.

Browsing ( ltemsChosen )

CheckingOut
( IncomPlete )

( CreditUnderValidation )

[ CreditDonied 1 [ Complete 1

Figure 16.'1 States and substates for OnllneShOpper class


STATE DIAGRAMS 373

{credit card
~ data
Incomplete]

{credit card
Incomplete I- Hit Sub;'it _ __ data .. ( CreditUnderValidation )
bunon
complete]

Figure 16.19 Conditions on events in UML and the resulting difference in transitions

16.6.3 Transitions

An event may cause an object to !rtmSlrio" from its current state to another state We denote a tran si ti on with an
arrow, labeled with the name of the event causmg the transi ti o n. Fo r example. when a S/'opptr o bject In IH complcie
state subm its valid credit card informati o n, It transi tions from IH comple'e state to C"d,tU"d"lIalidatio" state
Sometimes, when an obj ect is in a gi ven stJte and an event occu rs, th e object can transition to one or
several states, depending on a co"diho" . For example, when a sho pper submits credit card Informallon (by
clicking the mouse or hirtlOg r"t" ), the resulting tran sit io n depends o n whether o r not the d ata are compl ete.
As shown in Figure, 6. ' 9, conditions arc deno ted by square bracke ts In UML.

16.6.4 OnlineShopper State Diagram Example

A complete state · transition dia g ram fo r the O"li",Shoppcr is sh o wn in Figure' 6.20 When the Shopptr o bject
enters the ChcckingOut state, It automatically en ters the substate Incomplete (mo re preCisely, Ch, kingOul.
IH compl"c).

select item
put back
last item
(credit card
Browsing _ _ _ select item - - ltemsChosen data

Hit checkou' buNon

Incomplete hit Submit


hit button
Duit )I
{credit card
hltDK da'a
Credit Unde rValida,ion
complete]
denial received
validation hilDK
received
CreditDenied
Comple'e

F1gur. 16.20 State· trans !Jon diagram for OnlineShopper class


374 OiAPTER 16 THE UNIFIED MODEUNG LANGUAGE

16.6.5 The Relationship between States and GUts

When an oppllcalion IS displaying a CUI , o ne can think 0(" as being in a particular statc Mouse or keyboard
OCtion- arc romls thot affect this state. Although we ma y well want to define , totes that do not correspond to
CUls, and vice versa , , State-CU I correspondence ca n bc made (or many appi<callons

16.7 ACTIVITY DIAGRAMS

Flowcharts arc among thc oldest graphica l met hod (or depicting the Aow o( co ntro l o( algorithm' The UML
uses an extended fo nn of Aowchart called Activity Diagram s. The no tali o n (or activity diagrams is shown In
Figure 16.21 . This example includes parallelism, shOWing the aClivitles Do" Ta,k and Do AMol/", Ta ,k operating
in parallel. Control is no t passed to Do fum Mort until both have completed.
Figure 16.22 containS an activity diagram (or a sclNaln'O method , showing the most commonly used
Am.chart constructs; decisions (diamo nds ) and proces es (ovals).
The fo llowing example shows on act ivi ty diag ram involVinG two classes . It describes the backward
chaiOlng algonthm (or expert systems , and illustrates how Aowcharting can be helpful in exp laining
complex algorithms. Experl ,y,',m,
arc usua ll y based on knowledge In the (arm of rules. which take the
(orm
tltltcrtdmt AND QulcccdrJ11 AND . .. AND (wtcccdrtl l ~ cO lI scq utHf

",here Qtllcccd(J1 IS and cotlscqumls arc Jacls.


For example .
animal is mammal AND QtII"wI IS stn'pcd => animal is zebra
OUf facts will si mply be string such as "a nimal is mammal."

0 0 Something

00 Something More

[condition true) else

OoA Task 0 0 Another Task In


parallel

00 Even More

Agure 16.21 UML actMty chart n01anon


ACTMTY DIAGRAMS 375

else Parameter and settings make sense

Set name to Nominal pa th


· delauIlName·

Parameter
Output notification to console else name 100 long

jkOfeCIIld fN/void SSIName{ s/rifl(JJJName)


(
II Check IeQitimacy 01 parameter and senings
I/( (1IN.lile = null ) 11 (maxNumChsrs/nName(j <= 0) II
(rrwtNumClIars1nName() >a/III meUmitOINameLM>gthO ) )
Sel name Truncate
( name ;: new String( -ds{aultNa",. - );
to parameter name
S)sta II.out.printin
( ·clelau/lNllme seIecIed byGa/n8Chamcter.selNameO·);
}
Me
II TruncaIB IfaName too long
l/(aName.lBngthO >maxNumChsrs/nNameO )
name = new Stnng
( aNarne.fJ6tBytesO, 0, maxNumCharslnNamoO ) :
else II assign the pammeter name
name = new Strlng(aName };
}

Figure 16.22 Activity diagram example

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

• a ilst of fact s, such as -A, -


B, -
0 , and

.
• a list of rules such as A..R=:-L,
- AkB=:-C,
- and B.. C=:- -R
det<rm ines whether or not a given fact, such as L, can be deduced . The an,,"or is "ye " fo r tim example,
because
A(kll oum )&B(kn oum ) =:> C.
B(kIl OWII )& vu,1drdu crd) =:> R;
A(kllowlI )&R vu,' drducrd) =:- L.

We will store the current list o f known facts as a static Vrclor of Fa I ea llcd jacILi" , ond Ihe ),st of known
rules as a static Veclor of Ruf, called ",frllasr . We wi ll simplify the elup of these lists by hard coding the
example given above In the Facl and Rulr cla« es. T il i, Is hown in Figure 16.23.
O ur emphaSis IS o n the harder part · the "backcha ining" algorithm provrBack() fo r establishing whether o r
not a given fact, wh ic h we Will name sou9/' IFacl, call be deduced from the given facts and rules A 1I0wch,rt '"
thiS algorirhm is shown In Figure 16 24
Th is aCll vlty d' .lI'am he lp< to Si mplify an o d, erw lse complex algofl th m. An in pc tlo n 01the ,el1 " ""
diallram mlg hl un ove r th e fa t lh . I " fads to tenTI ln.tc If Ihere " a "u lar haln In the ru le b.'1: su h a<
X =:> Y and Y ~ X
376 CHAPTER 16 THE UNIFIED MODElING LANGUAGE

slaUc I.CILIsl static ruloBase

~
Facl consequent
Rule
1
conlent addRule()
addFaclO proveAnlecedenls()
l..n antecedents
proveBackO lorwardChaJnO
I
--------------------- )

Sel Facl.laclLisl 10 Ihe known lacls

and a Rule,ruleBase to Ihe known rules,

Creale Facl objec1 soughtFacl

Execule soughIFact,proveBack( ruleBase );

Figure 16,23 A class model for chaining rules In expert systems

I
I
Facl I Rule
I else
I
I
I
in lactUst I
I
I Another rule R exists with
I sough/Fact as its consequent else
I
I
I
I
I Apply
I Report FALSE
I R,prDveAnlecedents() •
I
I
I
I proof succeeded else
I
,--_ _--, I • Prove that every
RepMTRUE : antecedent fact is true

Figure 16,2 4 Activity for soughlFact.proveBackO involving two classes

16.8 DATA FLOW MODELS

D.ta Aow models wer< intToduced in Ch.pter II when we discussed requirements, Rec.llth.t they consi t of
aclia", . each of which takes place at a "odt . The UML not.t,on for thIs is exemplofied in Figure 1625. Each
node ha s Input and ourput pi"s indicating the corresponding data type . Data stores are shown with rectangles
and a data"o", stereotype,
A DESIGN EXAMPLE WITH UML 377

Ship
part
order
Parts lisl Parts lisl
Part order Process
part
Price lisl
order

Credil
card Charge
dala Charge amount
credit
card

.. datastore ..
Charge amount

Figure 16.25 Data flow models in UML an example


source' ADopted f,om Jacobson. IVar, Grady Booch ana James Rumoaugh. "The UnIfied SOftware Development Process," (AOOISOIl·Wes!ey Object Technology
seria). AMISOn-WE s!ey, 1m

16.9 A DESIGN EXAMPLE WITH UMl

As an example that illustrates several parts of the UML notatio n in this chapter, consider a graphics studio
specializing in drawing stick peop le. A CUI for this is dlustratcd in Figure 16 .26.
We will focus only on the "foot" requirements. Certainly, there is a need for Rtela"gl, and Elll psr clas os.
The first question is whether we need a Fool class. When we drag a rectangle near the end of a leg, the
application has to know that we want it to be placed at the end o f that leg In a standard positio n. Althoug h it
may well be possible to do this without the application ·'knowlI1!;·' about leg- and fee t, it IS muc h c'asier to

D 0 Facilitate dra wing stick


figures

0
0 Drag to vicinity to
0 auto-complete

6 0 Feet can be rectangles


or ellipses

o (Rest to be specified)

Releasing dragged Ilgure anywhere In this area


causes illo appear in posltlon al end 01 lell leg

Fllur. 16.26 Specifications (or figure.-drawlng example appllcallon


378 CHAPTER 16 THE UNIFIED MODELING LANGUAGE

Ellipse Rectangle

Fool

Figure 16.27 Bad attempt at class model for "A foot Is either an ellipse of a rectangle"

Foot Rectangle

""
El hpse Fool RectangleFool

Figure 16.28 Better attempt al class model for "A foot is either an ellipse of a rec1angle"

cany out if Ltg and Fool classes arc used . (For exa mple , a lLg object would aggregate a Fool object). The next
quesllon IS h ow to re late the classes FOOl, R,clnngl" and EII, plt. Co nside r the pOSSIbility sh ow n in F,gure 16.27.
n, is class model says that a Fool object is bot h an e llipse and a rectangle, which is not co rrec t. A berter
optio n is th e class model in Figure 16.28 .
This mod el is at least not incorrect as the firs t anempt was . It IS a little clumsy , however, in that it
prohferates classes (ElIip,tFoot, Rtclangl,Fool, elc.). Th is is nol te nab le (do we need RtaClaJlg/,Ear, elc.I) . It also
uses multiple inherita nce, whic h is problematical In general, and not available In Java . Now consider the
option shown in F,gure 16.29.
This is a reasonable solution excep t fo r o ne very awkward ISSUC : it makes every ElIips( in our application a
kind of FoolSbape, a nd likewise fo r every Reelallg/,. For o ne thin S, thi s cenalnl y lim its the reusab ihty of the
Ellipst class. For anot her, It is rather strange to Ihink of ellipses as FoolShapes in any case. Finally, if we continue
with thi s, Ellipst ma y also have to be a HnJldShnpe objec t etc. One way to deal WIth t hese problems i fo r
FoolShape to depend only "lightl y· on Elliplt and Reclangle as sh own In Figure 16. 30.

Foot FootShape
...-..•. /'
". ,
.' "
....v ",
..... . .~
I
Ellipse .-
.'
'" Reclangle
./ "
'.
Figure 16.29 Another atremp, at class model for "A foot Is either an ellipse of a rec1angle"

FootShape
Foot
I drawAsE llipseO
drawO
drawAsRectangle(h
I
,I \
\

Ellipse Rectangle
draw() drawo

Figure 16.30 Best atteillpt so far at class model for "A foot Is either an ellipse of a rectangle"
A DESIGN EXAMPLE WITH UMl 379

Area
~------------- - - - - - - - GeometricFigure
releaseCursorO
,, "- , - , leg
~~

,,
,,
,,
,, ~ ~
/
~

FoolShape
Fool
drawAsEilipseO
draw()
,, drawAsReclangleO
, ....
....-~ -- -- -- - /
/ ' "-
....
-- ---
/ ....
........ .... .... . . ..
Ellipse --
- --
---
-----------
/

p OSition
,-:
/
'~-.., "
- - - - - - - - -....
Reclangle
drawO drawO

Figure 16.31 A class model showing all dependenc ies in drawing application class model

This class model shows that the restrictions o n the shape of Fool objects are rentcted in the methods of
FooIShap, . They reference only Ellips< and Rtclallg/, at this point , but can readily be augmented to accept other
geometric shapes. We can no w fill in more detai ls, as shown in Figure 16.31 .
The Area's rt/,as,(ursorO method handles the auto-placement (at th e end of legs in the cases shown ),
and this information is passed along to the anatomical object (Fool in th is case ); olherwise the drau10
of Ellip s, and Rtclallg/, are used to do actual drawing . The class Posilion could be avoided . It contain the
x- and y -coordinates. For example, drawAsEllips,(Posilioll oPosilioll) in FoolShap, cou ld have the following
form .

void dr awAsEllipse ( Posit ion aPosition )


{
Ellipse ellipse: new Ellipse (); II the dependency shown in the
c lass model
ellipse _draw( aPosition ) ; II the actual work drawing the
ellipse
. . . .
}

Showing a ll of the dependencies in a class model can make for a complicated diagram , and for this
reason dependencies are often omitted. (This i< perhaps like swee ping thinSs under th e rug l) The sequence
diagram in Figure 16,32 specifics how the classes and methods work together, and show< details aboUl
parameters
The sequen e diagram speclAcs that when a geometric Agu re IS dragged to an area and the cursor It
released , the "ttllS' u" orO method of Arm execu tes with Ihe C,om,'n',Fig"rr as parameter The At,a Obll'Ct
deduces which anatomical obje t IS Involved (Fool in thiS case), <0 It ca lls upon that obie t to dra, ",elf, It als o
knows whar gcometn form IS required
380 CHAPTER 16 "!'HE UNIFIED MODEUNG LANGUAGE

:Area :Fool :FoolShape : Ellipse


I

I
-----+.,.,
releaseCursor
( GeomelncFigure
draw
I
aGeomelncFigure)
I
( Leg .Leg,
GeometrlcFlgure
drawAsEllipse'
I
aGeomelrlcFigure) ( PositIon aPosition)
draw( aPosihon)
I

, or drawAsRectangle() ...

Figure 16.32 Sequence diagram lor figure drawing application

16.10 SUMMARY

The Unified Mo deling Language (UML ) is a widely accepted graphi cal nolation for expressing object -
oriented designs. UML defines several ways classes can be related TI,ese are sum marized in Figure 16.33 .
UML models are diagram that show either th e cla.sses of a software design and how they are related , o r
the Aow of control 01 a design . Figure 16.34 summarizes the UML models covered in this chapler.

• Package
• Group of related classes
• Inheritance
• Take on attributes and operations from o ther classes
• "is-a" relationship
• For example, an Employee "is-a" Person
• Association
• Structural relationship between classes
• Aggregation
• Structural mclusion of object on one class by another
• "whole -part" relationship
• Composition
• Stro nger rorm of aggrega ti on
• Included object is created and destroyed when including object is created and destroyed
• Dependency
• One class depend on another
• Changes to depended ·on class aHect dependent class

Figure 16.33 various relatlonships between classes that can be shown In UML class diagrams
EXERCISES 381

• Oass Modds
• class~s of a design and their ~ I ation sh ip
• Obj«t Modd
• obj«ts of a desIgn and their relationship
• Sequence Diagrams
• seque nc~ of method ca lls among object
• usually corresponds to a usc ca e
• State Diagrams
• states of a design clement
• transitions among states caused by events
• Activity Diagrams
• Row of contro l
• si milar to Row charts
• Data Flow Model
• show processing elements and the data that Row between them

Figure 16.34 UML models

16.11 EXERCISES

I. Name three major re lati onsh ips that could eXISt between classe A and B. Describe them in your
own words. Express each 10 UML and in a typical Java implementation

2. Explai n the difference between aggrega tIo n and composition. Cive an example to support your
answer.

3. Which of the following classes inherit irom whic h7 Exp la In YOllr reasoning.
WOnt1. Ellips<. Al1ilnal. 2DF,gurt. Circ/,
4. D raw the class diagram for the fo llowing code . Explain the correspondence between the code and
the diagram .

abstract class A ( )

class B
(
B( ) ( )
)

class C extends A
(
B b = new B ( ) ;
)

5 A library ha, a aile li o n of 'tcm< (boob and magazine ) avai lahle to loan patrons Forea h 'tem ,n
the ollection . the system mJ,nt"", dDta about 'IS t,tle, au thor, and unique ,eI In adel,t,on , the
/
382 CHAPIER 16 "!'HE UNIFIED MODELING LANGUAGE

cop right year is malntolned (or books , and the edit io n number I; mo intalned (or magaz ines. Draw
a UML clas. diagram representing the library item;. Be sur< to include the required attributes. HI.'
U sc in heritance In your model
6 Show a class d13 gram (o r an application that displays automobiles. Depending o n the user's request, It
dl plays a tYPical Ford, T oyota, or C he vy, tOset herwith Interactive pages o( In(onnation about each
We want to be able 10 easil y add new auto mobile brands to the application in the fulUre and to reuse
parts o( the deSign where possible.
7. Suppose that your car has a buill ' ln applicalion that dISplays the status of Ihe cngi ne parts at all
times. Draw a UML stale diagra m (or Ihe 5larl" class that describes the automo bile's starter o nl y.
Explain your reasoning.
N o te that the starter is some times connected to and sometimes disengaged from the car's
motor The ~tarter react s to actions involVing the car key. The key ca n be in one of three positions:
vertical , 90·, and I BO·.
B. ConSider an applicalion used at a doctor's office. The application schedules patient appointments
and maintains patient medical hi stories. Suppose the application design contains an Appomtmrn !
class to lrack appoi ntments, and a Medica /Hillory class (or each patie nt. H ow would yo u draw Ihe
U ML class relatio nship between these two classes)
9. Consider Ihe fo llOWing use case for a web e·commerce app lication,
Use Case Name, "Select Item"
Actor, Shopper
Precondition : Actor has req uested product list

Sce nario:

I. Applicati on displays product list


2. User selects item on product list
3. User cl icks "add item to shopping cart" bunon
4. System acknowledges Item placed in shop ping cart
Draw a UML sequence diagram (or this use case. Explain your reasoning.
10. Draw a UML activity diagram for the "Select hem" usc case In Exercise 9. Explain your reasoning.

BIBLIOGRAPHY

I Fowler, M :mm, "UNLL DIJftIJcJ A Bnt! Ci1Aldt 10 1lH- SwnJnrJ Ob}tcl MoJtli"9LA"9~"gt.~ 3rd ed Addlson-Wnl cy. p 99 , l~' .........
2. )KOOwn, Ivat. Grady Booch .nd ) OImes RumbOlush, 'Th U'UfitJ SoJIv'4rt DtlHloplflt'n1 P~m." (Addl~n- \\:/ec; lc y O bJcct T C'Chnology
Sene'S), Addison · W(1.I~ . 1999
• What are examples of a recurnng design
purpose?

MaIntenance • What are ·creational" design patterns?

• What are "structural'" design pattems?


TIle Sof~vare
Development • What are ~ behavloral" desIgn patterns?
Ufecycfe Requirements
analysis • Can design panems be thought ot,n
terms of roles and basic forms ?

Figure 17.1 The context and learning goals for thiS chapter

DesIgn pauerns co ncern class co mb,n all o ns and accompanyong algonthm, that fu lfill com mOn
desIgn purposes Eac h desIgn pallern cx prcs es a desIgn co ncep t rath e r th a n an onllcXlble da ,
combination The aecompanylnj( algonthms cxpre the pauern's b."e opera ll o n Thl c hap te r"
Intended to famolianze the reader w Ith th e purpose, of de<lg n paue rn" probll'K theIr overa ll form,
and usage, (ju mm an z lng lhc..~ major one.. , and ('xatnIn1l1g (cve r~1 In ~omt.:' depth Th(·... t: arc lake n from
Camma "t al [ I ], th e clas"c ref ·re nce (or the su h) ee t hapt e r I dc<c nhcd t pl ca l software de,"!;n ):oa l,
and purpo,", We wol l ,tMt h rc w nh an exa mpl e de"gn purpme a nd follow It with a de"sn pallern
satlsfy,n/! that purpo,e
384 CHAPTER 17 SOFlWARE DESIGN PATTERNS

17 .1 EXAMPLES OF A RECURRING DESIGN PURPOSE

17 .1.1 A Simple Example

ll,crc are m.ny applica tio ns In whICh w~ defIOe. clas bu, for wh ich oilly onc In"an c wdl be needed As an
cxa m pic. householders arc forevcr co n,ernpla'ing ,he moderOl z. " oll of ,helf kl ,chen<, or.en usi ng software '0
vISualize 'he posSibili',cs Usi ng a K,rcim, class would be nalUral. Now suppose ,ha' a reqUirement IS that the
applica'ion does not allow ma rc than ooe kllchen to be under conSi derati on. It IS always. good idea for an
apphcallon to enforce what it mtends, so the patt ern needed here IS rhe enfo rce ment of th e o ne· in lance .onl y
reqUirement The Singleton design pauern . describcd in ec tl on 17.5. 1, fits th is bill.

17.1 .2 A More Complex Example

Let's con 'lnue wi ,h ,he kllchcn application, which we will call Kirch", V"u>tr. "enables ,he user ' 0 first layou t
th e parts of a kit chen \v' uhout comm itting to a style. The overall interface IS shown in Figure 17 .2.
Here is a usc casco

Layo ut a Kitc hen


Preconditi o ns: No ne

I. U5(r clicks o n ,he "wall cabinet" icon.


2 AppllClltiotl displays a wall cabinet in the center o f the work area.

3 Usn reSizes the wall c abinet.

Uscr drags ,he wall cablnc, '0 a posi tion "' ,he upper half of ,he work arc • .

0
Wall menu
cabinet
.!1
l1
Counter
./
display area

0 styles
Floor
cabinet
""
~ Modem 11b[I.,.,;;c;;;;laSS;;;;;;;,
ICdl~ ,
Anllque I~ Arts & Cra". I
Figure 17.2 Graphical Interface to the KltchenVlewer example application
EXAMPLES OF A RECURRING DESIGN PURPOSE 385

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 0 I
• 0 0
\i
I
I
,,
II ,,
, ,I
I I I
,

0 0 0 0 0 0
/

Agure 17.3 An example of a kitchen being deSigned with KitchenViewer

. 1.
I ,,
,
"

r -Arts & Crahs I


Fllllre , 7.4 selecting an antique style using KltchenViewer
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 In different
places.) A class diagram for this would look like Figure 17.5.
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 387

17.1 : The method renderKifChen{j in KitchenViewer

II VERSION IGNORING OUR DESIGN PURPOSES

I I Determine the style


· . . I I case statement?
II Assume that the antique style was selected .

I I Create the ant ique wall cabinets


Ant iqueWallCab inet ant iqueWallCabinet 1 = new Ant iqueWallCab inet () ;
Ant iqueWallCabinet ant iqueWallCabinet2 = new Ant iqueWallCabinet () ;
• • •

II Create the antique floor cabinets


AntiqueFloorCabinet ant iqueF loorCabinet 1 = new AntiqueFloorCabinet
() ;
AntiqueFl.oorCabinet antiqueFloorCabinet2 = new Antiqu eF l oorCabinet
() ;
• • •

I I Create the kitchen object, assuming the existence of add() methods


Kitchen antiqueKitchen = new Kitchen();
antiqueKitchen.add( antiqueWallCabinetl, . . . ); II rest of
parameters specify location antiqueKitchen.add
( antiqueWallCabinet2, . . . );
• • •
antiqueKitchen.add ( antiqueFloorCabinetl, . . . ) ;
antiqueKitchen. add ( antiqueFloorCabinet2, . . . ) ;
• • •

I I Render antiqueKitchen
• • •

ddegate. their creation , replacing phrase. such as the foll owing,

nell Ant iqueWa llCab 1net ( " //applles o nly to antique style: Replacet with the follo'W'lnq.
myStylo. getwallC~b inet (); Ilapplles to the s tyl e c hosen at runtia\C~

AI nuntime, the class of ,.ySlylt determines lh e version of gtlW,,1/ nbilltl() executed , th ereb ' produclllg
Ihe approprrate kind of wall ca binct To carry out tl", dclc~at lo n of re<ponsibility, we Introduce a new do s,
,.,hich we'll all KlichtHSlylt, supporting methods gtIWnI/Cn hllltl(), gtlFloor "h,"tl(), and <0 on Kllcht. I It Will
388 CHAPTER!7 SOFTWARE DESIGN PAlTERNS

Chent
(onderK.tchenO
___ __ - - ---- -- -- ..,. 1\
---- - - - ---
~"'/

; ",/ I \"
; /
Kitchen ; I
; / \
;
;
/ I \
; / I \ FlOOrCobFnel
WallCsbinot ;
; / I
; / \
;
; / I \
; / I \
; /
; I \
; /
/ I \
; / I
; / \
; I
; /
I
ModernWaliCabtnet AnllqueWal1CablnOI
I
I "
I
I
I \
I I
I

ModemFloorCablnct AnlJqueFloorCabinel

Figure 17.5 A design for KitchenViewer without design patterns

have subclasses, which we'll name Mod,,,,KSlyl,, A"'iq",KS'yl" and so o n, each supporting se parate imple ·
mentatio n of g,llVaIlC,bi"ct[), g,IFloorCabi",'(), and so o n This is show n in Figure 17.6.
Recall that, due to polymorphism, executing ",yStyk.g"FioorCah",,,() has di ffere nt effects when "'yStyk is an
object of ModmtKStyk vetsus an object of AHliq",KStyl,. The class model in Figure 17.7 is a more complete vetsio n.
Notice that th e client code rdere nces K, Ich,", K,'ch",Styl" WaliCabi"ct , an d FloorCabi",' , but docs not
rde rence pecinc wall cabinet sty les or Ooor cabi net sty les. For example, the class A"liq",W"IlCabi",' does not
appear in the clie nt code. T o sec how th is wo rks, let's assume that at runtime, "'ySlyl, is an object of the class
Mod,,,,Sryl,. In this case, when the method ","ItrKilch",() executes a statement such as

WallCabinet wallCabinet7 = myStyle, getWallCabinet () ;

WaDCabinet FIoorCabln8t

lI"IFIooiCabi""'1I C;

... AnllqueWallCablnet .. ....J AntlquoAoorCablnol


,, ;;
;

,
,.,--,---':'::_"'1'
ModemKSfV1e ;
gelWatlCab1nelO getWalICablnel() ' .... ,-
;
getFloofCobOnelO gelAoorCabinetO

I
AootC'tNl getFlootC.~1()
I rerum r4N .'cdllfoRoooc.btnlIO: )

Figure 17.6 The Idea behind the Abstract Factory design pattern
AN INTRODUCTION TO DESIGN PATTERNS 389

Cl"",'

. ..
rendef1(ltChOn( K1tCl'lenSty1e)

,,
KItchen
,,• --
,
~Wo!!('·, ... 1(1
.- - - ' - -

AoorCaolnot
,
I '--...n I'lIIiW U:OC'l.,hrwl.O.

M odemKS!y!e ModcmWallCtlbln81 AnllqueWaUCabinet

• • ••
••

'. • ••

•• • •

••
• • ,.
• •
Anllgue KStyie ••
getWauCablnel() •• ...
gelFloorCablnelO AntiqueAoorCablnel

Figure 17.7 The Abstract Factory design pattern applied to KitchenV,ewer


the metho d grIWaIlCab"1(rO is the ve rsio n defined ,n the class ModrrnSry/r, and so it actuall y returns a
Mod,rnWa/iobject.
Th. metho d rt1,drrKirch", (Kirr/m,Sry/r n,ySry/r) looks Itke li sting 17 .2
Th is version of rmdcrKird""O is much morc versatile than the pre vIous version since It IS not written fo r
any particular sty le . Figure 17.8 de cribes Ihe Abs trac t Fac tory desig n pattern in ge neral.

Ustlng 17.2: The method renderKltchen(KitchenStyle myStyle) in KitchenVlewer

II Create the wall cabinets : Type determined by the class of myStyle


WallCabinet wallCabinetl = mYStyle . getWallCabinet () ;
WallCabinet wallCabinet2 = myStyl e . getWallCabinet ( ) ;
• • •

I I Create the floor cabinets : Type determined by the class of myStyle


II Create the kitchen object (in the style required)
PloorCabinet floorCabinetl = myStyle. get Floor Cabinet () ;
Floor Cab inet floor Cabinet 2 = mySty le . get Floor Cab inet ( ) ;
• • •

Kitchen kitchen = new Kitchen(};


kitchen . add( wallCabinetl , . . . } ;
kitchen . add( wallCabinet2 , . . . } ;
• • •

kitchen.add( floorCabinetl , . . . } ;
kitchen . add ( f loorCabinet2 , . . . J ;
• • •
390 CHAPTER 17 SOFTWARE DESIGN PATIERNS

CUenl

--- -- -- --
" " doOper.tion( Stylo mySlylo)

-- ----- ,;'"
.",.
I \

Style
-- -"-"
""
I
I
I \
\
\
9O/CompoilentAO Collection \
I \
go/Compollom80 I
\
I
I \

'"
ComponantA ComponentS

l , L,

, Style 1CompcmentA
, ,•
Stylel ,
, Styte2COmponentA
getComponentAO ,1
getComponenLBO ,,
---- ---- -- '
, ,- -- - - - --- - ..,
, , --- Style ! COmponentS
$tyle2
,,
gelComponenlA 0
getComponentB 0 --- -- ------- -- --- --- -- --- Style2ComponentB

Figure 17.8 The Abstracr Facrory design pattern

The client method JoOpcralloH (Style myS/yle) builds an inslance of Collecrioll in the style indicaled by
myStyle by calling mySryle.getCompoH".tAO and myStyle.grtCompolln.tB() . If myStyle is a Styl" object, for example,
these two operat.o ns produce Styl" Compo"",tA and Styl" CompolI".tB objects, respectively. The pattern thus
ensures a consistent style throughout
We have mentioned that desi g n panerns , ho uld no t be rega rded in a literal manner. For example , the
desig n," the above figue< could also appear as shown in Figure t7 .9 .
In this alternative. Collerrioll aggregates Sty I" CIi",r docs nOl rderence Style directly, doOprratioll O
takes no parameters, and Collertioll has methods for getting the vari"us components. Collerrioll', aggregated
Styl, obJeci is instantiated at runtime . perhaps with separate se tup code . When JoOprrarioll O
calls grtCompolI",tA() in Collrerioll , conlrol is de legated to getCompolI",rA() in the aggregated Styl, object.
This is still the Abstract Factory pattern . The Abstrac t Faclory palle", is described in more delail in
Section 17.5.2.

17 .3 SUMMARY OF DESIGN PATTERNS BY TYPE : CREATIONAl,


STRUCTURAL. AND BEHAVIORAL

Gamma et a!. [ 1] classified deSIgn patterns in one of three ca tegones, dependmg upon whether It has 10 do
with one of the following ,

• Creating a colleclion of objects in Aoxible ways (<realloHal patterns)


• Representing a collection of related objects ("",ctu,al patterns)
• Capturing behavior among a collection of objects (btbooio,al patterns)
SUMMARY OF DESIGN PATIERNS BY TYPE: CREATIONAl., STRUCTURAl. AND BEHAVIORAl 391

Client
doOperatlonO
--- -- "- ,,
StylB
-
Collection /
/
/
,,
gBtComponentA O gelComponentAO /
,,
getComponentB{) gelComponentB()
/
/
,,
/
/
,
ComponentA CamponentB

7J:
, "'i Style 1ComponentA
, ,
Style 1 , ,
, Style2ComponentA
getComponentA() , ,
getCamponentBO - --- - , ,
-- - - - ~ ,- -
, , --- -
- -- - . - - - Style l CamponentB
,
Style2 ,,
getComponentAO
getComponentBO --- -------- - - - ------- --- - Style2ComponentB

Figure 17.9 The Abstract Factory design pattem alternative

These categones arc useful for recognizing when 0 panern may be needed and as the beg.nning of a
guide to sciectlng which one may be appropriate. Next , we wi ll elabo rate on each uSing exam ple applications

17.3.1 Creational Design Patterns


Creat.onal design patterns help us to flexibly set up co llecti ons of o bjects for subsequent processing. They
allow the creation of seve ral possible collec t.o ns fro m a single block of code, but wllh properties sllch as·

• Creating many versions of the collecti on at runtIme


• (0"llra'"'"9 the objects created: for exa mple, ensurin g that there' is o nly instonce of its class

Table 17. 1 summanze the use and nature of key creat. ona l dcs.gn pallerns The ab tract factory and
SIngleton pallerns are descnbed .n more detail .n sub equent seCll o ns.

17.3.2 Structural Design patterns


Structural des.gn pallerns he lp us ' 0 arra nge co lkc llo n of o b,eCt in fo rms such a hnked lISts or trees They
are u.dul when we want to manage omplex dala conSISting of ossa iatcd o bject . Table 172 summanzes the
u~ and nature of k(1' <lru tural de"Kn pallerns The Adapter and Facade pallern< arc des "bed 111 more de'."
10 wb\Cquent scCClonr. a .. rcprc~e nlallvc: examples of Slru Ctllfil l dC:'S18n pattcrn~
392 CHAPTER 17 SOFlWARE DESIGN PATTERNS

Table 17 • 1 A summary of key creatlonal design patterns

Example Application Purpose


Satisfied by This Pattern
Design Approximate Design Outline of the Design
Pattern Name Purpose Satisfied by Design for the following pattern
This pattern requirements without repeating
code unnecessarily. Make the
design easy to change.
Create objects at From a single version of control Create desired objects by
runtime WIth flexibility code, generate mail messages using methods that return
Factory
that constructors alone tailored to vanouS custOmers. the objects.
cannot provide.

Abstract Create coordinated Display a ki tchen layout, allowing Encapsulate each family in a
Factory (see fam ilIes of objects at the user to select a style at runtime. class whose methods return
Section 17 5.2) runtime, chosen from a (See Section 17.2.2.) objects rn that style.
set of styles .

Create an aggregate Display a kitchen layout. allowing Create the objects ofthe type
object in which selected the user to select at runtime a type by cloning a prototype.
Prototype
parts are essentially of wall cabinet. or a type of noor
copIes. cabinet, etc.

Ensure that a class has Build an application to evaluate the Make the constructor private
at most one results of a lab experiment Ensure and obtain the unique object
Singleton (see
InstantIation, accessible that there is exactly one Experiment by means of a public method
Section 17.5.1)
throughorJI the object at runtime, and ensure that it that returns it.
application. can be accessed by any method in
the application. (see section 17.5.1.4.)

Table 17.2 A summary of key structural design patterns

Ex3mple of Design Purposes


satisfied by This Pattern
DeSign Approximate Design Summary of the Design
Pattern Name purposes satisfied by Design for the following pattern
ThlsPattem requirements without repeating
code unnecessarily. Make the
deSign easy to change.
Represent a tree of Represent the organization chart of Have compoSite objects
objects. a company. Allow client code to call aggregate other composite
prrntOrganizationOon any Employee objects.
Composite Allow client code to object, printing the names of the
access uniform employee and all subordinates, if
functionality distributed any. Allow the additIOn and removal
in the subtree rooted by of subtrees at runtime.
any node.

Decorator Allow objects and Allow the user of an online clothing Link the objects using
functlonafity to be added store to see his or her Image aggregation.
to an object 8t runtime. dressed in a variety of clothes.

(continued )
SUMMARY OF DESIGN PATTERNS BY TYPE: CREATIONAL STRUCTURAL. AND BEHAVIORAL 393

TIllie 17.2 (continued)

Adapter (see Ailowan application to Design a loan application from intrOduce an inherited
section 17.6.2) make use of external (e. scratCh. but allow It to use any Intermediary class relating
g., legacy) functionality. vendor's classes that compute the application and the class
monthly payment calculations. with desired functionality.

Manage software Design the architecture of a student For each package, Introduce
architectures involving loan software application so that an object that IS the sole
large numbers of one group of developers can access to objects within the
Facade (see classes. concentrate on the loan option package.
secuon 17.6.1) database, another on the user
Interface (simultaneously). and a
thlfd on payment calculations.
Minimize coordination problems.

Obtain the benefits of We want to be able to visualize a Share objects by


having a large number of room with stenciling. There are five parameterizing the methods
Individual objects stencil patterns but thousaQds of with variables expressing the
Flyweight withoLit excessive potential stenCil marks on the walls. eontext.
runtime space This might be easy to do if each
requirements. mark were a separate object. but
we can' t afford the memory
required, and it's impractical to
name all of these separate objects.

Some methods are Assume that rendering an image Introduce a class standing
remote, or require lots of consumes a significant amount of between the requesUng
resources to execute time and space because the image methods and the resource.
(time or space). Ensure data has to be read from a file, fill a
Proxy
that they can be buffer, and then be rendered . If the
executed, but no more buffer is already filled by a previous
often than necessary. invocation of the method, then
Invoking the function should not
repeat this step.

17,3,3 Behavjoral Design Patterns

When an application runs, much behavior generally occurs among the objects. An example IS when a method in
one object calls several methods In an obJcct of a dlHerent class. Sometimcs wc want to control and label behavior
111 order to parameterize it or reuse It Each behaViora l pattern captures a kind of behav ior among a collectio n of
objects Let's consider the follOWing example of mutual behaVior among Ship and TlIgbonl objects Let's say that we
want to cstimate the amount of lime required to bring sh i ps Into and out of a harbor and tran pon them to dry
dock for maintenance, based o n their Size, and 0 on Imagine that thIS i, a omplex calcu lation ,hat requires a
systematic simulation o f the ,ransportation process !'igore 17. 10 suggests a configulUt.on
The classes Ship and Tugbonl are natural closs ch Oices, blll obJcc ts of rhe e lasse, play different role ,
depending on whether 'he ship IS entering , leaVing, or head i ng for d ry d ock 111 e th erc arc many pOlentl.1
applications In which we ca n usc SI" p and TIIgboll l, we d o no t wont th e,. la'5e' to depend o n ca h o th er, J,
• "'88«ted by Fil!ure 17. 1 I
We have a bchtlvloral design purpose h ere occa u,c we wan' to 'CI>Jfate the interd ependen t behaVior of
(hcse objects from the objects them,elve, The Mediator design pattern doe, th". Figure 17 12 ,how, the
core Idea of Mediator
394 CHAPlER 17 SOFlWARE DESIGN PATIERNS

U"
I ,

-
~
-
,.- ;.--J hA
h~
obstacles

Algorithms express mu tual behavior


-- "" ,
'- • " .,.. ~ 10 dry dock .;
\•

Figure 17.10 Example of behavioral design goaf-tugboat and ship port entry

Harbor application

I 1..n
Ship --......:......:- Tugboat

Customs application: reuse Ship alone

ILongshoreman I
Figure 17.11 Avoiding design dependency in port entry example

In this deSi gn. Ship and Tugboal classes do not refer to each other Instead. the I.r.. IIIgPo,./ class contro ls
how objects of Ship and Tugboat behave to es timate the tim e for that maneuve r.
The full Mediator pattern allow (or the fact that the mediated clas es may need to com mun ica te (e.g.,
to respond to events on either of them). T o accomplish th is. the media ted classes ca n be made to subclass a
bast' c1a~s that aggregates a genenc media tor class (PortNLsSlOt1 ) TIll S is shown in Figure 17. 13.
a te that 111 Figure 17. 13 the Ship class docs depend on the class V",tI , wh, h depends on P0r1Ml5lI0n , so we
can not usc the ShIp class wi thout these [Vo'o, These dcpcnclcn ics arc much more acceptable , however, than

Ship
LeavingPort
eSlimateTImeO

Tugboat

Agure 17.12 The Mediator design pattern concept applied to the POrt entry example
SUMMARY OF OESIGN PATIERNS BY TYPE: CREATIONAL STRUCTURAL, ANO BEHAVIORAl. 395

PortMlssJon
Vessol
eStlmaleTImeO
-z;; if
Med1al0f base class Tugboal
Ship

Ente ringPort
eSlimateTlme O

LeavlogPort
estimate TimeO
-t-

8eingMainlained
eslimaleTimeO

Figure 17.13 Applying the Mediator design pattern to the port entry example

having Ship depend for. 1I lime o n Tugboat Ships are always vessel<, and they usually have missions, but they are
only someti mes assoCIated w ith tugboats. T able 17.3 summarizes th e usc and nature of key behavioral design
pattern . The Interpreter, O bserver, and State patterns are described in more detail in subsequent sections as
examples of strucrural design patterns.

Table 17.3 A summary of key behavioral design patterns

Example of Design purposes


Satisfied by this Pattern
Approximate Design Purposes Summary of the Design
Design satisfied by This Design for the following pattern
Pattern Name pattern requirements without repeating
code unnecessarily. Make the
design easy to change.
Chain of We want a collection of Design a GUI for a Web applicabOn Link objects to each other via
Responsibility objects to exhibit to view automobiles with requested aggregation. Each performs
functionaltty. At design color, etc. The display Is dynamic, some of the work. and then
time we want to be able depending on the model. etc. calls on the next object in the
to easily add or delete chosen. Reuse the GUI parts among chain to continue the work.
objects that handle all or the displays.
part of the responsibility.

Command Make the execulton of Allow users of an application to capture each command In a
operations more flexible, retract their last four decisions at class of its own.
For example, enable any time (the " undo" problem).
" undoing."

Interpreter Parse an expression. Design an application that takes as Introduce a class to capture
SectIon Input an order for a network of PCs, expressions, and allow
17.7 1) expressed In a standard syntax. The expression classes to
output consIsts of Instructions for aggregate expression
assembling the network. (See classes
Section 17.7.1.5)

(continued )
396 CHAPTER 17 SOFlWARE DESIGN PATIERNS

Table 17 • 3 (contmued)

Example of Design Purposes


satisfied by This Pattern
Approximate Design Purposes summary of the Design
Design Satisfied by This Design for the following pattem
pattern Name pattern requirements without repeating
code unnecessarily. Make the
~
Mediator (see capture the interaction Build an application that estimates capture each Interaction In a
above) oetween objects without the amount of time required to separate class, which
having them reference bring ships into and out of a harbor, aggregates the objects
each other (thus and to transport them to dry dock involved.
permitting their reuse). for maintenance, but ensure that
the Ship and Tugboat classes can be
reused separately.

Observer (see A set of objects depends Keep management, marketing. and Capture the data source as a
Section 17.7 .2) on the data in a single operations departments up to date class. Allow It to loop through
object. Design a way in on sales data. Each of these the observer objects, calling
which they can be departments has different an update() method.
updated when that requirements for the data.
single object changes
attribute values.

State (see At runtime, vary the Customers fill out an order form on Aggregate a class
Section 17.7.3) effect of invoking an a Web site, and then hit the " enter" representing the state with
object's methods button. The result must depend operative method dOAction(j.
depends upon the upon the state of the form data: Subclasses effect the
object's state. " Product Information Complete," reqUired actions of substates
" personal Information Incomplete," With their own versions of
" Credit Check In Progress," etc. doActionO.

Template Allow an algorithm to Organize the huge number of traffic Have a base class contain an
execute partial variants light algorithms in a city by overall method, but with
at runtime . arranging them into a few basic functlon calls where
forms, with variants tailored to variability is needed. Have
specific locations. subclasses implement these
function calls to capture the
reqUired variability.

17.4 CHARACTERISnCS OF DESIGN PATTERNS; VIEWPOINTS, ROLES, AND LEVELS

DeSign pattems are partially described by class d iagra ms, but they also ca n be th oug ht about in two ways. th e
stolle and dynamic viewpoin ts of th e pattern. This secti o n cxplui ns these two view polIHs. It also describes th e'
(fbstracl and non· abstract (concrclc ) levels of design patterns FI nall y I it' covers the ways I n which de ign patt~rn
arc embedded In applications, The st'luic vs. d ynamic vicwpoim~ . ab tra ct '"S. conCret(' levels. and embedding
issues are acwally characteristic of mOSI deSig ns, a nd are not Itm itcd to de ign patterns, These characteristics
arc su mmarized in Figures 17. 14 and 17. iS .
CHARACTERISTICS OF DESIGN PATIERNS: VIEWPOINTS. ROLES. AND lEVELS 397

• Ifinopo,"ls-ways to descnbe patterns


I . Sialic, class model (building blocks)
2. Dy>lumic, sequence or state diagram (operation)
• wls--<iecomposition of palterns
I . Abslracl level de cribe the core of the pattern
2 . COllerrl, (= nooabstract) level describes the particulars of this ca e
• Roles-the "players" '" pattern u age
I. AppllCutloli of the design pattern itse lf
2. Oi,,,I, of the design pattern application
3. S,lup code initialize and controls
FIgure 17.14 Some characteristics of design patterns. 1 of 2

(class O( classes)

- - -role
1.-CII"", -- - _ --
-
"- -- ---- --
I
I
I
-- --,..
I 3. Role: Application of the design panem
I
I
I A. Static viewpoint B. Dynamic viewpoint
,-------,
: A 8 ~ 0) Abstract level
DOD
,_-
',.L I

:C D : (iI) Concrete level
_ _ _ _ _ _ _ _ .J

(sequence or
(crass model)
stste diagram)

- - - -> : 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 <peedy how the design actually work at runllmc whal
happens Rrst, <econd. and ,0 on . Figure 17 6 li\t< the ode for 9rtFloo, G,b"ltl() and g,tDoorCn I"'ltl(). and although
thIS code contribute, to the dynarnl ViewpOint of the de ' lgn I"ltern appltcallon. It " hard to <ec the
whole execution PI rure T () cxprc.., .. the d y namiC VICWpO lIll , we often U~l' ... cquence dlJ 8r.l 1ll'. J" IlIlI,lrillC I In
398 CHAPTER 17 SOFTWARE OESIGN PATTERNS

Cllont I mvStyle.KlfchoflStyle
,,
I
rr __ ~m~YS~~~le~.~~~~ ~
Lf. gelWauCabinotO - IFmyStyte BELONGS TO ModOmKS'Y'<>-
------,
myStyte: waltCablnet I
ModemKSlylo Mode rnWallCa binOI
rendcrKItcl'len ,,
(myStyte ) ,
gOIWallCabinetO
MOdomWallCabinotO l1 I

- IFmyS'Y/o BELONGS TO AnllquoKStyt"',

myS~I. : wallCablnel1 :
AntiqueKSlyle AntlqueWaJICablnel
,
:__~g~.~IW_'~I~IC~'~bi_ne~I~()__~ ,I
AnllqueWaliCablnetO '11
~ I

Figure 17.16 Abstract Factory sequence diagram (or Kitchenviewer

Figure 17 16. It shows the dynamic vIewpoint of the KltchenVicwer application of the Abstrac! Factory d«ign
pattern .

17.4.2 TWo Layers of a Pattern: Abstract and Concrete

allct: that within the KitchcnVlcwer Abstract Factory pattern application , some of the classes are
abstract. In conformance with Gamma et al. [ I ] we wi ll ca ll non·abst ra ct classes "concrete." Figure 17. 17

, , "
, ' '
, ," ,
,

• , , ,
--
,

, , ,
"
, " '


•••
Waf/Cabinet
,
-, "~ ~...
KlfchenSty/e
• •• FloorCsb,oet
••
Abstract level ••

Concrele level
...JO
KHchcnJ O +
ModemWaUCab'nel AnllqueWaUCablnet
" " '
---- , , •
,
,, ' '
MOdomKStyle
'- ,
'" ,
" , , , ,
, , , •

" " , •
'" - ,P'.-

, , , , "
ModemFloorCo.l)(net
, ,
••
AntiqueKStyle -----. ---- ---- -- ---.
-- AnflqueAootCabtnGt

Figure 17.17 Concrete and abstract layers in design pattems


CHARACTERISTICS OF DESIGN PATIERNS: VIEWPOINTS, ROLES, AND LEVELS 399

",arrang~ th~ physIcal placement of cia C In F;gure 177 to e mphasIze the abstract and conc rete
groupings ailed Ill),'"
Th~ mterface of cl,ents with a design palte rn application u ually needs to be at the abstract la yer. This
can ~ s~en in the code for rmd"Kitd"!l O, which is wntten in term s of KltchenSt)'le (and doesn', reference
ModemKSryle o r A!lloqu,KSt),/e ), W.II .bl/ltl (not ModentWallCabl!lrl o r AHloqueWaIlCabm<l ), and so o n
A divI Io n onto abstract and co ncrete layers IS a ohen a good d~Slg n practIce, regardless of whether
d~ig n pattem are beIng apploed, because clien t code can be wnlten in terms of the more ge neral cla«es of
the abstract layer, maki ng it more ve rsa til e

17,4.3 Three Roles Involved in Pattern usage: Pattern Application, Client, and setup

This section cxplains the th ree pans orroles-on volved in the usage of a desIgn pallem on a design. n,is dIScussion
is designed to help the srudenl surmount common problems uSIng design pallerns. The thrce roles arc as fo llows,

• The applicati o n of the desig n panem itself

• The code that uti /o zes tim application (the "client role")

• The code , of required , that inot ializes or changes the desig n panern application (the "setup ro le")

These theee ro les arc shown on Figure t 7. 18, and arc explai ned next.

17.4.3.1 The Design Pattern Appl ication Role

A design pattem-the desig" pa llcrn appllCn loo,,-involves a specific class model. For example , K,tchenVicwcr,
described in this c hapter, contains an appl,cation of the Abstract Factory design paltern Th is is the ubstance of
the d~ign pattern .

17.4.3.2 The Client Role

Many pans of a program can potentially usc a desig n pattem application We usuall y rde r to these pans as eli", "
of the paltem application. Each client is typicall y a method, but we often regard the method's class as the c/oent In

2. Client Rote 1. Deslgn PaNem Application

I Interacts with Interface to


the design the pattem
pat/em only
through Its
Interface
DPCllent
,,
- --, DPlnterface I
,,
, , ,. (frequently
abstract;
possibly
I
, , , several
,
I, ,, classes)
r
,
, ,- ,
3. Setull. Rofe
[}:;~-- ---- ------ -- --------.
No limitations -- -- -----
Res' of the A[!()tication
-- -- -- - Rest of the
--~ design

0 0 0 0 0 pat/ern
application
J
Flsure 17,18 The three roles Involved In design pa ttern usage
400 CHAPTER 17 SOFTWARE DESIGN PA TIERNS

Ihe K,t henV,ewerd<""lln, for example, the ,,,,dlrK,1 ImtO method 1<, chen l of the de<lg n pallcm appllCal,on We
, ,II use the tern, d,",1rol, fort he ommuI1Ity of cI,ents T yp, ally, the cI,ent Ull/' Z« the d<-<;,!!n pallern ,pphcatlon
onl y through spe , ted methods of speclflcd clas<cs of the des,gn patlern ,ppi.c.tlon The>c methods and cI",scs
onSlitule the ",,,,mce of the pallern apphcat,o n. In the case of the K,tchenVicwcr deSign, for ex,mple, the
'"terl.ee con"StS of ti,e cia, e K,lc/'",Sry/" K' ICh'fI, WoIICnb,,"I, and Floor au",,1. I,ents may nOlrder to any other
parts of thIS p'lIem app /'callon, and they generally do not overlap the desig n pallern ,pplicatlon.

17.4.3.3 The Setup Role

The third role involved 10 the usage of design p.llems is not terribl y Significant. but o ne ca n get co nfused If
o ne docs not recog 01 zc its pn:sc ncc: and necessi ty , It co nsists of the code that initiali zes o r hangcs the design
pauern applica non code at runtim e. YOli ca n think of th is as a ja nitoria l or housekeeping-role In th e
KitchenV,ewer des'gn , fo r example, cI,ents specifically do not reference particular styles, such as Mod,,,,-
KSry/, Reca ll that rrndrrKilc/'",O takes a Kilc/',,,Slyl, object as parameter, and deliberatel y docs not rderence
any subclass of Kilch,,,Sry/c. How arc these speCific style objects selected and instantiatedl Th, s is the task of
what we w.ll call the Stlup rol,. In the KitchcnViewer de 'gn, ,t is the code that r« po nd to cl icks o n ,he "Style"
buttons ," Figure 17 4 by ,"Slantiallng a Kitcb",Styl, object and calling ,mdrrKitcb,"O wi th this parameter va lue
Setup code needs access to man y parts or the applicati o n, is no rmall y runtime inten ivc , and is ty pically
no t Intended ror reuse Thi is becau e it tend s to be speci al to th e application and beca use it d epends o n too
many other classes. O nc can think of the setup role as not overlappin g ei th er the client o r the design paucrn
application, although both arc possible.

17.5 SELECTED CREATIONAL DESIGN PATTERNS

11,is section dcscnbcs the SIOgleton and Ab tract Factory design patterns as examples of creationa l design pattems.

17 .5.1 Singleton

17.5.1 .1 Design purpose of Singleton


Alt hough a typica l class allows the crea tion of many insta nct."S at nlntime. we ohen want a class to have exactly
o ne instance throughout th e appli cati o n, and no more. For example, many applications maintain a profile of the
use r. Often, there is no need fo r more than one U S(( instance at runtime . In f<lct , the eXistence of marc than
one InSlance cou ld lead to problems where one parr of the application c hanges the user's profilc in one wayan onc
Instance t and another part in another way on another instance. Thi S leads to an incorrect impl ementation. We
want a guarlmtcc of onc and o n~y one lIser instance al runtlmc . Fi gure 17 . 19 summan zes the purpose of Singleton.

DeSign Purpose
Ensure that th ere is exactl y one insta nce of a class S. Be abl e to obtain the
instance from anywht.·re In the appli ca ti o n

DeSign Pattern Summary

Make the constructor of 5 private; define a private stallc .tt"bute for 5 of type 5,
define a public accessor for it

Figure 17.19 DeSign purpose of Singleton


SELECTED CREATIDNAL DESIGN PATTERNS 401

We ",(er to the desired un ique instantia tion as the ""glrlo" of the class. and the class as a Smgltlo" class.

17.5.1.2 The Singleton Interface for Clients

As an example. if an apphcation ha< a U", class as described above, chcnt mothods 'uch as ocrifyAcctSs() .nd
snuIbn,,,IToU rr() would require a reference to the Si ngleton of Ustr To get the Si ngleton , they would con t.in •
st.tement such. the following :

User user = User . getTheUser ( ) ;

This requires that grln"Ustr() is a static method of LIm . NotICe again that a statement such as the
(ollowing:

User user = new User () ;

would crea te a truly new U'tr object , fai ling to guara nt ee the require men t that th ere be only o ne U,,,
instance.

17.5.1.3 TheS;ngleton Class Model

The first issue is· where do we put the sing le insta nce of our class) We wi ll nam e the class in question S. A
good place is within 5 itself, as a static variable. So far so good- but the problem is, what's to StOP another
pan of the appliCation from including the following sta:emen t

S myVeryOwnlnstanceOfS = new S ( ) ;

We prevent this by making thc const ructo r SOprivate. The o nl y remaining ISSUC is a way to obtain the
singkton, to do th iS we include in 5 a public statIC acce sor meth od
The Singleton design patlern IS actua ll y a specia l case of Factory in which the obje treturned I the o ne and
only in tance of the class With the Factory met hod. Si ngleton IS thus in the Delegation form · the method getti ng
the Singleton delegates ItS creation to the construc tor. The class model for Si ng leton IS , hown in Figure 17.20.
Let's sum up thIS dl<CU<Slon. Suppo<e that 5 is a class for which "'e requ ire one and only one instan e.
The Singleton deS ign patlern consi IS o f th e stcps shown in Figure 17 .21 .
Making the constructor of the class MyClnll private prevents the crea tion of MyCln" o bject except by
methods of Myeln" itself My In 5 IS given a tatic dal" member of t)' pe MyCl"" thaI ",'" be the Singleton
Ld, name this ob,cct ' IHtJ'rloIlOjMyCiall A public static f"Clory mtlh od 01 My la» ,!1/1S",glrloll ifilly IIIs, O. IS
defined that re turns 5,"glrI0IlO!My( In5s. Thus, to get thIS onc and on ly clement of IIlyCln's . "' e merel ,n\' ke
MyOass grISmglrlo"OjMYC/fIl'()
Our di'KuSSlo n on Inl(lcton doc not aU Io m.1I ally extend to clients operat ing "' parallel thread"
needing a e" to a SlnK'c to ll abJeCl
402 CHAPTER 17 SOFTWARE DESIGN PATIERNS

Client
,
I
I

I Singleton Design Pattern


I
I
I
MyClass slngletonOfMyCla..
"
getSingletonOfMyClassO: MyClass -static,.
1

FIgure 17.20 SlI7gleton class model

I . Dcnne a priva,. static member vari.ble of MyCiass of type MyCl.ss

private static MyClass sing letonOfMyClas s II: new MyClass () ;

2. Make the constructor of MyCiass priv.tc

private MyCla.ss () I / . . . . . constructo r co de . . . . "' / ) ;

3. Dennc a public static mcthod to .CtcSS the member

publlC static f1yClass getSingletonOfMyClass ()


I
ret.urn singletonOft1yClass ;
I

Figure 17.21 The Singleton design pattern, applied to MyClass

17.5.1.4 Example Singleton Application: "Experiment"

Let's look al Ihe following example,


An applicalion evaluates the results of lab experiments. The application for this phase does no
substantive evaluation . takes no input, and always prints the (ollowlOg message to the console:

Tht analYSIS shows Ibal tin cxptrimrnr was n rtSo~"dj"9 success

There is 10 be exactly one Exprri .."" objoct .t runtime, and it can be accessed by any mcthod in the
application. Each time the method is called, it displays the following message on the console to verify it was
called,

Noting thai the Exptn°".mt si"9'tfon rrjcrmc(d n limcs so Ittr


The output would havc the appearance ,hown in Figure 17.22 .
The simple c1.ss model for this experiment example is shown," Figure '7.20.
E_---

SELECTED CREAnONAL DESIGN PAffiRNS 403

Output

otEng that the Expenmt", si ngleton referenced I tEmes so far


The anal SI show that the experiment was a reliounding success ..

Figure 17.22 Output for Singleton Expe"ment example

E~ment
IheEx~riment; Ex riment
IClient f- - - - - analyzeO
theExperiment
.. static ..
getTheExperimenr{): Experiment
reportResultsO

Figure 17.23 APplication of Singleton to Experiment example

17.5.2 Abstract Factory

Now we turn our attent Eon to the creation ofjamilirs of o bjects. ThE S kEnd of problem was discu< cd En SectEo n
17. 1 using the KitchcnMasrer example.

17.5.2.1 Design Purpose of Abstract Factory

Our design purpose here IS to create a fami ly of related o bjects, chosen at runtEme from several pOSSible
families. You can ofte n think of a "family" here as a "style" choice . \VIc want to be able to ",nte code that
appl ies to these families without committ ing to one parlEcular family .
As an example, consider a word processor requirement that all ows th e user to view a document in everal
styles Modern word processors all ow users to view documents in a variety of ways, for example, En outli ne
form, shOWing only the headings. We w:ll si mpli fy this for Ellustration. TYP Ecal input to our pnmitive word
processor i shown En FEgure 17.24 .

- Enter title , - Entcr text


My Life I 8rew up playing in the wood •

- Enter Heading o r '··done", - Enter Heading or "·done".


Birth Ad ulthood

-+ Emcr text.
I was born In a sma ll mountaEn hut - EntC< Headi ng o r "· done·
·don(·
- Enter Headlni( or "·done·'·
Youth (toll ""!ltd )

Flcure 17.24 Word processor Interaction, 1 of 2- lnput


404 CHAPTER 17 SOFTWARE DESIGN PAITERNS

1
.... ." .
» Enler Ihe style you wanl displayed: » Enter tile style you want displayed:
big small ,

Option 1 Option 2
My Lile
--- Title: MY LIFE ----
Birth
Section 1. - BIRTH -- I was born in a mountain hut ....
I was born In a mountain hut ." .
Youth
Section 2. - YOUTH --- I grew up sturdy ".
I grew up sturdy ...
Adulthood
Section 3. - ADULTHOOD ---
•• • •

Figure 17.2S Word processor interaction, 2 of 2-output options

The application prints the document in a variety of styles. For si mplicity, we will use ,mall and big styles.
In ,mall style output , all headings are in left-justified lowercase a nd end with a colon. In bl!! style they are
capitalized with sectio n numbering, and so o n . The tide a nd the various subheadings appear differently in
these IWO styles. \VIc can assu me that mo re sty les wi ll be required in the future . The o utput for "small" a nd
"big" styles is shown in Figure 17 .25 .
\Vle want a design with a clean separation into the wo rd manipulC)tion pan and the srylc choice part. We
capture the various kinds of headings wi th classes In general , a · style" In volves a fa m ily of classes. For
example, CapitalStyle ,nvolves the classes Capit"ITit/e , CapilalLc"elrHcndin9 , Ca," laILevei2Hcnding , and so o n, so
the proble m is to be able to c ha nge the fa mil y at run time . The purpose of Abstract Factory, as expressed by
Gamma et aI. , is as shown ,n Fig ure 17 .26.
The rest of this sec tion explains the pattern that fulfills this purpose

Design Purpose

"Provide an interface for creating families of


related or dependent objects without s pecifying
their concrete classes .'"

Design Pattern

Capture fa mily creat ion 10 a clas comaining a


facto ry meth od for each class in Ihe fa m ily .

Figure 17.26 Design purpose of Absttact Factory

'Erich Gamma e( ai , "D~19n P;1t1C!ms, E1c.mc.'nts of Rcn~ablC' ObJC'cl ·OncmC'd Software: Addi~on . \'(I~.h~y. 1995.
--------------------------------~-------~

SELECTED CREATIONAL DESIGN PATTERNS 405

Client

-"
-"
-"
I
I \\ '<.,. . . . . ..........
Ensemble -"
-"
-"
-"
I
I \
, " " ..........
......
AbstractFactory
-" I getAPanl0bjeciO
setAbSlraC1FacloryO '" I
I
\
\ "" getAPal120bjeciO
doAFunclion() I \ ""
I
I \
\ ""
I \
\
""
"
Sty leA Factory StyleBFactory Style ....
Abstract Factory· ..J

• relationships within panem apphcallon not shown

Figure 17.27 The interface to Abstract Factory

17.5.2.2 The Abstract Factory Interface for Clients

Oient code has acce£s La the ent ily 10 be co nstructed wilh Ihe fa mll, es We wi ll name Ihis class EII s""bl, In
general. The class AbslraclFaclory encapsu lates the sryle of Ihe EII" ..bl, pans. The Inlerface fo r the client has
the appearance of Figure 1727 .
For a discussion on a narrowe r intcrbce alterna tive using the Facade deSIgn pattern , sec SectIon
17.6. 1. I . Fo r our word processor example , the role of EIIs""bl, would be held by a class such a OocllmClfl, wh,ch
suppo rts methods dependent upo n Slyl, (our Abstract Factory). First the chent or setup code-ha to
determine the required sry le, ty pica lly de pend ing o n use r input as in the fo ll ow ,n g

Style currentStyle;
... II interact with the user
currentStyle = new SmallStyle ( ) ;
_ . . or
curren tStyle = new LargeStyle ( ) ;
• • •
document . setStyle ( currentStyle ) ;

O nce the ty le has been sc t, the client makes calls to OocII,"rll l uch do ""'rIIl dlSplay(J. A cia. model for
thIS would have the appea rance of F,gure 17 28 .
But what does a "sty le" cla.s look hke, and how does it ac hieve our purposesl

17.5.2,3 The Abstract Factory Class Model

The Abstract Factory de<lg n patlern usc, a c lass 10 cn Uect coo rd Ina led fa cto ry met ho ds "' one plJ <, one
class pcr "style " In the <land.rd "allern , the base cia" for the<c >Iyle cI~s,cs ,s nJm ed Abs lflltlF" lory The
,dea IS that e.ch AbslrtICIFtlCIOry ,ub Ia<' In lerprets ,I> fa~lory m e l ho ds to produce obit I> of, s,ng le,t Ie
Abstract faclory IS ,n th' dcle/(.lIon form , dd el!a llll ~ the "ge lle r " of Ob,CC h 10 Ol1, lru l(lro. all In Ihe
deslfcd style
406 CHAPTER 17 SOFTWARE DESIGN PAITERNS

Document
Slyle
setStyle()
display()
/
/
/ // r---'---, r - - - ' - -
/ /' Small Style LargeStyle
/ /

/
/
//~----:::-------
/"
/

-
- --
/ // -
" -- --
/

• • • • • • •

IClient r':'" ~~ - L _ _......:.A.::p:.::P:..li.:.ca.:.t:..io:..n_o


.:.'.:.A
.:.b:..s:..l.:.
ra_C_1 _F._a_cI_o-,ry~
FIgure 17.28 The interface of Abstract Factory applied to word processor example

For th.e "ke of SimpliCIty we wi ll iliustTate this with just one sty le to beglO with . Let's call the class whose
complex objects arc to be constructed, ElIsrmblt. pigllre 17.29 shows how E" Stmblt objects are constructed in a
style encapsulated as SlyltA . E"s""blt consists of parts, Pari' objects, Pari> objects. and so on. The attribute
abslraclFaclory of E" s""blt is instantiated with a SlyltAFaclory objec, 10 ,his case. When a Pari' objec, is required,
the gtlAParl,Objtcl() method of abslraelFaclory is c,lIed . The virtual function property implies Ihat the
gtIAParl , Objtcl() method of StyltAFaclory is actu,lIy c,lIed, ,nd it returns a ParifStyltA object. Similarly, when
griParl2 0 bjtcl() of Ens""blt is called. it returns a Parl>StylcA object. Thus, all of the parts obtained are in the
same style . 11,e p,rtial class model is shown in Figure 17.29.
The full Absiraci Faclory class model . with two styles (AbslraclFaclory subclasses) is shown in Figure 17.30.
As dIscussed in t'he section above on client intcrf-accs, the client may interface with the AbsrracrFacrory
,nd PariX classes bu, specifically not with Ihe ,ubclasses of Par" . Pari> , and so on .

AbstractFactory
aMb.&::tFaclory 1
Ensemble gelAPan lOblectO -1
r selAbstract FactoryO golAPar120blectO I
I doAFunctionO 7'i 1
1
1
y 1
I
I Part 1 Part2 I
1 1
I L C. 1
I I
I I
I Part! StyieA Part2StyleA 1
I
1 " ,, 1
1
1
1 ......................... ,, I
I
1 , , , , StyleAFactory I
I -cr.e. ........ 1
1 " :.J:~panl0biectO I
1 , IAPar12Objoe'O I
1 1
I 1
I I 1
I I
I
------------ ---- - - ---- ----- - - - -- Client ----
I

Figure 17.29 The Idea of the Factory design pattern


SELECTED CREAnONAL DESIGN PATIERNS 407

-,
AbstractFactory
abstraclFaclory 1
Ensemble getAPartl0blecl() -I
doAFunctlonO getAPart20blecl() I
I
1.. n 1..n I
~
I
Partt Part2 Part... I
I
I
I
I
I
Part1 StyieA Part 1StyieB Part2StyleA Part2StyleB I
I
I
"- .... .... ,- I
I
I
"-
"-
"-
.... ....
.... .- " " ,-
,- I
I -creat... " "
,,' ,- I
I ....
, " .... , , ,- I
I
"-
" .... ....
I
"- " .... ,- " I
I
I
" I
Sty leA Factory StyleBFactory Style .... I
I I
I ""C"- _
-- - -- - - - ~ _ -'7
I
I
I1_______________________ _ -- -- I
I
Client -----------~

Figure 17.30 Abstract Factory

17.5.2.4 The Abstract Factory Sequence Diagram

A sequence dIagram for Abstract Fa ctory , including th e se ttlnB up of the parti cu lar "sty le" (the Ab,lracl Fa ctory
object ), is shown In Figure 17.3 1

17.5.2.5 EXample Abstract Factory Application : Word Processor

We now show the deSIg n of our Word Processor example USlnS the Abstract Fa tory deSIgn pattern The
follOWing use ca es describe the app licalJon

View a Docume nt

Precondition : none

I ApplICa tIon requests the tit le of the do umenl

2 US" provlde< th e litle


3. The "Headlngffext" usc case (see below) IS executed unttl the user enters "do ne"
4 AppllCa/lo" reque tS a style (r01l1 a lISt
5 UStr ent ' r' a sty le from the It,t
6 Applica tion ou tpu" th e do ument to the monitor In the sty le r<q ue'ted

The followln~ " the "11 .(hnWfext" use Ca>" rdere n cd above
408 CHAPTER 17 SOFlWARE DESIGN PA" ERNS

:Cllent abstractFactory :Ensemble


r ...J
:StyleXFactory
abstractFactory
I :AbstractFactory
Style XFaclo 0'
, ~

Selecting

setAbstraclFaclory a sryle
(abstracIFaclory)
I :Pa rU StyleX I
I
doAFunctlon O
.,.. getAPa rUO
Assume that ----
./
""~
I
Creating
objeclln
a ParU
this method
- / ge tAPa rUO I
required styIe
requIres a
...../1
ParUobject Part.J SlyleXO
, +rl
,•I
Virtual •
j
function
property

Figu re 17.31 Sequence diagram for Abstract Factory

Provide Hcadingrrext
Preco nditlons- user has provided the title
1. ApplICa ti on reques-ts a header
2. Usrr provides hcadcr tcxt
3 AppJlca lrol1 requcs ts text
4. U", provides tcxt to fit with thc header
Thc class modcl IS shown In Figure 17.32 .
T ypical output is shown in Figure 17.33.

17.6 SELECTED STRUCTURAL DESIGN PATTERNS

This seClion describes the Facadc and Adap<c r dCSlgn patterns as exam ples of structural design patterns.

17 .6.1 Facade: Interfacing with a Collection of Classes

17.6.1.1 The Design Purpose of Facade

In bUilding applications we parcel out sets of classes to separate developers Th is reqUires the clear
modularization of the design Developers typically require the <CrYlces of classes thar orhers are responSIble
SElECTED STRUCTURAL DESIGN PATIERNS 409

Document Style
style
geIAH.ad,ngO gelAHeadlngO
r-------, I
gelATilleO I Displa yable I gelA Tit/eO I
grtDocumenlFromUserO I
: dlsplayQ :
O•. n -- --- I
L ~
I
O••n I
Text• __ "-_--I Heading 1 I
Title
value v value I
'--- D,splayable '--7\""',-_.J value
:--7\:--
, ~

r
SmaliHeading LargeHeading I~ LargeTitie
d,splayO displayO dlsplayO d,splayO

'--~----
Ioj create» - - - -
~-~-r-~-~-~-~~~~-~--~-----
c.:::.- -
- - - -
~ LargeStyle
gelAHeadingO gelAHeadingO
gelAnlleO gelATille()
~, _.:::7

Client
gelStyleF romUser() -- - ----------- --~
dlsplayDocumenl()

Figure 17.32 Abstract Factory applied to word processor

- Enter the title of your document·


MY LIFE
- Enter heading o r '-done',
Birth
......,. Emc r the text:
I was born In a mountain hut
- Enter heading or '-do ne'·
Youth
'"""'7 Enter the tex t·
I grew up sturd y
- Enler headin g o r '-done'
-done
- Enter the <tyle you wa nt d i played ('small' o r 'large'),
largo

- -T,tle MY LlFE-
SectIon I - IlIKTH-
J wac, b(}rn In a moun lain hut •

Section 2 Youth- -
I grew up ,turdy

Figure 17.33 InteraC110n for word processor applica tion


410 CHAPTER 17 SOFlWARE OESIGN PATIERNS

Desig n Purpose

Provide an IIlter(ace LO a packa ge of classes.

Design Pallern Summary


Denne a inglelOn tha, ",he o le means (or
ob,alll lllg (un c 'ionali ,y (rom ,he package.

Nol<, The clas,es need no ' be o rga nlZl:d as a package;


mo re ,han o ne class may be used (o r ,he (acade.

Figure 17.34 oesign purpose of Facade

'0
for developlllg, so ,hat classes and packages ohe n ,elalC each o,her as clien! and server. The client a nd server
portio ns are deve lo ped re la'ively independently-,he problem is ,h., services arc typica ll y in va rious Sla' es o(
comple<ion as 'he projee! progresses. Complexi'y is grea 'ly reduced when ,here is juSI o ne o bjee! providin g
access to ,he fu ncllonality of a collectio n of classes.
A component acts cffcctivc:ly as a server when its interface is narrow. "Narrow" means that the inte rface
(I.e., a collection o( functio ns) conta ins no unnecessaty parts, is coll ected in o ne place, and is clearly defined.
The Facade design pattern e5lablishes juS! such an in,e rface ' 0 a package of classes. Facade regulates
communica ,io n wi,h the objects in ilS package by exposlllg o nl y o ne objee! of th e package ' 0 client code o(
the package, hiding all of 'he ot her classes. This helps organize developmen, because the programmers
responsible fo r a package can publicize th e services offered by a Facade o bjtet and stub them while ,he
package is under development. ("Srubbin g" is temporarily substitutin g the rea l content w ith very simplisti c
content, o r perhaps wi, h none at all .)
Clients o( ,he package have a conc rete reprosen,a'ion of 'he package's fu nctionality to use during
development . Th is Jdva ntagc extends to maintena nce. If maintainers can upgrade rhe way in which
functionality is coded wi,hou , d islU rbing the fa~a de , 'hey can be assured ,ha, all clients of the package
are not affected . The Facade objee, is a ,y picaliy a singlelOn . Figure 17.34 summan zes the design purpose and
technique of Facade

17.6.1.2 Interface for Clients of Facade

Suppose ,ha' a package contains a collection of classes and tha, 'he cl ient code, extemal to th e package, requires
a «rvice myCMtlhod() provided by a class C in th e package The c1 ,en' may interface o nly with the Facade
object, which we Will ca ll Ih,FacadrOhjrcl. Thus, the clien' code calls a method suc h as Mrt/)odOjFaeaa,Q
of Ih,Facad,Objtcl in order to accomplish this purpose.

17.6.1 .3 The Facade Class Model

The Faead, class model shows c1ien" inlCrfaci ng with a single class of a package, bu, With no o ,hers. Actually,
there is nothing to stop us from designaring more than o ne class as a Fncadt class. The non-Facadt c1as es a~
no' ac"<sible to code extemal to the packa ge. The Faeaar structure IS ,n 'he Delegation form since the Faead,
object delcgales commands '0
classes intemal '0
its package. This IS Illus trated In Figure 17 35 .
SELEC I EO STRUCTURAl DESIGN PATIERNS 4"

, 1
"- Fat;;ade
Client - .. - exposed.. I-not eXPOSed-I
cMelhodOfFacadeO
" "- I
This cat!
repla ced
"" I
I 2 I- not eXPOSed- I
by t an d 2. "" I
Client can't
reference C
" C
.. not exposed.. I.. not e~posed.. 1
myCMelhod()

I-nol exposed-I I .. not exposed.. j

Figure 17.35 Facade deSign pattern structure

A call that ",ould o ther"" e refer to an o bject o f a class wIthin th~ package IS repl aced by a ca ll to a
method of the Farad, object ThIS metho d ca n then referen ce the obJect'" que<lIon The seq uen c~ d,agram IS
shown," Fi gure 17.36

:Client si ngleton :C
'--
:Facade

cMethodOfFacadeO

myCMelhodO

(return it any)
---- -- - - - - --
(relurn If any)
- --- ----------

Figure , 7 .36 sequence diagram for Facade


412 CHAPTtR 17 SOFTWARE DESIGN PATTERNS

MyGameEnglne

MyGame
. '6CJJde IJ
MyGameCharacters

MyGameCast
f.,fsellde" MyGameEnvironment

MyGameEnvironment
,.fscs del>l

Figure 17.37 Using Facade for the architecture of the Encounter video game

17.6.1.4 Examples of Facade Applications

17.6.1.4.1 Using Facade for a videogame Architecture


TI1C'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.

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 413

obtained trom \nVC ling .ll!pv<:n amOunt (or a given number of year In a pcclaltypc of Investment , and
WC' want to u~c lhl) (lin [tonality In u~ing Ihi~ functionality . however, we want to modify our own

application as Imle a po<slblc . \VIe also w.nt to be able to easily witch to alternatwe
ImplementatIon> of tht· required functlonaltty F,gure 17 38 ummartze the e purposes and the baSIC
Adapter technIque

17.6.2.2 Interface for Clients of Adapter

The "client" IS the apphcatlon that must 1I e the ex. ling funcnonahry We create a deSign In whICh the chent
doe not directly Interract' wtlh the t:XiSllflg fun uonalay, however In lead. It Interra cs with <:In Clbstracl
method of an app roprtately named ab trac t class. The laller must be In tan!tated al runtime with an object of a
concrete ubclass. as exp lained next.
Let' call the ab,tract cia
AbslrnclClass . and ItS relevant method we need sta>ldllIForR<qu,,<dAt<lhod() .
Cltent code would be om"th,ng like the fo ll owing .

· -. - .
AbstractClass anAbstractClassObject:
... .. II setup code instantiates ... nAbstrdctC!a.s"Ob)ect
• • • •

anADstractClassObject.clientNameForRequ1redMethod() ; Il usetheexternalfunctionality
• • • • •

Setup code , tYPically executed at initialization , must in tanliatc cwAbslraCICltlSsOb)(ct at runtime In


somethIng like the fo ll owing manner.

• • • • •

if( ... ) Ile . g .,


from a setup file
{ anAbstractClassObj ec t = new ConcreteSubclassOfAbstractClass ( ) ;
• • • •

17.6.2.3 The Adapter Class Model

The d ..s model for IIdapt" IS ba ed on ,he delegation foml because an Adapl" o bject delegate> the o mmand
to the tars,;eted ommand , as <hown in F,gure 17 39

17.6.2.4 The Adapter sequence Diagram

Adapter works by handIng off function ca lls to cilclltNllnt,ForR,qllll"iAI<llrotl() as shown '" h~lIre I i ·,0
.1. CHAPTER 17 SOFTWARE DESIGN PAmRNS

alent adaplee

( ad'poee.requlredMoUIOdO:) I
Figure 17.39 The Adapter class mOClel

:Client I :AbstractClass I

:Adapter adaptee
:RequiredClaSS
I
I
I
d 'entNameFotftequ1redMethodO I
RequiredMelhodO
I
I
I
I
I
I
I
I
I

Figure 17.40 Sequence dlagram for Adapter

17.6.2.5 Example Applications of Adapter

Lds consider a Rnanci.1 application that needs to use the met hod

computeValue( float years, float interest, float amount)

of a legacy class Pn"cipit . We want to b<: ab le to e.sily switch to other impleme nt.tio ns of th is functionality if
necessary. We write our applica"on by giving our own names to the function of interest, and the class/object
that owns the function. For example , we can name a method as follows,

.mount ( float or iqinal"mount, float nllmYears, float intRate )

in the class F""",cial. This cia" is made abstract, as illustrated in Figu~ 17.41 .
SELECTED STRUCTURAL DESIGN PATTERNS 41 5

.,
AI!~lIcation Ada~latJon Legacy system

Financial
amountO Principle
computeValue()
...J

Client FinancialAda pter IOO)cyAdolplee

amountO "

.-------~~~----. "
( legacyAdaptee.computeValueO: )

Figure 17.41 An application of the Adapter design pattern

The Adaprc::r design pauern in this case co nsists of a class, which we wli l name: FlllulICltJ lAdap lt r here,
",hlch onherits fro m the application' c las (Flllllllnal on ou r case), and whIch aggregates the legacy cia s
Pmlnpal. This could be Impleme nted as follows .

class FinancialAdapter extends Financial


{
Pr incipal legacyAdaptee = null ;
/ / Constructors go here . . .

/** This method uses the legacy computeValue () meth od * /


floatamount (floa toriginalAmount , floatnumYears , floatintR ate)
{
return legacyAdaptee . computeValue
( originalAmount , numYears , i ntRate ) ;
}
}

The new application IS W,;ltt'l aga inst the clas ... Fmannai , but o 'cudcd at runt ime with OJ FmtH1CIaiAdapltr
object Setup code instantiates the Flt1tHlClfil obJcc t a'\ a FlllolicIfI1Adtlptr Insta n (' For example , the Ilcnt cou ld
be wflttt'n w ith a method parametenzing Fmatl cw/ , such a~ th c roll0,o,I,ng

void executeF inanceApplica t ion ( F inanc ial aF inanc ial ) ;

It cou ld ,hen b~ exe~utl·d "",h ,he followIng s" rr p 'tatement th"",,llZe' ,h e opprop""c ,ciop,cr obIt: t

executePinanceApplication( new FinancialAdaptcr () ) ;


416 CHAPTER 17 SOFTWARE DESIGN PATTERNS

octlonListencr
ActlonLislener
Resull 0 1 bunon (!f§SS

MyBulton MyClass
addAClIOnUslenerO myMethodO

Mylistener
actionPerlormedO
~

Figure 17.42 Adapter and the Java API

All ca lls '0


the amo unlO method of Fillan,ia/ arc passed to the legacy method compulrVa/urO
I. IScasy to adapt the applicatIon to an implementation ofamo,,"10 in a new class. We would on ly ha ve to
change the code on FinmlCialAJllplrr. The rest of the applocallo n would not be affected. Being able to re target
code by makong loealozed c hanges like this is valuable for development and maintenance. The alternative is
making changes In mult iple locatio ns, which is error-prone.

17.6.2.6 Adapter and the Java API

lava arc adapters for the following reason. Suppose that we want myMrlhod() in MyOaS5 to execute
liSlClftr5
whenever myBllffotl is pressed.. T o do this , we introduce a class MyListrncr that implements thc ActionLslcncr
onterface . The class model is shown on Figure 17.42 .
The class MyLis lrtl cr IS the adapter class in thi s casco At runtime ....u: ca n insta nt ia te aclionLisltH" with an
Acllotlustcntr subcla ss in lance slich as MyListtncr, according to thc effect we require when the button is clicked.
nle code in Myl3ulto" rderenccs only Acliol1USlt1ltr, not any particular subcla s.

17.6.2.7 Comments on Adapter

• Instead of aggrega ting RrquirrdClass on Figure 17.39, we could onherit from it, as long as the language allows
multIple inheritance. Thi s is shown in Figure 17.43 .

AbslractClsss

Cllen.

( requtredMethod():)

Figure 17.43 Adapter example inheritance version


SELECTED BEHAVIORAl DESIGN PATTERNS 417

~ ' c m. , be .tlSfied to make Abslra 10alS an Interface If the language does not suppo rt multiple
,"hentJn c le g ,I.va)

• Adapter IS often usC' d when we reate an application U1\lng library c1as es. bu t where we want to retain the
lle.,ib,l, ty to >ck· t other "brary clas e< For ~xampl e . we n1lgln use Verlo, In a Java application to store a
oilcctlo n, but find that It I> ,omcwha t awkward for the purpo e In question. \'(Ic could rhen de Ig n and code
thc application so that It use. an Ideal class of ou r IIl ve nti o n to store a co ilec tl on (e g., AUlomobilts ,vith meth ods
SlonA IIIO() e tc,), Then we wo uld incorporate a n adapter to fit th iS to Vrrlor \'(Ihen a mo re " " table o ilrc tlo n
managemenr l as~ appears, we could then ea dy retarge t to it , nceding to change onl y rhe adap ter

• Rewrntng (0 the fina ncial example, lO preserve the opti on to retarge t a1 runtim e , we cou ld rela in
FuulHClalAdap'rr, but Int roduce a new Adaptu class FlllmlClnfAdaptrr2 , inheri ting (rom FU1anCIai Whenever
we want to targe t the application to the t(o nd lega )' SYCi lem , we wou ld execute th e applICatIOn Wit h the
following .

execut eFinanceApplication( new Financ ialAdapter2() ) ;

17.7 SELECTED BEHAVIORAL DESI'GN PATIERNS

This seClio n describes the Interprete r a nd Observer d t's ign patterns as exa mpl es of particu lar behaVioral
design patterns.

17.7.1 Interpreter: parsing Expressions

17.7.1.1 Interpreter Design Purposes and Examples

Appl icati ons must somellmes deal wit h n:prcs5Io"S written Ir. J grommar. A comp lier, fo r example, must deal with
r xpressions wntt'c n in the grammar of a programming languJge. Compdcrs are th e: most common example,
but the,. arc many other needs for the interpretation of g rammars, The following X/l.tL, for example , IS an
expression, and the gram mar (ca ll ed a sci",,, • . no t exp liCi tl y g ive n here ) >pecii;e the permISSible form for the
XML used In thiS context.


«engl.neer > >
« nam e»
John Q . Doe
« /name»
«task»
Un iversal payroll Application
<<' /task > >
«task>.-
lnterglactic Web Site Analyzer
«/task>.-
<.-task»
"a CHAPTER 17 SORWARE DESIGN PAffiRNS

Financial For ecaster


«/task»
«/engineer »

Our purpose is to desig n an interpreter for gra mma rs. In th e XML example, our Interpreter should ~
able to interpret the fo llowi n g expresSIO n as we ll .


«engineer»
«name»
Sue W. Smith
«/name»
«task»
Fr iendly Server Application
«/task»
«task»
Intergalactic Web Site Analyzer
«/task»
«/engineer»

There are two parts relating to the Interpreter desig n pattern : pars"'9 and inlcrprcting . Parsi ng is the
process of converting an input-usually a string-into a trce of objects consistent with rhc c lass model . In the
XML example, this would include picking o ut individual pieces suc h as the engineer's name. Interpreting
consis ts of performing useful functionality with the result of the parsing phase. The purpose and baSic
technique of Interpreter are summarized in Figure 17.44.

17.7.1.2 Interpreter Interfaces for Clients

Once an expression has been parsed and represented usi ng the Inltrprder class model , clients interface with an
Ab.t,acIExprnsio. object that is the root of the parse tree. The client typica ll y ca lls an i."rprt'() method o n th is

Oesign Purpose

Interpret expressions written In a fannal grammar.

Oesign Pattern Summary


Represent th e grammar using a
recursive design pattern fonn :

Pass the: interpretatio n to


aggregated o bjects.

Fllllre '7'" Design purpose and summary of Interpreter


...----------------------------.... -

SELECTED BEHAVIORAl DESIGN PATIERNS 419

AbstractExpression
Client - - ------
inlerprel()

Figure 17.4S Interface to Interpreter design pattern

objecl. In the above XML example, suppo e that the twO express,o n formed by parsmg the twO 'nputs are
joh.Do,XML and "" ""IJ,XML Suppose that the appitca l10 n IS Intended to co nvert XML to conversano nal
pro e. When the client execute Johl1DorXA1L '"trrprd(). the fo llow m8 m' ght be output

En9'"W Joh" Q Dor IS ••o.king Oil th, joJJowI119 Ihm prowls, UI1 ..",,,J PnyroJJ AppJi "lrOl1. J"trrgnlaclle W,b
Sift A"alyzer. mid Finml ial ForcctJStcr.

The class model for the clien t/deSig n pattern Interface looks like F'gure 17.45

17.7.1.3 The Interpreter Class Model

The Interpreter deSig n paltern has th e Rccurs l v~ (orm because ex pressIO ns can con tain fu rth er expressions.
The class model is showr. in Figure 17.46
AbstractExprcssJolI objects are ei th er TcrnliualExprrssioll objects, wh ich the Interpretation function IS
0 11
simple, or No" Tm"il1"IExprrssion o bjects The latter aggregate Ab, lrll IExprrsslon objects ,n turn The ,"I,rprrt()
/unctio n o n a NOl1Trfmm"IExprmiol1 objec t operate by perfo mllllg required work o n the object It elf. then
essentially commanding each of Its aggregated AhslraeIEx!)((ssiol1 objects to execute Its mlrrprrl() method. Th IS
has much in common wit h the dynam ic viewpOint of the Composite design pattern

17.7.1.4 The Interpreter Sequence Diagram

The sequence diagram in F,gun: 17..17 cap rure s th e Intcrprctilt ion process.

17.7.1.5 Example Interpreter Application: Network Assembly

As an example of In terpreter. consider an applicat ion that handles orders from customers fcr networked computer
systems, and genera tes installation ins[fuctlons Forcxali1ple,conslderthcorderrora network shown In Figure 17.48.

AbstractExpression 1..n
IClient ~- ------ Inlerprel()

TerminalExpression Non Terminal Expression


InlorprolO Inl.rpralO

Figure 17.46 The Interpreter design pattern


420 CHAPTER 17 SOFTWARE DESIGN PAmRNS

:Client AbstractExpresslon
:NonterminalExpression NonterminalExpression
Interpretl)
...
.. create and
~ TerminalExpression
interpretO

... create and


InterpretO

..l.

Figure 17.47 The Interpreter sequence diagram

It con<o<l< of a 700 ," ' hz system wi th 5 12 I\I~ of RAM connected to a system th at consi ts of the following twO
con nected co mpu tcrs

a 8001\ Ihz system wi th 768M B of RAM

a 5001\Ihz system with 51 2MB of RAM

T h ,s is Ill ustrat ed In F,gure 17.4 8.


Th iS o rde r ca n be expressed usi ng the fo ll owmg ex pressio n

{ ( 700 51 2 ) } { { ( 800 76 8 ) } { ( 500 512 ) } }

800 Mhz and 768 MB


assemble .. ..

. - "'-;
.

700 Mhz and 512 MB

500 Mhz and 512 MB

Figure 17.48 EXample of a virtual machine " program"


SOCICf GraphicS reprodU(:.ed wttrl pel " ,!ss'on from Corel
SELECTED BEHAVIORAL DESIGN PATTERNS 421

ll,e ou'pu' prod<tced by the application wou ld be instructions to th e techmcian , d escribing how to
perfoml the a"cmbl y.
The ma", u<c case fo r this exa mpl e IS as fo llow All 110 is to th e console .

1 The application prompts the user to enter an order

2. The appit at ion d,splay the gramma r to be u cd.

3. The apphcat, o n display, an examp le

4 . TIle user e nters an order.

5 The appit ca t, on echoes th e o rd er.

Figure 17.49 speciAes th e grammar for th e orders and hows typ,ca l inpu t.
The ord er exa mp le ,n Figure 17.49 is ,ndeed a legi tim ate expresSIo n in th e grammar speCIfied , as the
fo llOWing veri Ae .

co mpo nent - nc r sys tem -lo

{ component } { comp o ne nt } -
{{ compo ne nt } {compo ne nt} } { computer }-
{ { { compo nen t} {compo ne nt} } {computer }} { (cp u ram ) } ~
{ { {compute r } {computer }} { (cpu ram ) }} { (444 -1-1 ) }-
{ { { (cpu ram) } { (cpu ram ) }} { (333 33 ) }} { (44444 ) }->
( { { ( 11111 ) } { (22222 ) }}«33333) }}{ (44444 ) }

The output of the interpretati on process-instructio ns on how to assemble thi S ncf\.... o rklng ord er- are
as shown in Figures 17 .50, 17.5 1, and 17 .52 In this case, th e user se lected th e exa mple prov,ded by the
application.
Our Arst ta k is to parse the ,nput and create the corresponding set of aggregated objects. After that, t he
output is generated in respo nse to a clie nt ca ll ing aNr,workOrdtr.asscmblr(). ll,e metho d a"""blrO takes the
place of ,",crpr<'O in this example , The Inte rpret at, o n of a primi,i1lc e lement alone (e.g .• a CP U In the examp le ) 15

Please deSCribe a network on one line uSing th e follOWing grammar for 'component '
Blank paces arc ignored .

compo nent :; = net system I comp ut e r


net system . = { component 1 { component 1 1{ compo ne nt 1
computer = (cpu ram )
cpu-: = Intcger
ram - = Integer
xamp lc: { { {(400 4 111 ( 900 3)) 1 {( 600 3)1 1 { (750 10 ) 1
An '"put With a sy ntae ll <"rror w,lI be iJ.:norcd With lit comment.

{ 1{( 11 I I I ill (222 22 )) 1 {( 333 33 )1 1 { (444 44 ) 1


You chrxe { { {( III Il ll1 (222 22 )) 1 {(3 n 11 )111 ( 44 " 44 ) 1
Aaure 17.49 Input loe networ1< assembly example
422 CHAP I ER 17 SOFTWARE DESIGN PAffiRNS

Pk.se de>eribe • network on one line USI08 the (olloWIOB grammar (or 'compone nt ' Blank paces arc
,gnorod. Inputs w,th sy nt.ctic error< will be ignored withou t comment.

component :: = net system I computer


net system ;: = (component ) (component ) I (component )
computer ;: = (c pu ram )1
cpu :: = Integer
ram :: = integer

Examp\c, ({{( 400 4 )){ (900 3)1) {(600 3»)) {(750 10») {{{ (400 4)11 (900 3) 11 1(600 3)11 {(750 10 »)

.. . Do some work with the order . ...

Assemble a network from either one or two parts as (allows,

'* F,rst Part, Assemble a network, which we will name 'component 1', as (allows,
Assemble a network , which we will name 'cornponent2', from eit her one or two parts as follows ,
-
Assemble a network, which we will name 'component3', from either one or twO parts as follows ,
-
Build computer component3 , (rom th e (allowing parts,
CPU with specifications . .. . .' 400
and

Figure 17.50 Output for network assembly example, , of J

si mple (see the CPU class 10 the listing). What remains is to execute an i"trrprrt() function when applied to a
morc compl(x expression.
Applying the Interpreter design pattern to the netwo rk order example, we obtain the class diagram
shown in Figure 17.53 .
For simplicity , we assume that every network consists of just two components , so that each SyS'tmr object
aggrogates two Compo"",t objects. This can be easily extended to mar< than two. The so~rce code for the
implementation is contained in the accompanying textbook Web site.

17.7.2 Observer

17.7.2.1 The Design Purposes of Observer

Softwaro roquiremenlS and design frequently involve a source of data, together with a number of chents that
must be updated whenever the data changes. As an example, suppos< that the headquarters of Internation.1
Hamburger Corporation maintains data on its s(rvcr abour hamburger ~11es throughout thc- count-ry
Distribur~d cli~nts for this data include Senior Management, Marketing, and Operations. The data c hange
SELECTED BEHAVIORAl DESIGN PATTERNS 4 23

RAJ\\ w,th spe ,Rcatlon< . .4


erond part --

As cmble a network, wh, h we wdl name componenl4 , as follows.

A emble a network, wh ,ch we w,lI name 'compone nt 5', from c ,the r one or IwO pans a follows ,
~

Budd computer componcnl5, fro m ,he fo ll owi ng parts:


CPU wllh specifica tio ns.. .. 900
and
RAM w It h specIficat Ions .... 3

-Now co nnect componC'nl3 wi th componenl4 to comple te cornponent2-


second pan : -+

Assemble a ne lwo rk , whIc h we will name com po ne nt6 , as fo llows·

Assemble a network , which we will name 'cornpo ne nl7', from eithcr o ne or two parts as follows·

Budd com pUler compo ne nt7, fro m Ihe followlOg parts:


CPU with speciflCat,o ns..... 600
and
RAM with pecifications ..... 3
- ow connect co rnponent2 with component6 to complete component 1-

Figure 17.51 Output for network assembly example, 2 of 3

continually , and each of headquarters' clients nee ds 10 updale li S dISpla y accord, ng to thelf various
requireme",s. Lei's say , for example , Ihat Stlllor IVlaIl"gcmclIl's bar c hart muS! be lIpdated afte r a 5 percent
change has takcn place, Il'tnrkclillg d, splays a new P'C c hart when a c hange of atieasl I percenl has rake n pia e ,
and OperatlollS reqUIres lables 10 be updaled when every c hange lake place .

~ Second part Now assem bl e a nClwo rk, which we will name 'compone nt S', as follows

Assemble a network, whIC h we wd l name 'com po ne nI9', from eilher one o r two parts a fo ll ows:

Budd computer com ponent9, from Ihe fo llo wIO t! parIS'


PU WIth speclC. al lo n, 750
and
RAM wllh speCIficati ons 10

• • Now con nect component I With componentS to gC I th e rC!l.ulting n(, (work = --


--
00 more work wllh Ihc o rder.

Flcure 17.52 Output for networK assembly example, 3 of 3

,
.2. CHAPTER 17 SOFTWARE DESIGN PATTERNS

-----------.....,
: 99[!1PQ'lltnl I 0 .. 1
Client r ------L--->
1 ____8ssemb/eO
- __ _ _ _ ~

r -- -------- ----- --- -


I I
I
I
: component 1
I NetSl/stem
I component2
I assemble() J<
I
I
I
I t; , ~
I ,, •
,, ••
: cpu CPU
Setup
Computerf: describeQ
gelinpulFromUser()
assemble() RAM parseO
ram describe()

Figure 17.53 Application of Interpreter design pattern

Th~ Observer design pattern is imcndcd to address these rcquirern~ nts . Irs purposes and basic techn ique
arc summarized in Figure 17 .54 .

17.7.2.2 Observer Interfaces for Clients

Suppose that the abstr.lct class Sour('( IS aware of {he data source. Whenever a client want'S all observers to
,ake notice (Iypically, of a c han ge in Ihe data ), il ca lls a de sig naled melhod of So.rer . In Ihe modd below,
Ih,s mClhod is named "OlifyO. The c hen, IS sh,elded from Ihe manncr in which Observer ca,,-ies oul thos
process.

17.7 .2.3 The Observer Class Model

The partic in the Ob!'crver design pattern requiring updating arc known as observers, and arc subclasses of a
single abstract class, which we will call Ob5<tVrr. Thi pallern is in the Delegation form SInce SO.'IC delegalcs
thc updaling process to Ihe Obsrrvt, objects. The pattern os show n in Figure 17 .55 .

Design Purpose

Arrange for a «I of objects to


be affecled by a single object.

DeSign Pattern Summory

The single object aggregates Ihe set, calling


• method wilh a fixed name On each member.

FIgure 17.54 The design purpose and summary of the Obselver pattern
..

SELECTED BEHAVIORAL DESIGN PATIERNS 425

Server part Client part

,-- -. --- -- - --- - - - - -.-- .-- -- - - - ----,


Source Observer
nOlily(/f:( 1.. n updale()
2 Lr
'-
fOl all Observers 0 :
o.updateO:

ConcreleObserver
ConcreteSource
observerS tate
state
updateO
3 r -1: ..J

Figure 17.55 The Observer design pattern

\"lIe will follow a equencc of step to . how how Obs~rver op~rates

Step I The lie n'! references a known '"terface object, requesti ng that the observer, be no tified For
example, the client could be a process programmed to no ll ee that the data ha changed , or It could
be a c1oek·dri ven ta k In the model , this is shown as a (1,<11/ object telling the SOllrer object to
execute Its lIolify() functio n.
Step 2 The IIoli/Y() meth od calls the II pdn l' () func tion o n eac h of Ohscro" object that It agg regate,
Step 3 The Impl e me nta ll on of II pda l' O depends o n th e part icular (ollerrl,Ohs",'" to which It belongs
Usually, updnl'O compares the (ollere/,Oh,,,,·,, o bjec t's sta te (variabl e va lues ) wlfh that of the
cen tral dat a ouree on the serve r, then deCides whether or not to change It S va nable va lue,>
accordlOgl y It probably perform ot he r actions uch a erea lln g a new dlSpla

1ne class model tells u that evel)' Ohscro" reference, a object. In fact , the 'ollIT",Ob,,",,, Will
011 "
reference the oncrt !tSOufet obj e 1 at nm tl me H ow do the COllnclcObcn'(r objects kn ow to reference the
Conc rete ou rce object] \"lIe could pas a reference to It 10 the parameters 01 IIpdnl'(), ", IS do ne In the Java PI
(sec Section 1772 .5).

17.7.2.4 Example Observer Applications

17.7,2.4.1 " Hamburgers " Observer Example


ApplYing bscrver to o ur Inte rnauo nal H ambu rger orpora tl o n problem , we o btain. modd ,uch a, thai
shown In Figure 1756

17.7.2.4.2 Mutual Funds Observer Example


We ",'(1 Ulke., ano ther exa mple .pp(,cauon "I b,erver the updating of mutllal fllnd po nfo ll , 1\llItU. 1fu nd,
IOV(:\t "1mull1plc slock'} , ('0 Ih a l when it parll <..ulJr ') 10 k\ pn e t hJngco;; , It arlC_h till' "Iut., 0 1alllhc nlutual
funds th at In vc') l In It orrn all y. '!ouch change, In J 1)(0 k.... pn \' j'lrc IrJ lhmlllcd t'lt:ttrootLali In o\lr t:\ \unplc
426 CHAPTER 17 SOFlWARE DESIGN PAmRNS

Sow' part Cliont opa


Cllonl ,- --- - ------ --- - - - -- --- - -
,, 1.. n Observer
Source
,- - -- -)
notify() update!!

SenlorManagement
forecast
Headquarters update() Marketing
demand marketinaOemand
/ updale()
If( abs( hq.demand - marketlngDemand) > 0.01 ) doDisplay()

( marketing Demand = hq.getDemandO;
doDisptayO;
)

Figure 17.56 Observer applied to International Hamburger Corporation

we will make the change to Awesome Inc.'s stock by hand. The application will then display the resulting
changes in the mutual funds canying Awesome stock. We will use the OhsrrvtrlOhsrrvahlt java API to cany out
this d~sig n and implc:mentation .
The main usc case is as follows ;

I. The application reports the status of mutual funds that invest in Awesome Inc.

2. The following repeats until the user signiAes quitting.

2. 1. The application prompts the user to supply a price for Awesome stock.

2.2. The user enters a price in decimal f.orm.

2. 3. The application reports the status of mutua) funds that invest in Awesome Inc.

Figure 17.57 shows a typical scenario.


The cia" model is shown in Figure 17.58 .
This cia" model uses OhStrotr classes in the java API , which arc discussed next.

17.7.2.5 ObseNer in the Java API

Many of the design panerns discussed in this book are present in the java API. However, one recognizes them
by their form rather than by ~ame. Observer is one of the few pattems explicitly called alit by name in the
java API. The java API Ohstnltt class model is shown in Figure 17.59.
The java API uses virtually the same terms as Gamma ct al. Notice that "pJa/t( . ) is a callback
method in the sense that it provides Ohstrvtr objects a reference to its source, thereby enabhng them to
compare their data and so on with the OhSlrvahl, object in executing "pJa/t(j . Because update is
implcmc:ntcd as a callback, there is this no need for concrete Obsrrvtr classes to maintain rdcrenc('S
to the ObsfflJQblt object.
SELECTED BEHAVIORAl DESIGN PAIIERNS ~7

otc, HGrowt hMulualFund qarts w"h 3 sharcs of Awesome, assumes price of 1.0, and has non-Awesome
holdings totalling 4000
'ote· kdGrowthMutualFund ,tarts wi th 2 hares of Awesome, assumes price of 1.0, and has non·
Awesome holdings totalling 300.0
NOle, LoGrowthMut\JalFund lart with I share of Awesome, assumes price of 1.0, and has non -Awesome
holdlnb'S totalling 200.0

Enter 'quit': Any other Input l o com inue.


go on
Enter the CUrTent price of Awesome Inc. In deCimal form .
32. 1
Value of Lo Growth MUlua l Fund changed fTOm 201 .0 to 232 I
Value of Med Growth MUlual Fund changed from 302 .0 to 364.2
Value of Hi Growth Mutua l Fund changed fTO m 403 .0 10 496.3

Enter 'quit': Any other Input to co nt inue.


go on
Enecr lhe CUrTcnt price of Awesome Inc. in deC imal form .
21.0
Value of Lo Growth Mutual Fund changed from 232 . 1 10 221 .0
Value of Med Growth Mmual Fund changed from 36 4.2 10 342.0
Value of Hi Growlh Mutua l Fund changed fro m 496 .3 10 463 .0

Enter 'quit': Any other input to continue.

Figure 17.57 va example for mutual fund application

---- ---------------1
I I
r---::-:- r- ----------------,
Observable I Observer I
notifyObservers() >-- I updste( Observable, Object ) :
~-------~---- ----

I
I
Mutua/Fund I
I
value I
I
numAw8someShar8S I
I
I

LongTermMutualFund
Awesomelnc
Client ------
price MediumTormMutualFund
HIGrowthMulualFund

Key-
IJava API CI8ssi ....
IOovelOPO' Cta.ss I updatel ... )

Figure 17.58 ODserver example class dlagram-mutual funds example


428 CHAPTER 17 SOFTWARE DESIGN PAmRNS

Observpble ,I< Observer


nO/ifyOirverso k - - - - - - - -- updale( Observable, Objecl)
~

MyConcreleObserver
MyObservable observerS late
subjecl updale( .. ,)

Key: IJava API Class II


Developer Class I
Figure 17.S9 Observer in tl1e Java API

17.7.2.6 Comments on Observer

• Observer also goes by the widely used name of "Model -View-ContToller" (MVC ), altho ug h there arc slight
differences in emphaSIS. The "Model" in MVC is the So ure, in Figu,e 17.55 (the Obsrrvabl, in the Java API ).
The 'Views" are the Ob,nv" o bjects, an d th e "Control " is client and possibly setup code. MVC emphasizes
the fact that the mo del is data and the views are C Uls, whereas Observer is conceived wi th broader
applica tion

• Observer aflows the additio n and removal of observers without d.sruptin g existi ng observer code. Only the
loop In Obsrrvabl,.nol1jy() must be augmented. Some times th e process of adding and removi ng o bservers is
co nside red part of the panern (rather than being a "setup" function ).

• Observer may be di sadvantageous if very few of the observers need to rcact to changes (in w hich case the
numerous nmi Rcatio ns waste resources).

• Obscrotr is di sa dvantageous when update is morc naturall y implemented ce ntrall y , or w hen update policies
among observers have very little in commun .

• Obsrrvrr ca n't work if the observable cannot have a reference to all of the observers For example, we would
not usc it in a clien t/server situation unless we were wi ll ing for the server to maintain references to all
clients.

• In general, having the observers update themselves (as opposed to eXlerna l sohware perfo nm ing it) .s good
o bject· o riented design because it keeps related fu nctionali ty together.

17.7.3 State

17.7.3.1 The Design Purposes of State

Many co ntemporary applications are "covent -driven," A word processor, (or exa mple, waits (or the use r to click
on an Icon or menu item, and o nly then reacts . Evc:nt·driven applicatio ns are often de igncd as STate-transi tion
systems. When a system behave by essentially transitioning among a set ofslalts , the State des.gn pattern can
be helpful. For exampl e. we can descriix the Encounter vi deo game at runt ime in term s of the state it is IO- i t
could transition among the StltH1g .up , WailiJ19 . StttiHg-<haraclcnSlic:s. and hnrnctrrs~j"tcrQCfi"g sta te . among
others. A desig n should capture th is behavior eff<ctivciy. As the ga me becomes better deAned, the design
SELECTED BEHAVIORAL DESIGN PATIERNS 429

Design Purpose
Cau<e an ob)c t to behave ,n a
manner determined by IlS state

Design Pattern Summa ry


Aggregate a I<Ilr objec t
and delegate behavIor to It.
Figure 17.60 The deSIgn purpose for the State pattern

hould al 0 be capab le of gracefull y absorbI ng new Slate and actIon handltng without dt<rupllng the e"Sllng
desig n. F,gure 1760 sum manzes the purpose and basic techn ique of the tate design pallern

17.7.3.2 State Interfaces for Clients

To use the State pattern , the lient imply makes a call o n a spe iRc method of a specik object The cl,ent"
sh,elded from the various possible dfects of ca ll ing the method, whICh depend o n the object's <tatc.

17.7.3.3 The State Class Model

In general terms, suppose that we want to use a method doR rq"rsl() of an object 'arg" of class Ta'9" , whcre
doR,qursl() can behave in different ways, according to la,g<l's state at the time of the ca ll . Th ,s IS solved by
introdUCing a class, which we ", til ca ll TaryrlSlalr , and givtng Targrl an all"butt (we'll call,tlary,1 lair ) of type
TO'9r1Slalr We ensure that I<Ir9,ISlo l, properly represe nt the Targ,' object 's current state at all limes ThIs IS
ensured by I<Ir9rlSl<lIr berng an objec t of the appropnate Tar9,ISlalr subclass FIgure 17.6 1 hows tillS. ote that
the State design partern is In the Dr/rgaltoll form .
The method doRcqursl()ca lis lar9rISlalr.lu",dlrRrq""I(), so the ca ll to doRrqlu,l() is tran<bt ed by thc vlnual
funct io n property IntO the parercu lar vcrsio n of /'a "dlrRrq",,'() approp riate to the Slate o f ""grl The elre llt docs
not need to know the sta te of Inrgrl . The fu ll cia s mode l is shown In F,gure 1762

17.7.3.4 Example State Appl ications

The Encounter VIdeo game ca n typIcally be In a variety of sta tc, When you Slart to play the game, you rna
have the o pportunity to sct yOllr characte ri stl s (" elllng Up" Slate ) When yo u ate III the mId" of lI11l'ra ting
WIth othe r characters, your state IS dl lferent ("Engag In g" <tatc , perhaps ). It I rcasonable to t' pect that you
can't cha nge you r charactcn t l S In the mI dst of an engage ment because th e game would no t he mu h fU ll to

{ largetSlate handleRequeslO; }
Chenl
I /'
, ; / Tarqe tState
Target lorgetStalc
•dcRequeslO 1 handleRequosf{)

Figure 17.61 1M basic structure of the State design pattern


430 CHAPTER 17 SOFTWARE OESIGN PA ITERNS

( l argel51al e,handleRequoslO: )
CHent

I
T Targ et l.rgeI518le TsroelSlate
•daRcqueslO ,

handleRequesrll
1
71

TargelSlaleA TargelSlaleB
• • • • • •
handleRequeslO handleRcqueslO

Figure 17.62 The Siale design pattern: doRequestO behaves according to the state of Target

play In tha·t case . If the ga me tnterface had the appearance in Figu re 17.63 , the dfect of pressing the ScI
Omractcn sl/cs button would depend on th e state or the game at the time .
Figure 1764 shows how the Statc design pattem can be used to handle the states and actions of Encounter
The cia s MyGame has an attribute called , laic of type MyGmncSlalt The type of the , Ialt o bject (I.e .,
" 'hich subclass of '"lyGamtSla le It belongs to ) delCrmines what happe ns whe n stlo,araCltri, It C5(J is called o n a
MyGamt obJect ,
The code for st lo,aracltnslt«(J In MyGamt passes contro l to Ihe handltCfick() function of slalt. Each
subclass of MyGarntSlalt Im plements l,andleCfick(J in its o,,,n manne r. For example , if MyGame is in Wailing state,
then the effect of clicking o n the "Sct C haracteristics" huna n is that a wi ndow appears thro ug h which the
playe r ca n change hiS charactenst lcs . O n the o ther hand, if MyCa,"c is in ScltmgQutlilhcS state , then nothing
happens because the user IS alread y s elling his characteri stics.

Set Characteristics

FIgure 17.63 GUI for Encounter role-playing game


~ COt.rtesy of Tom vancoun and Cent
DESIGN PATTERN FORMS: DELEGATION AND RECURSION 431

MyGame stale I~
setCharacteristicsO _ handleClickO

t
stato.handieCIlckO.
I

Setting Up Waiting SettingCharacteristics Engaging


handleClick( handleClick~ handleChckO, handleChckO
,
I, I
I ,,I i
I
I I { /I already respondJJl9 I I/ do noth'ng
showWindowO; showWindOwO: .. /I disp{ay message . ,_ /I dISplay message
•.. J/ more ... JI more I I
I I

Figure 17.64 The State design pattern applied to the Encounter role-plaYing game

17.7.3.5 Commen ts on State

• The State design pattern is particularly beneficial when new states are likely to be needed In the hltu re.
• State does not hand le the question of how to set up the sUCCesSIve state (if required ) once ha"d',E"",tO has
been perfonned. Although State doc no t hand le the tranSition funcllon , it can be a useful fnmework In
wh ich to implement transi tion . For example , halld',E""" O ca n contain code that swaps In the new Slate A
possible companion to ('he State deSign pancrn IS a state-transitIOn table whose entries indicate \~hal new
state the object tranSitions into for each "current s tale~vent occurrence" pair
• Whetheror not the State de ig n pattern IS applied, tate -onented arc hlte tures have been used with success
for many applications (see, for example, the work of Sh laer and Mell or (2 )) Real-time apphca tions lend to
benefit especially from the sta te architecture because they often rely o n a sratc/event perspective

17.8 DESIGN PATTERN FORMS: DELEGATION AND RECURSION

As the exa mpl es of deSign patterns above Iliu trate , they occur ," a ),mlted number of forms We could >a y
that there are patterns to the design patterns meta patterns. If yo u like . Mo,t deSign pallern are based on
the dcltgahoH or ftcursiotl forms , as descnbed In thIS secti on.

17 .8.1 The Delegation Design Pattern Form

ConSider a ta,k that needs do,"~ , the o bjec t thai initiates it , and an object thai doc< the actua l ",ork 0" '91111°"
IS a proc"", by which the Initi ator emp loy, a th"d obJc tto get the work done by the doer. An example from
re.llife IS the usc of a rcalLor In whic h th e . c ller (the InllialDr) wants to cllto a buyer (the doer, In thiS a<e)
To ach ieve nex,bd,ty, the KltchenV,ewer dC<lgn rep lace dlfcct code ,1Ich a,

new Ant iqueWallcabinet () ; / / applies only to ant ique style


432 CHAPTER 17 SOFTWARE OESIGN PATTERNS

.. , c1lenIFunc;Iron{ ... ) .. InlermediaryFunctlon( )


( (
... inlermodla.ryFuncllon( .. ) .. , .,' r&qutredFunctionO , ..
j j

Client
cllentFunctionO - - - - - - - - - - - - ~ IntermedlaryFunctionO
" I
" I
,X !
,, I
I
I
replace I

" , -!t
." requlredFuncllonO

FIgure, 7.65 The idea of delegation

with il version that delegates construction to an intcm1e diary method

myStyle . getWallCabinet () ; / / appli es to whatever style is chosen at runtime

11,e Abstract Factory design pattern replaces several dircci m<lhod ca ll s (constructor calls, actually )
with delegated calls to se parate methods, which ca ll the desired me lhods in turn. The basic idea of delegation
is shown In Figure 17.65
A common way in which design patterns put delegation into practice is through a clas~ that delegates
functi onali ty to the methods of an abstract class. When we apply Abst rac t Factory in Figure 17.7, fo r example,
the work of crea ting a Wal/Cahi"" object is de legated to the methods of a KilchrnSIyI, object.
A common lorm of Delegation is illustrated in Figure 17.66 . where an abstract class is aggregated and
acts as a base class for severa l concrete subclasses.
The client calls the method ml,rjacrM"bod() of the interface class OP/"',rjacr. In turn, inltrjacrM"hod()
delegates the reqUired fu nctionality to its aggregated Oorr&" object, do,rObjrcl. The functiona lity is carried
out by having dorrObjecl execute a method that we have named do/l( ). At runtime do,rObjrct is an object of
either the class Co"" ",OO''' , Co"crtItOom , and so o n. Since the effect of do/t() depends on runtime cond itions,
so docs the effect of i"l,rjaccM,'hod(J. The class OP/III,rjfl" thus has the followi ng fonm .

class DPlnterface
( DoerBase doerObject;
• • • • •
public void interfaceMethod ()
{ doerObject . dolt ();
}
}
DESIGN PA ITERN FORMS: DELEGA liON AND RECURSION 433

I
Client ... inte~aceMethod( ... )
I ! ( ... doerObject.doltO ... ~ ,
I - .,
I
I
I
I
r.-~ DPlnteriace doerObject DoerBase
IntertaceMethodO dol/O

ConcreteDoer1 ConcreteDoer2 ...


doltO doltO

Figure 17.66 Basic deSign pattern form nu mber , -delegation

DelegatIon . Implemented using ,he virtual functio n property. is the most common form of deSIgn
patterns . Another common form is Recursion : the usc of slnK,u res '0 cffcctl\·ely reference ,hcmselve,

17.8.2 The Recursion Design Pattern Form

Several deSIgn patterns require re ursion- In o,her words, part of ,he pattern essen tially uses I,self For
example, recurSIon is useful for represe ntIng a linked list of objects ir. wh, h each objec, of a cia> agg rega ,e
another o bjec, of the ame class. Anot her examp le IS construc'ing a graphical user In,erface tha, al low> fo r
Windows within Windows withIn windows . . and so o n. In lhl'> case, the \\'mdoIP object aggregates itself
In a recur Ive patte rn fo rm , a duallnhcrnancc-aggrcgal1 o n relario nshlp eXists between 3 base class and a
5t:Jbclass. as shown In F, gure 1767 No,ice tha, the Recur<lve form U$e, the DelegatIon form-In tI", case, the
deleganon doubles back o n Itself
From the dynamI C VIeWpOint , in a RecursIve form ,he ct.en, ca lls a me' hod of the Intedace, which we'll
name doOptration () If the object actually belongs to ,he subclass Rcn",,,,r IllS! , ,hen execut"' g li S doOprrahon ()
Involves the o bjec t(s) of aggrrgalt T hese objec" may once aga ", ca ll doOprmholl(), and so on
Let's take as an cxample ,he case where RccII,""on/3asr ",he la> Employer , doOprrallollO " ,he me,hod
pnnrOrgan'ZIlhonO, and Rrcurs,"cC/ass i< the class SII pm",or The Idea " to produ c a prin,out f all ,hc
~mployecs of an o rga nIZatI on The d a« model IS shown In F,gure 17 68
The method pnnrOrganlZllr.onO In SuprnJlSor would be prowammed '0
nrst pnnt ,he <upelVI< r' name,
Ih~ n u il the p"n rOrganlzarlonO method In each of the Employer o bject< III S"prrvlSccs For Employ" obJects of the
dass i.J,.,dualronr"huror, the m<·,hod p""rOrganlZnr.oll() prln'< only ,he name 01 ,ha, empl oyee For Employer
objects o f the clil~'" up,rVl sor. prltl l () rgaH IZtl ll otfO pnnt) th a l ) lIpcrvl,or's n a m~ Jnd the pnntln g pro (' '\ rcpt"ill'
re ur!lo lveiy Thl~ rccur'iIVC pr(lce~) eve ntuall y print all or th t: nJmcs The c1J" uprn11,or Ihl! ha, the:
fQlJ owlng form
434 CHAPTER 17 SOFlWARE DESIGN PAmRNS

RecurslonBase
Client - - - - - ;> doo".,. r'on(j

t:;>

NonrecursiveClass
doOpe,atlon(j
RecursiveClass
doO".,.tlonq
p aggrega.e

I
. void doOperation( ... ) I
II ... aggrega •• ... }
: - y

Figure 17 .67 Basic design pattern lorm number 1--<ecurslon

Employee
IClient fu_u p,lnro,ganIZlltlon(j

IndividualContrlbutor Supervisor supervisees


pnntOrganlzalionO prlntO'ganlzalionO
,

Gid •
pnntOrganlzation( ... )
I
... supervisees.printOrganizationO ...
J
~. _____________________~t~>~'

Figure 17.68 The Recursion design pattern lonn applied to an organizational chart

class Supervisor extends Employee


{
Vector supervisees;
- - -
void printOrqanization( •.• )
SUMMARY 435

{ • • •

supervisees.printOrganization(); • • •
}
}

17.9 SUMMARY

This chapter I ntrodu cd design pattern", which are used to ~atlsfy recurring de IS" purposes A df.:slgn partcm ,'\
a g-roup of cia ~c ( th e sIalic VleWpOll1t ) that tnteraClll1 a recognizable ..... ay (the d)'lwmlC V ICWPOlnt ) Typically. a
desIgn pattern consists of an abstracl level of clas<es and a nonabSlraCl ("concrete") levd Three roles ( et of
codd a", involved In the u<e of de Ign paltern<, lhe appl'<ntioll of the deSIgn pattern Itself. lhe code thal uscs It
(the e1,"'t role). and the code lhat ini tialIZes or changes the deSIgn pattern apphcatlOn (the " tu p role)
Most design patterns usc dtltgatioll . In whIch calls to an Interface method arc handed of( to another
method to facditate vanation at rtJmin"lc everal deSign patterns also u c a (orm o( ,tClm/OfI , In whl h a class
rderences either Itself or a base class from which it inherits
DeSign patterns can be rOllghly c1as ,ned as (7w llonal , sfru 11m,', o r btb,wlora'- Crw I/orlllI patterns create
nonrnvlal object ensembles In a manner determll1ed at runtime. Structural pancrns are used to represent
collectIons of objects. Bd,.",oral patterns deal AeXlbl y with behaVI or among a ot of objects
This chapter descri bed the following crealio na l design patterns by ,yay of example The S,n gleton
pattern i used to enforce classes with o nly a SIngle in tance. The Abstract Factory pattern IS used when an
interreiated family of classes is required but in a vanety of "styles " A "style" In thi< sense IS a haraCtenSllc
appli~ablc to every object in the family .
The follOWing behaVioral dcc;;i gn patterns WCft" discussed . Facade IS a way to treal a group of c1a ss~s JI:; a
unit. by provIding ItS functionality only through a slOglc object Adapter IS a way to SWItch u er obJe t ty pes
of given functionalIty at runtime
The chapter al<o dl cussed the followlOg structural de Ign patterns Interpreter" used when the
situation IS VIewed a the exe utlon of a language speciall y designed for the appJ.catlon Ob,erver" used for
deSigns thai I:;eparate control from presematlon and data tal C II:; used to deSign Clpphcation pilrt" bel:;t th ought
of term of a SCt of stales
In
These points are summa rized In Figure 17.69. The reader i referred to Fowler (3) and VIl<sldes (4] [or
further exploratIons of dC<lgn patterns.

• DC'Slgn Pattern s are recurring designs sat lsfy mg rc urnng dec;;lgn purposes:
• Des<:nbed by Static and DynamiC Viewpoints
• TypIca lly cias, models and <quell e d,agram, . re'peLllvcly
• Use of a pallern app hea llon 1< a lient Role
• heot Interface cardully Lontrollcd
• "S<:tup: tYPIc..ally Inltlahzatlon , a separate role
• Dc"gn pattern rorm~ u,ually Delegation or Re ur<lon
• Oas.. r.·d.s rcalional, trucllIra l, o r Behavioral

Figure 17.69 A summary of th.s chapler


436 CHAPTER 17 SOFTWARE DESIGN PATTERNS

17.10 EXERCISES

I. Which of the following arc applications of deSign pallerns) Exp lain your conclusio ns.
(a) An obJect,orlenta ted design
(b ) The ab ili ty 10 vary the order 10 whi ch a pn,,'O method IS app lied to the ciemen ts of a Veelor
(c) Varying the order 10 which a method is applied to the clements of a collection of objects by
introduclOg a ciass who e methods IOciude a method like go ToNtxIEl""ml()
(d ) Cap turing the mutual beha Vior of a pair of objects o f twO classes
(e) Capturi ng the mutual behaVior of a pair o f objects of twO classes by introducing a third class
aggregating the two clas es
2. Char.lctcnzc the fo llowing design purpose as , ,(aIlOMl, structllral, or btlJovioral. Explain your
conclusion clearly.
We must build an application with 15 different screens involvlOg va ri ous combina tio ns of 6
us., interface contro ls (e.g .. list boxes) arranged in a si mple grid Pe rfo rm ing a mouse ac tion o r text
e nt ry o n a co ntro l (e.g .. a butto n) in a screen affects other controls o n the same scree n. In all o ther
respects the screens are not related and are not si milar in appearance. The compOSition of th ese
screens is very unlikely to change .
3. Characterize the fo llowing design purpose as erralronal , structural, or bthavioml. Explain your
conclusion clearl y
We must build a hum.m resources application dealing with the management structure at a
large co mpany . We nee d to represent the organ ization chart withi n the applicati o n.

4 . Cha ra cterize the follOWing design purpose as ertel tional , structu ral , or bthapioral. Explain your
cone/uSion clea rl y.

We must build an application that allows users to build and change their stock portfolio with a
various ki nds of mutual fund picks from specified subcategories. The mutual fund categories ar<
ttchPlology , old mdustrits , utilities , rtal (stal(, and mining . The application allows users to pICk categories. It
then milkes portfolio recommendations depending o n the user's choice. For eXilmple, the user can
ask fo r a low· risk portfolio of utilities and mining Slocks. and the application describes its
recommendat ions within these constra ints.

5. Consider the followi ng two statement .


(al Obstrotr consists of an object of a class that reflects a data source, togethe r with o bjects of
classes that depend o n the data source.
(bl When the data changes value, a method with the name "pdateO is called o n each observing
object.
Which of these two tatcm ents takes a static viewpoint and w hich a dynam ic' viewpoi nt

6. The following figure shows the Obstro" desig n pattern class model. Group the classes to
show ab,tract and co"crete levels. Group the classes to show the three ,oles descTibed in this
chapter.
7. (a) What two design pattern form. are mentioned 10 th is chapteo
BIBUOGRAPHY 43 7

(b ) ~ h,ch of the ".0 fomls IS more lIkely '0 u'c virtual functions ) Explain your answer Jnd gIve
In example

(c ) Wh,ch of ,he two form IS a I",krd I'si of obJtCIS Ioke1y '0 be) Explain your an wer
(d ) Wh,ch of the two forms IS the Observer pallern In Exercise 61

S. Re ('arch the Java wing soflwarc ar hltcclUre, such as Java wmg, and descnbe In a few
paragraphs how It make usc of the Observer pallern Draw a cla<s dIagram a part of your an<wcr

9 Research the Java EE p ia, form and desenbe In a few paragraph, how i, makes usc of ,he Facade
de Ign pattern Draw J clas<: diagra m as part o( your solullon

BIBLIOGRAPHY

1 c'mma Ench. Richard Helm . Ralph }ohn ..on and John VI''iSl dcc; D(~I!1" PQlftnt ~. El('lllmh of Rrw.wbft Ob}tcl.OnnlkJ 50//11',1'1 dd"on .
Wc .. lcy. 199
'2 Shlaer, Sally. and tcphcn Melio r "Ohle, Lfrrydn /\loJrlIl19 1M World.,\ lollI'S, You m o n Pr~ ~ 199 1
3 Foy,·lcr, l\'brtln Pull"" H(mhl"9 f)MI9" Pallen" AppJltJ " Acid ..:;on '«'c"lcy I?'J$
of VIISS,dc-s, John ~' . MPOII(n.~ of E"'crpnSt AI'P',collon J\rrhl lrdlm " Addlf;on· \,(/c 'iIc)' 2002
Software Architecture

• How do you classify software


architectures?

• What are data flow architectures?

• What are three-tier architectures and


The Software their generalizations?
Development
Ule Cycle • What makes database-centric
systems a separate type of
architecture?

• What are service-oriented


architectures?

• What IEEE standards are there for


expressing designs?

• What do real -world architectures look


like?

Figure 18.1 The context and learning goals for this chapter

Th IS p.rt of the book , oncern ed with desig n, began by dcscnbing design go.ls and principles and then
described patterns of design that reCur th roughout. This chapte r describes d<sig n at the high leve l, and the
chapter that foll ows at the detailed level.
A sofl wtlrt archlfcch~ rt descnbes the overa ll compo nents of an apP'!ic,Hi on and how they relate 10 each
oth er. Its design go. Is, as discussed," C hapter 15, include suffiCIency , understandabil Ity , modularity, hlSh
cohesion, low coupl ing, robustness, fl exibi l, ty, reusability , err,clency, and reliability. For a give n softwa",
SOFlWARE ARCHITECTURE ALTERNATIVES AND THEIR CLASS MODELS 439

• Oatatlo,"l architecture!!. • Virtual machine


• PIpes and filters • Interpreters
• Batch sequentIal • Rule ·based systems
• Independent ompon('nt • RepOSitory architectures
• Clicm · elVer systems • Databases
• Parallel communicating proccs es: • Hypertext ~ystcms
• Event systems • Blackboards
• Servlce ·oriented (added ) • layered arc hitecture..,

Figure 18.2 Shaw and GarJan's categonzation of software archItectures


SCUte: Shaw, M.G and 0 Gartan. " Soltware AlcMecture PefspecUves on an Eme'ging OIsctphnc," PrentICe Hall, 1996

devel opment project, lhere may be several possible app ropna te architectures, and elecllng one depends
upon [he goals that ont wants to emphasize.
Flexibility , to choo c one of these qualities, is a key goal of many archilectures-the ability to
accommodate new features. This uc;uall y Invo lves Inrro duClng abstraction Into the praces For C"xample , we
mIght want the architecture for the Encounter Video game case study to support not Just thIS partICular ga me ,
but any role. plaYi ng video game
Attaoning one de irable deSIgn property ma y entail a trade ·off agaonst others For example , a de Igner
who uses abstlactions to obtaon a fleXIble architecture may make" harder lO understand

18.1 A CATEGORIZATION OF ARCHITECTURES

Shaw and Garlan [ 1] have claSSIfied software arch"ectures 111 a u cful manner Theor cia Slficallon, somewhat
adapted here, is shown in Figure J 82 . Section 18.3 explaons these ",ch"ectu res There IS a WIde variety of
problems requinng software solutions, and lhere is a wide va ri ety of archItectures needed to deal with them
In most cases, the architecture is unique to ,he problem Sometimes, o ne of the a rch itec lures Identi fied by
Shaw and Garlan matc hes the problem, in many cases they si mpl y proVIde Ideas o n whIch to base the
architecrure. This is Similar to arch itecture in hOUSl' construction, In which claSSIcal and standa rd Ideas
prOVide inspiration for great architecture but arc nor c;imply copied

18,2 SOFTWARE ARCHITECTURE ALTERNATIVES AND THEIR CLASS MODELS

The softwa re archItect develops a mental model of how th e application I meant to \ o rk, often with nve
to seven components The JrChlltCl '., mental model depends on the app li ca ti o n In qUl:.'!)l\on . of COll r~ e , but
may benent from architecture< that o ther ha ve de veloped In th e p. t, JU<!" a ,u>pcn" on brodge de>!gn
benents from the study of preVIously budl suspe ns Io n brodges . ThIS section e laborate< o n the arch ll ec·
IUr<S claSSIfIed by h aw and Garlan They calegonze architec tures as dota flow , ondependent compo ·
ncnb, vlrrua l machlne'l , repository archItectures. and layered aT h,lcclllrcli. Figure: 1 2 summanz.e'" th('~e
and 'heor subcate!!orocs, and the re~t of thl sec ti on cxp l"n< th e m It also add , serv l e · oroc nled
architectures.

18,2,1 Data Flow Architectures

Some applIcatIons are best VIewed a, data Oc,wlng among proce'Slng unlt< DOll 1I0w dl.!;"m, (I 1'0<)
IIiUstralC 5uch VI('WS Ea h pro csson~ unit of th e OFf') " de,,!<ned Independently of the oll1el ' Data
440 CHAPT£R 18 SOFTWARE ARCHITECTURE

member
Gel Gel
banks User Inquiry
deposil
J".
no"'" tlccounl no
act:ovnt no.
and doposlt

Validale Validate
deposil Inquiry
aca>unl no.
Display Make
scoounl no. account Inquiry
Printer
'''''depoSIt
tJccount balana>
dDra query
Do Create
deposit doposll S=><PII account
transactlon trat'lSBction - .. account_ dols summary
dalabase

Figure 18.3 partial data flow diagram for an ATM application

emanates (rom sources , such as the uscr, and eve ntually flows back to uscrs, o r into sinks such as account
data bases. The c le ments of the DFD no tation were explained i n C hapter 16 . A banking application is
sh own in Figu re I S.3.
Data Row from the user to a "Get deposit" process, which se nds the account number and the deposi t
amount to a procc,ss designed to check th ese data for consistency . If they arc consistent, the data may be sent
to a process that crcates a tran sac tion , and so on. DFD s can be nested . For example. the "Create inquiry
tran sac tion" ca n itself be decomposed Into a morc detailed data flow diagram .
The functions of a data Row d iagra m may reside on morC than one physical platfo rm . Figure IS .4 shows
one possible allocation.

ATM

Get deposit
o Get Inquiry
Display account

Consortium
server Bank
server
Make Inquiry
Do deposit transactIon
Create account summary
Validate deposll
Valldale inquiry

Figure 18,4 Platforms in data flow architectures, and an example


SOF1WARE ARCHITECTURE ALTERNATIVES AND THEIR ClASS MODELS 441

18.2.1 .1 Pipe and Filter

One kind of data Ilow ar hltceturc. <hown In Figure 185 , IS referred to as the plpcalldjiltcr.rehlteerure In thl<
kind the processing elements ("fi lter,") accept streams as Input (sequences of a untform dara element) at any
time, and produce output , tream . Each filter must be deSIgned to be Independent of the other filter The
archItectural feature in FIgure IS 5 I< Implemented by UNIX pIpes, for exampl e
Pipe and Ill e r architecture" ha ve the advantage of mo dlilant y An exa mple IS shown In Fi gure 18 6 .
In It 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
function would ha ve withdrawal Input su h as 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
their op"ratl o n

stream>
filler

hlter
filte r filter IiIter

pipe
filter

< stream

FIgure 18.5 Pipe and filter architectures

Requirement: Maintain wi red fi na ncial transactions .


- - - - - - account data - - - - -

,.--- account data - - deposit


, transaction result
_,-- I account data r depoSIt data
Ba nk transaction ~L'---......
a na lyze re cord Log
d a ta Iransaction '--~
wllhdrawal
Comm transaction result

L _ _ _ bank address withdraw

L _ _ ___ account data - -- ---'

FIgure 18.6 Example of a plpe·and·fllter architecture, to mai ntain Wired fInancial transaction
442 CHAPTER 18 SOFTWARE ARCHITECTURE

Transaction
analyzeO
recordO

l..n Account
w~hdrawO

Bank 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<qu",IIa'
foml of data flow As an example, consider a banking application that computes the amount of money
available for mortgage loans (secured by properties) and the amount a~ailable for unsecured loans. A data flow
diagram (DFD) is suggested by Figure t8 .8.
n,is DFD is batch seq uential because the functions arc executed using ail of the input data of a given
run, taken together. For example , we collect the funds available for mortgage loa ns by uSlllg all of the account
data . Th is is In contrast with the tr.msaction example In Figure 18.6, in which there arC" many nvirtually
continuous" transac't lons, each using selected data from thClf sources.
Figure t 8.9 shows one mapping into a class model in which the functions of the data flow are realized as
methods of the &H. class. The "batches" of processing arc executed by running the relevant methods of th is dass.

Requirement: Manage bank funds available for


mortgages and unsecured lending.

Architecture: Collect Mortgage


mortgagelunds pool
Account
balances
-« Collect
unsecured funds
>-- Unsecured
pool

Figure 18.8 Example of a batch-sequential data flow architecture creating a mortgage pool

r o
--- -- -- -------- -----
: Accounts package : : Bank package :
.-.----.-
• ... -.. -.------ - ----- - --------------~,, :.-.--. -- - .------------------~
,,• ;: Bank :


,•
Customer LA_c_c_o_u_n_t --:-
: ---!: getMtgPOOIO :
•· : : getUnsecurePoolO :
.... ----.----.-.- .. ~--.------.-.------.---- .. , -
' _.. ----_.------- -.--...
_.. _.',

Figure 18.9 Class madeller batch sequential data now--<reatlng a mortgage pool example
SOF1WARE ARCHITECTURE ALTERNATIVES AND THEIR ClASS MODELS 443

For dcca dt" • data flow has been the: mos t CO rnm o n way of cxpr~~sl n g architectures, and It IS bou nd to
be u~c:ful (or some lime to come EnSlAccrs nawrnlly think ol data Oowlng, from one prace Si ng "statio n" to
th~ n ~x t and of proce<slng taking place at ca h ta t Ion . The disadvantage of data fl ow d,agrams include
the fact that they do not map very cleanly to code , whether obje t .onented or no t An excep lt on to thIS
appites to specIfic data flow language, (,ome beIng actuall y graph ,c In nature ). wh Ich arc butlt around the
very co ncept of data ilow We WIll use the data flow mo del once again when we dISCUSS detatled deSIgn In
C hapter 19

18.2.2 Independent Components

The i"Jcpmdnll compOHfll ts arch ,tecture consl IS of componen ts operatIng In parallt:1 (at least in prul Clplc )
and commUnicating wit h each ot her from time to time An obVIOUS Instance of thiS can be found on the
World W,de W eb. where milli on, of servers a nd browsers operate conttnuou Iy In para ll el and penod ,cally
communicate with each other.
·Components" arc portIons of software th at do no t change and that do not rcqutre kn owledge of the
software usi ng them . IT assemblies and JavaBca ns are example component technologIes omponents
sati fy gui de l",es aImed at maktng them self·conta lned. They use other components by aggregatton, and
generally Interact wi th other components throug h {'vents
The case studies tnclude a d,scussion of the Eclipse project. Ecl ,pse IS a development platform deSIgned
to accomm odJtc plllg-IIIS Th ese arc independent component that can be created by developers fo r vanou~
purposes. and added to the platform wit hout affec ttn g exi ting functio naitty

18.2.2.1 Tiered and Client-Server Architectures

In a df(nt-S(rv(r architecture, the server componc nt serves th e needs of the chcnt upon rcque~t Clie nt -
server r~ latl o n s h ips have the advantage of low coupitng between the parti CIpating compone nt s. When
morc than o ne person perfo rm s Implem entatI on It is natural to parcel out a package of clas es to each
developer o r g ro up of deve lopers , and deve lo pers ty pica ll y req UIre the services of classes for wh ,ch ot hers
are res po nsib le In other words , de ve lope r;' packages arc o r. e n re lated as citent and ,erver The prob lem
IS that these service arc typica ll y in va ri ed sla tes of rC3dln es 3'> the app lica ti on I - In the process of

being built .
A server componen t acts morc eHcclIve ly when its Interface IS narrow - arrow" m(,.-a ns that the
mterface (essentially a colle tlOn of fun tion, ) co nta ins only neCCSs.1ry part>. IS coll ected ,n one pia e. and"
clea rl y defined As exp laIned 10 hapte r 17. th,· Facade deSIg n pattem es tabl"hes Ju<t ,uch an Interface to a
packa!!e of clas os Facade regulates communIcat Io n WIth th e objec ts 10 Its package by exposIng o nl y one
object of the package to code USIng the package , hIdIng all of the ot her c1a<ses
hent.server architectures were a steady feature of the 1980, and 1990s !vIa" of them replaced
malnfram terminal arch Itectures Olcnt/'>crver an. h,ttcturcs have c;ub ...equent l>, bee mc more ;,ophl heated
J

and more va ned orne arc now de~igncd as three· tlcf arch lt ecture~ Instl'ad of the ongmal two tlC~ (chent
and server) Tht third tl c r it t< betwee n the c1 ,cn l and the erver, prov Id,ng, Itsehtl level of II1d,rc tlon A
C()mmon allocalton of (unction IS to de Ign the C UI fo r thc cl ,e nt , the database management, 'tem . or
procedure management for the mIdd le layer. and »sorted app l,c, tlo n prosra ms a ncllor the dataha,e Iheli lor
the thtrd la ye r The mIddl e la ye r ca n he a com mo n data "bitS" that br kef< commltnt a lto n ItcrnJtlwlv
the mIddle layer can operate vIa a \l.nliard ",eh a, M ,cro,oft', ET . " (IIIMIt! FInall y the World ~ Ide \'(Ieb
Un be: onlJldcred a bre d of ellcn ... rrver ar hnc(. turc In whl h "one- wrvrr/tcn ... of <..ht.""n l," .'> ft'plJ.ccd hy un
krver/mdl,oo> of iten" ·
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 Platform 3

comun/catlon

e xecutJon

Figure 18.10 Platforms for communicating processors


SOFTWARE ARCHITECTURE AlTERNATlVES ANO THEIR CLASS MODELS 445

Requirement: Manage A TM traffic.

Architecture beginning with first session:

Customer_n session_m customer_n_


:Customer: :Sesslon checkJng
:Account

create
0: .: retrieve" ®
0
deposlt-+j deposit·
°
(",ore wo~
(thread detail omitted),

Figure 18.11 Example of parallel communicating processor architecture managing ATM traffic. fragment of secuence
diagram

call. The Cuslom" object Immediately pcrfoml s a deposit "ansaClion by sending a me< age to t h e 5,,,,0"
object (4 ). TI,C 5",io>l object executes the d c poSit by sending a depos it message async h ronously to the Ac oU>l 1
object. spawning a new thread ( 5 ). Other w o rk can go on-lilcluding by o th er seSSIOn s whde the deposit IS
processed
In parallel , o[her Customt'r obj ects such as customer s are creating and operatmg on other <':;CSSlons such a
seSSion k. This is shown In Fi gure 18 12 .
Figure 18. 13 shows the beginning of a class m o del that handle thIS kind of architecture

Requirement: Manage ATM traffic.


customer_
s_saving
Architecture: : Account

6) Customer_n sesslon_m
:Session
session_k
:Sesslon
customer_n_
checking
:Cuslomer:
:Accounl
;
customer 5 create
0: I retrieve" : 0
-Customer
..J create I
ret neve'
'"
4 depoSlt+j r_0
::;5_ d_e_P_OS_It_. +-- - --n
Withdraw
---+j Withdraw'
f - - -- - -
U (Ihread detail omitted)"

Figure 18. 12 Example of parallel communicating processor architecture managing ATM trafOc - secuence diagram
446 CHAPTER 18 SOFTWARE ARCHITECTURE

,---------- .,
,_.-._.-------
. _. ___ • ____________ _______ _______ _ CuSlomers
I
~ __________ J'
.
.
; Sessions : ,, ,
,,------.- .,
,, ,, ,•
•, ,, ,,,
,,,
,
J" ~ Account ,,
,
,
,, depositO ,
,, Session , ,- ,,
, ,, Customer withdrawO ,,
,, ,,, , relrleveO ,
'-- • ---- ... .
• . • • -- -----.---_.----- • •

Figure 18,13 Example of parallel communicating processor architecture managing ATM traffic-<:Iass model

18.2.2.3 Event Systems Architectures and the State Design Pattern

Let's tum to """I 'Y,'mos , the third type of "independent component" architecture cla ssi~ ed by Shaw and
Carlan . Thi s architecture views apphca ti ons as a set of components, each of which wa lts until an eve nt occurs
that affects it. Many contemporary applications are event systems. A word processor, for example, waits for
the user ' 0 click on an Icon or menu item. It then reacts accordingly, by stonng the fi le, enlarging fonts, and
so o n. Event systems arc ofte n ful fi lled as state transition systems, which were Introduced in Chapter 11 .
\,(,hen a system behaves by essentially transitioning among a set of states, the State design pattern
should be conSidered fo r the design. This design pattern was explained In Chapter 17. For example, we have
described the overall requirement fo r Encounter In terms of the state diagram in Figure I 1.26 of Chapter 11 .
Encounter tranSit ions among the Sellin9 up. Wailin9 , Sellin9 qualilies , Reporting, and Engagln9 states, among others.
Our design should capture this behavior effectively. It should also be capable of gracefully absorbing new
states and action handling as the game becomes more complete, without dISrupting the existing design. For
these reasons, we wdl app;)' the State design pattern described in Chapter 17 to Encounter.
The State pattern solves the problem of how to use an object without having to know its state. In the
CQntex't of Encounter we want to be able to wnte co ntrolling code that handles mouse actions but does not
reference the possible stales that the ga me can be in , or the specific effects of the mouse actions. This makes it
possible to add new game situations without disrupting th is controlling code.
Figure 18.14 begi nsto show how the State design pattern can be used to handle the states and actions of
Encounter. The framewo rk class RPGame ("Role· playi ng ga me") has an attribute called ,'ale , which is of rype
Gam,sln'e . The subtype of slale (i.e., which subclass of GameS'ale it belongs to) determ ines what happens when
handl,Ellrn'() is called on an RPGame object. The code for /,andleEv",l () in RPGam, passes contTOl to the
h."dl,Ev", ,() function of state.

-- --------,
: RolePiayingGame I
,- -- •
.-------------------------------~-------
_____1
I I
I Slale I
I RPGame GameState
I
I handleEventO iI
handleEvenlO
I I
I I
I I
I ( state.handleEvent{); ) I
I I
-- --- -
I
'
------------ . ----- --------- . ------ - I
-,

EncounterGame

Figure 18.14 Beginning of tl1e State design pattern applied 10 EnCOunter


SOFTWARE ARCHITECT1.!RE ALTERNATIVES AND THEIR ClASS MODELS 447

------------,
lRolePlayingGam-:J
-- -------
RPGame state
GameState
handleEvenlO hand/eEven'!)

( slale.handleEvonIO;)
f:::,

... ---- - ----- ~

EncounterGame : EncounterGam e 1l
-- --- ------------ --1------------ ~

Waiting Setting Qualities


handleEvenlO handleEvenlO

SettingUp Reporting Engaging


1
handleEvenlO handleEvenlO handleEvenlO
1
~-------------------------------------------------

Figure 18.15 State design pallern applied 10 the Encounter video game

As shown in Figure 1815, each subclass of Gam,5Ial, implements handl,E"cnIO In its own manner. For
example, if Encounler is in 5,"in90ualilirs state , and the event is the arrival of a foreign character. then the
window pcrrOitting the setting of characler quality values disa ppears because th IS IS wha t the method
ba.dl,E"rnIO in 5,111.90ual,Il<' is programmed to do An additional co nsequence of ,hIS particular even t/Slate
comblOa tion IS that Encounter transition to rhe EII9agrng state , as required by the tate · tranSitIOn diagram
This lransition is Implemenled by code <uch as

EncounterGame.setState ( newEngaging( » ;

The nexi ttme an event occurs in Ihe ga me, the I,alldI,E"oI IO funcllon of En9119in9 Will exeCUle, rcOectt ng
the fac t ,h al the game IS now in Ih e En91191119 tat e

18.2.3 Virtual Machines

AVlnual machmt ardulel.lurc:: trea lS an appli cation as a program written In a special-purpose language BecJuse
an Interpreter for such a language ha< lO be budt, lhl arch,tect"rc [.lays off on l If everal "program>' arc to be
wmten '" the lanljUaHC, ge nerallng several appl,cal ,ons
The Impl ementall on of a tO mpltlc vlftual rna h,ne requ lfe< the buddln!; of an Ifllcrprett r The
lnt(:rpreLation requlrt:<; us to execute an o perall n- Iel 's JII It 1tI1trl'rt"() on a pro gram wntten In our
lanllWge The 'nterpretall on of a prlmil ive clem ent alone (e g , a I'U '" the exa",ple of ~ h aplcr 17, ",here
lhe part, of a " PU " are no t relevant ) " genera ll y Simple (flJr lhe ex.lIll l>lo, tim cou ld be >lmpl 10 pnnt lake
448 CHAPTER 18 SOFTWARE ARCHITECTURE

PU o ut f.t bo "l. The problem IS ho w to execute an i"'trprt'() (unct.on when ap pl. ed to a mo re complex
"program ." T o do th .. , we may usc th e Interpreter de>l g n pattern.
V.rtuaIOl" h". e arChllee!Ures arc advantageous .f th e application co ns"ts o f the process.ng of compit-x
entit.es, and if these e nt itic , II h as th e v rders in the example , arc readi ly describable by a gramma r.
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 Program 2 written in language


understood by inte'l''''tcr 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 449

Analysis - -~ Control Analysis


process process
• •• ••• • ••• ••
1 n
DBMS

Key:
Control flow : II ~ Database
Data flow: .. ..

Figure 18 .17 A typical repository architecture

Blackboard architecture , developed for artificial intelligence applications, art reposltones that behave
in accordance with posting ndes. The reader IS referred to [5] and [6] for a detailed treatment of blackboard
archlt~ctures
The final ryPl" of repository architectures we m ention here IS the hypertext architecture The m OS l
common u e of hypertext is on the Web. An application that manages the artifacts of a software engineering
application is another example .
The word "repoc;ilory" is often used in industry to den o te an app lication [hat provi des a und,ed view of a
collection of databases (, e., not just one). Th i relates to data wa rehouses RepositOries do not change the
structure of these databases, but they allow lIn,jonn acce s to them ThIS is a peclal case of repository
architectures as defined by Carlan and Shaw
Repo nory architecrures occupy a significant frilctlOn of applications. Since so many architectures make
databases their core When the proces In g i negligible compared to the fonnattlng of data from the databa e,
repOSitory architecture are appropriate . On the other hand , the presence of a large database can sometime
mask the fact that a large amount of procesSing may dnve the architecture Ad hoc da,abase programmmB
(e g., "stored procedure ") can eas ily mushroom into messy applitatlOns, wh ich perhaps should be conceived
differently from the repository model.

18.2.5 layered Architectures

An archltecturalltlytr I a coherent co llection of software artifacts, t)' picdlly a pa kage of classes In Its common
form, a laye r u,es at mOst one other layer, and I used by at most one other layer. Budding appl, .t,on layer by
layer ca n greatly <,mpl,fy the proce<s orne layers, such as framewo rks, ca n erw several applica tion>
We have already seen the layered appro. h applied to the Entounter applICation , where clas«s '" the
Encounter packa,!cs ",hent from cla<st' In the framework pack.ge> TI" " hown '" Figure 18 18 n,e Agure
'hows how we might orga ni ze the u'e of a 3·D graph ItS ens,"e", a laye r acce Sible from the Role· Pla 'Ing
Came layer
Fll!Ure 18 19 ,how, an examp le of a layered art hlle ture fran AJax bank pnntlng appil atlon n,ere arc
four layers In thiS arth,tecture, and FI~urc 18 19 show, dependency 111 the reve". dire tl on ompared to
Figure I ~ 18 The appli allon layer, AJax Bank P"ntlnl;, h., 10 do With prlntlnR and f rmattlnN II " olilit
Upon (, e , u'>,,,) the Aunun!> and the AJax Bank ommon las> layer, The latter are blllh upon a \'endo l
~ppiled layer, which ~onlalns ~enera l utilitl su h as <ortin g and ear h"'H TYPlcall , a 1.I'er" I~ail :c " a, a
,SO CHAPTER 18 SOFTWARE ARCHITECTURE

3D onglne loyer
D
Role-playing 9IIme Ilyer .. uses ...

ICharacters I IRolePlayingGame I ILayoul I


Application layer . - uses-

Encounter
Characters
Encounter
Environment
IEncounter Game I

Figure 18.18 Layered architectures. and example of 3D engine and video game

Requirement: Print monthly statements.

Architecture:
-uses"
Ajax bank printing Layer
I Accounts Layer I Ajax bank common IIbra.-Y' Layer
Vendor-supplied Layer
+
Figure 18.19 Example of layered architecture for Ajax Bank-highest level view

package of classes. For example, the Ajax com mo n library comprises classes used throughout Ajax
applications, and addresses such issues as the bank's logo and its regulation s.
The "using" relationship can be inheritance, aggregation , or object reference. In the example, only
aggregation IS applied between layers, as shown In Figure 18.10.

18.2.6 Sen/ice-Oriented Architectures

ScrvlCe-Orirnled Architectures (SOAs) arc gaining in usage. They are closely related to the idea of software as a
service and cloud computing, and warrant inclusion with those discussed above. SO As arc combinations of
S(flJicts: components that provide functionality according to an interf'ace speciAcation They differ from many
other application architectures in that they describe a sc t of interoperable components thilt can ~
dynamically harnessed to create functionality-rather than as a way to create a si ngle application
SOAs arc in the spirit of facade objects, and include Web services as a means of Implementation. SOAs
ace not necessarily obJect·oriented. In the case of Web servic« there is no assurance of globally defined
classes as we have proVided for Facade In prior examples. For example, suppose that an SOA is for a business-
to · busin~ss application concerning orJm. In an SO A, we would not assume that a unique Order class is known
to and usable by all service suppliers and consumers. Web services in particular deals with this by dennln8 3
schema for an orderdat. structure, and referencing the schema when Web services Involve orders. Thi uses a
Web service capability known as Web Seroicr D<scnption LAnguage and has the dfect of making an Order closs
known to clients. This is summarized in Figures 18.21 , 18.12, and 18.23 .
SOFTWARE ARCHITECTURE ALTERNATIVES AND THEIR CLASS MODELS 451

Architecture •

Ajax bank printing Layer t ~u s es"

Acoounrs Layer Ajax bank common library Layer


Vendor-supplied Layer
-
Class model:
(relatIonships WIthin ,-- - _. --_. _.. _. -----_. ---:' Ajax bank pnnting :,
,, ,,
packages nol shown) ,,
: Accounts :
,,,
------- ...
IPrinter_-_._----_.
I Formatter
----_ _- _ ..
Page
.. - - _ .. _- _. "
,

,----====,-;'
r - - - - --. _. _------ --------.,
iI
,
Account I Customer
,
,,
,
Vendor·supplied
layer nol shown
---- --- ----- --- . .. _- --- - -- ----- ...
,-- - ---- .... -. _- ---- ---. --- --- .
:'-_" Ajax bank co mmon library ,,
,
,,
,,
w .
---- - - - - -- -- - - .. .._----_._- ---_ .... ---_ . . _- _. _--.,
,,,
,, Ajax Logo AjaxDisciaimer Regulations ,
, -----.----_.-._-
-- --------- .. ---------_ .. _-- .. ------_ .----- --.-- ------ .. __ .,
Figure 18.20 Layered architecture example uSing aggregation

Based o n compo nents th at provi de han ctio naln y accordin g to an interface spec
• Princ ipally via Web ervlces
• In Ihe spiril of faca de o bjecls
• NOl necessari ly 00
Example, An app lica ll o n co nce rnin g ordm
• Wouldn'I assume an Ordrr class known 10 3 11
• Instead_ Defi ne an ordrr schema , refe rence when Web services involve orders

Figure 1·S.21 Service-oriented architectures, 1 of 3

Servlcc -onented architecture,> e nvisage () network (mos tl y an Interne-t ) ·domlnated cnVlronml'm In

which applications (and pans of app licatio ns) arc no t permanen dy wedded 10 each o lher Ralher SOAs
~ek to allow dy nam iC li nk ing of serviceS. For exa mple.-: , suppa e that you walll to write an appl. atlon that
orders <tatlonrry for a company_ You would wanl Ihe app l,ca ll o n 10 Identify all qualified vendOr<, check
prices and ava il abililY, call for b,d, and lenTI' , <clect a ven dor, and place Ihe order T o do dllS, Ihe appllCallon
can 't be permanentl y wedded to a c;c t of ve ndor For thl' rcao;;o n, OAs are bu dt around a rC!llS lralioH .. vstcm
Figure 18 23 ill u""'Ies Ihe fourSlcp Invo lved In publl<llIng and accessin g a service ·'Query ln g" IS like look ing
up a bU5Incc;~ 10 a te lep hone book . "BInding" mCJn s cont ac ti ng [he crvi C In order 10 Invoke It

(The rderence for Figure 18 21 , 18 22, and 18 23 " l7] )

• ' Fire and forget"


• Stateless as much a< po-"ble
• Extenslbte
• Add,l",nal fun~lI o nalil Y eas il y added
• Discoverable
• Accou nt fo r Q ua lity o f Service
• h), exa mpl ', security

FIgure 18.22 service-Oriented architectures, 2 of 3


452 CHAPTER 18 SOFTWARE ARCHITECTURE

• "Fife ,nd forget'


• Sta teless 3') much as pOI:i'11 Ie
• Extensible
• Add,tional fun tionahty ea" ly added
• Discoverable
• Account for Quali ty of Service
• For cXiimple. security

Figure 18.23 service-oriented architectures, 3 of 3

crvice-onented architectures frequently uSc a bUSUltss proctss This defln<..'"S the components or the
"'Y"
bu iness such as the customer data base and bu int."Ss. Credit poltcics arc cxampk--s of the latter. The s(nllCt 1t1Ier/aCt
layer dennes the ser necs available that arc based upon the busincs proCl'SSCS. It specifics functionality such as
listing all customers In the database and checking a transaction for conforma nce 10 buslncss rules. The .ppr.c."""
laytr con iSt5 of applicat io ns buill usi ng the sCIVice internee la yer. These points are shown In Figure 18.24.

18.2.7 Using Multiple Architectures within an Application

Applications typically use severa l subsidiary arc hitectures wIth in an overa ll architeclU re. Figure 18.25 shows
how the fra mework for role-plaYing video games could use everal of the architecture types lIsted by Carlan
and Shaw. It could make se nse, fo r example, to orga ni ze the ArtifMt, package as a database. The game
characters could be VIewed as parallel communicati ng processes. We will design the overall control of the
game as an event-driven sy tern .

Appplication A Application B Appplication C


(J

.. uses-

Service Interface Layer

.. uses-

Business

Figure 18.24 Llyerlng for service-orlented architec1ures


SOUn:f'. AQIc)ted from En. nlOfT'laS. " seMc:e<lflented AlchltectUre: COncCOts. Tec.tt''10608V. and Oes.ian." Prentice Halt,. 2006.
TRADING OFF ARCHITECTURE AlTERNAnVES 453

CharaCfers
RolePlayingGame
Parallel
communicatmg ___ ___ Event system
processes --______----
---------'
Rule-based Poslble
system - -j'- architecture
types used
Layoul

Database

Arlifacls system
Layered _ _ _ _ __
system
Database
system Encounter Layout

Figure 18.25 Example of the use of multiple subsidiary archltectures-Encounter video game extension

18.3 TRADING OFF ARCHITECTURE ALTERNATIVES

Since the hOler of a software archlte ture IS 0 lI11p Ortanl , It IS wi se to create more th.m one alternati ve for
consideration . As an example, we will create and compare two Jrchit cctllrC'S fo r the video store applicat ion
For the nrs. candida.e, we separate .hl· applica'lOn In.o .hrce majo r pans, The "back ·end" da.abase , the
middle pan , w hich cOnlains the bus lncss logic, and .he C Ul s. This IS • 1/",,·II(r archi.ecture . It IS often an
appropria.e choice when some or all of .he .iers resi de on phYSically separa.e plattomlS In parllcular, If .he
CUls are all on PCs, the middle la ye r on • server, and the databases controlled by a database managemen.
system , then three· tier architectures map neatly to separare hardware and software unitS Note that there IS no
n~ccsslty that hardware decompositions bt., the sam(.' as sofrware archltcctures, we ma y want a logical
(conceptual ) view of an applic.llon to be cnllre ly independen. of .he hardware platform, hosting " (These
are the phYSlca' VICW vs .he 'oglCa' view .) App lYIl1£ three tiers to .he video Store applicallon, ,,'e cou ld ob .aln
the architecture In Figure 18.26

VSGUls VSOperalions VSData

Presenta tIon Dala


lIer tier
I

Figure 18,26 Three-lier architecture alternative


4S. CHAPTER 18 SOFlWARE ARCHITECTURE

[" .......;;;;:;~~...............-..............'...........................'.................~;;;.~;~~,..~~~::::;~..............'..···...............··1
I ,
I., !I
I
, I
: I
II VSCuslomers
i
i
I 1
I
1.. _ ••_ .... __ ..................... ..................... _ _
........................................... ............... ........-
' ........... .i•
Figure 18.27 Altemauve architecture for a video store application

The strength of this architecture IS that it's easy to unders tand. Anolher strength is that since the CUI
part IS separate from the rental ope rati o ns it can be changed withoul di sturbin g the latter. O ne weakness is the
coupling between the GUh package and the V50ptratio", package; there may be severa l CUI classes
corresponding to the C. "om" class, for example. Therc is also cou pling between the classes in the V5Data
package and the classes in V50p"alio", . A second architecture ca nd idate IS show n in Figure 18.27.
Th is architecture g rou ps all of the classes pertaining to the vi deos in a package. The R",tal, package
contains classes that relate videos and customers. The C" stomm package contains the classC"5 pertaining to
customers, includi ng assoClaled CUls. A third option would be to group all d isplays in a package. Figure 18.28
summarizes onc opi nion of th ese architecture alternatives.

18,4 TOOLS FOR ARCHITECTURES

Various computer·aided software engineering (CASE) tools arc used to facilitate the software engineering
process. Some tools represent classes and Iheir relationships, such as Rat io nal Rose by IBM Corporation.
These tools facilotate the drafting of object models, linking them with the correspo ndin g source code and
sequence diagrams.
In selocting a modeli ng tool , a list of the requireme nts fo r the tool IS drawn up using procedures si milar
to the requirements analysis process for software application development. Here is an example of some
requirements for modeling tools .

• Essential: Facilitate drawing object mo dels and sequence diagrams

• Essential , C real e classes quickly

Three-tier Alternative

Understandable ) Yes Yes


Flexible) Yes, CUI easy to change Yes, Basic building blocks easy to
identify
Reusable) Not very, Each layer is spocial to Yes, Easy to generalize to generic rentals
video store rentals
Easy to construct) Perhaps Yes, Clear potential to use Facade

Figure 18.21 A comparison of arChitectures example


EFFECTS OF ARCHITECTURE SELECTION ON THE PROJECT PLAN 455

• Es ~ntt" Ed,t cI,sses ea"ly

• Dcslrnble· hould cost no more than $X per user


• Deslrnblc. Zoom Into part< of the model

• Desirable. Possible to Ju mp direclly from the obJecl model 10 the source code

• Optoonal , Reverse englneero ng available (i e., create object models from source code)
• Oplional. Use color coding for tatu of class Implemental io n

Tool packages frequen tl y try to span arch,teclllre, detaoled desIgn , and ImplementatIon . Varoous
vendors are developong the capabi lity to hyperlink from source code to documentatoo n and VIce versa
Implementati on-oriented tools uch as Javadoc can sometomes be use ful to supplement the desIgn process
Javadoc is useful for navigatlllg packages because it provides an alphabeticallosting of classes and the parent
hi~rarchy of each class.
Interac tive development environments (IDEs) are delIvered with compolers and arc WIdely u ed as
partial modeling tools. Object -Oroented IDEs ge nera ll y show inhentance In graphICal fonn , and developers
are frequently auracted to these <ools because of their closeness to the compilat Ion and debuggIng process
Eclipse, used as a successfu l software engineerong case study itself in this book, is an example of a WIdely
usod IDE.
Component assembly tools create applicatoons by dra ggi ng and droppi ng icons that represent proces-
si ng elemenrs. Java Bean environments are typica l of the se. Within such environments, beans Uava objects
whose classes confonn to the Java Beans standard ) can be obtained from libraries, cu tomized, and related to
each other by means of events. The Java Beans standard wa created with the express purpose of fa.cilitating
such simple asscmbloes by means of graphical tools.
A disadvantage of usi ng modeling too ls is the project's dependence on a Ihird -party vendor. In add,tion
(0 the complocations of the application and the project itself, engoneers must be concem~d WIth the viabol,ry
of the 1001's vendor. Suppose that the vendor goes ou l of business or tool upgrades become too expen IVe,
How WIll the project be affected7 DespIte these ISsues, the use of design and development too ls has Increa cd
steadily. The rig ht tools leverage productivity, and economIC factors favor their usage

18.5 IEEE STANDARDS FOR EXPRESSING DESIGNS

The IEEE Software DeSIgn Document (SOD) slandard 10 16- 1998 provides gui delInes for Ihe documentation
of deSIg n . The lable of cOntenlS is shown In F,gure 18.29 IEEE guidelones explain how the SOD could be
written for various archilectural ryles, most of which are de<cribed above The case study uses the IEEE
standard with a few modl~catlon< to account for an emphasi< o n the obJec l-oroented perspeclive As hown In
the figure , Sections I through 5 can be considered soflware arch,lcc lure, and ection 6 can be conSIdered the
detailed deSign, to be covered In the next c hapter

18_6 EFFECTS OF ARCHITECTURE SELECTION ON THE PROJECT PLAN

Once: an architecture ha< bee n selecled, Ihe schedule ca n be made ma re >peclr, and more detaIled In
partl ular, Ihe order in whIch part< are bUIlt can be dctennlncd For examp le , on the cas. study 11m, kes <ell,"
to fir" develop the (hamCler! fram ework pack.ge , followed by Ihe speCIfic EllcoulllrrCl",,,, I", appl,cat,on
package S,n c thes packages w oll nOI be comple ted In Ihe ('''1 Iter.tlon f the ' llIr.I , we n.nte the
456 CHAPTER 18 SOFTWARE ARCHITECTURE

1. Introduction •
4. Dependency description

1.1 Purpose Architecture 4 .1 Intermodule dependencies


1.2 Scope 4 .2 Interprocess dependencies
1.3 Definitions, acronyms. ' ..... 4.3 Data dependencies
and abbreviations IAI 5. Interlace description

2. References y 5 . 1 Module interlace
3. Decomposition description 5.1.1 Module 1 description
5.1.2 Module 2 descriplion
3. 1 Module decomposition
5 .2 Process interlace
3. t. t Module 1 description
5.2. 1 Process 1 descriptIon
3. t . t Modute 2 descnption
5.2.2 Process 2 description
3.2 Concurrent process
6. Detailed design
decomposition
3.2.1 Process 1 descrlpt jon 6 .1 Module detailed design
3.2.2 Process 2 descripl10n 6.1.1 Module 1 detail
3.3 Data decomposition 6.2.2 Module 2 detail
3.3.1 Data entry 1 descriplion 6 .2 Data detailed design
3.3.2 Data entry 2 description 6.2.1 Data entity t detail
6.2.2 Data entity 2 detail

Figure 18.29 Tlte architecture parts of IEEE 1016-1998-500 table of contents


SOurce" IEEE Sttll016-199S.

corre ponding tasks ' Charac ters I" and "EncounterCharacters I." Arrows indicate depe ndence of packages on
others. For example, "EncounterC haracters ('. cannot be completed with out th e completion of "C haracters I:
as shown i n Figure 18. 30 . The sch edule sh ows th at "Integrati on and Te st I" canno t begIn until all of the other
tasks In Iteration I have been completed.

Month 1 Month 2 Month 3 Month 4 Month 5


--l
12341 234 1 2 341 234 1 234
---------- ~-

M ilestones
Freeze I Complete testing

Iteration 1

Iteration 2

Figure 18.30 Schedule following architecture selection


CASE STUDY; PREPARING TO DESIGN ENCOUNTER (STUDENT PROJECT GUIDE CONTINUED) 457

18.7 CASE STUDY: PREPARING TO DESIGN ENCOUNTER (STUDENT PROJECT GUIDE


CONTINUED)

Thl c tlon de)cribes a '\ccnano of how the Encoun - proces os. Ea h could be run o n a \Cpa rate parallcl
ter proJC t team may havc go ne about the creall on of thread, and the c threads would commuOicate when -
the- Encounter ar hltccture ever th4.: c haracters encou ntered each o lhe r. They
no tcd lhl s as a candidate architecture .
18.1.1 preparing The y onSldere d "cl lcnl .. erver" ne xt, but it was
In accordance with th,' PMI', Karen Pe ter, was the unclear to them what the "client" and "scrv<:= r" roles
dcslgn leader, with Ed Braun backing her up and would be, 0 they dism"scd th l alternative "Event
in pectlng all of the desig n work . Karen aimed to systems," the nex t type listed, appeared to be a
develop two thoroug hly prepared alternative archl ' cand idate architecture slOce the game responded
tectures for the Encounter project and bnng them to to cnher user- In itiated evcnt~, such as the presSing
the team's preliminary design re vlcw. She was deter· of an area hypcrlmk to enter an area, or to th e arnva l
mined to aVOId unpleasa nt haggl ing over anch ltectures of th(" ( reign character \0 the sa me area as the player
that wcre devi l·d by different engineers She fe lt that c harac tc r They no tcd thIS as another cand idate
ego rather than technical ISSueS predominated in such JrChllC Hire.
ca cs . She had even wo~e rnemanes of architecture ext , Ed and Karen conSidered "Virtual ma -
- ·compromiscs" {hal were crea ted lO reconcile com - chines ," asking whether each game executton con -
peting architectures. These freque ntl y resulted In po r sis ted cssl"ntlall y of th e interpretation of a cnpt
designs that everyone had to live and work with da ily Th is d id no t appear 10 them to be the ase
for months, if no t years. On the ot her hand, Karen did They co nsidered whether the ga me could be
not want to produce an architecrure in isolation. She thoug ht of as bu ilt arou nd a reposllory of data (a
decided that she and Ed would sclCL t architecture "repository system"). The data could be the va ilies of
candidates together, research them thorollghl y, and the harac ters and the statuS of the game They
present the choices to the team deCided that thiS might indeed be a po. IblillY if there
were man}' characters and many artifaCtS, bccau e In
th at case , rht' manipulation of large amOllnt~ of data
18.1.2 Selecting Architectures
might predominate Sin C Encounter \Va ... not to be
AI Pruitt had been thinking abollt the deSIgn of the
data -cen tn c, however, they rejected (hIe;; candidate
game application , and he gave Karen a sketch of an ad
- hoc CU I-driven anchltectu re. He pOinted Ollt that It Fin ally, they co nsidned a la yered architecture
T he quesllon here was whether Encounter could be
was simple and would be qUick to Impleme nt Ed and
Vlc\oJcd a a c;;cncs of clac;;\ grouping wtth each
Karen rovlc-wed Carla n a nd Shaw's 1"<lf!Catlo n of
groupmg: uSing o ne or two of the othcrs Karen
architectures to dl-t<.: rmmc whether Encounter ap -
fe lt th" t th ere wo uld indeed be at Ica t two u eflll
peared to matc h any of the archllecture a lte rnallves .
la yers one fo r role -play ,"!; games In ge ner"l , and
They Ars t asked whether Encounter oliid be
o ne for Encollnter They m.dt· " no te of thi S ca ndl -
descnbed as the flow of data fTom o ne procesSIng
dJle ar hltcctll re , and ended th eIr con'i.lde:ra tl ol1 of
dement to another The data would have to be the
arla n and Shaw' optlo ne;;
IXXltlons of the game c haracter< and/or their qllalllY
Now the y II ted the "rChllenlire candldate<
values Thl View did not ,ccm to them to ma tc h th e"
conception o( the same AI Prultt'< UI -dnven ardlltc ture
ext, they turned to arlan and haw's, oIlnde_
pendent components· arch ltectllres, the (Irst of Parallel I11munl calln~ procC'se'
whl~h w"' ' parall el communicating procc'ses ' To Evei'l l ... y'll' 1ll 1;"
Karen thi S seemed to he • flO"II)lo mJte h be~au;c
tach game char. tN cou ld be ()n"dercd onc uf the I.ayncd
458 CHAPTER 18 SOFTWARE ARCHITECTURE

TI, CY dl cu"ed w hl h of th«e described the to commIt· to archItecture. no advan tage of the
ovc",11 archltccture and whIch wcre <ub"dia ry to th e labl e (Table 18. 1) IS that It all owed th em to more
ovcro ll archlto ture T o d ecIde among th ese candl . ea sil y reevaluate th eir reasontng
dat es they evaluated thcm on terms o f th e qualotics n'lCIr conclu'\loll was that layenng was the

de crobed in th is charter. Th ei r sch eme gave 2 as pnmary archilc tural prin iplc Ince there was a
th e hIgh es t value and 0 as thc lowest. In the case of generic ro le·plaYIllS game layer and the Encounter
close scores, th e team would h ~)Vc ques tioned the ir laye r Itsc l f. They env lsaKcd the · cvent sysrems"
Scores closely In additIon . as they learned more architecture as ubSldiary to the layers They post·
about the applocation . they unders too d the need po ned a d etai led diSCUSSIon of parallel communicat·
to re VIS It thi s table up to the timc that thcy had ing proccsses for th c game c h aracters. Concep tuall y .

Table 18.1 Evaluation of architecture candidates by means of design qualities

parallel
Candidates AI communicating Event
Pruitt's processes systems Layered

Qualit ies

Sufficiency: handles the 1 1 2 2


requirements

Understandability: can be 0 2 1 2
understOOd by intended audience

Modularity: divided into well·defined 0 0 1 2


parts

Cohesion: organized so Iike·minded 1 0 2 2


elements are grouped together

Coupling: organized to minimize 0 1 0 1


dependence between elements

Robustness: can deal with wide 1 0 2 1


variety of input

Flexibility: can be readily modified to 1 0 1 1


handle changes in requirements

Reusability: can use parts of the 0 0 1 2


design and Implementation in other
applications

Information hiding: module Internals 1 1 2 2


are hidden from others

EffiCiency: executes within 1 2 0 1


acceptable time and space limits

Reliability: 0 1 1 2
TOTAlS 6 8 13 18
CASE STUDY: PREPARING TO DESIGN ENCOUNTER (STUDEN1 PROJECT GUIDE CDN1INUEDI 459

lhdr mam archw::,cture sele tlOn is reAeeted In 18.7.4 Refining the Architecture
ngun!IS. 35 Karen and Ed wen! now faced with the task of
Th~y
decIded to ~XP"'ss the "evcr.t ystems" decomposing each layer. They performed this by
arch,tecnon! by m~ans of tates and transitIons. Then plaCIng the two additional archllecnoral elements in
they debated whNher to use the State deSIgn pattern se parate packages. In the role-playong game laye r they
or a tatelaction table to describe the eventltransl' formed a package for the state machine called Role-
ttons, and deCIded to apply metrics to assist in PlaYlngGmh'. To handle the game characters, which
choosing from the architecnores under consIderation, move around in parallel , they created a Cha racttrs
Including AI Pruitt's. package They also created a Gam,f".iro"",,,,t package
They used e-mail to try to get agreement on the to contain classes describing the places on which the
""(:Ightlng of critena for architectures (extension, charac ters would move . Finally, they envisaged an
change, etc ,-see Table IS I i.e., "Evaluation of Artifact. package for the funore to describe the miscel-
arch,tecnore candidate by means of design qualit- laneous Items such a shields a~d swords th.t would be
ies,") 10 advance of the meeting, without mentioning involved. This package, postponed for future releases,
the architecture candidates themselves. They then e· would have a Repo.itory architecnore.
,
maIled AI a draft of the comparison table in advance Their decompositoon of the Encounter applica-
of the meeting to make ure that they had not missed tIon layer was analogo us since man y of its classes had

- any aspects of his proposal Al pointed out that the


choice of architecture was heavoly depende;]t on the
to inherot from the generic game level They decided
to create narrow access paths to the packages of this
weIghting, but was willing to accept the team's layer to prevent a sinoation In wh,ch any class could
- weighring. Karen and Ed drew up the spread sheet reference any other class. They felt that such un -
restricted references would soon become impossIble
Table IS. I, comparing Al Pruitt's architecture (a her·
natIve 2) and two others they had developed , and to manage durong development and m.intenance. To
- maikd It to the team members so that they would be accomplish this narrow access they used the Facade
prepared for the meeting. design pattern fo r each applicatIon package . Ed had
- 18.7.3 Team Meeting (Preliminary Design
some reserva tions abom doing (his because it 10 ·
creased th e amount of code the team would have to
Review) create .nd manage. Methods would not be called
At the meeting, Karen and Ed first confirmed agree · directly, he poonted out, but only through speCIal
ment on the weighting of croleria Because of their methods of the facade o bjects , thereby increaSIng
use of c-mail pro o r to the meetIng , th e team did no t the total number of methods It also Introduced
take long to Iron out the: few remaining Inconsisten · compl ,cations in that internal classes could not
cies No mentio n was made ye t of the arch Itectures even be mentioned by objects external to the package
themsel ves They presented the arch ,ttcnore altcr- (although theor generic base classes could be), but
natives to the team , shOWI ng the pread heet result< Karen convinced h im that the price was worth the
Aiter some d,SCUSSIon and mod,ncati o n of theor beneRt of havong a lea r onte rfa e for each package.
v assessments, the team conRrmed thtor selec tion of They obta Ined approval for their archotecture
the laye red arch ,tecture and the u« o f th e tate at a ubscquc nt team meeting .
desIgn pattern Karen and Ed', thought process and
preSontallon had been thorough The tcam's dISCUS· 18.7.5 Documenting the Architecture
SIan focused on how to Improve the arch,tcctu,c Ed and Karen used etlan I through 5 of the IEEE
I<!I~cled They so lICIted Idca< for rennlng the ar h, - standard IOl6 toexpre s thear hotcc ture lna oftware
tecture, but Karen dId not try to ra nk the Ide.s or DeSIgn Document ( DO) Ince the h.d dIVided the
ueate a s ln~le r ·(Ined vcr\lon or the arc hitecture Jl app lo a tl On Into two layers, one of wh, h wa slated
lh. mcetln,! '>he wanled to thInk thrOuRh the <ug - for reu e, the y de Ided to do lIment the framework
I!tsllOM ofll,ne "ro l c- play",~ I/a me' 10 er In • <cpamte DO
460 CHAPTER 18 SOFTWARE ARCHITECTURE

18 .8 CASE STUDY: SOFTWARE DESIGN 2. References


DOCUMENT FOR THE ROLE-PLA YING VIDEO
GAME FRAMEWORK SojlUln" EII9",ccrill9 An b)",-O"e,,'ed Pcrsprc"oe, by
E. J Braude (Wiley. 200 I).
We have two designs to describe The Rrst I that of UML The UHtfied Moaef"'9 u"'9""ge u,"
Guide, by
the Role-PlaYIH9 Video Gn IMe framework ; the second is C Booch, J. Rumbaugh , and I. Jacobson (Addison -
that of the Encounter role -plaYing game . The DD, Wesley
for both de Igns are split into twO parts_ The first IEEE standard 10 16-1987 (reaffirmed 1993)
parts, DD ectlons I through 5, shown below, !,'Uldcli nes for genera"ng a Sofrware DeSign Document.
consist of the architectural aspects of the design .
The second part, SDD ection six, appeanng at the
3. DeComposition Description
end of Chapter 19, con IstS of the detailed designs.
n,e dependence of Encounter on the framework IS
spccd,ed 10 the Encounter case tudy ,
Note to the Student:
HIstory of versions of thI S document;
This s<ction speCifies how the framework clas-
yylzzz K. Peters: Initial draft ses for role-playing video games arc to be
grouped . This reAects the top-level decompo-
x/yy/zzz K_Peters: revised, incorporating com- sition : the detailed decomposition into meth -
ments by R. Bostwick ods, for example, is left for the detailed design
x/yylzzz K. Peters: moved details of c1asse to (see cas< study at the end of the next chapter)_
Section 3

1. Introduction 3.1 Module Decomposition

1.1 Purpose
ThIS section shows the decomposition then
This document describes the packages and classes of explai!1s each part in a subsection.
a framework for role -playing Video games.

1.2 Scope n,e framework consists of the RofePlayiH9Game,


CiJllraricrs. Ar"jael" and LAyo,,' packages_ These are
This framework covers essentials of role -playing decomposed into the classes shown in Figure 18_31 _
game classes. Its main intention is to provide an The classes in these packages are explained below.
example of a framework for educational purposes. Unless otherwise stated, all c1asso in the c packages
It is not Intended as a framework for commerCial are public. As indicated by the (UML) italiCS nota-
games si nce ItS size is kept small to facilitate learning. tio n, all of the framework c1asse are abstract.

1.3 Definitions, Acronyms, and Abbreviations 3.1. 1 RolePlayingGame Package


This package IS deSigned as a state - tranSition rna.
framework : a collectton of interrelated classes used, chine. The concept is that a role -playing game IS
via inheritance or aggregation, to produce families of always in one of severa l states. This package makes it
applications pOSSIble to describe the pos ible sta te of the game
RPG, Role-playi ng game: a video game In and the actions thai can take pl~ce in response to
which cha~cters Interact in a manner that depends event>. It implements the State deSign pattern (sec
on their characteristics and their environment [8]) The Sta te of the game I< en ap ulated
CASE STUDY: SOFlWARE DESIGN DOCUMENT FOR THE ROLE·PIA YING VIDEO GAME FRAMEWORK 461

RolePlayingGame Characters

RPGame state
handleEvenlO
GameCharacter
..J

O.. n
( Slale.handleEvenl(): )

.,
IRPGEvent r- GameState
handleEvenl O
GameEnvironment

GameLayout
2
GameArea ~
Artifacts For future
releases
GameAreaConnection

Figure 18.31 RPG fra mework for role·playing video games

(represented) by Ihc part Icu lar Gam,Sla l, obJe tag · 3.1.3 GameEnvironment package
gregated by the (s Ing le) RPGam, object Th is ag!."e · T his package de cnbcs th e phYSIca l envIronm en t of
gated object i named statc. In other words, state is the ga me . T he class GntllC'Llyolll aggregates co nnl'C -
an attribu te of RPCam, of type Gam,SI,"'. tion obj t:ct" Each connecti o n obJc 1 aggrcgatc~ the
The functIo n ha>ldl,E""'I() of RPCam, I ca ll ed to pai r o( Gam rA,m objects that Il connect<.. Tlw. arc hl .
ha ndle each event occurnng on the monItor (mouse lectu re allows for multiple connections between twO
c"cks, etc ). It executes by ca ll ing the hmldl,E"",:() areas . Eac h GamrAr(Q object aggregates t11t~ game
functIo n of state The app licab le versIon of handl,· characters that It ontalAS (If any ) and can detect
Evtrll() depends on the particu lar ubclass of Gm.,Slal, encounters among chara tl;'r~
that state be longs 10
3.1.4 Artifacts package (Not Implemented-
3.1.2 Characters package for Future Releases)
TIl\'; packagc IS Intended to store e l c m c nl~ to be;.'
10CCllCd In areas, slich as tree or tables. and Cnt ltl C
It may seem strange to have a package co n· posse< ed by character , such as , hIe Ids and bncka es
tai nlng JUSt oAe class, but most arll faclS In
software desIgn have a te ndency to grow 3.2 Concurrent Process Decomposition
Even if the pacakge docs not grow, this
d~ not dISqua lify it< usefu lness. For anot her nl(' framework dOl's not II1volvl" conClIJT(:nl pro ~'C'
example of a package with just one class, sce
jaua appl'l, whose only class IS Applrl (but 11 . 150 4. Dependency Description
contains a few '"tertaces)

ThIS 'c lIon dc< "be all the way' In ".hl h


TIm package containS the Cdrn,r/wdCItr' la" the modules depend on cach other
whIch dC>CTlbes the charoet rs of the ij3me
462 CHAPTER 18 SOFTWARE ARCHITECTURE

Tl,e only dependency among the framework UML Th, UH ifi,d Modrl"'g UlHgung, U><r CUld" by
module, I the Jggregation by Cam,Arra of Booch, J. Rumbau g h, and I Jacobson (Addison -
Gamr ham fer Wesley.
IEEE standard 10 16· 1987 (rcafflrmed 1993) gUide·
5. Interface Description lines for generating a oftwar. Desig n Document

All classes in these packages arc public, and thus thc


Internces conSi t of all of the methods in thei r classes.
3. DeComposition Description

The Encountcr architecture is deSCribed usi ng three


18.9 CASE STUDY: SOFTWARE DESIGN mode ls· lise casc, cia s (object) model , and state. In
DOCUMENT FOR ENCOUNTER (USES THE addition, the relationship bet,,'een the domain pack-
FRAMEWORK) a8es of Encoun ter and the framework described '"
thc SDD enti tl ed "Ro le · PlaYinS Came Arc hitecture
HIStory of versions of this document,
Framework" will be sho wn .
x/yylzzz K Peters, initial draft
• • •

x/yy/zzz K. Peters, addcd decomposition by The IEEE standard is extended usi ng Sections
usc casc model and state model 3.4 and 3.5 in o rder to descri be th ese models.
Recall th at the other possi ble model is data
1 . Introduction
flo w, whic h we have no t co nside red useful in
this case. In the particular case of this video
1.1 Purpose ga me , we chose to use th e statc descri ption as
part of th c requirement as we ll as the design.
Th is docu me nt describes the desig n of th e Encounter
rolc· playing game.

3.1 Module Decomposition (Object Model)


1.2 Scope

This deSign is fo r the prototype version of En· This section sho uld no t dupl icate the "detailed
counter, which is a demonstration of architecrure , design" secti o n described in the next chapter.
detailed design , an d docume ntation techniques. The We do roOt go i ~to dotail here regarding the
architecture is inte nded as the basis for in teresting con tents of th e packages.
versions in the future . This descrip tio n excludes
the framewo rk classes, whose design is provided In
the SOD cnlitled "Ro le· Playing Came Architecture T he package architecture for Encollntl!r is
Framework." show n in Figure 18.32. T he th ree packages arc
E'1C'OUl1tlrGamc , El1co ,mttrCha rac1trs , and fl1C"o"nttr-
1.3 Defi nitions, Acronyms, and Abbreviations EH OtrOtfmrnl. These have: facade c1as cs El1 counfc:-Gamc,
El1couPltcrCasf, an d fn co uPi ttrEl1lJiroPlmtnt respectively .
None The facade class of each package has exactly onc
instantiation , and is an interface through whic h all
2. References dea lings wit h the package lake place . Th e re main.
ing classes are not accessible from outSide the
"Role· Playi ng Came Arc hilecture Framework: sec· package (Sec Section 17.7. 1 In Chap ler 17 and
tion in Software £.9i."n.9 A. O'J<ct-Orirnt,d Pmprcti." [ I ] fo r a complele deSCri ption of the Facade deSign
by E. J. Braude (Wiley, 200 1). pattern .)
CASE STUDY: SOFTWARE DESIGN DOCUMENT FOR ENCOUNTER (USES THE FRAMEWORK) 463

EncounlorGamo

EncounterGame
.. facaC16,.
EncounterCharacters

EncounterCast
.. fscade,.
Encoun18rEnvironmeni

EncounterEnvironment
.. facade ..

Figure 18.32 Architecture and modulanzatlOn of Encounter game

3. 1. 1 EncounterGame Package The data stnl ru res Aowing among lhe pack·
The EncoIHl,crCmt1( package consi ts of the classes can· ages arc: defined by the Area , EncoIH1!rrChnrtJc frr, and
rrolling the progress of the ga me as a whole 11,(, Ellco lI~llrrAr(Q Dill/teflon clclSSC.,
package IS dl"signcd to react to lIsc r actions (eve nt,).
3.4 State Model Decomposition
3.1.2 EncounterCharacters package
The E'1C'ouHttrChamc frr5 packa ge cncompas lOS th e EnCOUnl('r co nSIst, of the slate, <;hown In FIg.
characters invo lved In the game. These Include ure 18.3 .
character(s) under the co ntro l of the playe r toge ther
with the foreign chllra lers ,
This state diagram was provided in the SRS ,
3.1.3 EncounterEnvironment package Section 2 . 1.1 , where it was used to des nbe
The EnCOUHltrE,wiroH,"oll package dcc;cnbcs the phys - the rcq uirements fo r En ounrer Tht, remaIn ·
icallayout of Encounter, oncluding the areas and the ing stares mentioned in the reqUtremenb WIll
connecti ons between them It doce; not Include be implemented in ubsequent relea<es
moveable Items, Ir any
3.5 Use Case Model Decomposition
3.2 Concurrent Process Decomposition

There are two concurrent proccc;c;cs In Encou nter Th e


fir<;! IS the maon VISIble a tion of the game, m whIch the Thl section IS added to the IEEE 'pcclflca tl on,
player manually moves the maon chara ter from ,rea to whICh doc not address the use case concept It
adjacent area The second con<"t< of the moveml'nt of has been added at the end of thIS section 0 a,
the foreign character (rom area 10 ildJilCC lll area., not to dl>turb the st;;ndard order

3.3 Data Decomposition EncounH.' r onS I ~ t s f thrl'" u .. e JIi;Co;; IPlllwl,:r


Trfwrl 10 AdprtCtlI Artll , Jnd EtltOIHlltr FortHl11 Chili" Il't

~nH.' St' u,(, ('xplJlI"lcd In del;)!! In thc R


()'c<;: :lrc
Descflbc, the <tnKtur ' of the data WIth", the
"cellOn 2 2, Jlld Jr(' clt·tollled In ,cellon ... kllcr III till'
applIcatIon
dot-um ' fll
464 CHAPTER 18 SOFTWARE ARCHITECTURE

Setting up
Player _ -1 Reporting
dismisses Setting
report
Player
qualities
window
compleles
setup
Player
dismisses Player
set requests Player
qualities status requests to
widow __-- , qualities
Foreign
character
Waiting I---<: enters SleB
Foreign
character
Playel enters area
moves to

Player
adjacent area
\ Encounter
campleted --l Engaging
quits

presenl]
absenl]

Figure 18.33 State·transition diagram for Encounter video game architecture

Details .,.., given in the "detailed desigr." There are no significant dependencies among
section. the usc cases,

4. Dependency Description 4.1 Intermodule Dependencies (Class Model)

This section describes the dependencies for the The: dependencies among package interfaces arc:
various decompositions describe d in Sec tion 3. shown in Figure 18.34.

EncounterGame

EncounterGame
EncounterCharacters

Encoun1erEnvironment

FIgure 18.:W Architecture (rnodularization) of Encounter \/ideo game


CASE STUDY' SOFTWARE DESIGN DOCUMENT FOR ENCOUNTER (USES THE FRAMEWORKl 465

Th~ Ell OIm,rrCnmr pa kage depend o n all of the 4.4 State Dependencies
other En ounter p() ckage~ The En oJmlrrEmmotllnnst
po kago I d Igned to depend On the E"co""lrr- Each State I related to rhe <tate< Into whIch lhe game
ebara,'ers pa kage ThIS IS becau c the game'. charac · ca n lranSll ion fro m it
ter Int~rnc tl o n takes place o nl y on the context of rhe
4.5 Layer Dependencies
~nvl ronm ~n t. I n part icular, Arm objec t arc re po nsi ·
ble for detcmllning the presence of the player's char- The Encounter app location depend. on the Ro/r-
.ctcr together with the fo reign charncter P/IIYJIl9 Gllmr fra mewo rk a , hown on F,gure 18 .35
O,'pendenclcs among no nln terface classes arc Each applICa tion package u'c< exa t1y one frame-
expJalnl.'d late r i n th i.; docume nt.
work package

5. Interface Description
Such dependencie arc detailed deSIg n
specIficatio ns. TIll<; section descnbes the InlC-nan.· .. lor the obJcct
model o te thaI ,eve ral of the cla',cs descrobed arc
dehned In the de<ogn dc< roptlon of the Ro/r-PIIIYIIlg
4.2 Interprocess Dependencies Ga me Framework .

When an engagement rakes place, the pmcess of 5.1 Module Interfaces


moving the mai n charac tt: r about and the pro c;,; s
contro lling the movement of the fo reig n charac ters
Descrobes the interaction among the packages
Interac t.

4.3 Data Dependencies 5.1. 1 Interface to the EncounterGame


package
The data tructures OO'oJ '" B among the pac kages arc Th e Inter face to t h c Et1 colwfcrGnmr package IS pro ·
defi ned by the classes, whose mut ual dependencIes v lded by th e the obJ e 1 of the E" colmttr
Etl COlwtrrGm11c
are descro bed on ccto o n 6 of thIS docume nt. GII,"r racade cia It conso" of the follOWIng

j._---_..._ .._--;::-=..-:::..:::-.=-=:::-=:::-:::._:: ;......


_ _--:::.-:::-::.=._=:::.==:::.: ._: ;._._. ~

i Characters GameEnvlronment AolePlayingGame


I I l
• •

, Role-playing game layer (framework) .. uses .. ,,
:.. .•.......-.....--·1-..... ,.._ ..•- .... . ........ ... . . . . . .. . .,...: :': '::'
.. ~
===~:;-
=
I•
,, IEncounterGame I I
,
I
• IEncounterCast I EncounterGame ,
,
, --'---------
j
,
EncounterCharacters
I EncounterEnvironment I
\ • by member classes Imp/emen·
I ring framework Interlaces EncounlorEnvlronment
.- -- -- --.- -. - - - .-- _. - -
Agure 18.35 FramewOrk·i-applica tlon depend ncles
466 CHAPTER 18 SOFlWARE ARCHITECTURE

1 Encounler "mc ~e lTh cE n oll nlcrCamcOllgcl\ 6. InMHe HeINclghborhoodArc.s(Arc.;llgct\ II,,.


the ani , InS tJIl e and areas one or two connc.:(ll() n~ dlstilnt

2 arn e laIc uC I la lc OIl urre nl sta le of Ihe f


~ 5.2 Process Inter ace
EtlcoutllrrGmttt In sta nce

3 VOId SCI lale(CJl11eSlatc)lI- of th e Ell ol!ll lrrGamc


In StanCe
W e stated on Sectio n 3.2 th at there a rc twO
processes In volved in Encoun ter. Th ere is a
4. IIAny even t aHec lmg th e . ingk- Ell ou,lll'r ,ame SIg ni fica nt design decisIo n to be made in re·
In stance: gard to the interface to th e fo re ig n c harac ler
5. voi d handlcEvc nt (AWfEve nt ) movement process, and we describe th e result
here . O ne o ptio n is to have the fo re Ig n c h.r·
ac ter a thread, contro lling itself. This has
5.1.2 Interface to the EncounterCharacters
advantages, but requ ires this c harac te r e ither
package
to know the enviro nment- a disadvanta ge in
The intcrfJce to the Encol/lflcreharnel,n pack age is
te rms of c han gi ng and expanding the game-
provided by the tbrEncolmlrrCnst object or the E"colwltr-
o r to be able to fi nd out about the e nvi ronm ent
Ca,' f.. cade class It consist of th e fo llowing.
dynam icall y, whic h wo uld be an elegant de·
sig n but too ambitio us lo r the scope of this
1 Encou nlcrC3st gelTheEncounterCast()//gc ts the
case study. The architect'ure o pts for another
single lO~ta nCt:
alternati ve, wh ich is tated here.
2. CameCharacler getTh ePl aye rC harac ter()//i e .,
the uniqtJc character

3. C ameCharacle r ge tTh eFo cclg nC haracter()/lthc 5.2. 1 Player Character Movement Process
un ique ch arac ter 11,e interfaces to the process that moves the player's
4. IIExchange q ualI ty values specific to th e game charac ter aboul th e game consist o f the g raph ical user
area interfaces specified in Ihe SRS. TI,e process reacts 10
events descri bed in Section 3 4, whI ch are handled by
5. VO Id engagePlayc rW ithFo reignC harac ter th e El1colw lrrCmnr package in accordance with its
(CameArea) spcctfk~H jo n s , described later In th is document.

5.1.3 Interface to EncounterEnvironment 5.2.2 Foreign Character Movement Process


package The process or moving th e forc lgn chara cter is a
The interface to the: Etlcotm frrEHv;rollmrnl package is separatc process associa ted wi th and co ntro lled by
provided by the EncouttlcrEnvirottmt'Ht object o( bfCounttr
the Etlco14 ntrrCamt si ngleto n object. Th is process IS
EPllJlfomnrnt Facadt class. It con ists of th e fo llowi ng: contro lled by th e me th ods inherot ed fro m Jalln lang
Thread
t . EncounterEnvi ronment gc tTh eEn.counter
Envi ro nmentO//gers th e Facade o bjec t
18.10 CASE STUDY: ARCHITECTURE OF
2. CameArea getArea(Stri ng ) ECLIPSE
3. CamcAr<:aConncction getAr<:aConncction(StTing)
No te to the Student,
4. void movePlayc rTo(Area )
The description that follo ws describes the
5. VO Id mo veFo reig nCharac terTo(Area) thro w< anchitecture of Eclipse in a top·down fas hion.
AreaNolAdjacentExceptio n
CASE STUDY: ARCHITECTURE OF ECUPSE 467

18. 10. 1 Scope • The PI"g-l" Drotlop",'''1 EII""o","rnl altows develop -


(1111' p~,.,graph makes PCCIr.C Ihe , ope o( thIS ers 10 crcatc and add plug-inS It uses the Java
documenl (the tide "ArchItecture of Ecl,pse" seems development tools.
clear enough untd we rcad In th" paragra ph that ;t "
quailfied) 1 18.10.3 Platform Module
. 01 Apnl 2004 . thcre werc three Eclip.e The platform decomposes", shown In FIgure 18 37
",kases \'lie wdl pro Ide an veralt descriptIon of The modult< ,n Figure 18.37 are as foltows .
the architecture of rciea,e 3.
• Rutllime handles the avallahle plug -ins at runtime

18.10.2 Overview • Wor po, manages proJects. which con",t of files


The Eclipse ar hitecture has been de<cnbed i>y and folders
Gamma and Seck [9] a <hown In Figure I 36 • SIU/IJorJ W,dgrl Toolsrl (SWT) prOVIde< graph,cs
Cieml."nlS

Rgure 18.36 has just three part>-a manage· • JF<IC' " a se t o( UI framework USlnS \xrT , used (or
able number to comprehend Eclipse" a large co mmon UI
and very complex pro duct, however. T oge the r • \Vo,kb,,,c/, "defines the Ecl,pse UI paradIgm Th"
with the brIef explanatIons below, this decom- Involv('<; editors, Views, iln d perspectives
"I

poSition IS helpful. One has to searc h for a


whde to find a de<cnption like thl by lookin g 18.10.4 Java Development Tools
through http"'www ccl'p<e org. The deSIgn phdo<ophy of Ecilp,e " to e able to budd
Jny language CIlVlronmcm on lOp of tht.' Pilltform The
Java Development T ool UDT) module" the Java
• The Plaifonn IS the InfTastn.lclllre of Ec J.p<e a nd is cnv,ronm(,; nt It on I Sb of [he Jm}tI (orr module ThiS
Independen t of languages with which Eclipse ca n is shown In Figure 18 38 .
be used and Independent o( all plug· in<
• The Jm", O",tlop,",,,t Tools utiJ.ze the Plalform and IS We won't pursue thIS module or further par"
class model (or a Ja va In«'raWVe development o( the Eclipse architecture In till ca,e study
environment

I Plug-In Development Environment


I
Jj. depends on
I Java Development Tools
I
Jj.
Platform

Rgure 18.36 very high level architecture 01 Eclipse


St:Iuru MiC-UtO from Ct.tmn"Ia (net'!. and 8«k ~''f'Il "CMlflovung 10 Ecllp~ PnnclO'~. P,'tter~. Plug Ins. I\O(llson W{W;1ey 2OOJ, P 5
468 CI1APTER 18 SOFTWARE ARCHITECTURE

I UI

I
I
I
I Workbench
I
Plug-In Developrnent Environment
'- I
I
I
I JFace
I
I Slandard Widget Toolsel
I Java Development Tools
1/
Pla~orm ~ depends on

",, Core

, \
I Workspace
I
\
\
, \
I Runtime
I
Key: 0 A depends on B.
@

Figure 18.37 Architecture of Eclipse platform


source ' AOapted hom G3mma. Erkh, and Back., Kent " contrIbUting to Eclipse Principles, Patterns, Plug-InS," Addlson·wesley. 2003, p 283

The architecture of the OprnOfficr or!! sui te is


18.11 CASE STUDY: OPENOFFICE
designed to be platfo rm·independent. It consists of
ARCHITECTURE
four layers, as described 10 Figurc 18.39.

NOle to the Student,


It is not straightforward to locate the description We will no t discuss the StarOfficc API here. As
of the OpcnOffice .rchitecture in a single, iden· indicated in Figure t 8 39, however, three lay·
tiAable place. ers depend on it. The author has made local
improveme nts in the writi ng of the origi nal.
This architecture description is at a very high
The following is a useful white p.pcr th.t cts ou t level.
the design methodology used for OpenOfRce, and
nluch of thi s section is .d.pted or quoted from ( IOj

UI

I Workbench I
I JFace I Java Development Tools
I SWT I I Java Core
I
Core: Workspace

Core: Runtime

Figure 18.38 Architecture of Eclipse the Java development tools mOdule


Source Adap{eO 'rom Gamma. Erld\ and e ....1(, Kenl " contributing to Ectip$e: Pnnc:~l r5, p"ttcms. ano Plug-InS," AdcfISOn-'''ltSI~. 200J. P 282
CASE STUDY: OPENOFFICE ARCHITECTURE 469

.-~ Application
Dependent
IU·
"

80::

Framework
-'"
en Infrastructure
l.1Jyers

System Abstraction
-L
Operation System / GUI

OpenOffice Architecture

Application
-0.. SW SD SC SM Layer
= ,_._ ......
« Framework
Q) Layer
.-u
~

o~
UNO UCB SO
l::===-:::;-;::===~-;::==;
e-'"n
Infrastructure
r Layer
VOS TOOLS
.- ---- -- -------- ._--- --------_ ... ------- -- -- -_ ..System
-----
STL RTL OSL Abstraction
Layer
------- ------- --- _... -.----------_._.--.---- -----------
[ OS / GUI I
Figure 18.39 The architecture of OpenOffice
~ Edited from Qpe:/OfflCe. hltpJ IWwW openoffice OI'glWhiteJ)aJ)ers/l ec.h. overview/ tech3wervlew I'ltmJ,J

The System Absttilct.o n laye r "e ncapsu lates all 18. 11.1 System Abstraction Layer
system spec.fic APls and prov.de a cons. ten t o b· Th is sec tio n is reproduced from [ 1 I) It references
Ject·oriented AP I to .cce« sy tern resources in a Figure 18 39
platfonn mdependent manner · It provides a k.nd of Platfonn ·dcpe nded implementation take pia e
single, v.rtu.1 opctilt .ng system on wh.ch to build below the ys tem Ab. tractlon Layer ( ALl or arc
OpenOff,ce part of 0 pl1o nal modules "In an ideal world an
The In frastructure layer . a platfornHndcpen. .m ple mentat. on of the SAL·,peciRe [unctlo mhty
dent environment for bUilding app lica tio ns, compo - and recompi ling the upper I. er module will all ow
ncnt~ Clnd <;crvlces you to nm the appl.catlons To prov.de the whole se t
The Framework laye r· To al low reu<e, tI", laye r of fun ctio nality, the opti onal platform spee dic mod ·
prov.d('S the envlto nm ent for appi1ca llo ns. It al ° ule" I.ke telephony suppon or speech recog n.t.o n,
prQv.des all shared funcllon.l.ty ,ueh "' com mon have to be ported , too " To reduce portin g cfforts.
d.alogs, (.Ie ac(css, and eonfigur.l1on mana gem nt the AL fun ctio nality I ) reduced to a 011111",,,1 " . ." t,
n'e Appl.c.at.on layer "All OprnOffic< 0'9 appl •. avallJblc o n every pladom, " (or ~Omc ,v,tcnh
cat1<Jns are part of thIS layer T he way the. appl. · th e laye r Inc1udc'i ~o m (" Impl Clll cntallO lh to emulate
cat.ons .nt·rou I~ b., d on the lower layer> .. "'ul11 e runCtlO Il i.1 hl y or bt' havlor. F r example on
Th next ~CC llOn\ dc\Cnoe ,hesC' bytr~ In mort "'y, lc.:m, whe re n nilllVc nudtllhn:ild ,ng I ,,,pportcd
the layer ca n su pp rt <0 ailed ·u<e. land' thrc:ad, •
470 CHAPT<R 18 SOFlWARE ARCHITECTURE

This d~>crlpllon IS not very lear, In (act, It is The last <entence is useful and appropnate at
difOc\l!t to wnte meaningfully and clearly at a this level. The meanlnS o( "semi platform
high level. What follows nc"" however, IS Independen t" is unclear, n,e
second se ntence
Indeed clear and meaningful. IS not clear but is presumably explaIned in the
more detailed sections

Asshown in Figure 18 40, the AlconsIStsof the


Operating ystem layer (0 l ) the Runtime Library 18.11 .1.3 Standard Template Library "As age·
(RTL), the Standard Template lIbrary (STU , and the neric co ntaine r library the standard template library
platform -independent pan of the Visual Class Library is used . It supplies imp lemcnlcllio ns for list, queues,
(VCl) Thesc are descri bed neXL stacks, maps, etc."

1B-11 _1.1 Operating System Layer 'The oper- The relationship with the Standard Template
allng system layer (OSl) encapsu lates .11 the library that comes with C+ + should be c1arifittl
o perating sy tern speciflc functi onality for using
and accessing system speCific re ources like Rles,
memory, sockelS, pipes, etc. The OSl is a very 18_11 .1.4 Visual Class Library 'The VCl encap -
thin layer with an object-orien ted API. In co ntrast su lates all acce 5 to the different underlying CUI
to the upper layer this object-oriented API is • C- sys tem s. The implementation is separated into fWD
API." The reaso n for this IS to allow easy porting to major parts. One is platform · independent and In -
various platform s using different Implementation cludes an object -oriented 20 g",ph ics API with
languages _"For embedded systems or Internet app li - metafile-s, ron~s , raster operatio ns and the Widget
ances, for example, an assemblc:r language can be set use by the OpenOffice .org sUIte. ThIS approach
use d to realize th e Inlplcmentation ." virtually gua",nt.es that all widgets have the same
behavior independentl y of the CUI system used. As a
18.11 .1_2 Runtime Library "The runtime library result , the look-and·feel and the functionaliry of the
provides all semi platfonn independent functionality . widgets on all platforms arc the same."
There i an implementation for string cia scs pro -
vided. Routines (or conversion of ~tnngs to diHcrent
This explains the squiggly lines in Figure 18.39
character sets are implemented . The memory man -
that separate the rwo parts of the VCL
agement functionality resides in this modu le ,"

Infrastructure Layer

System Abstraction layer


I Operatjng j Runtime I Standard Visual I
System Ubrary Template Class !
Layer

(OSL) (RTL) ,
LlbJ1lry
(STL)
I Library
(VCL)
I
I I I I
Operation System I GUI

Ftgure 18.'0 OpenOffice architecture system abstract!on layer


.soc.n. Edlted from ~I!nolnce, httP.JIWWW.OOCnofflcO. OI..B/WNto~O\Ic;..oicwItec.h-.M.••\Iiew.html.l.
CASE STUDY: OPENOFFICE ARCHITECTURE 471

The platfoml .dependent pan Implements a hbraru,:s Thl~ Includes a co mmon Implementation
JD·gr.lph,c drawing anva, that IS u<cd by the for handlinS date and time re lated data , an Implc ·
pladonn' lndependent parts. ThIS canvas redirects mentation of "lru lUred storage) , a generic registry .
fun 1I0nailly dll-ccdy to the underlYing U I , y,tem l ypc~af(' managcmc.' nt , and pcrsl",tcnCc of property
Currently, there CXI"-l Hllpk'mcnlallon" for the data "
Win32, X· Window , 0 /2, and Mac The a e <
to the prlnllng functionality , clipboard and drag. 18.11 .2.3 Universal Netwo rk Objects Un lUmal
and·drop IS also reali zed In"de the V L. " Ntlwork Obit Is "the o mponent tt-chnology used
wllhln ptliOlficr or9 "It . IS heaVily bascd o n multi ·
threading and n(:( ..... ork communlCJtlon ca pabilities
18.11.2 Infrastructure Layer It

The Infra<tnlcture layer on<l ts of the pan, ,hown


in Figure 18.41. The e arC cach explained nexL
ThIS paragraph says something imponant
about [he architecture of OpenOf~ e
The figure implies that ompou"J Ob)CCI, (for
example) depends on the AL and that the
I_fra,'",c'ul'< layer depends on It It implies no "The system con"stS 01 several p,ee An IDL·
depende nce between Compoulld Objrrl' , UCB, Compiler, whi(h generate, out of the ,pecd,ed def"
and SBL. nitlon of an Interface a binary n:prcs(.'n13110n and
tht· associated C.Header o r Java tcc hn o logy Iii",
The binary repre entatIOn" platform and language
18.11 .2.1 Virtual Operating system Layer The mdependent and is at runllnH.:.' lIsed to marshal argll-
purpose of thiS layer L "to make the usage of 'Y tem ment ror rem ott' n.m lion call..: or to ge nera le code on
rc<ources like files, threads, socket , etc mo re conve· [he fly for a specific language to acCeSS the Imple ·
nient the: virtual opera ting system laYlor en apsulates all mentation provided by the Interface TIll> tec hnique
the functionality of the operallng system laye r Into + .. reduced the amount of generated codt' for the dl .
classes. The CH classes here offer an easy to use acces krent language b,ndllig tremcndously The draw ·
to all sy tern resources in an obJect. oriented way · bJck i that not only for every language binding a
speclA backend for the code ge neratio n" needed It
18.11 .2.2 Tools Libraries "The tool functional · IS lhJl for every speclhc o mpd er a bndging n1 0 dulc
Ity of Open Office conSists of vanou sma ll 1001 IS needed a t nll1limc "

Framework Layer

Infrastructure Layer
,
Vlnual
~

I Tools

UnIversal Compound I •
ScriptIng
Ope ra1lO 9 Llbranes Content ObJecls and BaSIC
System Broker Library
(TOOLS) I
Layer
(UCS) (SSL)
(VOS)
I
System AbstractIon Layer

FIgure 18,41 OpenOllice archl tectur Infrastructure layer


5oLw(# l<lrtttllrOtn 000t10t1.u, "up I/WNW opt~rofflC.e OI"¥f'NIlrlO .P<)ocrSi I n CWM/lI"'WfteCh 0V\'fVi('W htm!.3
472 CHAPTER 18 SOFTWARE ARCHITECTURE

prov.des a platform ·.ndepe nde nt .mpleme ntat.on of


till S functionality for ompo und documents and
This paragraph is no t ea~y to undcrsra nd but it for embedding v. ual controls <uc h as mult.med.a
Is at a high levd and becomes clearer as o ne players ano vJnOU~ v l ewc r~ Storage IS compatible
reads more details. It m ixes a description of the w.th the OLE structure slOragc format. Th.s allows
arch.tecture with • ration.le for il. Require- accts to OLE compound documents on t-very plat ·
ments documents frequently include piece of fom, whe re OpenOmce.org is ava .l.ble. O n Win ·
rationale . dows the implementa tion interacts with OLE services
and so .1I0ws a ti g ht .ntegratlon of OLE·ca pable
"Many parts of the UNO technology . re impie - appli alion s"
mented ClS UNO components. This (acl lat alcs Ac xl'
bility and runtim e exte nsions: c.g., providing new 18.11 .2.6 OpenOffice.org Scripting and Basic
bridges or communication protocols. U NO provides Library
l~n spare nt access to components locally or over the
network. 1I0P ca n be used fo r network commun ica-
"Scrip ting" refers to the ability to write proce ·
tio n. J( components arc realized as shared libraries ,
dures that cause the application to execute
they ca n be loaded by UNO in to process memory of
application functions in a dG'Si red sequence.
the app lication accessed by fu nction calls. Th is does
For example, .ba l Ales in Windows and .,b files
no t require mars halling of arguments as requi red (or
in Uni x arc scripting files. Design documents
remote function calls."
inevitably rel y o n jargon that the reader must
be f"miliar with .
Th is paragraph seems to be hera lding an am -
bitious design , consisti ng of objects available
"Th e scripting functiona lity that comes with
o n the network.
the Ope nOfAce.o rg suite is a BASIC dialect featuring
an interpreter that parses the source sta teme nts and
ge nerates meta instructions. These instructions ca n
18.11 .2.4 Universal Content Broker "The Unl'
be executed direc tl y by the supplied meta ·i nstruc·
vcrsal Co ntent Broker allows all upper layers to
tions processor o r can be made persi stent i n modules
access dirf~re nt ki nds of structure content tran spar-
o r libraries fo r later access. All fun ctio nality supplied
e ntl y. The U CB consists of a core and severa l
by the upper level application compo ne nts is acces·
Universal Content Providers, which arc used to
sible via a scripti ng i:1tcrfacc i n the component
in tegrate different access pro tocols. Th e current
tec hnology . Thi s wi ll help to ensure that new com·
implementations provides content providers for
po nent · usi ng the OpenOffice.org compo ne nt tech ·
the HlTP protocol, FrP protocol, WebDAV pro ·
nology can be fu ll y scriptable without spending a
toco l, and access to the local fi le system .
huge amo unt of dfort.
The U CB docs not o nl y provide access to
The scripti ng interfaces are also implemented
the co ntent, it also provi des the associated meta
as compo nent's ('hat will allow an easy in tcgrCltion of
information to the content. Actua ll y there is syn-
other scripllng languages." They provide fu nctional.
chronous and asynchronous mode for opera tions
ity . such as core reflection and introspection , Similar
supported."
to Java platfo rm functionaliry .
18.11.2.5 OpenOffice.org Compound Objects
"The Compound Object implementatio n provide 18. 11.3 FrameworkLayer
the functionality to build compound documents, The Framework Layer has the parts shown in FI!,'Ure
where fo r example a spreadsheet is being embedded in 18.42 .
a word -processor document." Inc implementation These parts arc descri bed next.
SUMMARY 473

-
Il..
Application Layer
«
Q) Framework Layer
u
-
:s::: I
Applicallon SVX Library
0~
Framewo rk library I !
-'"
rn
Infrastructure Layer

Figure 18.42 OpenOffice architecture framework layer


~ Opttr.ofRce. nup I/WWIY openolhce orgIWh1le..Papefsltech overvieWl1ech
- -oveMew hlml_3
18.11 .3.1 The Application Framework Library 18. 11.4 Application Layer
ee Figure I 42 Th IS layer conS ists of ,h e acnoa l appllCatlo n< such as
"Functionality shored by all applicat io n ond no' the word proce sor, spread!)hcCl pn: entation , hart -
provided by any ot her laye r is realized here. For ,he Ing, and ° on All ,he<e are rea lized a sha red
fram ~work , every v l~ual applica ti on ha s to provIde a libror,,·s , loaded by the app llCatoon framework at
shell and can provide several views The library runtlme _ Th e framework prov ldt's th e environment
prOVide all basIC func"onal,ty so on ly ,he appli a· for these appl,ca " o ns and prOVide ,he functionailly
tlon speCific fearu re have to be added ." for InterilClion am o ng them
"The Frame'"ork is also responSible fo r co n'ent
detection ond aggregation " The AFL prOVides 'em ·
platc management and co nflguratto n mclnagcment It
-is in some areas rela ted to the compound docu-
Software architecture de cnpllons I nform
ments. because of the fun tio nolity for merging or
the reader, but in a oeneral manner Th ey
swltchong menu and 'oo lbors It olso prOVides the
arc necessaril y impreci c: abollt the meaning
capabdlty for cust omizatlon of appioca too n "
of the part Arc hi, ecture of nontnval soft-
ware appli ca ti on ha ve to be learned over
18.11 .3.2 SVX Library 'The SVX library proVides
time JUSt as It [akc tim e to learn any Com -
shared funct ionali ty for all appl,co ,ion< whICh is not
plex subject Tho< proce 'IS helped by delv -
related to a fT3mework a pan of ,he library IS a
Ing in,o el ected dNad s as needed . p(-rhaps
complete obJec"orlen,ed draWing loyer that is used
even to ,h e code level , and ,hen rc·readln g
by several applica " on< for grap hIC editing and ou'pu,.
needed", hll ec ,ure and detaded de"!:,, de ·
also a complete 3D-rl."ndcnng sy,tcmc;; 10;; part of the
<ulptl o ns. In thi s book . we omll the detailed
drawong funct iona li ty The common doaloS' fo r fan,
de<o gn of Open O ffi ce
selcctlon, color chooser, e'c . are all pan of thos library
AI~ the whole <latab.« con nect ivity 0< rea li zed here"

18.12 SUMMARY

A software arthltCClUrC dcc;c.n l c th e components of a ... oftware ~y'-lem and th e \\I JV III whic h th e II1tCr.\U
WIth each olher Ther il rc many ddft'rcnl way ... a "YSlcm ca n be archllccled Jrl an and hon\" h;)\I(, dJ ...... dH.~d
\Qhware arch lt ·Cturcc; Into <'JtCJ,(O (ll-'''U h a<; dJlanow, IIHJ c pcndc nl cUlllpOncnh , Virtual 111 3 hl nc , fl"' 0"
tory, and lay "red ')CrvKC -OfI Cnlcd arch lte lure I ;'InotiH.' r type.: uf Jrc.h lt c llIrt' In w h lL h VJ llUU \ C mpOl"wnh
art' (.omb lncd to provld ~ a ., 'rvlCt
~()ftware d -"11m arc dotumen,ed In J <ol,wore d -"gil d(lLum"n, ( 1)1) ) The 11: 1: [ pub l"hc, IFI-I ~,cl
IOI6- 1'j')ij for ~uch a !'>urpo<e TIl(' 1)1) lor ,he I nwuntcr to>e <1lI<iy 11«, tim " J dOLum n' ,eml)iate
474 CHAPTER 18 SOFlWARE ARCHITECTURE

For large ' oitw;lrC project I ll " Impo rtant lO modulafl zc th e 'OrlwOlrc dc., lJi(n. Modu lafl zlIllon facilItate!.
dlfferenl wo up' of devcio pe,", work lnll o n Ihe d,fferenl parI, sHllullancously T o make Ihi' work as efficlen ll y
a, po"iblc, Ihe Facade desIgn pallern an be u cd 10 provide a clean inlN!ace for each module. n,e Facade
pillh..'rn I typ i all y appropria te when developers arc colloca led. In di stributed enVironments, Web service!.
a n often be u cd.
Once an archOlcclure I <e lecled, Ihe proJeCI « hedule IS updaled 10 reRec llhe order In which Ihe p.rt<
are 10 be developed.

18.13 EXERCISES

I. In a paragraph . ex plain the purpose o f a software arc hOleclurc and how il relales 10 design.

2 Suppose Ih.1 yo u arc deSIg ning a batch imulatio n of cus tomers in a bank. BCln8 a batch si mul atio n.
the charactcnstlc~ of the si mulation are Arst sct, then the si mulation IS execu ted wit hout
Intervennon H ow could you describe this as a data Aow applicano n) U sc a simple skele ton
co nsisl1ng of fo ur parts 10 Ihe dia gram . (Identify you r four parts . and Ihe n look at how yo u cou ld
descnbc this applical'ion as a state-tran si ti o n dillgram .) Which perspective offers more va lue in
de scnbang the architecture]

3. Wh en desig ning a client -se rver architecture, th erc arc generall y two altern ati ves: Ibm an d Ihick
clients. A thin clien t implie that client hmctionality is kept to a minimum; most of th(O processi ng
is performed via th e server. A th ick cl ient implies that much of the functio nality is con tained in the
diem; the functional ity o n the server is kept to a miniml.!m. D iscuss the o ne o r two major
adva ntage and disadvanlages 10 each of these approaches.
4 Operating system are frequently desig ned usi ng a layered archItec ture. Resea rc h the linux
o pe~tlOg sys tem o n th e Internet, and explain how it utili zes J laye red arch itecture. What arc the
benefit of such an architecture,

5. Conside r a word proce SI ng appl,cat ion with which you arc lamil,ar. Sketch the software
architecture of th at program using one of th e architectures descri bed In this chapter. DeSCribe
th e purpose of each of the components of your architecture.

6 . Selec t an alternative software architecture:." for the wo rd processing appltcallon of Exercise 5.


Compare bot h architectures you selected and desc ribe their relative merits.

7. Some design patlern are particularly relevant at the architectural level. Na me two of these and
explain their r('levancc.

8. Which software arehitec ture is the best ca ndida le fo r each of the fo llowIOg app l,cations
a. An applicallo n for reordcnn g auto parts from hundreds of stores
b. A roal-time appl icatio n Ihal shows the heallh of an automobile
c. An appitcJtion that provides advice to stock CUStomers. It uses a multi·platform design
consisting of several Web sites O ne si te conti nually collects and stores pnces and o ther
In(orma tion about stocks; a second site conti nuall y collects stock advice from anaiysts; a third
recommends pon(o lio suggestions to users
d. A sclenti(ic instrum ent com pliny builds equipment (or analyzing molccu lilr tnlctures. The
application you are 10 design analyzes .he structure 01 DNA mo lecule , which arc very large.
BIBUOGRAPHY 475

TEAM EXERCISE

Architecture

Develop the architectLire for your proJect. Dcscrlbe YOLir ar hltcctLire u;tng the IEEE tandard, as tn the
JSC srud a compa nYing thn. chapter (vlakc It clea r what type of archrtccrurc and cit! rgn paltern
arc bemg applied how at lea (one other architecture that you considered , and explain ,,,,·hy you choc;:;e
the altematlve descnbed Include the u e of metncs It IS not reqUIred that YOLI automatically chao e the
architectures via metn ~ alone: .

Track the [arne YOli pend dorng this exerCi Se In increment of nvc: mInute , and Include a lime: heet
haWI ng the time pent by IndIVIdual and by the team U,e or Improved upo n the loml tn Table 182
that reco rds the time pen t per person o n Cil h modu le Give your opinion on whether your (!(Icklng of
tIme paid off, and whether YOLir time cOLild have been better managed

Table 18.2 Form showing tIme spent per module

Module

1 2 3 4

Team member Smith 10 4


Jones S 12
Brown 2 14

BIBLIOGRAPHY

I ha ..... i\1 C and 0 Carlan Sol,w.Hf A"b,'rdlotrr PmPtdlt'f"> 0" an Elflctl/llfl) 1)'«('llllIl( Pn:nlr c Hall 19C-16
1 DIJL.stra E A DISCIpline of P' 09ra"'," I",/ Prentl(.(' Hal' , 1976
3 ua D CDrlCW'rt:t'I' P'Oljr.JPI4"IIHtlIH IlUll1 D~'9 " Pflfl( lrtt1IHtJ Pall(t'?u ( /"JI'O Slnf') Add,,>,)n ' \'(' <:"olcy I tno
.. Kaluznlolcky, E K , and V Kanah;H X~., ~ P,ol}fa,../PI'"9 /or '/,( True lkl,I"H" All IIII,~u dlo" Ii) Inr Xb.lSt Llff~W.19 ( ,II Iht C(m 'ex l ~f JH.I\( tilT.
I", i Fox",o. aYlJ (lIPW, "'lcC r:.w Hill l)rofc"u,mJl 1996
S )ap3nn;:uhan, V KaJcndra I odhlil"",ab and l...Jwrcncc: lbum editors. lIIa.k~o.u .1 A,.b,ln.lutn .,lId "f'"lnoJllclI\ A(oldcn),<. ll r " 1999
6 rnf'clmofc. Robrrt Jnd Amhon y MnrJNn (Ed ,to,... J. DlDclcJlO.lrJ Sy~ltm S (n" In 'fIJIJI 'tnt'i '" ArlIPC I . l lllllr"l~rnl( i'J,J""", \\,,,!ry 1<)88
7 Erl Th om ii~ . £ '1" (( Onf"ll lfJ Ilrd"'fdillf ronH/lIS, T nhflotogy IInJ l)f"SuJ" P(cnt,,-c Ii all 200(\
8 C.lmm.l Er.<.h , Richard t Idm Ralph John,on , ilndJohn VI"'>ldC"'> /)«ollill P.lllff"' EI,mOl" 0/ Rt\4\abk Ob/I'\ I·()nrJI,tJ 1 1 ~ ,Jrt Add,'>on
W ~1C'f , JlJtJtJ
9 Gamma l,.,h , and Ikc.k . KC"m ( on,,,bwlrll!/ In Fdtp\( Prlll0l'lt , PlIflrm> UI1J PIWII ·'"t: Add, ..o n Wcdcy 20<.P
I(} CJpc:nOflK:C' ProJect, htlp www vf')t'nl)(hce nrw", h'le. PJpcr>. Icc h OV('rvl('W Ic;<.h _ ovcrvlcw html ll ~ (,I(.(.c: ..,cd 0' C'mht-r 2'. lUt)") I
Detailed Design

• How do tJse cases and architectures


Planolng relate to detailed designs?

/ Maintenance • What are useful object-oriented


design principles?
TesUng
The Software • Why design against interfaces?
Development
Ufe Cycfe Requirements • What IS detailed design ror agile
analysis processes?

Impls" .entation • How do you SpeCify classes.


-.::::: functions, and algorithms. panicularly
in UML?
Dnlgn
• How do you plan for component
reuse?

• How does one use standards for


expressing detailed design?

• How is detailed design performed for


large. real-world projects?

Figure 19.1 The context and learning goals for this chapter

O(;{:;lIlcd design is the technicill activity that follows architectural selection and Covers all remJinlng
aspeCIS of Icch/llc.1 crealion shorl of aClUal code. It addros es major goa ls of software deSign (from
Chapler 17 ). sufi1C!cncy. understandab il ity, modularity , cohesion, coupling . robustnes , fleX ibility, ,""us'
abi h ty , In formaiion hiding , dficiency, and rchabdllY· Th is hapter start> by relating lhe detailed design
RELAnNG USE CASES, ARCHITECTURE, AND DETAILED DESIGN 477

pro<.""" to the artlf. ts that have already been dcvdopcd by ,he tIme we get to this point , especIally the usc
ases of the requirement, analys" pro c" and the hIgh -level de Ign-the arch,te ture ( e tlon 19 I)
With regard to suffi lency , detailed des Ign provides enough partIculars for developers to implement the
",quorement of the appll atoon As for unde"tandab,llty and modulanty, obJect-onented desIgn specIfy classes,
theor attnbutt-s, and the or meth ~ i'nncipb of de,alled object-onented designs arc Introduced on Section 19 3
This fom1 of the applicatoon allows u to Inspec, deSIgn for strong coheSIon among grouped components and
weak ouplonK with others FleXIbil,ty, ,he reu e of component , and informatIon hidonll are d,scu ed on SectIons
19 4 and 19.6. Detailed deSIgn cntails the developmen , of sequen e d ,agram from usc cases (Secllon 197), whIch
are pnncipal SOUrcL-S for the pec,(, Olion of classes and me,hods The chap,er ends wIth case srudies
The agde method, d"cussed In haptcr 4, hegIns codIng without a full detaded deSIgn , and pcrhaps
wIthout any detaded de Ign at ali ThIS means that ,he detaded de Ign essentIall y lorms in the monds of the
programmers and IS gencrally documented wlthon the code Neverthcles<, dctaded deSIgn contonueS '0 exi t
for agde developer . We d,sc uss this further In eCllon 19 .

19_1 RELATING USE CASES, ARCHITECTURE, AND DETAILED DESIGN

The rclationship between lise cases, architecture, and detailed de 'sn ca n be understood by analogy with the
process of deSIgning a bndge . U,c cases would be part of the requirement> for th e bridge (see ,he use case
example in Figure 192 ). Based on the r('qulrC~mcn(s, cnginloci would then selec t an archllcClurc by stcpplng
back, as it were , and looking at the big picture U sua ll y, more: than one architecture ufnccs In this case , a
sU5IXnslon architecture wa~ selected . ThiS process is diu trat-cd by FI8ure 192 .
Once the architecture ha been elected , engineers ma y develop the detailed deSIgn ' 0 enable ,he
reqUired use cases with the architecture selected This is suggested by F'gure 19 3.
In the software analogy to the bndge example. each corre pondong stage accumulate, additIonal c1a«es,
wh,ch arc shown to F,gure 19.2 and 193 In Step I, lise cases are spe lfied as part of the requirements. In tep
2, these, together with other sources, are used to Identify the domaIn classes. In tep 3, we develop the
software .rchitecrure, as described 1<l Chap ter 18 In Step 4 we develop the detaded design b), definIng deSIgn
cI.s es. We ,tart WIth the domaIn cla«es (e .g , Auto, Road ) and add additional de 'sn c13>se (e g , Guardrail ,
Cable) to complete the deSIgn. \'Qe then verify that th e arch Itecture and detailed deSIgn sup pOrt the requored
use cases For the bridge analogy, we venfy that cars can Indeed use the bridge de<ign '0 travel from Green's

1. Use case (part


of requirements)

' Cars should be 2. Domain


able 10 Iravel from classes
Ihe lap of Green's
HIli al 65 mph , In
-+l IAuto I t-
a straight hne, Road
~

and amve at 3. Architecture


Jones Hollow
Pylon
within 3 minutes,"
Cable

Figure 19.2 The relationship among use cases, architeClure, and delalled design an analogy from bridge bUilding. 1 of 2
.78 CHArTER 19 DETAILED DESIGN

1. Usc case (pan 2 Domain 3, Architecture


01 requirements) dasses

-Cars should be
ablo to ltavel l rom
B
Road
the lOp 01 Grecn's
HIli a t 65 mph, In
a Str81gh 11108 . (addecllor r------------------------------------,
I r::::l I
and amv.!) at dll.OIlledck ) gn) : SuPPOrt use case ~ :

Jones Hollow ~ Guardrail I Cab~ 1


within 3 minutes: 4. Detailed Road :,
,, ,
,,
Design
I ,,
Green's
H ill Pylon
'--- - - -----------

Figure 19.3 The relationship among use cases, architecture, and detailed design-an analogy from bridge building, 2 of 2

Hdl to Jones H o ll o w a< specified Fo r software de .gn, we verify that Ihe classes and methods specified by Ihe
detailed dC~ l g n are capable of executing the required lI'i;{" cases .

19.2 A TYPICAL ROAD MAP FOR THE " DETAILED DESIGN" PROCESS

Deta.led des 'll n 51arts wilh the resliits of the .rch ilecture phase and ends with a complete blueprinl for the
prog rammin g phase. Figurl' 19.4 haws a typica l sequence of steps taken to perfo rm dctaded deSign . There is
rcally no universa l <landard way 10 go abo ul Ih.s process-and , in fact , we frequenlly cycle back to designing
\\"hen co n fTonted with the real ity of turning il deSign into reJ,!.ty The agile process in partic ular, d iscussed
bclo \1/ 10 celio n 19.8 and 10 C hapte r 4 , is an exrreme example of th is.

1. Begl" with archrtectural models


• dass model: domain & architectural classes
• overaJl stale model'
• overall daLa now model '
• use case model

2. Introduce classes & design patterns' that connect the


architecture classes with the domain classes
• concentrate on riskjesl parts first; try aJtemallves

For C!Kh 01$" 4. Specify class Invariants' =


FOI' e • •" mell':od _ 5 . Speedy methods with pro- and post·
conditions. acttvity diagrams.' & pseudocode"

FOI' os:l.!IIIt 6. Sketch unit lest plans

7. Inspeci lest plans and design


• 4 ••.J" h'o
I s.Release lor implementatIOn I

Figure 19.4 A typical road map for creating detailed designs


OBJECT·ORIENTED DESIGN PRINCIPI ES 479

tep 2 of F'b'llrc 194 rcates the cia scs that associate the architecture on one hand with the doma", c1asse on
the o ther hJnd , a, .!Iu tTOted ,n the prev,ous seCllon. J)c"gn pattern may help in doi ng th, < for software designs.
We oft n begin the dcta.!ed dcs'gn process wlIh tho e aspec ts of the deSIg n that must be Implemented, come what
mJY, or that presentthc m ost n ,k Forcxample, in dCSlllfl1nl! En o unterwe m,ght conSIder risky the way In whIch
the c1as<cs were mod ulJ nzed (all charactef> "' o ne pa bge, etc ). Th,s shou ld be settled as soon as possible by
specify, ng the deta'!s of the Interface methods <0 that wecan get an Inllmate Idea of how th IS modulanzallon work
out. If the u<c of the ratc deSIgn pallem \,'cre perceIved a a ri.k. we would specify 11 5 details first
tep 3 of Figure 194 Includes chec kin g that we ha ve a complete de" g n It also In ludes c nsunng that
the object model supports the u e cases tep 6 co nllnues the praCllce of ,pecifYlng a test a< oon as each
ckment IS speCIfied .
In teSt ·dn ve n development , o ft e n a soclated wnh as .!c development, Steps 6 and 7 arc performed pno r
to some (pe rhaps a ll) of teps 1-5 , and their Il11pl eme ntall o ns art Included "' the process In other words,
tests are develo ped truly as early a pos ible, and the n de 'g ns and code created to sal1sfy them RegardJc<s of
the methodo logy used, ea rly <pec lR atlon of te t< ' 5 usuall y an excellent idea.

19.3 OBJECT-ORIENTED DESIGN PRINCIPLES

Marton [ I , 2) Identified five prinCIples fo r class desig n of o bject ,o rl e nted sof twa re that also go hand" n· hand
W1\h ag,le development These are <ummarized in Fig ure 19.5
These principles arc similar to, or follow (rom ~('v('ra l (hat we' havt" already discussed.
The '"91, Rrspo""bofily Prmcopl, emphasi zes the need for classe to have one clearly understood
rcs-ponsibtllry slich as "represent eu to mer data" or "represenr order (or ca mp ing Items ," rather th an very

• Sing1.e . Responsibility PrinCIple


• "A clas. sho uld have o nl y o ne reason to change."
• _ cohesion
• Open-Closed Princ ipl e '
• "An art Ifact should be o pe n for ex te nSIo n but losed for ma diRcat io n on way< that affect 1\, cI,e nh."
• especially modules, cia <es , a nd fun tlo ns
• -a modu le ca n be extended wlthollt chang ing It S code
• Liskov Substitution Princ lple l
• ' Subclasses shou ld be <ubsl1tutabJc for their ba 'c classes "
• Dependency. lnversion PrinCIple'
• "D epend on abstractlon~ Do not dC'pend o n concretI o n" "
Bot h should de pe nd o n abstra ctIo n,
• AbstractIons <hould not depend on dc taol s
Detads shou ld depend on ab<t racll o n •
• Interface Segregation PrinCIpl e ,I
l
• "Many chen t <;PC("(I Intcrfllc...es are better th an one ge nera l purpo,c Interfa ce '

Figure 19.5 SOme obJect-onenled design pnnciples


- .
I I~nr.lnd Meyer, "OhJ ec. t O nclHc::d ,...(IWJrt on,tru( li o n," . c(.on d Felltlon, Pn.' IHII..t:' Iiall , 2007
1 l1arb.HOI 1.... .. kl)V Jnd j qhn ClllI ~ ~ . "Ab<.tril(.tlon ;'Ind C;pc..'<"lflu tI VIl 111 PlOgl~111 D cvt.'i opn1l'nl j\ tlT Pn."' .. 19$0
• Ro~n Martin, "I\~II oit w.u c f)c vclnpmc: m PIIIlc..IPIc: .. PJlu:rn ... ,"nd Pr~(tl'C""" Pn.: nl ltC' 11311 2 1
• Ib,d
480 CHAPTER 19 DETAILED DESIGN

bro.d tOpiCS such as "all there i< to know aboutlustolllers and their habits"~ or "campinS prefere nces." In other
wo rd<, I.>ses should ex hibit. hlsh level of cohe Ion When classes have only onc re pon"b d,ty. they arc
ea.slcr to 1ll311lQln and reuse .
The pClI .(J. <rd Pn" Iplt (0 P) states that module should be open lo r extension but closed for
modlAcation . That is, if an eXiSli n!! mod ul<' needs to support add,tlOl,al requirements, thcn the eXISting,
working code would remain Int.ct. It would no t need modification. In o ther words, new fu nctionality should
be Impl emented with new code. Consider the example shown In listing 19. 1. as described in ( I]. The code
sati sfie the reqUirement to draw a set of shJPcS consisting of clrclc~ and squares However, thiS code vtolatc'§
the 0 P because shapes o ther than ci rcl es and squares cannot be drawn Without modifying-not Simply
adding 10 th e body of th e fun c lio n.

Ustlng 19.1: drawAIIShapesO--ildding functionality causes erasures


void drawAllShapes ( Vector<Shape>someShapes ) {
for ( i=O ; i <someShapes . length ( ) ; ++ i ) {
i f (someShapes.get(i) .type() == "circle"
drawCircle ( someShapes.get (i» ;
else if ( ( someShapes. get ( i) . type () == "square"
drawSquare(someShapes.get(i»;
}
}

A common way to avoi d modification and conform to the OCP is by lItil izi ng inheritance and
polymorphism . liSling 19.2 shows how thIS is accomplished in a new ve rsion of drawAIIShap"O. In this new
version . shapes such as Circles and Squares inherit from the base class Shape. A a Shape is extracted from the
vector, its polymorphiC drawO meth od is called to draw that shape . This mea ns that each type of shape i
respo nSible for knOWing how to draw itself. If Rew shapes need to be suppo rted. drawAlISI,up<> O does not need
to be modified-It au to maticall y calls the drawO meth od of that new shape when it is removed from
the vector.

Ustlng 192: drawAllShapeSJ -lmprOOJed we sion now open for addition


void drawAllShapes ( Vector<Shape> someShapes ) {
for ( i=O; i < someShapes .length () ; ++ i )
someShapes.get(i).draw() ;
}

Th~ U".u S"bsl;,"tio" Pri"ciplt states that any code referenCing an instance of a base class must also work
co""ctly if, instead. it is p.ssed an instance of a derived class. In o ther words, a d~rived cia", must honor the
semantics of. base class. If this principle were to be violated. then every time a new derived class is cre.ted,
cod~ would have to be modiR~d to rd~rence the n~w class. Violating the OCP.
DESIGNING AGAINST INTERFACES 411

Copy

,,,
~ ........... --.-.. --... -... .,
•• ••

Read Wnte
Keyboard Pnnter

Figure 19.6 Dependency InverSion

Copy

Reader Writer

Read Write
Keyboard Printer

Figure 19.7 Avoiding dependency Inversion uSing abstractIOn

The Drp",d",ty IH"""OII Prill iplr (DIP) IS concerned with hiding detatl" It ask us to deSIgn hI g h-level
module In such a way that th ey do nOl depe nd o n low- level mo dule , Instead. eac h sho uld depend on
absrracti o ns Th,s makes the modules undcr< tandab le and usable In lhemselves o n<lder the example
descnbec! by Manln (3).
The Copy modu le IS depe nde nt o n the lowe r level modules-Read Ke yboa rd and Write Pnnter. mak Ing
II dIfficult to reuse a' a gene ral purpo c copy modu le By appl Yin g the DIP, we abstra t the read and wnte
modules, as shown In Figure 197 Now , opy depend, o nl y o n the abstract Reader and W nter, mak lllg It
more flexIble and ponable If new ty pes of Readers and Writers arc c reated , Co py" un.fle ted
The IH/rifaa 5r9" 90/I OH PrlllClplr te li , LIS to colic t related me th od, Int o separate Inte rla os rather than
mI x,"!: un re lated methods (even when needed as a whole gro up ) Il draws Irom Ie so n of com ponen t de -Ign
Ie II . MIcrosoft's 0 1) where we learned to package set< of me thod, In relatively mall , l11anagl'able set< By
keepin g Interfaces I\mall , we Increa se their co h e~ l on

19_4 DESIGNING AGAINST INTERFACES

The Id a of dcslllnll1g allaln,' Inll'rlacc< " lIke emplOYIng a contrac t The program e lement ,uppl II1g lun -
llonaJlly (c g the (IHlomcr c.liJ", } ~lIilrantc('s 10 prOVide ,nt cdi) e ftln tltm ... wllh ~pcL dH.:d name parJnlc:lcr
l"yp<: •• and return type, (e K , VOId h,Il("OId) an d /,oo/ra" prllll/\ 0 .. ", . ( ' Irlllq nCtv IIIIITypr)) The pr gr.lm cle mem,
USIOII the (unctlonalll Ycan lhen be d ,,~n d wllh ollt havlnlt 10 ~n ()w how th e ILIIKtlo nal, ty" 100plemen tcd-
all they need to know" how l() ",e the Ill te riate We have d"tu,wd Ih" CO ll tcp l In the o nte", 01 de,' gn
.82 CHAPTER 19 DETAILED DESIGN

Client code Used code

Bili ingClient Customer


IISICuSlomersO -- -- - -- bil/{)
blliCuslomersO printAccounts()

.. wntten in lerms 01
Abstract la yer
Customer (not
specific Iypes ot
Customer) RegularCustomer
biliO
printAccounts()

Concrete (non-abstract) layer

Figure 19_8 Designing against Interfaces-an example of designing against Customer rather than RegulanCustomer

patterns \\,herc patterns have client Also , the Facade de Ig" pattern is a way of providing a clean interface to
a package o( cia es.
Designmg against interfaces takes man y forms . One is the usc of ab traction . For example, if code is to
be written about l\ltnmmai objects, then we try to write it so as to mention on ly AJlimnl objects. In other words.
we try to usc: only the Animnl lntcrface . ThiS allows gn:ater applicability and grea ter flexibihry for our design
As a hlrth.:r example, suppose that we arc writing code about eu tamers . Thi s ca n be understood as
writing against the ( usfomtr interface. We ca n actuall y consider uSlOg an abstract class Clcstomtr, which may
have nonabslraet subclasses such as Rr9u/arC,,' to",cr, as hown in Figure 19.8. This desig n is mo re nexible than
writing again 1 a concrete (nonabstract) class Rtgu/arCustomrr because we ca n easily add other types o(
customers, such as Sn v"'9,C,,' to",cr objects, with 'pecia lized verSions of hillO, without haVing to change the
code that uses ( us/orner objects. The diVision into an abs tra ct and a concre te la ye r is characte risti c o( many
deSign pattC'rns.
For Java In partICular, one tries to use Java ·speCific "Interfaces" (or the interface role descnbed ilbove.
These specify method signatures (name, return type, and parameters types ) o nl y. Unlike Java inheritance,
classes can Implement any number or interfaces The UtvtL notat ion (or an interface is a dotted-line rec tangle,
and a dOlled line triangle is used In tead of a o ild one.

19.5 SPECIFYING CLASSES, FUNCTIONS, AND ALGORITHMS

The goal of complete detaoled design is to prOVide a complete blueprint from which a prog ram can be
constructed A good house blueprint leaves Ihe builder with as (ew doubt as po sible about the .ntentions of
the designer, and the same is true (or detailed software design . Figure 19.9 describes typica l steps in carrying
out detailed deSign for each class, and the succeeding te" explains the Slep in delail.
A fully detailed class diagram includes all allribute and operatio n names, signatures, visibol,ty, .-.,mm
types, and so on. Accessor methods arc commonly omilled . It IS customary 10 omit accessor function (e g ,
9rtSiuO and srtSizt()), since th«c can be inferred from the presence o( the corresponding attribules (e.g ., 'izd.
UML tools have the benefit of allowing designers to suppress (I.c., to not show ) cortaln clemonts of the
Rgu~-for exa mple, the "responsibilities" section or the variable types. Many tools allow designers to view
only the class« and their relationships, in order to get Ihe big picture.
SPECIFYING ClASSES. FUNCTIONS. AND ALGORITHMS 483

1. alher Ihe attrlbule< l"Icd In Ihe R .


• If the R J< or~an.zed by class
2. Add addll.on.1 .trnbules required (or Ihe des.gn
3 ame a mel hod orrespondlng to each o( Ihe reqUlrement< (or th. clas .
• ea,y,r the ~ RS Ie; organized hy c1a<;,
4 '.me .odll.onal method, reqUlrl'd (or Ihe des.gn .
5 how the attnbute, and methods o n Ihe o b,e I model
6 tatc c1as ,nvanants.

Figure 19.9 Fully spec.fy.ng a class

One language.lndepende nl manner III wh.ch 10 speedy classe IS Ihrough Ihe OREA Interf.ee
Oefinillon Language ( lO ll Th" " a slandard. teXlual (ormal (or ,peedYlll& Ihe .ntcrface, prov.ded by
collect.ons of las es their a"nb"Ies . and Iheir funcllons Fo r Ihe spec .f.ca l.on o( IDL. sec [4 ]
In some organi za ll n . detatlod dcs. g ns arc spec.fied by prov.d.ng code w.thout fun I. o n bod.e, ralher
than UI'"IL. Th" IS somcllm.s Ime of agtlc de velopers Th e advantage o( Ih" procedure" that there" no need 10
rranslale del.tled speedicatlons 1111 0 code A d. advanlage IS thai a code fo nn IS somew hat less rcadab le than
ordma!)t pro c The funcllOns In the code form arc then filled Ollt at Impltmcntat lon lime by programrne~

19.5.1 preconditions, Postconditions, and Invariants

An effective way to specify functions is by means of prrC'oud,floI15 and p05tcotldlllO tlS Precond itions specify th e
relationships among vanablc') and constants that arc assumed to ('Xlst pnor to the runctlon' cxeclitio n.
postcondltions speedy the req Uired relallon shlp~ after the funcnon 's ext ution For example , the func ti on
w.,bd,.w(.1l1 UJill>drnw"IAlno" .. IP) of an "cco" .. 1 cia < could be spectiicd as ho \" n In F. 'ure 19 10 Anolher

Invariant of withdra w{):

balancel >= -OVERDRAFT-MAX AND

availableFundsl = balancel + OVERDRAFT_MAX

Precondition" : Conventions used


xl denotes an
withdrawalAmountP >= 0 AND aUnbute:
xP denotes a
balancel- withdrawalAmountP function parameter;
X'IS the value 01 x
>= OVERDRAFT MAX - alter execution:
X denotes a class
Postcondition" : constant

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


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<t be pec ,f,ed., well. In the
cXptTICn c of the JUlilOr\, sohware eng lflccrs rcqulfC.: slglll AcJnr tltllOlnij In the capacity to SpeCIfy
pre ondltl o ns and po,,\condl(IOnC;; with preCISion , JIi III Figure 19 . 10
In l'anauh of a method are JSSCrLlon'i: thill are both prc cond 'll on~ and PO<;lc.ondltlons They arc a way to
mall,lall' ,nlelle lual control over the behavior of functions They specify relalionsh,ps Ihal do nOI change,
which IS wei orne in the envi ronme nt of an application, where complex change IS so ohen difficult to manage.
An exa mple fro m Encounter" the fo llowll1g possible ,nvaria nt for the "dju" Q,w'"y() method.

Invariant - th e- sum of the va-lues of the qualities.

In other words, when the value of one quality,s changed with nd)u" Qun'"y(), the values of the remaining
quahtles change )n a way thtH Ie'aves their sum unchanged.

19 .5.2 Expressing Algorithms with Activity Diagrams and Pseudocode

It is helpfu l to specify nontrivial algorithms at detaded desig n time. The adva ntage of doing this is that
engineers can Inspect the algonthm separatel y without lhe intrusion of programming com plexities , the-reby
trapp,ng man y ,mport.or defects before they magni fy into code defect . The more critica l the method, the
more Important thIS activity Methods wi th complicated branching art: candidates fo r actwity diagram s
("advanced flowcharts") . Activity diagrams were described in Chapter 16.
PsrodocoJe is a means of expressing an algorithm textuall y without having to specify programming
language detads. As an example, pseudocode 'or a hypo thetica l autOmated X·ray controller is shown ,n
Figure 19. 11 An adva ntage of pseudocode is that it is easy to understand but ca n also be made precise enough
to express algorithms. Anot her advantage is that algorithms can be: inspected for correct ne ss independently
of the clutter of a programming language. A third adva nta ge is that defect rates in pseudocode can be
collected and used as a predictor for ddect rates in the product. usi ng histonca l defect data.
Some orga ni zat Ions use inspected pseudocode a annotated comments in the source code listin g. Tool s
are then able to extract the p eudocode from the source. For example. using "lip" to preface pseudocode
statements, the code could impleme nt the pseudocode cited above-see F'gure 19 . 12
ActlVIry diagrams and pseudocode each have the advantages listed In Figures 19 . 13 and 19 . 14 . The
decision whether to use them or not depends on (aclOrs particular to th e ap-plication Some devel opers shun
act,vity d,agrams as old· fas hio ned, but activity d'agrams and pseudocode can be worth the trouble for
selected parts of applrc.tions, where they help to produce better quality products.

FOR number of microseconds supplied by operator


IF number of mICroseconds exceeds critical va lue
T ry lO gel upend oris approval
IF no supervisors approval
abort with "no supervi sor approval
for unusual duration" me sage ENDIF ENDIF
IF power level excee ds Critical value
abor! w,th "power level exceeded" mes age ENDIF
IF (patient properly al,gned .I< shield properly placed .I< machine self· test passed)
Apply X·ray at power level p ENDIF . . ENDFOR
Figure 19.11 Specifying algorithms with pseudocode a critical X.ray example
REUSING COMPONENTS 485

II p FOR numb e r of microsec o nds supplied by operator


for ( int i = 0; i numMicrosecs; ++1 ) {
II p IF number of microseconds e xce eds cr itical value
if ( numMicros ecs >
XRayPolicies . CRITICAL- NUM - MI CROS ECS )
IIp Try to get supervisor ' s approval
int supervisorMicrosecsApproval =
getApprovalOfSuperForL o ngExp osure{) ;
II p IF no supervisor approval
if ( supervisorMicrosecsApproval < = 0 )
throw ( n ew SupervisorMicrosecsApprovalException{) ) ;
• • • • • • • • •

Figure 19.12 Pseudocode as extractable comments In source code

• Clanfy algonthms in man y cases


• Impose Increased disc lphnc o n the r> roc~ . . s or do umcnllng detailed deSi gn
• Provide additional level at which inspec tio n ca n be perfom,ed
• Help to trap defects before they become code
• Increase product re liabi hty
• May decrease overall co,(>

Figure 19.13 Some advantages of pseudocode and activity diagrams

• C reates an addll ional level of documentation to maintain


• Introduces error POSSlb,hucs In tran slat ing to code
• May requ ire too l to ext ract p cudoco dc and facilitate drawing;) lI vity dlagrJm~

Figure 19.14 Some disadvantages of pseudocode and activity diagrams

19.6 REUSING COMPONENTS

Most e nHlnee nng dlSclphncs (elec tnca l, mec hanl ai, c tc ) rel y o n th e u·. r of compo nents that ca n be procured
s<paratciy Bndge deS igner" for exa mrle, try to u,e standalu I-bea ms The wlde,pread adop tio n of ob)e t-
onented, ob)cct -hke, and ot he r co mpo ne nt paradigm, ha, helped to promo te oftwarc reu'e Ikea,,'e of the
large numbe r of methods pack'Bcd with each ci a", ftlf' l1 0 naht y that we need " ofte n In ludcd and i<
r<:lallvely conven ient to 10 ate The usc of MKro,oft I, brane' , V"u . 1 ila,ic Lontro l" '1IGro,oft A"embhe$
Java Bans, and Java App ilca u in Prowamm ll'!; Interface Lia"c, arc exam ple\ of w de reu,e
FfilffiCW()rks. dl scllc; d In hap tc r o n Jrc..l lllt'C lu rc . Ire pJc ka gc\ of ompo nellh dC"d,.;ncd
th e: prCV IO U \

r(Jr r ·U\C We d ~c1t) p {rMl1ework ... to ~U ppOrl ilPp1K<111 0 11 Jr tHl el- lUrc, . il nd '0 the Jrt" clf('ulv(' ly n.'u'Jble
The Java co re Al'l "anr,lher exa lllpic of a Widely
u,cd framework lava ilea n, prov ide ret" .b lc tu mp nent'
for }ava applKatlOm They In Iud grap hl , II al" and "c nlc rrnsc" bean;, wh ic h e nca psula te COl 1'01'. te ta'~<
-
486 CHAPTER 19 DETAILED DESIGN

>u h J> datJbJ,e a e <. In additio n to th. advanlaj(cs afforded by bClng da"c" beans obey sta nd ards that
make them cJ pable o f mallipulalio n within devel op ment e nv ironment ' Web · ba cd programs (i.e , nOt
o mpo nc nt< ) '" h a Java c npt and C I sen pt> art o ften reused
At • dirrerent level , the tandard Templal c Library ( TL) prOVides m ,. · a nd · matc h ca pabili ty of
,t.ndard ,' lgo rithms suc h as >orllng and scarc h ing . STL IS applicable to a va"ety of data struc tures a nd
to objech o f virtually any clac;s. In summary, a omponcnl marketplace ha~ emerged and IS g rowing
co nlilluall y
n,e Encounter video ga me case stud y prese nted at the end of this c hapter CO nlalll cxamples o f reuse
with in an cnterpr.isc: in this case, a Ham," de .... elopment business T o he cO~ l - dfcctlvC'-and thus compelltlve-
the 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<ltlon .
3. PrOVide sequence diagrams With co mplete d~tails .
• be sure that the exact obJccts and their clas.c;cs arc s pcci~cd
• select specifk function names in place of natural language
(calls of o ne oblcct to another to perform an ope"'t lo n)

Figure 19.15 Refining models (or detailed designs, 1 o( 2-seQuence diagrams


SEQUENCE AND DATA FLOW DIAGRAMS FOR DETAILED DESIGN 487

I. Gather data flow diagrams (DFD<) co n<tnJ ctcd fo r de tail ed requlrcments andlo r archll OClUre (i f a ny)
2 In tTOduce additio nal DFDs, If ne ('"ary, to explain data and procesSI ng flows
3 Indicate what part(s ) o f the other model , the DFD, correspo nd to .
• for example, "the fo llow"'8 DFD is for ea h Aceou"! object·
Provldl' all details o n the DFDs
• Indl ate clearly the nat\lre of the proccs-o ng at each nod e
• ",d ,c. te clearl y the kInd of data trnn,n"ttcd
• expa nd pro C - SlO g n odl"~ Int O DFD, If the procc~sin g descnp tion requi res more detail

Figure 19.16 Refinong models for detailed deSIgns. 2 of 2-data flow dIagrams

19.7.1 Detailed Sequence Diagrams

Recall that use cases ca n be utili zed to exprc,>s reqLllfcmcms, and that \\Ie also usc them to determine t he key
domaIn cia se for the apphcation. For th e dt·tailed design phase, \ve proVIde cla'>es WIth the methods
referen ced i n the sc:qucncc d iagrams.
As an exa mple, the sequence dli:lgram fo r the: "Encounter Foreign Character" IS ~ h own In Figure 19 . 18,
hawing th e message between obje ts on the software design. The reaso non g beh ond the h",ctl ons chosen IS
as follows .

1. Forro9110Itlrael" is to have a d, <p lay ftlnc tl o n. We woll implement Ih o< wit h a method d"piay(J. (Since all
characlers will need to be displayed, we ca n actua ll y ensure thIS re q ulTeme nt by g IvIng the ba,e cia
Gam,O,"raelt' a dlsplay (J metho d .) The ,equcnce dia g ram shows Ellco""""Gam, c reating the fore Ig n haractet
(Step 1.2) and also an Engage men t o bject, and th en ca lling d"piay() An engagemcnt" to take place, and a
good design is to capture Ihis by creat ing an EII9a9Cl"ClII object Th,s IS ill ustrated", F,gure 19 17

2 ThiS tcp 10 the usc ca~C' Indicates [hat we need a n cxrcutr() melhod In E"!1agcmnlt
2. 1 Th i step requires that Freddie and th e main playn c harac ter be able to hange thelT qua lo ty va lues
Inee th is capab ll, ty i<; comm o n to al l fucol/'Ilrr Char.:lCic". w (' prOVide the base EII(.olmfr r(JJararlrr clas
WIth a wQuallly () me th od

:Encounter :Encounter freddie: engagement:


game Cast Foreign Engagement
-'-'-"----'
Character

1 1 dlsplayForolgnCharO

1.2 dlsplayO

1 3 new Engagemo:..n=-I"O--_ _ _ _ _ _ _ _ _ __
I

Figure 19.17 BegInning of sequence diagram for Encourl! r ForeJgn CharaCler USC case
0188 CHAP tER 19 DETAILED DESIGN

:Encounter :Encounter freddie: engagement:


arne Cast Foreign En a ement
Character I
1.1 displayFore'gnChorO I
I
I :Engagement
1.2 d,splayO I
I Displa
1;] I I
~ 1.3 new Engagemenl() ! I
I
~ 2. execute()

2.1 setPlayerOual,lyO
J :Player's

maIO
character
I
I
I
I
I
2.2 setOuai,tyO I
I
t I
2.3 setForeignOuality()
3.1 new Engagemenl0ispiayO

2.4 selOuaiityO
3.2 displayResul t()

Figure 19.18 Sequence diagram for Encounter Foreign Character use case

3. This step requires that the re ult of the engageme nt be shown. The following two substeps constitute one
way to do th is.

3. 1 Fu'St Engage ment crea tes an E"9a9"""' tD;,play o bject.

3.2 Now we show the engagemen! dISplay by calling its d;,playR<suliO metho d .

Si nce the me thods required to execute this usc case arc now known . we can include them on the class
model , as in Figure 19 . 19 . Con tinuin g ,his process , the class mo de l and the use case mo del (in the form of
seq uence dia g rams) arc complet ed in detail , a show n in ,he case study. T he state model (if app lica ble)
mus t al 0 be completed in derail. A data flow di agra m is ye t ano,her possibly u efu l mo d el, and IS discussed
next.

Engagement EngagementOisplay
executeQ displayResultO

EncounterGame

PlaverCharacter
EncounlerCast
setOuality()
disptayForelgnCharO
setPlayerOuailtyO
ForeignCharader
setForelgnQuality()
selOualityO

FIgure 19.19 Classes for Encounter Foreign Character use case


SEQUENCE AND DATA FLOW DIAGRAMS FOR DETAILED DESIGN 489

19.7.2 Detailed Data Flow Diagrams

To relate dala flo'" model, to I."e•. we ca n map ('ach proce sIng elemenl 10 a meth o d of • cla.s. F,gure 19 .20
shows a h'gh ·level VIew of a dala flow d,a gra m fran ATM banking appilcaHon Dala flow mo dels can be
lc/mop,.1 For example. F,gure 19 2 1 exponds proce"In!! clement< tro m lhe DFD In F,gure 19 20
T ele, op ing allows us 10 show a hlgh · level VICW, fo llowed by successIve 'tages co nta in Ing as much
delJl1 as we WI h. Th. " aVOid .. overwhel ming the viewer Each pro e"~ ln g tlt'mem IS expanded Into a mo re
detailed DFD. a nd thI S expa nsion proccs~ is continued unl .! the lowest level prace . sin s l'!ement are reached
The latter are typically ,nd,VI dual ftlnct lo ns, pOSSIbl y of dIfferent cla<St< For example, lhe g"D,poSl'() fun c lio n
IS expanded in lO lhree un tlons (gelllnl! lhe I)asswo rd, verify,ng II , and makIn g a dISplay ). T wo o f lhese
Inleract WIth dala Slore> (a local log of lransa lIons, a lISt of problem users, and a templale for <creen d,splay»
that were not show n In l he h,gh . leve l DFD I o le lh.l lhe data enlran os and exItS from t he dela dod
expansions match Ih o~(" In the Vc,"",an, fro m wh ich the )' arc expanded

Account. Customer.
Balance User 1--
getDepositO getDetailsO
Customer

Logical (unction
(software or hardware)

Figure 19.20 Detailed data flow dIagram for bankIng application, 1 of 2- hlgh level

.'~'
.. , .' . ,.' "'" .''%...,. '"

f" Expand details "" ". '..


...~... ", ........ ~-----
Balance Account. Customer '·'1~1::.:'.'" ,.f' Customer.
'"
• ,
getDepositO ,. getDetails()
• User
""
' .
".

.
' •
".
. .... " ........

, .. ". ' ", . -.


....,.
,
Customer
Balance ", '
"

," ,..::.:------, - -----; ",'" '." ,~,


. .. datastore ,. .. datasloren .. datas tore,·
-. "',
Screen template Local log Unacceptable
ATM users
'-

Deposit- Account. Account. •

• screen . verifyPass· getPass- •

--.
, display() wordO Pass- wordO
--

status
word

"
,. I,U

Figure 19.21 Detailed data flow diagram for banking appllcallon, 2 of 2- wllh details
490 CHAPTER 19 DETAILED DESIGN

Ea h processln~ elemenl " expanded 1111 0 a mo rc de,ailed DFD, and 'h" cxpan>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<c onlera t w,th data ,tores (a local log of l",nSOCtlOn<. a
10 t 01 problcmusers, and a lemplate forsereen displays) Ihal were nOI shown ,n Ihe h'ljh · leve l DFD Ole Iha' the
data cntr.mces and c>ats (rom the detailed cxpancolons malc..h tho C In the vC~ l o n ~ from whl h they arc expanded
DFDs arc nol hclphil for .11 appiocal,on . For example, rhey do nol add mu h '0
Ihe Encoun ,er case study

19.8 DETAILED DESIGN AND AGILE PROCESSES

Ag,le procc<scs, descnbed in hapler 4 and referred ' 0 throu g ho ut Ihis book . ernph", zc work,ng code and
place documentation at a lower pnority The lauer includes dctai Icd d('s l ,gn~ An cx tTcmc I nterprctat Io n of thiS IS
thJt detaIled de: ign countS (or very little, but a more mca lIrcd Interpretation is lh~H an agile process would
crca!'e detaolcd designs for o nl y t hose parts of app lieation< where the effort to produce them is worth the beneht
An example is a complica,ed bUI important algon'hm . A non ·agile developmen, effort , on the o the r hand, may
document every method For large development erforts, Ieavon!; ,t to ,he judgmen' of hundreds 01 sorrware
engooeers as 10 whe ther deSIgn de'ails should be documented o r no' may nOt be favored by projec i managers
It is obvious that oftware cnglllcers should not engage in ~ cti v lt ies with Insu ffiC ient benefits. One issue
that makes this less than clear, however, is whether one a . esses benefi ls in the shon tem1 or the long lerm
Good , deta,led design doeumen'ation of a class ,hat supports the code (possibly as comme nts) would help
ma,ntainers. I, would also have 10 be kep' up· to· date by main,ainers. This is probab ly a long· tem, bencfir ,hal
is not as clear in the hon term

19.9 DESIGN IN THE UNIFIED DEVELOPMENT PROCESS

Recall ,hat 'he unified development approach 01 Jacobso n 01' aI. , described on Chapter 3, groups iterarions ,n lO
the "Inception: "Elaboration ." "Construction ," and "Tran <i'io n" ca tegoric (sec F'gure 19.22). Design rakes
place primarily somew hat during ''Elaborat ion'' but mos tl y elming the "Con truCtlOr." iterations. T he idea is

U. P. Term Inception Elaboratlonl Construction Transition

ReQu1rements I
I
I
Analysis
I
Design I

Implemen- I
tatlon

I I
I
Test
I I

Prelim. Iter. Iter. Iter. Iter. Itor


Wn 'n+1
..... ..... Uer .
lIerations .1 • m I'm. 1 _k

Figure 19.22 Unified software developlllent method process-deslgn


UPDAn NG A PROJECT WITH DETAILED DESIGN 491

1. Introduction 4. Dependency description


1 1 Purpose A.,I:",,..,, 4 1 Intermodule dependencies
1 2 . Scope 4 2 Interprocess dependencies
1.3. Oef,nitlons . acronyms. 4 3 Da ta dependencies
and abbreviations 5, Interlace description
2. References .,. 5 1 Module Intertace
3. Decomposition description S 1 1 Module 1 description
3 .1. Module decomposl1ion 5 1 2 Module 2 descnpt 'on
3 1 1 Module I descnptlon 5 2 Process Interface
3.1 1 Module 2 descnptlon 5.2 .1 Process I description
3 ,2 Concurrent procoss 5 2 2 Process 2 descnptlon
decomposition 6. Detailed design
3 .2 1 Process 1 description 6.1 Module dela lled design
3.2,2 Process 2 description 6 .1.1 Module 1 detail
3 .3 Data decomposItion
6.2.2 Module 2 deta il
3.3 1 Data entry 1 6.2 Data detailed design
description 6.2.1 Data entity 1 detail
3 3.2 Data enlry 2 descnp~on 6.2.2 Data enllty 2 detail

Figure 19.23 IEEE 1016· 1998 Software Design Document table of contents. With focus on detailed design section
SGut:e' IEEE 10' 6-1998

that most of [he requ"e m~nt < wdl have been gat hered by tho e sta ge, An "Analy"s" pha,e " freq uentl y
identified a part of the waterfa ll proce s omp.red with the term ino logy of thi s boo k. the Ana lys " phase
cons! (s partly of requiremen t. aniliysis and panl)' of ilfchitt'crurc elc::ctlon
The unified process encourages three types ("stereo types") of classes althe analYSIS level · "'lity bou"dary
and (antral classes, wherea Lhere I no or;;:uch n:slriction on deSign clas cs Entity classes exprc~" th e es cnce of
the concept. and arc ur.likely to req uire c han ge ove r time or between al>plo c olions Boundary cI.sse, h andle
communication with entity objects, and control c1ilssC' contain methods th at pertain to th e C'ntlty ObJl'c t but
Ihat are Iyplcally speCia l to th e app li ca ti o n in which th e en tity class is beong used . Bo unda ry clas e' are
typically like the M,d,.'or objet! on the Mcdoator de ign pattern descnbed In Chapter t 6 The umned proce
promotes VI ual tools for deSig n An example o f th" " Ihe Rat io na l Ro<e tool sold by IB I\\

19.10 IEEE STANDARD 890 FOR DETAILED DESIGN

Recall IEEE ta ndard 10 16 · 1998 for olt ware DeSign D ocument, , how n on hapt er I o n 'olt",. rc
architecture. ae; shown In Figurt' 19 23 Thl~ format for tht' dc·taded d<.: or; : lgn \CC[ lon of thle; documcnt co nsl<;ts
of speclfyon~ a desuipllon o f each mo dufc (po ka g l' ) In turn , With a det.oIed desulptlon 01eoch d a la part Fo r
00 deSign , . the lalter c. n be repl aced with a detaded de,c nptlon 01 each cia"

19.11 UPDATING A PROJECT WITH DETAILED DESIGN

On(: a detadc:d uco., lgn I ~ hand, the projC t pl;)n ca n I c mJde morc '11<'CdlC In ')(."vcral rce; pl'C ts III partl ubr
In
(.ost estimation Cil n he made.' mu h more pre I':;C , chcdul co., an be brfJk t' l1 cl own Into tJ,k,. and tJ,k .. an be
.lIocated to ond,vldual, r ,,,!urc 1924 In( lllCle, mO<l o f Ihe Impo rt a ntupdatl" to be pe ri orm e d o n e dClOoIcd
design" <omplete
<; 1Ilc..c we can ~ tlm a t e th e I1llmhl' r "110 'I ze of thl' mc·thud, IIlvolvc d In th l' app ll lJ l 101l U,U1 t-: dl' t.lIlcd
d(!,,)IKn ~. J mOre pre 1St' c, tlmal lOI1 o ( the proJc(.( ,IZC 1,\ pU"lb lt A, dl'\ nhc 1111 C h a pt e r ~ . pi ICel LO'h tJn
then 1><: Inl ~rr~d f"lm Ih e " Z.l· II ~lI rc t 'l 25 , h ow< line ",aj' o f orrylng th" lit
.92 CHAPTER 19 DETAilED DESIGN

I Make ,u"" Ihe SDD renect< I.te,t version of dctadl'd de,i~n , ., Set lied on after Impcclions
2 G,W complele delall 10 Ihe ,chedule ( PMP)
3 Allocale precise lasks to team members (SPMP)
4 Improve projeci co I and time C limates (sec below).
5 Update the CMP to renect the new parts.
6. Review proce s by which Ihe detailed design w. crealed, and determine Improvement< Include •

• time taken . broken down to include


• preparation of the de igns
• Inspection
• change
• defect summary
• number remaining open, fou nd at detailed desig n, closed at detailed design
• whe"" injected; include previous phases and detailed design stages

Figure 19.24 Bringing the project up·to·date after completing detailed design

The COCOMO model can now be used again to refine the estimate of job durati o n. It IS be t to usc
personal data to eSlimate th e LOC for very small , sman , and such jobs. In the absence of these data,
department, division, o r corporate data can be used. Otherwise, Humphrey's table (Figure 19 .26) [6] may be
usefully applied. Figure 19.26 applies to C+ + LOC per method. On the average, Java and C. + requ ire the
same number of LOC to implement si milar functionaliry [7, 8].
Calculation methods perform numerical comput.tion; data methods manipulate data (e .g .. reformat·
tlng); logic methods consist mainly of branching; setup methods initialize situati o ns; text methods
manipulate text Estimates for methods that combine several of these can be computed by averaging. For
example, an unexceptional ("medium") method that performs calculations but also has a substantial logic
component can be estima ted as having ( 11.25 • 15.98 )/2 = 13.62 lines of code.
Descriptors such as V'ry Small and Sm.1I are "fuzzy" in that they describe ranges rather than precise
amounts. These ranges can overlap. in which case an aVCr.lgc of the correspondi ng table values can be used.
(This IS actually a simpli fication of fuzziness . but adequate for our purpose.) Fuzzy descriptors arc practical

I. Start with the list of methods.


• ensure completeness, otherwise underestimate will result
2. ESlimate the lines of code (LOC) for each .
• classify as IJfry ' ",nil, 'mall, m,dium . "',g', "'ry I.,g,
• normall y in ± 7%/24%/ 38%/24%/7% proportions
• usc per onal data to covert to LOC
• o therwise usc Humphrey's t,ble below
3. Sum the LOC.
4. Covert LOC to pe,,;on·hou,,;.
• use personal conversion (actor, if possible
• otherwise usc published factor
5. Ensure thar your estlmales of method sizes ,nd time will be compared and saved at prOject end.

Figure 19.25 Estimating size and time·to·complete from detailed designs


UPDAnNG A PROJECT WITH DETAILED DESIGN 493

Calegory

Very small Small Med ium Large Very large

Calculation 2 34 5 13 1 1 25 24 66 54 .04
Data 2 .60 479 8.84 16 .3 1 3009
Metho d type VO 90 1 12 06 16. 15 21 62 28 .93
Logic 7.55 10 .98 15.98 2325 33 83
Set-up 3.88 5 0·1 6.56 853 11 09
Text 3.75 800 1707 364 1 77 67

Figure 19.26 Lines of code


.sc:ure Humphrey. Watts S. A Otsclplcoe lor SOltware Englneenng (SE! SolEs In SOftware Englr'leenng), AdcJlSkln-We<'Jpy, 1m

~cause they arc ca'\y to understand They ca n be made more precIse.: by ca te gorization \\Inh the normal
distributi on, as shown in Fi gure 19.27
On Ihe average, about 38 percent of the meth od sho uld be claSSified as "medium ," 24 percent "<mall ,"
and 7 percent "very small: a< illustrated in Figure 19.27 These numbers arc oblalnod from the fac llhat about
38 percent of the va lues in a normal d, tributlo n arc wilhin a half of a standard deviation of Ihe mean In
practical tenns, If the fract ion of metho ds yo u e lilll ale as "very large" differs much front 7 percent , for
example, Ihen you shou ld be satisned that yo ur app lica lio n rea ll y does have a n unu sua l numbe r of very large
methods. O lhc lwi ' e , yo u sho uld revise your es tllnales.
As an ,,"ample, lei's <Stlmale the size of the <xccul<() metho d of th e Eng"gem"'l clas l111s mel hod Involvo<
the recalculation or qua li ry va lues, which is th e cssenria l mechanism of executing the engagement process
For this reason , we could clasSify Ih e ",tmltO met ho d a, a "calculati o n.' The size of the "'t(ultO mel hod is not
particularly remarkable, since it consi ts of a fairl y straightforward co mputat io n of va lues, so we'll cla<>.fy II as
' medium : Thus , the e timated co ntribution of "'t(ult O is 11 .25 LOC
A level 5 orga nizatio n (sec C hapter 5 o n the Capabilit y Maturity M o del ) would IYPlcali y pl o t method
size estimates against acrual Sizes In o rder to improve thi S es timJtlon process. In th t- ca ... e study , these
estimates arc app li ed to the Encou nter Video ga me .

Approximate
percentage of
methods
classified with this
description s M L

7% 24 % 38% 24 % 7%

v v
-2 -1 o 1 2
Standard devia tions Irorn the moan

Fl&ure 19,27 Normal chSlllbuUon of "small," " medium," and " large"
.94 CIiAPITR 19 DETAILED DESIGN

19.12 CASE STUDY: DETAILED DESIGN OF ENCOUNTER

\'\fhat follow> ISthe detailed de. llln for Encounter, based the l,audl,E.CIlIO method of Its al!grel!ated Ga",Slal,
on th e architecture speciRcd earlier 10 dHS book, and ob)e t. The seque nce d ,al!cam for th is IS shown In
U lOll the IEEE standard E.ch use case is rea!.zed a< a Figure 19,29. For th e current fe lease , the methods arc
sequence diagram by dl'CldlOg, for cach u<c ca<e step, either trivlJI or arc 'ihow n In Figure 19 29
willch object <hould initiate and wh ich should perfoml
the work Slep IOvolvecl ll,eclass models should contain
Ihe classes that appear 10 the equence diagram Pseudocode (or selec ted method within se ·
lected classes may be included he re. In addi ·
6. Detailed Design of Role-Playing Game tion , detailed usc cases can be included. Si nce
Framework the methods and thei r detai ls arc still o ne or
two lines in rhis case, it is sufficien t' to elab·
orate o n the (barely) nontnvial me thods wllh
6.1 Module Detailed Design
the no tatIOn shown in Figure 19.28 .

Note to the Student·


These sections give all of the nontrivial required 6.1.2 The Characters package
details on each of the modules described in This section elabora tes on Section 3, 1.2 of this SOD.
Section 3.1 in this SOD for the game framework. There is one clilSSin the Characltr package, Ga..tCharadtr.

6.1.2.1 GameCharacter Class


6.1.1 Role-Playing Game package Methods of Ga .. ,Charac/cr
All mouse eve nts are liSle ned for by objects of the
classRPGMollScEvrn IUsto1Cr, which Inherits (To m setName ( ) .
Mou"L "",,, as shown in Figure 19.28. Each object Pr eco ndition s : n o n e ;
that is cns ltivc to mOllse eve nt's Jsks an RPGa mr p ostco nd itio n s : none;
object to ha ndle the eve nt. RPGa .. , passe control to invar iants : no n e

MouseListener

I
( rPGameS .handleEvent():
I
rPGameS RPGMouse£ventListener
mouseEnlerO

RPGame
handleEventO slateS handleEvenlO

( stateS.handleEventO: )

Figure 19.28 Derailed design of RolePlayfngGame package


CASE STUDY' DETAILED DESIGN OF ENCOUNTER 495

user eventTarget :RPGame :GameState

:RPGMouseEventListener

1. mouse-+(-,
action

2. mouseChckedO

3. handle Event
( Event)

4 . handle Event
( Event)

Figure 19.29 Sequence diagram for handling mouse events

Pseudocode, 6.1 Module Detailed Design for Encounter


IF aNam~ parameter OR
max umChars ln ameO make no ense
Th~se sections give ali of the reqUired detail
er name to default va lue and ,how
on each of the modules descnbed In cct,on
thiS In system window
3.1 in thi s SDD (i.e ., for Encounter).
ELSE
IF parameter stri ng too long
truncate at max 'urn hars lll ame() 6.1.1 The EncounterGame Package
ELSE aSSign the parameter nam e

This section glve< ali of ,he required detat!, on


6.1.3 The GameEnvironment pacKage Section 3 I I In thl DO. It descnbe com·
This package IS descnbed completely by F'l(urc 19 .3 1
pletely the classes of the Ell o,,,,'uGa,,,,
pack·
age, and .11 of thelt nontnvial behaVIOr. Mosl
in Section 3 I of thiS DO (C hapter 18)
of ,hI< " desc ribed b , ,he state tranSition
diagram In the Inlerest of keeping ,he cia
6.1.4 The Artifacts Package model fre~ of ciuller. we do not show all oblecl
Ot appltc.ble ,n thiS ,ter. lI on referen ces

6. DETAILED DESIGN OF ENCOUNTER


The ,lille ,"aJ.;rJIll lor Ell ounter 1'" ... hoWI) In
The ove rall arc.hllc:<.tur 0, ,howlng the r 'IJlIOn,hlp" SeUinn 2 I I (JI the RS (h Mure I I 2{) I (hopter I I )
amonl! the package, .nd th domain d."e, dc· To rt"al ,zc lhc,c tl" l il l l'" and lI~n' llI o n , the E 'I(C'IIIIltT(;,IIIH"
'iCnbed In th" seCllon, " shown tn I' Hure I') ~(I l)atbgc tI " mod·1 " dC"Rned ." II'
l,gIII'<: I'l 1 1
496 CHAPTER 19 DETAILED DESIGN

RolePlaylngG.me
. f_work package w
Characters

- U~6S •
EncountorGame
.. use -application package -
EncounterCharaclers
- application package- I EncounterGame
I I Engagement
I
EncounterCharacter I EngagementDisplay
I
-z;;- GameEnvironment
Ir
PlayerCharacter
- framework package-
r
ForeignCharacter
- u~es w
EncounterEnVlronment
I PlayerOualityWindow
I ..application package ..

Gam8Art~acts
Area
I EncounterAreaConnection
I
.framework packsge- I Con nectioflHype rI ink
I
Figure 19.30 Encounter game architecture packages, showing domain classes only

,
~------- ------------ ,,
:
,, RolePlayingGame ,,
-,- ------------------- --------------------------------- ------------- --,,
,, ,,
,, RPGMouseEventustener
,,, notilyOfEventO
RPGame GameState ,,,
handleEventO handleEventO ,,
,,, ,,
,, ~ ,
,
---
--- -------------- -------------------------------- --------- -- ------- ---- ----- -
1-------£------------------- -- ---- -- ---- - -- -- ~ ---- -,
--------

I I
I EncounterGame I
I «singleton» I
I Engaging Wailing I
I I
I handleEventO handleEventO I
I
I
I
Engagement
t <>l I
I
I
I I
I I
I Reporting Preparing I
I handleEvenlO I
I EngagementDlsplay handleEventO I
I I
t I
fL.. _ _ _ _ _ _ _ _
----------~------- ------- - - - -I
,, -
I
,I,
, EncounlerGame ,
EncounlerEnvironment EncounterCast ----- ----- -- ----- '

Figure 19.31 Detailed design of EncounterGame package


CASE STUDY: DETAILED DESIGN OF ENCOUNTER 497

n ,crc ,.. {''(actly one 1O,,{a n l' of the E"tOUlltrrClltn( Q"alVal,,,DlSpl " a rcad ·o nly tex i box fo r d,s-
c1as n,e <r.llc, 01 Ih, obJecl rene I Ihe ; Iale, . nd pl .y ing the value of a qual,ty.
~bo- ratn ~hown In the above tatc· transltlon diagram
"Q".lValll,D ..pl " an ed'i able lex I box fo r
The fncou"tm"9 'laic aggregale all E"909""",1 obJecl
ellong Ihe value of a qua l,lY
that en ap ... ula tcs the cllgilgcmcnt of th e gJmc charac -
lers n,e E"gogm,,,,1 lass aggfl'galCS a d,splay called Enco'lIIlrrD;splayllrm ab<tracls Ihe properties and
f"g.!I"",,,IDospl.y . The laller IS m u<e ·sensollve. reg's. melhods 01 d,splay.hle Encoun ler ,terns uc h a.
lenng w'lh an RPGA IOll" E"noILslno" obJe I When Ihe Ihesc.
Encounter game IS execulcd , thl li stener 0 1 Jeet rder-
EIlgagcmrt" D,spl"y IS des'gned to do< play the
ences Ihe E"co,mlrrGano, obJecl (an RPC."" obJe I) Th"
current va lue.: of any selec ted qualIfY·
enables E"co,,,,trrG.m, to handle all evenl< acco rd ing 10
the game's tate. uSIng Ihe I.IC dl'<'gn pa llCIn The S"Q,wl,tyD,splay , dc<ogned to enable the
E"counlrrG.m, package ha, Ihe «'Spon ,bolllY 01 d, recl · playe r 10 SCI Ihe va lue of any qua lilY
Ing the movement of th e fo rc-ig:"} charactcr over l ime.
Ell o""!r,DlSplay ab traclS Ihe propcrt,c of Ihese
Th, , perlom,ed by melhods of the cia, ham 1,,-
dosp la s and IS. med,.to r base lass
MOV<mml. which os a thread class
tale classes need to rdert n e other package on
Th, document does not prov,de further dCloois
orderto ,mplcment IJall,Il,EIJtI,tf), and th,s is done th rough
of Ihe deSIg n of the,e lasses
the Fdcadr objects EncolUlkrCn!lt and E,,(OlltlttTftlViromnnl f

6.1.1.1 The EncounterGameO;splays Subpac k- 6 .1.1.2 Se quence Diagrams for Event Ha ndli ng
age of the EncounterGame Pa c kage Di splays
correspo nd ,ng to some of Ihe tales arc hand led by a
separa te: ubpackage , Ellcou"ter ,(JmcD,splf1Ys, w hi h IS 6.1.1.2.1 Player Dism isses Report Window
shown on F'gu re 19.32 Event Fi gure 1933 hows the wqllence ,,,volved
i n di sm ISS i ng th e cngagc:mem d,o;;pla tTh,<; di .
QualLslD;splos a lost box conSIstin g of Ihe qual,, · m ls' al eve nl IS ~ h wn on the ,IJtC - tran Il io n
ICS or Encounter ch ar.'l ctcrs d,agram .)

MouseListener
-_..... - ....... _..... _.. _--
r- I
I
-- --- ------
EncounterDisplayltem 0 : ~ EncounterCast I
II ~ I
,,I EncounterOisplay
,
I,,
,I Oual listDispl SetOualValueDispl
..,
I OualValueDlspl
II
I
I
I EngagemenlDisplay Reporting
,I
I
I
i '- handleEvonlO

,I SetOualityDisplay !- Preparing

- - - - -- - . _-1 handloEvonl()

Figure 19.32 DeUllle<l design of EncounrerGameDlsplays subp ckage


.98 CHAPTER 19 DETAILED DESIGN

user :EngagemenlDisplay

1 • hI! :RPGMouse
dismiss EvenlUslener :ReportingEncounler
bunon
2. mouS<lClockodO :EncounlerGame

3 handleEvenlO

4, handleEventO

5. solVlsible( lalse )

6. setState
(new Walling ())

Figure 19.33 Sequence diagram for dismissing engagemenl display

6.1.1.2.2 Player Completes Setup Event Fig. connec tio n hy perl ink. (Th is dismissa l event IS shown
ure 19 .34 ~hows the scque nc(' Involved when the o n the state· transi ti o n diagram .)
player completes the SC:l"Up . (Th is di missa l event is
shown on th e ~tatc ' lransition diagram .)
6.1.1.2.4 Sequence Diagrams for Remaining
6.1.1.2.3 Player Moves to Adjacent Area Event Events The remai nong eve nts are handled very
Figure 19 .35 shows the sequence when the playe r sim ilarly 10 th ose described in Sectio ns 6 . 1 1.1
moves to an adjacent area by cl icking o n a Ihrough 6. 1.1. 3.

user :PlayerOualityWindow :SettingUp

1. hIt :RPGMouse
dismiss EventListener
bunon
-l
2. mouseClickedO
:EncounterGame

3. handleEvenlO
or
4. handleEvenlO
"r'1
5. setVisible( false )

r'r 6. selSlate
(new WaltingOi

Figure 19.34 seQuence diagram for Player Completes Setup use case
CASE STUDY DETAILED DESIGN OF ENCOUNTER 499

Us er :AreaConnectionHyperl ink :EncounterCast :Waiting


, L
l.h
area" :RPGMouse :EncounterEnvironment
...J
con neetion -+n EventListener
hype rlmk :EncounterGame
...J
2. mouseChckedO
3. handleEventO
4. handleEventO
5. selVislble( lalse ) +0-, -+n
6. d,splayAreaO
U' I
7. d,splayPlayerCharacterO
________ J___ __l ___________ ___ _______
,,----- ------------ -- --------------- ---- ,
,
~ ____________ _________ ___ J!!9!'!!.Jl'! _c'!.<}~c'er present
--- ---- , -----r-- ---------------- --
8. dlsplayFore'gnCharacterO

9. setState
U (new Engag,ngUi

Figure 19.35 Sequence diagram for Player Moves to Adjacent Area use case

6.1.1 . CM The CharacterMovement Class 6.1.2. EG The EncounterGame Class ThIS "
the faca de , IOgltton lor th t E" o""'rrG"",, package

As in the SRS, we arc UStng an alphabetical Inherit ance


"numbenng" scheme to make It eaSlcr to find 1l1is cia 0;; in hents from RPGafl1( 10 the r..ln1cwork
and tnsert classc . There is . 1 0 a be nefit 10
being able to trace the requireme nts to the Aunblltc"> of Ell olwlcrGflmr
SRS.
EncounterGame encounterGameS :

11" s .s thl.: ",nglcton EtlCOlltllrrGmnc obJc t


Th is cia." co nlrol~ the movc:men l of the fon: lg n
o n ' lrlJ C l or~ of E"loll"lcrGtlmc
character

pr ivate EncounterGame () :
Inheritance
Th is cia'> Inhent< from Java 1""9 Thread Precondition.:; none
Post ndillon... rcJ t (~ I n EII(Olmtcr(,(lrtlc In,l"J,nte
Methods of (haradrrMov,""H I
Mcthod" of E",outllcr(,mnr
publi c static EncounterGame run ( ) ;
Slart, the foreign ~ h .ract"r ,n th" dung""n public static EncounterGame
Muve, the f",elgn haractor Irom arCJ to area getTheEncounterGame() :
Via area ('onnC('II()n<. , cha n~l!l~ area.., to a ran PretO lH.h l IOn\ no ne
domly ,cI~~led n ' Ighbnr, at random IIme< 11o\ltOlldlll n, ttlco lHllrrC,tltnrS not nlill
a\,("raKln~ f..:vc:ry two \ccond ... I e turr)«; ('It CO IIPlI('(hl "' t'~
500 CHAPTl:R , 9 DETAILED DESIGN

6.1.3. EN The Engagement Class ThIS clas< Each of Ihe« cla< e' Implements Its hand/,tDatIO
n Jpsulatco;. cnHagcmcn ls bct\..,1 ccn the players char· method in a corda nee WIth the sequence dIagrams of
aCter and th e fore lg" c harac ter. and corresponds to ection 6 I. I I,
reqUIrement 3 2.EN .
6.1.2 The EncounterCharacters package

public void eng_geO; II This section elaborates on Section 3. 1.2 in this


SOD.
orresponds to reqUIrement 3 2.EN .3. 1
Precond,ti ons, The player's character and the
foreign charJctcr arc in Ihe amc area. TI,e deSIgn of the tllcoun l,rCharaclm package is
Postcondition,>: Th e valul"'S of th e characters' shown in Figure 1936. It is implemented by the
qualitlcs are as reqUIred by SRS requirement Facade desig n pattern , with EllcounltrCn" as the fa ·
3.2.EN .3 Ii the player's character and the for· cade object .
cign character arc in random but different areas.

6.1 .5. EC The EncounterCharacter Class This


6.1.4. ll. The Engaging, Waiting, preparing, and
class encapsulates the requirements for El1coul1ttr
Reporting Classes
charac ters that arc not covered by R.PGam,Characlm .
It satisfies requirements SRS 3.2.EC.
The '7:z." numbering is used to collect classes Class invariant, The va lues of qlla/lla/ur/ arc
that arc not specified individually. nonnegative (see lfattnbulcS" below (or the deAni ·
tions of qua/lla/",n .

Inheritance Inheritance
The e classcs inherit from Gam,Slal, in the This class mherits from GameCharacter in the
framework package. framework package.

Characters
. Iramework package"

GameCharacter

EncounterCharacters
..application package-

EncounterCharacter

PlayerCharacter
.·facade-
EncounterCast
ForeignCharacter

FIpIre 19.36 Detailed design of Encountercharacters package


CASE STUDY: DETAILED DESIGN OF ENCOUNTER SOl

Attnbutc of EI1C'Olmltr baraclcr Set Ihe stated q uality to the destred amount
These att~.f requ irement 32ECI IF the caller adjusts the on ly nonzero qual ·
private static final String[ J ity value , divide the adjustment amount
qualityTypeS 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 .
Sct each quality whose va lue is now less
private float [J qualvalueI than 0.5 to zero.
11u IS an array COnt3 1nlflg the valuec; of the public float qetQualityVillue
qualtttcs. ( Str ing qualityP )
Constructors of EnC"ounlrrCI){zracrrr Preco nditions qua lt tyP IS a val,d q"altty string
These satisfy reqUIrement' 3.2 EC3 of the SRS Returns the va lue of qua lt tyP
Null constructor pub 1 ic f loa t qetToleranc e ( )
Po tconditton The qualit lc arc all equa l
fracttons of 100 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 of Encounrer characters
(2) the character's name IS ameP public float sumOfQualities ()
Methods of EncolI" I"Charact" Returns, the sum of the value< of the qualltlc,
public synchronized void Thi s meth od sallshes requireme nt 32 EC3 2
adjustQuali ty public void showCharacter
( String qualityP , float ( Component componentP ,
qualityValueP ) Graphics drawP , Point posP , int
TIll method ,.ttsfle< requirement 3.2 E .3 2 heightPixP , boolean faceLeftP )
Invananls none Displays the character in cO"'PO,,"'IP. with ccn·
Precond,tIons, tcr at posP, wit h heI ght l)<Igh/P,xP, facIng left If
qualltyP I< In qualttyT ypc<S[ J
JacruJIP true
AND qualltyValue l > =0
AND quahtyV. lueP < = the sum of the TIllS metho d at"Res requirement, 3.2 r C I
quality values and 32 PQ I
Pcxlcondl t lon\
pr ivate void setQuality ( Str ing
quahtyP has the value qualtty Value P
quali tyP , float va lueP )
AND
the remaining quality values arc tn the qmc Prc onditlo ns, qlla/ltyP " a va hd qualir' 'trlng
proportion 3\ e " the qua ),ty ,nd, . ted by Ih e pM.meter t
prt()r to Invocallon , exc.ep t th at va lue:, I c,,~ Vllilltp.r th e latter t< > = 0.5. oth e rwi$~ sets
than 0.5 arc zero oal",P to Zero
The followIng" the p<cudo ode for TI,l" method 'aw.he, r~qll1n:n1t.·nt 3 2
the method aJ)u"Oua/IIY() 2 (lower Im1lt t) llll onZt>ro qUiJhlV value, )
502 CHAPTER 19 DElAILED DESIGN

6.1.6. ES The EncounterCast


Class n e 6.1.8. AR Area Class This clas< encapsu late< the
me thod ,pe ,A Jt,o ns for thos inglcton . interfa e place in wh ,c h the chJractcrs eXISt , and corresponds
cia ... , af(' given In Section 5 of dll s document to reqUIrement 3 2.AR

Inhent ance
6.1.7. FC The ForeignCharacter Class n is Thi S d.,o;s Inhents (rom GnmtA rra
clas. i analogou to Plnycr(l",raclrr. described Attributes,
nex t, and ,s designed to sa tisfy the SR 3.2.FC
pri vate St ring nam eI ; I I
6.1.8. PC The PlayerCharacter Class This class corresponding to requirement
,s desig ned to satISfy the requirements 3.2.PC 3 . 2 . AR. 1. 1
private Image i mageI ; II
Inhcrirance cor r espo nd i ng t o requirement
Thl c1asc; Inherits fro m E'ICOlilllt rCha ra clcr. 3 . 2 . AR . 1.2
Attnb utes, private Stri ng [ J qu alitiesI ; II
co rr es pond ing to requireme nt
private static final Play e r 3 . 2 . AR . 1. 3
Cha racter playerCharacterS ; pr ivate Vector co nn ect io n
This is the si ngkton object representing the HyperlinksI;
player's charac te r.
Metho ds
Methods, pub lic v o id display ( ) I I
public static final Player shows the area objec t's image on the mo nitor.
Characte r getPlayerCharacter( ) ; public static Area geUrea
nis me thod returns play,rCharaclcrS. (String areaNameP )
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
In which the game takes place. It is shown in getAreaConnection ( St ring area
F,gure 19.37. ConnectionNameP )

GameEnvlronment

GameArea -..f GameCharacler


~
GameAreaConnection

I
Area
rC EncounterAreaConnectlon

EfiOO' mterErMn.",·. fLe,lI ConnectlonHypeftlnk


oJ

EncountetEnvlron,icent

FIgure 1'.37 EncounterEnllironment package


CASE STUDY DETAILED DESIGN OF ECUPSE 503

rerum~ the areJ object co rTcspo ndlng


0,,"((11011
Atlnbutcs:
to ,lrc.1CO""KhoPiNIll1ttP ZI ordr l1g to reqUIre-
ment ' 2 AR 2 2 private Connection connectionI ; 11
the corresponding connection
6.1.9. CO EncounterAreaConnection Class
Methods·
This la cncap ulatc.:; the way~ to get rrorn areas to
adjacent a~as. It Inh erits (rom ArWCOtltl(( tJOIi and The only mean~ngful method is
COrTe pond. to requirement 3.2 0 mou s eC li ck ( ) "

Inhentance 6.2 Data Detai led Design


This cia" Inhents rTom Gmll(A,rn Co.l ~
"crholl I n the framework package There arc no data structures beSides lhoc;c mentioned
Aunbulc); as part of the ela ~e) 111 e tlon 6 1

pr .lv ate Ar ea f irst Areal : 19.13 CASE STUDY: DETAILED DESIGN OF


/ I con esp ond lng tor equ l r erne-ot 3 . . CO . 1 . 1 ECLIPSE
pr l va t e Ar ea seco ndAreaI ;
//co rr espondLnq t o requir<.'rne n t 3 . 2.(0 . 1. 1 Rdercnce, The lavaDoc for Eclipse IS at http /l
"'w\vx hpse org/d cumcnlatlon/ html/ plugln or" ~

I-Icthods Th~se are acce sors for the attnbute.


eclipse platform .doc Isv/ do reference/api
above overview -summ ary ,hlm1

6.1.10. EE EncounterEnvironment Class ThiS


is the facad~ cia s (or the E"colll1lnE,wlfolHllnll package.
No te to the tudent·
Attributes,
Eclipse i a large project, and this ca e study
private EncounterEnvironment docs not attempt to dcscnbe its des.gn in
encounter EnvironmentS; detai l-merely to provide excerpt from a small
l i the singleton Facade object example of how detailed de ign IS some times
II {Area name] {Area connection speCified in the ca l' of Eclipse. The co mplete
Ii name] {' ' North " I ' ' South " document would be based on the archltect\lrc
I I I " East " I " West " ] , decomposi tion describ ed preViously It would
private String[3] lay o utS; have a section on ca h of the Plaifo,," , the Java
DWc/Ol'm,"1 Ellvlrollmrnl, and ,he Pluglll Dn",'o"m",'
1ethod, EHVlrOHmrnl. \'(Ilthln the Plaifo,," <eClion , It would
have a Workspllrr and a Corr ,cClion \'(Iltll1n the
pub l~c static Encount e rEnvironment Corr "cellon , It would have a RlUllmt( t:C1lOn
getEncounterEnvi ronme nt ( ) Part of lilt, lauc.:r IS shovm next.
Retutns: enc o un te rEnvironmentS
public static S tr i ng{ 3 ] g etLa y o u t{ )
Returns : layo u t S
Platform. Core. Runtime
The rema1l1111~ metho d, arc ,pecdl d,n Sett lon
5 ,>I th" dowment
Ideally , th" ' C tl o n ould be t",u'd to the Ecll!,'e
6,1.11 CH ConnectionHyperlink C lass 11", requirem e nt> Although the re~der r
'he Eclip'c
cia., encapsulate. the wa y ' to Het fWIll area' to documentation C~ n undcraan I the tm e In gen-
adJac..cnt areas It <.orrcspo(1d lO to n: flUlrClnCl1l l 2 cr~ 1 h:nn .. , It ,\ not \rr.llt-;hLl f\\fard (0 IOC~' tc.- lilt"
C.H Tim da~s Impl ' mcn" the M OlI srLulrlltr eXilet r feren <" to rl'qulrl'ml~nt~ ,c tlon,
Intcrfac t'
S04 CHAPTER 19 DETAILED DESIGN

All maU oodo


am1lc
1\
IT'
,
Platform
s.ngIolon 1
Plugin
getlnstance() - - - getCommandLineArgs()
gelPlugln()
Eclipse command
line opIiOnS

getPluginPrelerences() •• • by

/ ,, Idoolificatlon

/
/
,,
/
/
/
, \
r-_-',I'-----, ~
Preferences Palh

Figure 19.38 Core classes of Eclipse

PI.ifo,," Corc.R""'i,", is o rganized around a smal1


set of core classes, as sho wn," Figure 19.38 .
Features include :
The classes in F'gure 19.38 are described next.
• the platfo rm regIStry o f instal1ed plug·ins
PLA TFORM CLASS
• the platform adapter manager
• the platform log
The fol1owing is from the Eclipse ja"adoc <as
edited by the author). An alternative would be • the auth o rizat io n info management
to provide the skeleton of the class itself in the
fol1owing form . The platfo rm is in o ne o f two states, ""IH'"9 o r
1101 num iHg , at all times. The o nl y wa ys to stan the
platform running, o r to shut it down. are o n the
I/ Th e centr a l c l ass of the Eclipse Pla t form boo tstrap BeolLoad" class.
IIRun time
• • •
pu blic f i n al c lass Pl.tfo~ e xte nd s Obje c t In other words, the methods that sta" or shut
( down the platform arc found in the class
p ubli c st a t ic ge t Instance ( ) () - n o c ontent Be.d.oad".
-. ..
}
publi c final cla ss Pl.ttoJ:a extends Object Code in plug . ins will only observe the platform
in the running state. The platform cannOt be shut-
Thecentral cla.ss of the Eclipse Platform Runtime, down from inside (code," plug-ins have no access to
This class cannot be instantiated or subclassed by BoorLoad,,).
clientsl al1 functionality is provided by static mel hods. • • • •

public static Plugin getPlugin(StTing id )


R~rum the plug-in runtime object for the
If a clns is 10 haw no instances, all ilS methods identified plug. in or null if no such plU8-in can be
an: made Slatic. found. If the plug-in is defined but not yet activated.
the plug-in will be acrivated before beong returned.
SUMMARY 505

Parameters. Id - ,he unIque Idenllr.er of ,he


desl",d plug -II, (e g , "<-om .example .acme") sense of how documentatIOn reads that I

Re, urns_ ,he plug-on run"l11e obJec" or null generated (via Javadoc) from source code

comment An advantage of uSIng Javadoc is
that it lend, to ren'liUn up-lo -da te a long as ,he
progr.Jmmcr comments the code accordmg to
We have provided Just a '.s'e of the beglnnong
the standard
of the Eclipsc design . Th, example provIdes a

19.14 SUMMARY

DetaIled de Ign IS an actiVIty In whIch components su has clas c, and me' hods are denned In enough de,aol
so th at implementation ca n comme nce We Start \\1 1th the domain lassc!t from requlremcnb analysi and add
the necessary deSign classes to complete the design DeSign patterns arc Introduced as reqUIred to Implement
any comm onl y n.:curring deSign prob lems.
Dunng detailed design, l!lterface functions \ ../ith spec ified names, parameter types, and rerurn rype, arc
de fi ned The program eicments USi ng these func'ions can [hen be designed wllhou, haVing '0 know how
,he fu nctionality I Implemented-all ,hey need '0 know IS how '0 usc [he Interface Th,s faclllla ,es ,he
develop me n' of each design clement epara,dy. The Facade deSIgn pattern lone way of prov,d,n g an
intcrface to (l package of clas cs
When designing o bjec, -oriented software. severa l wc ll -esta bli,hed de>lgn pnnclpies help en,ure a
robust and extenSIble design : Slngle · re<p o nSlbol" y , ope n·closed , LlSkov substitutIon , dependenc -inVersIon
and interface segregJrio n.
'.It'lhen speCIfying ,he detaol< of a class, we start wllh the do maIn cia ses def,ned durong requirement< Wle
ga,her the attrobu'es already defined a nd add addi ' io nal attribu ' es reqUired for deSIgn Wle also der.ne cia,s
and method Invariants, and me' hod pre - a nd postcond " ions . Pseud ocode IS wrottcn '0
de,cnbe how each
me' hod is '0 be Impleme nted. W e ' hen add ad diti o n classes necessary ' 0 comple ,e the dc<ogn and dra'" a cia"
model shOWing ,he SlatlC relationshIp between classes An ac" v,ty dIa g ram an al<o be drawn '0
graph l all y
describe nontnvlal algorithrn~ Some.: detailed designs are best commun icated via detaded scqllcncl.' dlagramc;
o r de,ailed da,a Row d,agrams. Sequcn e diagrams sho w , he obJe ' s assoeoa,ed with a partIcular use ase and
the messa ges (, c ., func"on ca lls) ,ha, flow be,ween ,hem . Da,a flow d,a gra ms show procesSIng demen', (, c .,
methods) In a program and ,he da,a ,h., flow between ,hem
The de ,a lied de<osn IS documen,ed "' a sof,ware deS Ig n speclhcallon . Wle have on'rodu cd IEEE
standard 1016-1998 lor oftware DeSIgn Document< as a n exa mple of slIch a document
Detalied deSIgn conclude, by upda"ng ,he ,chedu le in , he PMI' ' 0 relk , ,hl' de ' aols learned The
proce < hould also be reVIewed with respect '0 ,he amoun, of "me ,aken and thl' number defec,' d"covefl·d
Im provcmelHs can be planned ba,ed on how these mtln ... compare agaln')t the pbn

19.15 EXERCISES

1 Explain the followln !!


la ) -rn, purpose nf detaolcd deSIgn (I", 'hrec hendl" )
Ib ) Howl' dolfers from s,,(,ware ..th"e<.lurc
Cc) Why Il ,\ gencrJlly i1 quc"Illonablc ,dcJ to J.(O dire dy from JrChlit:<..lurc to Imp! cf1l l.'nti1t1on
506 CHAPTER 19 DETAILED DESIGN

2 Your ompa ny produ es <ohw3re Ihat con tro ls a rohot 3m> for manufac tUring Name four clas.cs
that wou ld he appropria te me mber< of yo ur o mpa ny', ,0flwMe framework Expla in your
reaso ning.

3 E. lIm atr the num ber of lines of Jav3 ode fo r the fo ll owln 8 sc t of me tho ds. T he met hods arc
o rdered fTom malles t to large t. Assum e t bat th ere IS no thin g un usual abou t t he Job ",apt as
indica ted In th e informatt on below ,

Met hod L 110, Me th od 2, T ex t, Me tho d 3, Calcu latio n; Me th o d 4. Log ic,


Met ho d 5: Data , Me th o d 6: Calcul atIO n; Me th o d 7: T ex t, Me th o d 8: Da ta;
Me th o d 9: et· up. Me th o d 10: Calcul ati o n; Me th o d II : T ex t; Me th od 12· D ata

4. o mpic te th e fo lioWIn!:, ex pl ai nin g und er what ci rcumstan ces you would use th e fo llowi ng in
detai led desig n.
(a) Usc activity d iag rams whc n the logic _____ .
(b) Use p eud ecode fo r a meth o d whe n _ _ __

5. Define appro priate interface th at th e fo llowing cia , exhibits (o r "impl eme nts" in Java te rms).
Assume that addll'l o nal meth o ds w ill be required as th e appl ica tio n g ro ws. Ex plain your reaso ning.
Hi,,! Th e Interfaces ind icate w.hat kind of tran saction th is is.

6 Describe in your ow n wo rds th e advantagc:s of specifying preconditions. postcond itions. and


In varia nts. H ow, speCificall y, do th ey help to increase th e quality o f fun ctio ns?

7. Perform a desig n (bo th architectural and detail ed ) fo r a check· ba lanc ing appl icatio n with the
fo llow,"g req uire me nts. Fix defects in th e requireme nts if yo u Rnd th em . Yo u can play th e role of
customer If and w hen the cusromcr's input is required. Repa n the l ime you spent on Sig nificant
actl viril-s to the neares t five minutes.

I. The system , hall d is play th e current balance ," th e system windo w.


2. The sy tern perm its the user to reco rd deposits of up to $ 10 ,000.
3. Th e system perm its th e user to wit hdra w any amount (rom th e current balance. A n error
message 1""his wi thd rawa l amount exceeds your bal ance" is d ispl ayed w hen (he user att empts to
withdraw an amount exceeding th e balance.

S. A cl05S1C Liskov substitut ion princi ple exa mple co nSiSts of two closses, Squa re and Rectan gle. Since a
square is-c, recta ngle, the rela tionship be twee n the two ca n be modeled using inheritance, w ith Squarr
derivi ng fTOm Rerum!!/,. Sup pose that Rectangle has met hods to setlget the width, and setlget th e length .
Explain how th IS relationship betwee n quare and Rectangle vio lates the Liskov substitutio n princi ple.

TEAM EXERCISES

SOD

Provide an SDD fo r )'our project. Usc, or improve upon the IEEE standa rd. Please enclose the btest vorsion of
yo ur SRS.
BIBLIOGRAPHY 507

Report [he rime pent h) the indl vldu :l l!) :l nd th e- group on rh e parrs o f (hl ~ as::,.ignrnenc. Break rh b down IntO
a ctl\' Ltlt"~. in ludlllg 3fl· hu ("<.'tu re, lnsPCl..' tl O!l , reV ICW, and dt l3i led design. o mmcnt o n how lhl" tim e spe nt
uJd h.I' " heen hen "r olJ"""tcd.

BIBLIOGRAPHY

1 f\ brtm RolX"rt A9.1t Sojhi •• Ht Dn'tlopI'IICI'II P'lP1ul'ln Purim!. DIlJ P,.ldlCt'I P"mltlC Hall 100J
2 M~"ln Roben 'DnJ9" P'JP1ctpln .",(11)0111" P,,'knh 2000 ''''''''''' ohlcctmcntm l.()m ' n;..ourc<..~"'r1Ic1C'VPnnclplc.",_i) nd_I),mcrn' pdf
l )(.cc"~ No\'cmtxr 2<) lOOQ ]
3 13rtlO Rolxrt . Th Dt~J(JIIY Itlw,.,u)r\ PnP1C1p/r . •• Rerort lI.1.:J.) 19Q6, hup ''''......., obJC'clmentOr com..r·c.. ourcc .... 3n .cll!"'i. dip pdf
l.lcC'e-...ed 'ovcmbcr 29 2009 }
" Thc ObJct t ~li"lJ8("mcnl ,mup ...."""'" omg orlo: ( ! 999)
5 lurJcn!!o Iln StUff Sy)rt7rl\ I)nxlop"'(11\ 11"111, Llt\ ll pnnRer, 2005
6 Humphr("V \X'ltl.. A D')(lp/"t( jilt ojIU',H( En911fuwlQ 'f=( Snln In _oJhi'.Jtr EII9"l(trI,,!/ ), Add, ..on Wc:..lcy 1(1')
1 Jon~, .:apcr .. "ApplIed Sof/lI'tl rt ,\t(;l\u ft'l'llrrrl As\un0l9 P'O.rUtlll'l/), uOIn (.lw.,llly. 2nd c:d'Llo n Nc",' Yorl.. M Cra\\ HIli 199(,
Q M r'1Jm.tlon Pornt Lan.,.'U:st;c.. T.:able, (A pn l 2005 VersI on ~ O) Imp '1 ",,,,.,,,. q ~m cOITlJre~ourcc"dun<.hfJn pOint Lm,,;u.lMe<. ·tahlc
,"deJe htlnl [accc:,.. ovcmbc:r 2Q 20091
9 !cyer Ikruand Ob)t'C I.OnmleJ 50jlll'<I(( "n>I'II./"JOI ~ccond Edition Prcnt KC' 11311 20<,7
10 L,~l..ov B.a rbJr.l and John UU;:J.I<: Ab-t,... dIOIf anJ IltnfiWh"" '" Pr~rdm DnH/"pmtnl i\IIT rrc:-.~ IQS6

/
Design uality and Metrics

• How do you assess the degree of


Planning understandability in a software
design?
Maintenance
• How do you assess the degree of
Testing cohesion and coupling?
The Software - degree of sufficiency?
Development - robustness?
Ufecycle Requirements - flexibility. reusability?
- time efficiency. space efficiency?
analysis
- reliability?
Implementation - security?

• How is quality in architecture selection


measured?

• How is the quality of a detailed design


measured?

Figure 20.1 The context and learning goals for thiS chapter

Si n c a se t or requirements can be accommodated by several possible de igns . we can compare


lhe q"<1/ily o f ca nd id"e designs . As explained in C hap, cr 15. 'he qua lilies a a design Include
uHdcrsttJnda b.lily , modularity , ('obtsio 'l , cOL/pIing , suffi ItH CY, robiot sh1rH, flexibility , r(u sab""y~ rjfintHcy. and
rcl,obil"y . PrO)CCI leadership specif,,:s the desired level s of quali,y in lhese respeCIS, ba lanced allain t
the: avai lable rc s o urcc~ .
Reca ll that suffiCIency meilns that the desig n accommodates th ~ requirements. Any measure of design
quality includes this at a minmlUm . For example , suppose that the requirements arc tor an application that
DESIGN QUALITY AND ME I Hies 509

manage, I 0 renlol , A de"g n o n"'lln8 o nl y of Ihe cia <cs ""a""9" and Ma lla9"C lIl would nOI be
!tuffk u;'nt to ac omm odalc the reqllirlomenl!l Th is IS because there is significa nt data and fun lI o naltty
IXCl h all ' a" o lal cd wllh Ihe o n epl of a DVD Ihal IS m!>Slng Frgurcs 20.2 , 20 3, and 2004 summanze
ho'" deSIg n quailly an be a «sscd al a rough level
The u cedIng cel l n of Ih " chapler <lab rale each of Ihe deSIgn aspecls IISICd In Ihc c F,gure,

How •

• understandabl e (H ow coheSive Jnd cleJr arc th e parh and hov.' low I the number o f o nnectl o n
between pans)
0: IIH lcdr p,uts mId many (Dlmecllom mtlot'g limn
10 very Llndcrst,wdablr pa rts t()llh feu 1 mlCrCOlltiCc/l ons
• sufficient (H ow eVid entl y It accommodalC:s th e requlrc." ml'nts)
0: "",rla'rd to the rcq l4lrcrnnTh
10· Ob l1l0U I)' accot1llnoda lrs (PO), rcqlUrctflol l
• robu st
0: (IHY ,"put alforuoly hilS scnous oll srqu(Jl(ts
10: tvtr)' ",put (momaly acconlltl oda ttd smoothly

Figure 20.2 Qualities of a deSign-rough metrics, 1 of 3

How •

• flexi ble
O. a~hclpattd (lddr "o~al rrqrurmwrls rtqulrt rxt(H ~Wt ciJangc 10 tlu drsrgll
10 most tml' ,palta rtqurrtnltllfS rrqUlrt 110 I](wgr to flu drs /gIl
• reusable
O. t10 part of tht dtSlg t1 eml br IIsrd III otlJtr aPP/IC(lII01l5
10 mort Ihml 75% of Ihr classts Cntl br used", ol/'rr appi,ca lrOPls

Figure 20.3 Quahties of a deSign-rough metrics, 2 of 3

How

• dficient. Imp lcmwta lr oll basta OJ! tim Jr '9" .


o WIll probably 1101 c.uel/lr (II rcqurrrd sptrJ or IfSt rrqUlrtd slomgr
10 . wd/ exe "Ie ","h as much sprlll mltl slorngc 10 PIlrC as rttl)ol/ably ,"ouerllla!,le
• reliable: ' ,"plt,","I""o» blll<a Oil Ih .. d,"glI .
O. w,1I prollably f",1 u" ,h a drnrly I,"JlC«PInb/c /rcqllC II
10 u,,11 probllbly fa.! .. ell u"tI,,» 1/)( "lIoll",bl< frrqllCIICY
• SeCu re .
• 0 wdl probal,/y rxccrd 11K rrl'tl X/lfIlHn alloulnnlr 11IIII/crab,l,t)' tWill
• 10 • w/II,lrob"bly heW! IH jtW lJuhlrmbrl"Ir\ tH ( .111 IJr rXI)rc /rJ
Fjgure 20.4 Ouahoes of a design- rough metriCS, 3 of 3

,
510 CHAPTER 20 DESIGN QUALITY AND METRICS

20.1 DEGREE OF UNDERSTANDABILITY, COHESION, AND COUPLING

The main rcason for a design is to (orm an lInd('r~tandIO B among the software engineer) of how the applicatIon
wIll a nlally beeoded I,' reall y a foml of communi a"on , and ,0 ,he qua lilYof a desIgn depends, In pari , on II<
under<tandabiloty to people. For cach pari ' 0 make clear <ense " has 10 be cohesIve And of the parts arc no'
related by ' 00 many relatIonships, we ca n ,ell ,hem aparl more CJsol y. Thl 15 the concep' of low couplong Thu.,
Ihe ex'cntto whICh ,he cohesio n of ,he modules is hIg h IS part of a measure of unders,andabol, ty. and so 15 the
extent '0 wh,ch ,he cou pling be,wccn ,hem I< lo w. (The I.Iler I unlI kely to be zero, however, otherw ise one
Ilugh t as \\.Ie ll co nsi der tht" clpplica tlOn to co nSist of emirci y scpar.ltc ones.)
Fan-III andfnn.olll are measures of the degret" of coupling of modules Fan -In (or a co mpo nent counts (he
number of co mponents that referen ce , to' f<ln -out is t he number t hat I t re (c renet's, These: definitio n ca n be rcA ned
by spec,al,z ,ng ,he na'UTe of the refe rences (e .g , ' call ing a funct io n o f"). Low coupling is refleered by low fan- in
and low fan-oul.
For morc o n ,h is , sec [ I ) and [2].
TI,e fo llOWIng IS an example of a melTic for understandabiloty. It de pend o n definitions of "stro ngly
cohe ivc" and "ve ry few ," but the c can be made precise fo r a givc"'n fa m ily of app lica tions.

Understa ndabil ity metric = III x Percen,age of strongly cohesive modules


+ !II x Percentage of modules co nnec ted to very few oth ers
Section 20. 10. I descri bes melTics for connectedn ess alo ne.

20 .2 DEGREE OF SUFFICIENCY AS A QUALITY GOAL

An c se ntial quality goa l is to produce a design that accommodates the requirements. Designs can co nsist of
man y parts, bu , we' ll co nsi der a si mple exa mple '0 illustrate degrees o f sufficie ncy. Suppose that o ur VIdeo
store appl ica ti o n ha the fo llOWing requ iremen t

Clerks shall be ab le '0 c heck in DVDs


Clerks hall be ab le to check out DVDs

The Jrgrrt oj ,.JfiCl<,,0' measures the ease with which a design accommodates these requirements. DesIgn
I In , F,gure 20.5 , for example, would probably score very low o n this q uali,y scale because it fai ls to capture
'he DVD , the CUSlomer, o r the rental on a rea dIl y Idenlifiable way. (This desig n could be ",ad, to work-it's
Just not a high ·quahty deSign give n th e reqUirements .) Design 2, on th e oth er hand , is su fAcie nt to capture the
requiremen ts (or a reall ti C vi deo store
The following is a useful me lric measuTlng sufficie ncy I, depends o n having a tho rough set of detailed

requirements.

Sufficiency metric = Percentage of de,ailcd requirements clearl y accommodated by the des ig n

IncreaSI ng the number of classes does not necessaril y raise the quali ty of a deSIg n, Redundan, classes
act uall y derract from qua lity . AdditIonal classes may be needed fo r other quality measures such as Aexib,llty
and robustness
DEGREE OF ROBUSTNESS AS A QUAUTY GOAL 511

Design 1 /'
/
.-
/
/
VldeoSlore Design 2
/
/
checkln() //
/
checkOuI(j /
/

./ VSCuslomerBase VSCuslomer
/
/ 1
/
/ 1
/
/
/
/
/ ,----, DVDRenlalSel
VldeoSlore :::::: 1
checklnO DVDR ental
checkOutO

1
1 •
DVDlnvenlory DVD

Figure 20.5 Measuring the sufficiency of a design-video store example

20.3 DEGREE OF ROBUSTNESS AS A QUALITY GOAL

A good SRS contains explicit robustness reqUirements. For exa mple , Ihc vi deo store ma y requ ire that the
application react to the entry of an inva lid vIdeo name by refreshing the rdevant screen " 'Ih a blank In the
oidro 1111, window an d popping ul' a window stali ng "No such video - Please re ·e nter." Explrcit ro blls mess
requir<menls like this are measured with the "sufficie nc y" qua lity metnc. If a slalement like thi s IS nOI an
t:<pliclt requ irement, then it is measured with the des ig n robu lness metric . Fi gure 20.6 shows a pair of
designs for the video store applicalion .

Design 1 Design 2


VSCuslomers VSCuslomer
1

VSCuslomer 1

VideoSlore
customers •
DVD VldeoSlore DVDR eniais DVDRenial
DVDs I
I
renlals
I
I
DVDRenial I
I 1
I
1

I DVDs DVD
I
I
I
I

Raure 20.6 Measuring the robustness of a design- VIdeo slore example


5'2 CHAPTER 20 DESIGN QUALITY AND METRICS

Degree (0 which (he


design rea cIs ideally
10 anomslous mput

10 ..---.--.....- - - - - - .. - ..- .- -..- ..--------..... ---.........- -



I•
I
I

I•
------_.._-----_ ... - ... __ ..

I

5 I
I•
••
••
i• I•
, •
•••

I
AppliC<1(ion will crash hall _ _ _ _ _ _ _'---->

o the time when it
• :>

Application w/IJ crash encounters any wrong or


Application will recover
WIthout a trace if It unanticipated input:
Ideally from any wrong or
encounters any wrong or Will recover ideally half unanticipated input
unantIcipated input the time

Figure 20.7 A rough robustness metric

In Design I . the VideoS ,"" class cOnlains a collecti on of VSC",'omrr objects, a collection of DVD objects.
and a collection of rentals . Each rentJI can be maintained as a paIr consisting of a Customer object and a DVD
object. DeSign 2 wa.s discussed above. To assess the robustness of Design I , we think about how to handle
anomalous irualions such as attempt to en ler data for a none xis tent custo mer. This is more easily
accommodated with a class con taining all customers- si mdarl y for DVDs. The deSign should also
accommodate: erroneous rental cntries-for example, a customer forgetting to take hi s vi deo rental with
him from the store. Thi s IS more easily accommodated with a separa te DVDRrulais class than with a vector
attribute of V,JroStort, because the latter is less visib le and because it occurs among several other, differing
attributes.
A metric for the robustness of a design is shown in Fib'ure 20.7. It uses the ph""es "reacts Ideally" and
"recovers Ideally." These have to be defined in the co ntext of the application .

20.4 DEGREE OF FLEX IBILITY AS A DESIGN QUALITY GOAL

It is com mon to assume that the more fl exi ble a design, the higher Its quality Reca ll. however, that flexibility
may come: with a price in lcmlS of deSign, development, and maintcnance time required. For these reasons, it IS
not always pursued. Agile programming. for example, aims (or deSigns that atlsfy clear requIrements and no
more . Nevertheless, a judicious choice of fleXibility in a design can save time by facilitatrng change Figure 20.8
show the trade·offs of creating flexibility in dcslgns.
To measure the degree of flexibility of a dcsign. one can CO Unt the levels of class inhentance and th.
number of dcsign pattems used . Although these give some indication, they can al 0 encourage poor qualities
in other respects if pursued Simply to make a metnc become favorable . Exton ibility is one face t of flexibIlity
And so another way to measure extensibility, in pan. is to make a I,st of reasonable additions to the
application's requirements and to evaluate the deSign's ability to extend and cover them .
DEGREE OF REUSABIlITY AS A DESIGN QUAlITY GOAl 513

Costs of Flexible Designs


® EXira cost (time) needed
Benefits 01 Flexible DesIgns ® May resuil in clunered and
e Facilitates added requirements less understandable design
e May result in more elegant ® Time wasted if requirements
and understandable designs expand in unexpected direction

Figure 20.8 Cost-benefit trade-off of design flexibility

20.5 DEGREE OF REUSABILITY AS A DESIGN QUALITY GOAL

Reusability has many benefi ts but may detract from an application's quality because it I intended to benefll
future projects rather than justth. current one For example , some energy is di verted from the current project.
However, if the application under design '"'' a reusable component , then thIS usua lly benefits Its quality
because the component is likely to be more reliable than those ye l unused.
Ler's assume that we want a particular compone nt (e.g., a cia 5) to be reusable. Fo r example, how do we
ensure that the DVD class ca n be used in multiple applicarionsl How do we measure the extenr to which a
particu lar class is reu ablel First , the component must have high quahty in the usual se nse-be wellte ted, for
example Interestingly, Items can be reusable because they arc generic (we use "wood" In many projects) but
also beca"s. they arc speCific (we use I 'I. -inch machine screws 10 many projecrs). Th i difference places
classes into roughly lWO reuse categories· those that are usefu l becau e they belong in a framework and arc
reused because they are general : and those that are special to the business al hand, and form part of its too lkit.
ParameterizlOg a method makes it reusable but too many parameters make it clumsy. Figure 20.9 hst
some of the key qualities we want for reu ability, and their limitations. (The last point In thIS ~gure refers to
multiple parameterizations of methods with the same name and si mdar purposed.) Figure 20. 10 indica tes how
these may be measu red
listing 20. 1 is an example of a cia s that would rale high o n rell abdity , as explained below U s 109 the
measure of Figure 20. 10, we would rate the reusablhty of this code as follows ·

• Abstract enough to get wide coverage


• But too abstract = usc Ie.
• For example, class R<lai/Arlifac/ may have too ILuie o ntent
• SpeCific enough to be useful
• But not too SpCCI fi
• For example , Aon,Numbtr6IlrowIIP"'(1/
• Parameterized methods
• But not mOre than \ I X par;)mcter~
• Con .. dcr f(x I) al,o fl...: I, x 2) al so f(x I, x 2, x 3), ,
Filllre 20,9 Attributes of reusability
5'~ CHAPTER 20 DESIGN QUALITY AND METRICS

• Degree or coverage
o = ncghgi ble cove ro se or dllle"' ''1 apphCJ II OnS
2 = as wide as co n be expecled
• Degree or conlenl
o = neglig ible o nlt'nl or subslance
2 = very n ch onlcnt or associa tion...
• Parameterization of method.s-a llows method reuse
o= very restrictive meth ods; very narrow scope
2 = widely applicable methods

Figure 20.10 Measuring reusability

Degree o f coverage: V.dlOP(odu Cf covers any video item thal a vi deo stOre could possess, so "coverage"
would rale 2.
Degree of content: The complete version of this class docs not have extenSive content , but nor does it
havt:-° negli gible content , so we can rate this as I .

Parameterization of methods: The names arc about as complete as one ca n expect so thi s would rate 2.

lis reusabililY index is Ihus 5 OUI or a possible 6.

Usting 20.1: A detailed design example to be rated for reusability

1*
* Example of a class design highly rated for reuse
*
* Intent: Capture all of the properties and functionality of video
products
* that companies can deal with.
*
* Examples of potent ial subclasses: DVD, Video
*1
public abstract class VideoProduct
{
II CONSTANTS --------------------------
--- ---------------------=----------------
----------------
pr ivate final stat ic int MAXIMUM_TITLE_ LENGTH = 100;
private final static int KAXIMUM_NAME_LENGTH = 100;
private final static int MAXIMUM_NUM_STARS = 20;

II METHODS --------------------------
-------------------------- --------------
---------- ------
----
--
j ••• * •••• ** ••••••••••••• * •••••••••••••••••••••••
* Returns: The copy number
* Example: 3; i f title is "Gone With the Wind," then this would be the
DEGREE OF REUSABIUTY AS A OESIGN QUAUTY GOAl 515

* third copy of this v ideo product.


*/
public abstract int getCopyNumber ( );
/ ***********************************************
* Returns: durat ion of this video product in minutes -- if > 0;
* otherwise 0
*/
public abstract int getDurationInMinutes();
j***********************************************
* Returns: Title of this video product in English
*/
public abstract Str ing getEnglishTitle ( ) ;
/ ***********************************************
* Intent: Enter the title of this product in English
*
* Preconditions:
* (1) aTitle !=null
* (2) aTitle has between 1 and MAXIMUM_TITLE_LENGTH characters
*/
public abstract void setEnglishTi tIe (St ring aTH Ie) ;
j***********************************************
* Returns: Name of the director of this video product, if known;
* "unknown" if not
* Example: Returns "Stanley S. Kubr ik IV"
*/
public abstract Str ing getDirector ( ) ;
/**********************************************-
* Intent: Enter the name of the director of this video product
* Example: setDir ector ( "s tanley S. Kubr ik IV" ) ;
* Preconditions:
• (1) aDirectorName != null
* (2) aDirectorName has between 1 and MAXIMUM_NAME_LENGTH
• characters
* (3) aDir ectorName is the name in the form fir st / last, fir st / MI /
• last,
• or first/MI/last/suffix
*/
public abstract void setDirector(String aDirectorName);
/* ••• **************************************** •••
• I n tent : Enter the name of the director of this vid eo product
• Example: setDi rector( " Stanley ", 'S', "Kubrik", " III " ) ;
* Preconditions:
516 CHAPTER 20 OESIGN QUALITY AND MEmlCS

* (1) aDirectorFirstNarne ! = null


* (2) aDirectorFirstName has between 1 and MAXIMUM_ NAMEJ,ENGTH
* char acters
* (3) aDirectorLastName ! = null
* ( 4 ) aDirectorLastNarne has between 1 and MAXIMUM_NAME_LENGTH
* character s
* ( 5 ) aDirectorSuffix ! = null
* (2) aDirector Suff ix has between 1 and MAXIMUM_NAME_LENGTH
* char act er s
*/
public abstract void setDirector (
St ring aDirector F ir stNarne,
char aDir ectorMiddleInit ial ,
Str ing aDirectorLastNarne,
StringaDirectorSuffix) ;

/ **********************************************-
* Returns: Title of this video product
*/
publ ic abstr act Str ing getTi t le ( ) ;

/ ***********************************************
* Intent: Enter the title of this product in characters as close as
* possible to the orginal
*
* Preconditions:
* (1) aTitle != null
* (2) aTitle has between 1 and MAXIMUM_TITLE_LENGTH characters
*/
public abstr act void setTit le (Str ing aTit le) ;

/******************************* •• **************
* Returns: Stars of this video product if known; otherwise
* a single object "unknown"
*/
public abstract Str ing [1 getStars ( ) ;

/*******.***************************************
* Intent: Enter the stars of this video product if known; otherwise
* a single object "unknown"
*
* Preconditions:
* (1) someStaxs !=null
* (2) someStaxs has between 1 and MAXIMUM_NUM_STARS obj ects
*/
public ahstJ:act void setStaJ:s(StJ:ing( 1 someStars);
}
DEGREE OF TIME EFFICIENCY AS A DESIGN QUALITY MEASURE 51 7

20.6 DEGREE OF TIME EFFICIENCY AS A DESIGN QUAUTY MEASURE

~7~ In~ct desIgns, and Quantl(y how fa>! they arc likely to execute whcn bU Ilt . F,rst. one identifies each
who e peed o( execution IS o( interest For example , we codd (ocu o n the speed Wllh which the
op''ra11 0 11
Encounter video game transit lo n< (rol11 arca to arca " ,he n a hyperlinkcd connection i pressed. ( I( thIs take
tOO long, the game loses the player's intN.S!. ) This opera tion IS illustrated in Fig"'c 20. 1 I.
To assess the timc d lency o( thIs actIon , we trace the sequence of method calls that require its
<,xecution and exa llllne ('ach o( the method< (or timing F,gure 20. 12 ,how the seque nce of function calls
begInning with the pre si ng o( a hyperlll1k and end Ing with the mo nitor d,sp lay, ng the de tlnatio n arca.
T o assess probable time delays, a table lIke T able 20 I can be used , It identifie the methods that are
potential sources o( delay .
We then tackle prob lem method one by one For example , we usc double buffering or build a
compo ite image before rendenn g It on th e monitor.
The example in Figure 20. 13 co ntains no paralle li <l11 , 11> timIng IS not complocated to calcula te as long as
one has relIable estimates (or the parts o( the operatio n Recall that sequence d,agram are capable of
descnbing para llel operations, however. In that CJse, a '''"1119 dltlgram would be ncedt:d to deal \\Tuh slich Issues
a dIfferi ng sta rt times a nd the need (or more than o ne thread to usc a resour e that It cOllld altcr To handle
th os we commonl y perform uch handl ing vIa a metho d , and "'< lock all o ther ca ll e r Oll[ of ca lling th e method
while it is ope rating Figure 20. 1 IS a n example In ,,' h ich [hread I executed method 2, whIch locks out all
ocher calle~ lIch as thread 2 The la ltcr wailS unti l me thod 3 ha completed for thread I. The estimated
elapsed time IS measu red on the rime aXI

Figure 20.11 Time effitlency example from Encounter VIdeo game-lime to transition among areas
518 CHAPTER 20 DESIGN QUALITY AND METRICS

user :AreaConneclionHyperlink :EncounlerCasl :Wailing

:RPGMouse :EncounterEnvironment
1. press
EvenlLislener
area
connection
:EncounlerGame
hyperlink
2. mouseClickcdO
3. handJeEvonlO
4. handleEvenlO

X~
5. sotVlSlble( lalse ) on
:Area 6. dlsplayAreeO
7. display()

:PlayerCharacler
8. dJsplayPlayorCharacterO
-j
9. showCnarllctorO
I

Figure 20.12 .o.ssessing time efficiency example using a sequence diagram from Encounter video game

Metrics for time efficiency include the fo llowing,

Averaged elapsed time for opor-llion X.


Maximum elapsed time fo r opcr.J ti on X.

Table 20.1 Identifying methods that are highest pOlenlial source of delay

Relative speed
o = negligible
1 = neither
Step Function 2 = sigmficant
, Press area connection hyperlink a
2 mouseclickedO a
3 handleEventO a
4 handleEventO a
5 setVislble(false) ,
6 displayAreaO 2

7 displayO ,
8 displayPlayerCharacterO 2

9 shOWCharaclerO ,
TOTAL 7112
DEGREE OF SPACE EFFICIENCY AS A DESIGN QUAUTY MEASURE 519

1.. 1_ _ _ _--'1 Execute method 1

[I=====:JI Execute method 2

thread 1 LI_...JI Execute method 3

----------------------------------------
I I Execute method 4

I I Execute method 5

,-w_a_it/ L.I_ _ _ _--.JI Execute method 2

thread 2 IL-_--'I Execute method 6

1 --It------II~>
f-I- -1--1--t-I- -1-1--t-I--1- 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 Maximum rate Minimum rate


of storage creation or Temporary or of Increase, of decrease,
reclamation permanent? uncompressed uncompressed worst case
Rental: saveRenralO T 514 bytes per 6 chents; Title 100
minute for 2 days bytes; director 30
bytes; stars 4 bytes
• 30; length 2.

One title every 3


minutes.

Rental: removeRentalO P o bytes per 90% of rentals


minute for 2 days returned within 2
days

DVDlnventory' saveDvD() • • • ., • • • • •

DVDtnvenrory removeDVD() • • • • • • •
'"
~

9 101 11 1 12 13 ':1 Q
~
;;1
;0

'"0
- 0
m
-
VI

"z
0
c
l>
·:J)I • c
-- - .4~t
.45 1 I, ~
- - I -- - - ·75 i
-- »
z
0
;:
• ~
•• • • • ~
'"n-
VI
-

' 500
«OJ
J<OO
3000 +- 1

1,;oQ

2000
1500
1000
500
o
1 2 3 4 5 6 7 8 9 10 11 12 13

Figure 20.14 secondary storage needs over time video store example
DEGREE OF REUAB ILITY AS A DESIGN QUALITY MEASURE 521

Data are often compressed pnor to storage (at the ex pense of speed) . In that case the uncompressed IOrage
needs are converted inlO comprt'Ssed·form needs. Usuall y, the key Issue in slorage i the amount required over
the long run-in other words, the accumulation of dala . Suppose for simplicity that the 514 maximum bytes are
compres cd to 100 bytes and that the store is open 15 hours a day. The accumulating needs are shown in the
spreadsheet and grarh 10 Figure 20. 14. and they sugge t thc problem that requires resolution .
Storage needs that increase without bound require special consideration. For this reaso n. designs often
IOvolve periodic archiving or purging. In the ca. e of the video store, this could consist of itelating through the
database weekly, charging all customers with videos whose fi nes exceed the DVO's value and archiving those
DVD records.

20.8 DEGREE OF RELIABI LITY AS A DESIGN QUA LITY MEASURE

This section discusses means for e nsuri ng and a sessing reliability at deSign time To assess re"abili ty 10 an
overall deSign , we look for points at which the applicat io n i most likely 10 fail. Recall that the UML deSign
models are us< casr. class , dala flow . and laIr. We look for a h ig h level fo r failure likelihood withIO each of these
models. Figure 20. 15 indicates places for use cases where failure is typicall y most likely.
Now let's consider how failures arc likely to be evident at the cla ss level. Here . we seck parts of the las
model that are most likely 10 harbor failures . Figure 20 16 illustrate< twO likel y ty pes of fadure , choke pOlnls and
deep mbrrilaHcc.

• Data collection
• From users
• From other applications
• From data communication
• Steps causing complexity
• Use case indicates involved ope ratio ns
• Anomalous situations
• For example, attempt 10 rent multiple copies of a mOVie

Figure 20.15 Identifiable places in use cases where failure is typically most likely to occur

Rental
• Cho ke po i nts
A class that relates to VStoreRental
many other classes ~
DVD VStoreCuslomer

Customer
• Deep Inheritance ,~
Three or more levels of RentalCus\omer

substantive inheritance
VStoreCustomer
,~
DVDRent.ICuatom.,

flcure 20.16 Identlflable places In class model where failure Is typically most likely to occur- video store example
522 CHAPTER 20 DESIGN QUALITY AND METRICS

member
banks Get Get
User
I deposit inquiry
bank
name error accounl ll account
& deposit account /l error
dlsptay
Validate
atert/none Check for atert/none- - -
deposit Validate
accounlll
accounl/l
inquiry
launderingy /
& deposit account # "-~__/

Make
account /I • •
& deposit Inquiry Printer
Display
account balance
account query
Do Create
data
deposit deposit account - account
transaction
transaction - _ __..
. database -
account data summary

Figure 20.17 Identifiable places," data flow diagrams where fail ure is typically most likely to occur-ba nking example

Ch oke points arc potentially probicmatica l because developers tend to make mIStakes when the
sirua ti on IS complicated Deep inheritance can harbor errors because inherited propcnlcs arc not readil y
apparent to the develo per. The number uf types employed should be reduced, or aggregation should be used
Instead to Indi ca te what qua l itlC~s arc added between ty pes.
Dataflcw diagrams can expose failure pOints most readil y where multiple StTC3nl of datil converge.Figure:'
20 17 how< a partial data now for an ATM application. The valldal' d,posi/ and oal,da l' Inquiry functions eaeh
relate to the most streams . The ilccount da tabase <l lso relate to a relat ively higher number of data tre('tms. For
these reasons we would Investi ga te these Arst for reliability . Ince use cases co ntrol (unction call equcnccs in
dara now dia gra ms, we would invesligate by checking whether u e eases behave clearly 31 these points. We
would ask whether a different decomposi tion wou ld make thiS clearer-fo r example, whe th e r it IS advisable (0
ge t separale types of Inquiries via separa te operatio ns
Choke points can be reduced by introdUCing additional proces ing nodes and by dccomposlOg nodes
into multiple nodes. For example, we could split \Ia',dalt {nqUl ry IOto several validation o perati ons.
The final desig n model we can inspect for reliability is the ,'a',
mod". Figure 20. 18 <hows the sra te model
(or the Encoumc:-r Video game Tht: Wailmg state involve the mOS t transit ions , so Wl' would check It
«liability first If time allows, we wou ld thcn move o n (0 £.9a91119, and so on .
State d iagram bottlenecks can be avoided by splitting Slatcs into several states o r by IOtroducing
subSt3l(S. For example, if Wo,li,lg state becomes excessively invo lved , It may be possible to di stingUish . cvcr;)1
modes of waiting
DEGREE OF SECURITY AS A DESIGN QUAUTY MEASURE 523

Setting up Player --i Reporting Setting


dismisses qualities
repon
Player window
completes
setup
Player
dismisses Player
set requests Player
qualities status requests to
window ___~ set qualities Foreign
character
enters Brea
Waiting
Player moves t~ Encounter
Player ad/soont Drea "
l,orelgn
compleled
quits character
presenl} .......... Engaging
{foreIgn Foreign ___~::::
character character
absent} enters area

Figure 20.18 Identifiable places in Slate models where failure is typically most likely to occur- Encounter video
game example

20.9 DEGREE OF SECURITY AS A DESIGN QUALITY MEASURE

~QJrity is a special casc amo ng metries because it concern illcgillmate "functionality" of the application that
it i capable of but is not specified. It may requ ire a ski ll ed perpetrator to obta in rh is functionality An example
IS ' shall be capable of sending custome r c red it card info rmation to any specified e -mail !"
How can one measure the degree of secu rity of a design? Recognize first that every applic ation must
commu nicate with hardware or oftwa re externa l to itself, otherwise it could not execute. In so dOi ng ,
however, it acquires some vulnerabi lity . Figure 20. 19 illustrates the kinds of .n ifacts with which an
applica tio n's object code co uld make o ntacr. These, in turn , ca n make con ta ct with o ther an,facts.
In a sessi ng the degree of securit y of a design. we arc thus obliged to take a systems approach-that is,
one that aCCOunts for the vu lne rab ili ty of o ur application In th e co ntext of the large r system within which it

[ Drive c: I

Objecl
code
Operating
system
I Drive Ed: I

FIgure 20.19 Analysis for security quality


524 CHAPTER 20 DESIGN QUAUTY AND METRICS

I no",
oontMltl~
In • u 'gll IOCIUon
Security
encrypl()
gelUsersFromURLO •

User
/
/ Id'
/ passwordl
/

""""""'
to
tot " .....-
and password

Figure 20.20 Beginning design for simple secure login

must operate. The added dimension here is that we must look not only at the potential of our application for
exploitation and damage . but also at its potential to harm artifacts to which it is connected .
Figure 20.20 shows a start for a design of a cmica l security clement of an application . Inspecting it for
each security factor in Figures 20.21 and 20.22 provides a framework for assessing its level of security. We
need to satisfy ourselves that an Impi""",lalioH neisls of the class model that satisfies every security factor-the
class model by itself does not guarantee any of Ihe m.
There are many approaches to measuring the security of a detailed design . We will discuss a few
examples. In the Arst example , we make rough assessments, on a scale of a to 10 , of the main aspects of
securi ty, as introduced in Chapter 18, These arc shown in Figures 20.21 and 20.22. Although it is difficult to
make these assessments based on • detailed design , this process is better than making a single, overall
assessment about the d.egree of security.
For a second appro.ch example, consider the following metric examples, adapted from (3).
Metric I Baseline Defenses Coverage, This is • measuremenl of how well the detatled design enables
o ne to protect the environment of the application against "the most basic infonnation security thrcats"ll,ese
require careful deAnition. but they do include viruses, for example. This metric assumes that security tools will
be used such as firewa ll s and antivirus softw.re. Some vendors claim thai the coverage of devices by these

• Confidentiality
• Degree to which data passed may become visible 10 the unauthOrized
• Estimated percentage of data compromi ses'
• Nonrcpudiation
• Degree to which parti e can prove the existcnce or agreement
• Estimated percentage or unprovable agreements
• Integrity
• Extent or ability to validate that data are not altered In transit
• Estimated percentage or messages alterable: in transit
·i.e., of a specified severity
Figure 20.21 Property· based security metriCS, 1 of 2
ASSesSING QUAUTY IN ARCHITECTURE SELECTION 525

• Authentication
• Extenl of ability 10 validale user's Identity
• E timated percentage of improper authentications
• Authorization
• Degree 10 which pcm'ission to deal wllh pnvi leged dala may be compromised
• Estimated percentage of unauthorized permisSions
• Availabi lity
• Degree 10 which availability could be compromi cd; c.g., by denlal ·of·service attacks
• Estimated number of availability' compromises per year
"i.e , of g iven severity

Figure 20.22 Property·based security metrics, 2 of 2

security lools should be "in the range of 94 percen! to 98 percent." The meaning of these percentages would
require definition 100 , and backup for claims would be needed .
Metric 2 Patch Latency, This is the time between the iden tification of a succe'Ssful securi ty exploll and Ihe
devdopment of a patch that renders it impossible . Patches are usually replacement files . Thus, if the detailed design
decomposes the application into an appropriate number of ,vell·iden!lfied (, Ies, patch latency is likely to improve
Metric 3 Password Strength: This metric measures how hard it is to break (guess at) a password , in some
",ell·defined sense, including finding pOlential weak spo t where systems use defaull passwords. BreakinS
passwords is usually perfonmed with Ihe assistance of separate software.
Melric 4 Legilimate T rafflc Analysis: This is a family of metncs that measures the extent to which
iIIegilimate traffic cou ld be allowed. It includes incoming and outgoing traffic volume, incomi ng and outgoi ng
traffic size, and traffic Aow wilh the app licalion .
A third approach is 10 put the detailed desi gn under a microscope, as it were, and measure Ihe extent to
which it is likely to avoid common known securily gaps. One example is buffer overAow, In which the bound
of an array are exceeded in order 10 access data in regions of memory adjacent to it. The content type of Ihese
regions is effectively guessed al . Another IS SQL injection , which exploits the manner III which database
queries are processed . This exploit e(fectively insert commands such as "send all credIt cards .. • wilhin an
appa rontly innocuous input data Reid . Detailed designs ca n be speCified that help guard against many such
oxploils. Tools are availab le to c heck for these type of overSights in code, but desig ns are less slandardized
and tools checking for secu rity naws are rarer.
In reality, we combine elements of all three approaches. A good reference for some of Ihe Ideas In this
section is Anderson [7].

20.10 ASSESSING QUALITY IN ARCHITECTURE SELECTION

So far, Ihis chapter has ba cd design asse sment on the individual qualities that good de igns mllst po«c«
ow we explore a more holisllC VICW of quality, starti ng with the hi gh·level view.

20.10.1 Metrics for Architecture Quality

Although most applications can be Implemented USIOS one of evera l possible architectures, some cholce< are
much better than others Important decisions like .rchite ture e lectio n arc made by first developing and
comparinij alternatives Proposed archllectures are thorough ly exammed for defe ts, be allse finding a dde t
at an early development ,tage has a huge payoff compa red wllh allOWing one to pC""t through the proc(' ,
and thcn trying to rcpalr It.
As described In F'gurc 20 23 , one si mpl e way to comrarc ar hll ccture<" to weight the attnbllte, reqUired
lind then »slgn a fuzzy qualifier to each candidate The kmd of procedure d("'~nbed In l' lllure 202 Lan then be
526 CHAPTER 20 DESIGN QUAUTY AND METRICS

Architecture alternative

I. State design 2. ad hoc CUI· 3. State·transillon


paltern driven table

Quahty weight ,
Quality I· 10 High = 9; Medium = 5 , Low = 2
Extension 9 Hig h Low Medium

Change 7 High Low Medium

Simplicity 5 Low H ig h Medium

Efficiency , speed 5 Medium H ig h Medium

Efficiency, storage 2 Low Low Medium

TOTAL. (higher = beller) 183 126 140

Figure 20.23 A tuny method for comparing architectures

used to compare alternatives. For the sake of simplicity, we have omitted some of the design qualities discussed
above," this example. One way to weight qualities is to pick the most important one and give it a weight of 10, or
9 (if you want to provide for a qu.hty that may be introduced later). The least significant are assi g ned 1. and the
remain ing ones arc given weights in between.
Important decisio ns such as architecture are often made by groups. A group uses a Dtlphi process when
the members make individual deciSIons first . then submit them to the coordinator or leader. Boehm and
Farquhar (sec. for example, (4)) introduced the "wideband" Delphi process in which the leader plots the
results on a chart without artributlon to the owners and leads a discussion on the faCtors involved.
The (oIJowtng metrics from the IEEE (5) can be used to measure the complexity to software designs.

IEEE metric 13 . Numb" of ",Inrs a"d ",ils per madill, (package ) This can be equated with the number of
public methods accessible from outside the module. The number of exit poi nts can be counted by the
number of public functions that return values to the caller or make changes in the environment external
to themsel ves. The goal is to keep this mea sure as low as possible to favor narrow interfaces.

IEEE metric 15. Gr"ph.lb,ortlic complrxily for a"hil,elu". 11,e simpler ("static") version of this metric is
(Number of modules in the architecture) -
(Number of modules having at least one connection between them ) + I

The goal is to keep this number high, since a low number indicates many connections and thus an
increased potential for errors.

IEEE metric 25. Dala or i"formalto" flow complrxily. Thi measures the information flow of large.scale
structures, the procedure and module How compleXity, and the complexity of the interconnections
between modul ... The read .. is rderred to metric 4.25 of [5 J for the delails
ASSESSING QUAUTY IN ARCHITECTURE SEUECTlON 527

~ ... ----.--- ...

;. __ u . _ u n _ n . __ u ,
: Slmltems :
,I !. _n"
,-- --- ---- --- -"j
: SimEvents :
I SimConfiguration : : : ;.n ___ n u __ .! __ ___
, "': : ISimltem L L . . ; :
: //:..~ _________
__ Cl ----i SimEvent l
r - - - - - - - - , ,, ,/ " "
~ ......

·i· ...·.. ·· ..
I

, laueueForTefle¥ / / / / / / ' .... ·!

: ~...... ...... I
,,
, /
... I
,, /
/
I .------------,
/ Simulation
I : SimDriver :,
SimConfiguration exeoute() •
---~ - --~ -- ------ - --- ...
,, initlalizeO I :,
,,, setUPO I
,, time() I
,, ,, I
,
,, ,-------- _ ... . ,,,
,,
,
,, :, Random :
,, ~- ' - -- ---
,,,
.,, ScheduledEvents
ITellerl<> serviiouration ,, ,,, addEvent()
j,olNumberl ,,
,,, ,, removeEa~ iestO ,,
,, , , ~. , __ • ___ ___ _ __ _ __ ___ _ _ _ ______ _ _ J

- --- ---- --------- -. --.--.~ ~-- - - --------- -- ..


Figure 20,24 An architecture for a simulation

A conn,etion between modules A and B is dependence in either direction As an example , we can app ly
metric 15 to the architecture of a bank simulation shown in Figure 20.24 .
The architecture d ivides the simulation into the following pac kage .

SimConfiguralion-which describes the way in which the stat io ns are laid o ut wilhin the bank

Sim/irms-which describes the e ntiti es that move abo ut with", the bank (primaril y customers )

SimEvrnls-which handles the pre ent and fu ture simulated eve nts that take place in the bank (e .g ., a
customer arriving at a teller window )

Simu/o,ion-t he mechanism that drives the simulatio n (primarily by selectin g the next even t to execu te ,
eX~c\lting it, then orchestrating the consequences, includin g the ge ne rati o n of resultin g events, and
queuing them in the Sch,du/cdEoOl ls o bjec t)

Random-the package that ha ndles th e ge ne rati o n of random numbers accordin g to variou di stributio n
(for example, produci ng th e duratio n of service for the ne xt transacti o n)

This architec ture is desig ned using th e Facade deSig n pallern , and we will suppose th a t th e o nl y
inl<rfaces between pac ka ges arc th ose show n The re are five nodes (packages ), and there are five pairs of
module:< between which there arc function calls (either way ). Thus, th e graph · theoretlc archite ture
complexity is 5 - 5 + I = I. Thi S suggests an un compli ca ted ar hitecturc , which is ge nerall y good.
Metrics like th ose listed above prOVide quantiAcation, but how do we use the re ultlng numbers
TYPically, thiS has to do with h is torica l da ta . For exa mple , we ca n ea,ily tell that th e Ell o"nlaG."" , package
has four public function s a t this point ( ec the ca e s tud y o n the book Web si te ). Perhap we ca n fore as( that
thiS number will gTow to between 10 and 15. These number, arc compared with the carre pondlng average
numbers for past proJects. If th e average number IS 10 and we have bc('n >a tl sRed wllh the mo dllian za tion of
past proJccts, then thi S va lue causes no alarm . H owever, if th e average number for "ast proJect< I . 8 a nd we are
headed toward 15 , th e n a cl o>er look at th e ar h,tccture a nd slic h IS needed.
528 CHAPTER 20 DESIGN QUAUTY AND METRICS

-------------,
i RoiePlaylngGameJ
r-- ---- - - -------- -- ---- - ------------ -~------ -- - -- I
I I
I ~l1a l. I
I RPGame GameState I
I I
I handle Evenl() lIandloEVtJnI() I
I
I
- I
I
I .l I
I ( stalo .handleEvont{). I I
I I
- -------- ----- - ------------------- ----- -- ------ ,
I

~-- -------- ~
EncounterGame : EncounterGome II
-- --------- ----- - - --- --- - - - -- - ~

.,. I
I
I
I
I
Waiting ~ I
I
handleEvenlO handleEventO I
I
I
I
SettingUp Reporting Engaging I
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 or
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
,,,,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 event-
handli 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
AreaConnector
Area 2 • areal
dlsplay(} area2
IransilionO

ForeignCharacter

PlayerCharaclerWindow
set( Quality. float)
PlayerCh.racte r exltO

Figure 20.26 A second alternative architecture for Encounter


ASSESSING QUALlTY IN ARCHITECTURE SEI.ECTlON 529

Kry if"'- Event


tMll 0Ct1i"
d..Ir~1rr Rcqu<St DlsmiU Forc!an
.", ... 1 Old on q .. llty qUJllity character
_m.- exI. CNnac window .nten Foreign dYractCT Ic.ava
,..[onorht
('0110,...:»1,"9 Co '0 Show quality ~~ qua,llty how both
dOflrllltbc Ind.otcd uca window window, and Ch1r.lClcn, and
0& Tr3osltion to tnMltlOn 10
W4rlrnt1 st3te &.Jilgi.., SI41tc'

Compute
results or
engagement,
Engoging (do 00Ih'"8) and transition
Current to Wallmg
State "Iat~

SrHlng T r;lnSllion to Tr.lns,llon to Tran"llIon to


quUttcs \\'''1/'''9 Slate E"g3!11J19 Siale Wall/Kg :l.lale

Figure 20.27 A tIlird alternative architecture ror Encounter: table-<1riven state·transitions

In this architecture the hy perlinks at the exi ts to areas are (C UI represe ntati o ns of) Art. Co"",elor
objects; and each has event . handhn g code . Fo r example, clicklOg o n an exi t to the dungeon sh ould cause
the screen to display the dunge o n arca . The resulting design is CU I·drive n, somewha t ad hoc, an d
language· specific . There is no clear connection , howeve r, between the code for this design an d the
conception of the game as a series of srate transi ti o ns. As a benefit , however, the lass model co ntains fewer
classes.
Alternative 3 for the Encounter case stud)" stare · transitio n t.ble.
A third architectural alternative is to re tain the idea of states, bur ex press the slate transitions by means
01 a table. Table·driven state transi tio ns arc emphasized by Shlaer and Mell o r (6), fo r example r.gur. 20.27 is
an example of such a table. n,is architecture uses the State co ncept, but it does not use the State design
pattern .
Here is a list of pros and cons contrasling the Srate desig n patte rn with the table·driven approach . A
flliler comparison of the three architectures follows .
Pros of uSIn g the State desig n pattern,

• Can easily add o r mo di fy states to accommodate c han lle in ga me desig n

• OariAes what actions ca n be done ," various circumstances

• OasSifles all mouse eve nts that ca n affect En o unter

Cons of using the State desig n pattern '

• Oa<s model is more IOvolved ~nd In.tially more difficult to under<tand

• Duplicate dat. · The st.tc of Encounte r could be dedu ced from v~rlable o ther th an the "ate obJe t
IOWrring the pos, ib.hty of programmer error if these va n ab les and the , tate object be o me IOCon istent
530 CHAPTER 20 DESIGN QUALITY AND METRICS

Fuzz me tho d for compann!;


ar h,rectllrcs Arc hitecture alternative

I. Stall design 2. ad hoc CU I· 3. State · transitIon


pattem driven table

Quality weight,
Quality I . 10 High - 9; Medium ' 5; Low = 2

Extension 9 Hig h Low Med,um

Change 7 High Low Medium

Simplicity 5 Low Hig h Medium

Efficiency, speed 5 Medium Hig h MedIum

Efficiency, storage 2 Low Low Medium

TOTAL (hig her = bener) 183 126 140

Figure 20.28 Fuzzy method for comparing architectures for Encounter

Pros of lIsi ng a table (or describing state:

• The table IS easy to understand and the contents are C,lSy to cha nge .

• n"us architecture can be implemented in a non -abject-ori ented language.

• DocumentatIon o n thi approach is av.i lable using the Shl.er- Mellor metho d .

Co ns of usi ng a table for describin g state,

• It requires a data <lnlcturc that is vi rtuall y g lobal (the tab le).

• Augmenting the table with new Slares and actions may disnlpl existing code and design.

Fi gure 20.28 shows a comparison of the three architectures usi ng the proslco ns tec hn ique described
above. Given th e weightong shown, which favors extensibility and chan ge, the architecture based on the
State design pattern comes out ahead.
R~ga rdlC'ss or the sys tematic means one uses to evaluate alt crnativt"s , engineers also perfonn "sanity
checks," uSing holisti c pcrspcctiv~ and the in tuition and experience o r tearn members . Thi s may concern the
number of classes Invo lved or even subjective factors such as e legance. If the result disagrees ",ith th.t of the
more objective process we have d~cri b(:d. engeneers ma y re -ex amine th e process and the result'S.

20.10.3 Verifying Architectures

Usc ca es are developed to expre ss customer requirements . Th ey ca n't take IOto account the applicatIOn's
architecture SInce it wi ll nOt yet have been dt:tcnnincd. Once th e architecture has been e1 ~cted , howcv~r, it
is <<sential to revisit the usc cases to check that the arc hI tecture supports t hem adequatel y. For example, the
Engag<Foreign Chara ItT use case shown in ChapteT II must execute upon the arch,tecture we h,ve developed.
ASSESSING THE QUALITY OF DETAILED DESIGNS 531

Setting up ..._--1 Reporting


Player
dismIsses Preparing
Player WIndow
completes

Player
dismisses
qua/Illes Player
menu requests
status

Move 10

Foreign
character
Player enters area
Waiting ready 10 _ Engaging
_____~p~r~oc~e:e:d~-=~
character
enters area

Figure 20.29 Defects ,n the state· transition diagram for Encounter

Since we r("tam the domain classes throughout the process, th e cla .. sc~ Orlg mally rel'e rred (0 111 the u.. e CJC<C'
should be present among the lasses in the deSign. T YP icall y, Ihe <equcnce d,agr.lms for Ihe u<e ca,es now
involve additional architectural clas es (e.g., Facade cI",es).
Architectures are inspected against rcqwn.:mcntCi. The me-t n c; nlcntl o lH.-d above provide.: a oncrc[C'
baSIS for the inspection. For example, in<peclion of the architectural fra mework package' for Encounter ould
lead 10 the conclu ion that there arc no requirements yet fo r game anifacts and thai the pre>ence of theArllf.1C1
package IS a defect Consider lhe Encounter statc · tranc;ili o n d,ag riln1 ,hown In Figure 20 29 3') In addltronal
example . A perusal of thi< State diagram could yield the defects nOlcd In thc figure. These defect, can be
removed by clarifying the names and/or de cnp"on, of the eve ntS referenced.

20.11 ASSESSING THE QUALITY OF DETAILED DESIGNS

Recall that detailed de Ign con<osts of a\l de"gn that" nOt at the higheSt , arch,tc lural lew l, but I

code Itself In th. S("C ll o n , we fl""'Vlno/ quantltiltlve mea,ures of cHe lI vcnc..;s In dClalkd dC:~lgn

20.11 .1 Techniques for Assessing the Quality of Detailed Designs

Figures 20.30, 20 3 1, and 2032, how "cpS for en<unn l( Ihe qua l,l y of delaoled dC>lgn<
MetroLs fordclallcd deSign arc proVided III thiS ,cellon that '01"lv tep I In Figure 20 0 _tep< 2, ~ , and
4 arc checks that the detaolcd de 'Bn expand, on all of the ar hlle ture , and noth ing m rc
Slep 5 e nsu r<.-s that a dt',.gn 1'\ compicte h I') c:3 v l'nough to c he k lhJl every 111c...' thod of evcry clao;;~ .,
properly 'rc ,f,cd , bUI how do we know thai we have InLlu(kd a\l of Ihe la"e, and method, that arc
nccC5~ry? To do fhlet , we r ' IUrn to the: req UIrement .. Jnd ell.)urc: that th e dt'tal1cd dC'lgn We have dl'vclol"cd
accommoda tes all of lh r QlIlfl.'Il1Cntf.o If we lI~C: tl1(; rc:qulrc nH;' nt~ org;\lHzilllon ", In tht· CJ ;"C ,Iud tht'n \\.:
kncsw Ih;lI every (uncllonnl r ' qulfCnlCnt Lorrc<.pond, to J ~pl·c..dl C fncthocl nlll''' , th e fun cIIOll:l1 COlllpICtCIlC,\'
tilk II r duccd '" cn,"r/ni/lhat ca( h of thel Ill~thod, Lan be la ll ed at an appr pnate pOint In the c'c IItlon
CUn!.,d r, (or ex.amplc.', the r<.'qul(CnI ~ nt
S32 CHAPTER 20 DESIGN QUAUTY AND METRICS

I Prepare to record metrics durong the design process .


o Include ( I. 1) time taken , ( 1.2) Iype of defect; ( 1.3 ) severity

2. Ensure that cach architecture module is expanded


3 Ensure that each element of the detailed design is part of the architecture.
o If an element docs not belong to any such module , the architecture may ha ve to be revised

4. Ensure that th e de is n fulfills its required functions .


5. Ensure that design is complete (classes and methods ).
6. Ensure that the deSign IS testable .!
!See C hapter 5 for inspection procedures.

Figure 20.30 Inspecting detailed designs, , of 3

7. Check detailed deSign for -


• Simplicity
a design (hilt few can understand (after a legitimate dfort!) is expensive to maintain , and can result in
defects
• generalit y
enables design of si milar applications)
o cxpandability
enable c:nhancements~
o effiCiency
speed , stora ge
o portability

Figure 20.31 Inspecting detailed designs, 2 of 3

8, Ensure that all detail is prOVided


o Classes
• C lass Invaria nts clear] (required limits on attributes; required relationships among attribut~ )
o Method
• Preconditions
• Invariants
• Postconditions
o Pseudocode

Figure 20.32 Inspecting detailed designs, 3 of 3

3.2.EC.3 .2 ConM u,.bifity of Encounter eboraetrr quafity vafu"


Whenever an E"counttr character is alone in an area, the value of any of its qualities may be sct.
The value chosen must be less than or equal to the sum of the quality values.

We have already ensured that a function to perfonn this requirement exists, but to verify that our desill"
supports the execution of this function , we have to dfcctivdy walk through a fully rep~nt'li~ s..! of
- .

ASSESSING THE QUAUTY OF DETAILED DESIGNS 5]]

functio n alhng sequences. each of which exe rCises the funclion . This amounts 10 develo ping a scI of menIal
tOSI aSt'>, and the re ult< should be aved for Ihe tcstlng pha e Here" such a set.

Bcjln game'l cflll liP wmdo w to stt qwaillJC), srI quality, sri qualify "galli , dJsmls wmdoUl

AIOl't 10 area Ull'" no forti9" hamrlcr, call liP u.),"dow to 5(1 4I1al,IIrs, sri qual,ty, d'srtusS wmdolD
Camplttt rngagtfflnrt, wall 1111111 jomgll charaeltr drpnrts . call liP Illllldow to 5(1 quaI, tits, set qualIty, dISmISS
IPtndow

For each of these cenanos. we verify Ihat Ihe classes and method< do Indeed eXist 10 accommodale II
Once we ha ve done Ihls fo r every functional rl'quirement, we will have ve ri fied our deSign from the fu ncll o nal
POint of VICW \Vlc can perform a Similar process with our detailed deSign for every nonfunctional rC'qlllrcmcnt ~
\'(Ie can venfy mentally, and via calculalion (e g., In the ase of liming) Ihatthe deSign suppons each of Ihem
Once again . the work we do to crea te each of these sequence can be used to develop lest Ihat we apply once
the impleme ntatio n has been performed .
Step 6 calls for testabdllY In o lherwords. is It a reasonable process to te I Ihe elements of Ihe design' A
design thaI can'l be readily separated into parts rend to be untestable An effecllve way to ensure Ih,s
properry is to wrlle tests for each deSign eleme nt as "oo n as it IS SPCCdlCd
Step 7 concern the properties that we deSIre from our detadod deSigns We de Ife all of these
prop<rties, but it IS usually nOt possible to have them all In particular. "mploco ly may be In conn,Ct Wllh
9",,,al'l), and rxp.>ldabdily . Design pa tterns often Inlroduce add iliona l cia <e<, too Thu<, II IS be" to speCify In
advance which of the e properties we care most aboul, and then evaluate the deSign agalnS! them If
ponabiHty is paramollnt , we can es tablish scenario ror implementation on each dl.'slrcd platform
Step 8 checks that every detad is given, short of code. The onhodox definition of "de tad" refers to a complele
description of the design ho n of code itself. Agile methods te nd to foc us o nly on key detads up front , t)' pKally
leavmg most detads until code time It is common for de Igners to po<!pone many delads until ImplementaliOn
tlmr because the specificati on of detail,s time consuming . Forcr1 l1 cal ponlons of an application , however, thl~ I

usually a mistake. There are many ISSUl'5 to consi der at implementallo n tim e, and so thinking through the detad . of
critica l seCtions beforehand, and IIlspectlng them separarely, can pay 011 handso mel '

20.11 .2 Metrics for Detailed Design

Detaoled deSign metncs include cou nting the number of mo dule , functions , cntry pOlnl" and e "POint For
oblect,orlented Implementallon<, th i' translate IntO ountlng th e number of package<. the number of cia se<.
the number of metho ds, the numbe r of para me te rs, th e number of atrrlbutes, and <0 on When clas es are
proVided wllh complete class ,"varlanl , th is ,"c reases the han es that the re>ultll'g method i of high
quality When pre ond,t ,ons, Invariant<, and PO<l o nd,tl o ns for a method are all ,tatcd In precl<e term,
chances arc that the resulting mt·thod i of higher qu. lllY Ihan o therwl<e These ca n bc mea,ured a follows

Percentage of cla"c> supplied With pre I<C class In varlan t<

Pcrc.cnta~e of nontrivial m('lhods \upplled WIth pr llie pre o nclitlon\ . IIl VanJll h and p ,tLondltlcm,
534 CHAPTER 20 DESIGN QUALITY AND METRICS

A o mprch cn"ve , .Ihelt more complicated metric IS IEEE met'rlc 19 "deSIgn structure" (sec (5]), whl~h
dc te",,,ne, "the <Imp liCl ly of the det.ded deSIgn" of a program .

20.11.3 Inspection of Detailed Designs

The overa ll pnn iples and practice of inspectIons were expressed in C hapter 5 The Inspection of deeaded
dCc\Ignc; consists or inspec tin g clast;Ocs , thclr metho d pro to types ( name, return type , and parameter ty pe~), th e
nowchans and p eudocode. and the relatIonships amo ng classes and meth ods WIthin various models. Th ...e
modds ca n Include ,he usc case models and their associ ated sequence diagram s, the clas model, the state
models, and the data fl ow model.
As wnh all inspecti ons . data about eac h defect arc no ted, including its seve rity, its ty pe. and the
probable source of the defect in the project life cycle. The IEEE standard 10 44 . 1 classifies seventy as shown In
Figure 20 33 .
Designanng a defec t classification scheme helps to pnorltize repair work: H oweve r, we avoid usi ng
more categon es than necessary because time is con sumed categorizing ddecls. The triage classifica tion,
shown in Figure 2034 , IS fast but provides less information than IEEE 1044 . 1.
Defect Iyprs can include those listed below , which have been taken fro m IEEE standard 1044. 1·1995.
TI,e types that apply 10 detailed designs for Jav.doc· level inspections are marked "XDOC: and for
pseudocode · level inspectio ns arc marked "PS".

• Logic problem (Forgonen cases o r steps; duplicate logic; eXlreme conditions neglected; unn~cessary
(-unc ti on ; misinterpretation; mI ssi ng condition test; checking wrong variable; itcrating loop incorrectly.
etc) PS
• ComputatIo nal problem (eq uation in ufflcient or incorrect; precision loss; sign convention fault) PS

Severity Description

Urgent Failure causes system crash, unrecoverable data loss; or jeopardizes pcrsonnel
High Causes impairmcnt of critical system functIon s, and no workaround solution does exist
Medium auses Impairment of criti ca l sys tem functions. though a workaround solution does exist
Low Causcs Inconvenience or annoyance
None None of the above

Figure 20.33 IEEE 1044.1 Severity classification


SOUra' IfEE lOU 1. 1995

Defect Severity ClaSSIfication using Triage


Severity Description

Major Requirement(s) not satisAed


Medium Neith('r major nor trivial
Trivial A ddect that will not affect operation or maintenance

Figure 20.34 Classifying defects by severity using triage


ASSESSING THE QUAUTY OF DETAILED DESIGNS 535

• Inrerta "ffm"ns problem (lnlcrruplS handled Incorrectl y: 1/0 liming incorrecl : ubrouline/modulc
Im,ma l h) PS
• Dala· handlms problem (miliali zed dala incorrectl y; accessed or lored dala Incorrec tl y, ,caling or Ullits of
d,ta mcorrect; dimension of dala Incorrecl) XDOC, PS

• pc of dala Incorrect XDOC, PS

• Data problem (sensor data In orrect or m"si ng, o perator data Incorrect or miSSing, embedded data In table<
InCOrTCct or missing; external data inco rrect or missing; output data Incorre ct or nllSslngj Input data
Incorrect or missing ) XDOC, PS
• Documentation problem (ambiguous descripti on, etc. ) XDOC, PS
• Document quality problem (app licabl e st andard not mel , etc. ) XDOC, PS
• Enhancemcnt (change In program requ irem en ls, <I .) XDOC, PS
• Fadure caused by a preVIOliS fix XDOC, PS
• Performance problem (associated "'ilh tesl pha eJ
• Interoperabdity problem (not compatib le with other oft",are or components ) XDOC, PS
• Standards conformance problem XDOC, PS
• Other (none of the above ) XDOC, PS

Lds Inspect pseudocode examples . The In pectl on focu ses o n defec ts in com mISSion (wh ether the
methods chosen .re appropriat e) and omi ssion (whether thtr. are other methods that should be
Included ). The pseudocode for a me thod hou ld be c hecked aga inst th e corre pondln g reqlllrcment in
the SRS or in the SOD . For example , the follOWing is an early draft of a D ' reqlllrel1le nlS of Encoun ler
fro m the SRS ,

-(essentia l) Evrry game charaettr has 11]( SlI m( srI of qual,tlrs Each qualIty sb,,11 be a IIo" -l1 rgah(!( floatltl9 po""
numb,( wl fh (II itast o.u arC/mal oj preciS/ot! TI,ts( {1ft all i1ll llfll,zcd ('fually so tba l IJ;r SIIIt! oj II)(Ir IJ"Iur5 IS IOU
For Ih, first rC/(flsc fbc qua/illcs shall bc (otl tclI/rallo", slmnUla, Jt11rll,gCtlrr, I,a fimtc, tmd ( /(('119 11, Tllc pal,u oj t1
quailly ca"" ol be bOI/' 9ft. 'rr IIJall u ro ."d 1m Ihml as ..

Th is reqUiremenl IS Implemenled by the fun cti on IId)II"OII.IIIy (Slnll9 .0ll.I,Iy, flolll "OIll,I'Iy\l"I",) Wllh
the pseudocode to be In<pected as show l1 111 Figure 203
An inspectio n of Ih" pseudocode sho uld ex po, the roll ow lI1 g de k e "

1 Line 9 method scrQ".llIy() should be menll o ned


2 Line 10 lacks delad on how 10 alloca te the rcmalning qllal ,ty va lue" also, wh alway "redu c" (why n t
~me llm(" s "increa"c"),

Recailihal the In<pectlon prOLess sho uld merely c<labli,h Ih at there I< 3 defec i In cach ea , e IlillC
should be spe nt by the In spec ti o n rca m Iryll1J.( to repalT till' defec i dUTIng th e In<pec tl On Illce tlll!! T hl'
I"age seveTity cia<slf'C3t10n of defec i 2 (re lallng to li ne 10 ) " ""'3J Or" beea u C It< "'''' '1" e I311 0 n an lead
to "S I"flCant dlff ren 0< In th e produ I U'lIlg the I~ FE 1 0~4 1 'Iandord , 11< cla",h OllOn "
" Comput atl o n.. 1 "
536 CHAPTER 20 DESIGN QUALITY AND METRICS

1 IF aQuality is not recognized


2 Log error to log Ii Ie
3 Inform user qualities unchanged
4 S8tOU8111y()
5 IF aQualityValue out of bounds should be
mentIoned
6 Log error to log file
7 Inform user qualities unchanged
8 ELSE
9 Set the stated quality to aQualityValue
Reduce the remaining qualities,
'-----,
Make these ... retaining their mutual proportion ,
preconditions ... making the sum of qualities unchanged
as well
F Lacks detail on how to allocate
ENDIF the remaining quality values

Figure 20.35 Inspecting pseudocOde for defects

20.12 SUMMARY

A soft ,,'are design IS assessed in term s of desig n qualities sllc h as ",ffidrnty . robu' h"'.' , flexibilily, rtu,ability,
cffi"tllty . and rtllllbolity. Metrics are defi ned , collected, and assessed fo r each quality . In addition, the IEEE has
defined several metrics for assessing the com pl exi ty of designs. These include nllttlbtr oj (ulries mid exits pcr module ,
graph-lhcortllC (omplexlty for ard'ltccturc. and data or IIIfonnal/oll ]low complexity.
When se lecting an appropriate softwa re archItecture for an application , we explore several alternat ives
and co mpare their relative streng th s and weaknesses . Each is mea sured against severa l qualities to determine
which alternative I the strongest.
The quality of detailed des,gns is pursued by fo llowi ng steps such as ensuring that each arch itectural
module is expa nded, each part of th e detailed design maps back to part of the architecture, the desig n fulfills
ItS reqUirements , the desig n is complete and testable. and all the necessary deta il s arc provi dcd .
Inspecllons arc used to fi nd des,g n defects TI,ey focus o n inspecting classes. their me th o d prototypes
(name . return type, and parameter ty pes). th e flowcharts and pseudocode, and th e relatio nships among classes
and meth o ds within vanous models, such as use case , class, data Oow, and state. D efect types can be classified
U inS th e ca tegories specified In IEEE standard 1044 . t · 1995 . These include the fo llowi ng types of problems:

logic. co mputational , interface/timing, data handling , incorrect scope, data , documentation , perfonnancc,
Interopcrability. and standards conformance:: .

20.13 EXERCISES

I a list the qua"ti.s that desig ns sho uld possess. In your ow n words, descri be the meaning of each
b Choose three of these qua"ties. For each, give enough of two differe nt des,gns for the
follow, ng appl ,catio n to clearly distinguISh one that cores hig her than th e other on terms of
BIBUOGRAPHY 537

the qualit>, The appl, at ,on takes" ,nput the academi record of a h,g h <chool stude nt and
produ es as ou tput three career< to which the <tudent appear< to be well·suited. An
e.wlanation 's prov,ded as well

2 o n"der an apph allon that helps manage a fabric store A sume that the storrs sell fabncs and
as ociatcd Items >u h as buttons and ribbons. Give three 10 (our robus tness IS ucs spccd\c to (hl~
applicallon Explain your c ho,ces.
3 Below is code for a me th od d,o,d,() Make the method more robust ,n at least twO ways.

public double divide( Double aNumerator, Double aDenominat or )


{
return aNumerator . doubleValue( ) I aDenominator . doubleValue();
)

4. Con ider a design for a video SlOre appl' allon


a Suppose that we usc ju tone clas. \/,d,oSIOrt, wh,ch allows the entry and removal of a v,deo
name ass igned to a customer, s tored via a telephone number as key What exactly 1<; In nc~(Iblc
about this design )
b. G,ve an alternallve U ML clas, model that would accommodate the inclUSI o n of addlt ,o nal
operations.
c Wh,ch of the classes that you introduced arc likel y to be reu,able In other app hca tl ons)
d. How can you make more reusable the classes that rderence \I,d,o )
c. Which classes are unlikely to be reusable 111 o ther applications In any case)
5 Your instruc tor will pair up student project team Conduct an ",spec t,on of the othe r team's
softwa re desig n. Evaluate the classes spec ified", the des'gn and core them U<lng the hst of
quahllcs and metriC< de c nbed in thi c hapter. H ow \~ould you rate the ove rall dc"gn l

BIBLIOGRAPHY

I H enry . , and D KJrur.l ~Sohwan: <;tructurc "' Iem Bil\.Cd on InfomliHlon Ao.... , IEEE T"'I1(';ldI O'1\ Or! oflll'l," &t.J1"an~ , Volume E-7
No s pp 5 10-518 SC'ptcmlxr 198 1
1 ShC'p~rd. Milnm , "O C'oIj7(n melne: .. an empIrical 3naly ..... , (EEE SO/IIl',m tnill"lf"ll1!/ 'ournJ I Vol 5 0 1 IJlluarv !lNO pp ~ - I ('I
3 BcnnatO, ScoIL A FNJ C.oo.:l 'n/Of?14Jlb./:m Savnly Mrln('\, July 2005 , hltp J/~' c-.oon llne: convolrtld 220 1621AJ't:w_ :~.xUnformallon_
R

Staul1Y 1<~1pal« I ) I"w:<<<<l o"<mlx, 29. 2()()<)]


.. Eothm Barry Scfhoarr En41HttnHil £'0"0".'(' I>rcntu..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,<)2
7 AndC'n(Hl, Roo. .. , "5wUl I), f.nqIHttnnl/ John Wiley ~ C:;on.. ]0(1 I
Advanced and Emerging
Methods in Software Design
Online Chapter

21.1 DESIGNING IN A DISTRIBUTED ENVIRONMENT

21.2 INTRODUCnON TO ASPECT-ORIENTED PROGRAMMING

21 .3 DESIGNING FOR SECURITY WITH UMLsEc

21.4 MODEL-DRIVEN ARCHITECTURES

21.5 THE FORMAL DESIGN PROCESS IN B

21.6 SUMMARY

21.7 EXERCISES

To access this online chapter please visit www.wiley.com/college/braude.


principles of Implementation

• How do teams choose programming


Planning: - languages for Implement'atlons?

Maintenance • How does one define classes? methods?

TeslJng • • What are standard Implementation


The Software practIces?
Development
Lile Cycte Requirements • How do you handle vanable namIng? Global
vanables? Function parameters?
analysIs
Initialization ? Comments?
Impllmlnlatlon
- • What IS ~defenslve programming"?

Deslgn • How do you handle errors?

• Wh at does It mean to ~en f o r ce Inlenhons?H

• Whal are good codI ng siandards?

• What Implementallon lools and enVlronmenls


are available for programming?

• How do sollware engineers working on large


projecls go aboul programming?

• How should Siuden t toams organlzo lor the


Implemunlatlon phase?

Figure 22.1 The context and learning goals for thi s chapter
540 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

ode IS realed fro m de<lgn, whe the r the de,,!; n " expre<sed In "'fllInR or nOt In the 00 ca,c:, thiS
mean, that man of the cla"e, -a nd !lerhap, the method, as well- may a lready have been Identified and
deflned by the tu"c prog rammlll8 Deglns. The l11all' goa l of the programme r" to translate the deSig n Into
code that IS correc t, bug free, and mOilltalnable. Many lechn IClue. and guideline exist to help the
programmer achu:ve lhe c goa ls, and th cc;e arc covcr(,d in thi S chapler.
ode listi ngs arc provided In ect lon 22 . 15 lhat Illustrale <evera l of the precepts discussed In thiS
chapte r

22.1 AGILE AND NON·AGILE APPROACHES TO IMPLEMENTATION

ThIS book ha< reviewed the idea that agi le and no n·agile approaches differ but also support each o ther. If the
approach used on a proje t I agile, the n impleme ntati on-the subjec t of thi s c hapter- is begun just as soon
as the Rrst user Story has been understood . That is very earl y compared with no n. ag " e approaches. Fo r agile
projects, Implementation IS viewed not o nly as building the applicat io n bUI also as a process of understanding
the requi reme nts The very act o f determining classes and methods is a process or fleshing out a realization
or th e C'J rrcnt user story. There i no oth er requirements analYSIS o r deSign or documentation process unless
th e team fetls the need fo r these III the course of implementing each user story As the implementation
progresses, the proce of refac to ring (see C hapter 24 ) is viewed as enabling devel opers to alter the deSign
and implementat ion to suit evolVing requirement .
O n the o ther hand , if the approac h is non·agile, then req uiremen ts and a design (though no t necessarily
of the enllre application) arc in place when implcmcnt(Jtion beg inS.

22.2 CHOOSING A PROGRAMMING LANGUAGE

The programm ing language selected fo r implementing a de ign is usuall y dICtated by the company, the
customer, or th e environment 10 which th e applica tio n must run . For example, if the application is Web -
based, some JavaScnpt ma y be reqUired. If the compa ny is a Microsoft ·o nl y shop, then CN may be the o nl y
choice. Given a programming lilnguilgc, it IS th en necessary to selec t an interactive develo pment environment
such as Eclipse fo r Java o r Visual Studio fo r Cff. When the freedom eXISts to select a program ming language,
an Ident ifica tion and weigh ti ng of selec ti o n criteria can be used to aSS ist th e deciSIo n. Features of languages
needed for th e appl iCCl tl on constitute o ne set of cri {cria. Another criten o n is th e avai labili ty of uscfullibrancs.
Th e degree of softwarc engineers' expertise in a language is yet an o th er ractor, and its weight is usually hi gh
As of 2009, most languages used are o bject·oriented . Many of the principles dis ussed in this c hapter
apply, whether the language is object·orie nted or not, o ther< make sense on ly fo r 00 app lica tio ns.

22 .3 IDENTIFYING CLASSES

Let us f,r<t look at the ori glll of classes, whICh is the basIS for an Implementat ion, Each class has o ne of three
Ori gi ns. Dotnaltl ria ssrs refer back to the corres po nding partot; or th e requ irem ents for their intent, drsig" ("faSStS
rcler to the Software Design Document (SDD) Inev itably, addilio nal classes wi ll be needed that were
not enVisaged 10 the desig n. \Yl e can call these impJrmnllation c1as sr The ongi ns of a class arc summarized in
Figure 22 .2.
A class should have a name that makes sense to Irs (ludlcnce. For example, V.droSlorr G15tom" IS uch a
name, whereas SIObsNobKl probably i<n't. Class invarian ts shou ld be stated and observed by all of tho
meth ods of the class These arc concre te statements (e.g, IimllS o n valoc ) about the class attributes and their
relationships. The constructors and nonst3ti c meth ods of th e cla ss arc designed \'0 as ume but al so to enforc("
th e cla ss invanants, th ereby mak.ing their purpose within th e dOl s more expliCit ilnd, In consequence, making
DEFINING METHODS 541

• Domain class
• rrc ponds to a fCQlllf('ments paragraph
• Example, DIID
• Design class
• peClhcd in DD
• lot a domain cia,,,
• E."mplc· ROllal/le,.
• Implementation class
• Too millor to ~ pecdy In design

Figure 22.2 Where the classes In an 00 Implementation come from

Ihe la more reloable . The ROII"I class In LISting 22 .2 ( eClion 22 . 15 I), for example, specifies the fol lo"10£
Invana nt and a method, heck/"ullnaH I() used for unit test ing

/ * Class invar iant :


EITHER
the rental is inactive , id == IO_WHEN_RENTAL_NOT_IN_EFFECT,
rentalCustomer == null , and rentalItem == null
OR
10- l'iHEN - RENTAL - NOT-IN- EFFECT < id < =
HIGHEST_ALLOWABLE_RENTAL_IO ,
rentalCustomer 1= null, and rentalItem 1= null
*/

The mo I Importa nt goa l of a block of code IS for it lO sa tisfy Its purpose. We refer to ,uch code a,
"correct " Th is means, first , that the programmer knows w hat that purpose IS se a nd , th(· programmer wntl'S
do",n that purpose precisely wit hin th e com ment s, thord, the ode Im plements the purpose, and fourth , the
programmer explain , formally or IOformall y, why the code fulfi ll s the purpo,e The IIIIOIl/pr(co"JoIIOII'
postconJ",om/rrtundm/ltlc (0 ,","01' (ormat cover<.:d III lhe next ~c lion I S de Igncd to ht·l p realize the goal of
correctness .

22.4 DEFINING METHODS

When alliS said and done , the work of an application IS performed b It S method< (also know n procedure or
funclIons ) ror that rcason we ,ake spe ,al care to ,tatc the purpo,e of eac h w,lh,n the c de comment< The,"
can be effec ti vely organized under t3 tC'J.:0rJC, c;uc.h JS mrwI , prrcoml,',oll , pO~llo"Jlllo'l . rdunl , UHleIr"",t, rxcrp'loPi
and blow" ISSUes The HtUut .:lnd Jmoum I NlC~ arc Informal , but th e rcS t <Ire pn.'t. I'C: The , peclfy comp letely
couthlO8 sta tcm 'ms In lcml~ of nllmed va nablc,
The IOU:nt il) documentation thai pJo..:ralllllu: ro; u",ullll y prOVIde an In formJ\ ' I JIC nl l' l\l uf what the
method 's Intend d to do ~()r cxampk. the method l,r,NrxIRrollflIN"",llfl () In the la" R"II,,1 of L" t,ng n 2 ha,
the follOWing

Intent : Gf' h n xt av ilable number for ass igning a 1 ental


542 CHAPIER 22 PRINCIPLES OF IMPLEMENTATION

l1"s help, 3 lot In expla"",,!: the meaning of the melhod. NOle thai II " not a precisc or thorough
deAnttlon If the method corresponds ro a documented detailed reqUirement or if it i, ,pcc,f,ed in the de,ign,
the '"'nl' · tatcm~nl may simply rdcrcn e th,'i.
11,e preconditions deAne the assumption lhat the method makes about the value of variables external
10 the method , including the parameters. nIl excludes loca l variables. The method srlldO In Listing 22.2./or
example, has the followln8 preconditions,

anld > RENTAL_IO_WHEN_NOT_IN_EFFECT &&


anld < = HIGHEST_ALLO·WABLE_RENTAL_IO

In ot her words, rhe method's code assumes that mIld is within the legal bounds. Notice that the
specification of preconditions IS precise-usually Slated in term s of concrete, named va riables. For all but the
"lnlent" SeCtl OM , vague statements lead to ambiguity and should be avoided .
The po tconditions specdy the method's effects. Every method has a return or a postcondition . This is
because methods exist to have dfects. There is no reason for rheir existence otherwise . The effect does not
have to be permanent. For example , a method that displays the acknowledgement "DVD Rental Completed"
has the following postcondition,

"OVO Rental Completed " is present on the monitor,

More commonly, postconditions refer to variClblcs whose values could change . The co nstructor

public Rental
( intan ld ,RentalCust omeraRentalCust omer, RentalltemaRent alltem)
throw> Except ion

has the following postconditions,

(1) as for post conditions of setld( anld)


(2) RentalCustomer == aRentalCustomer
( 3) RentalItem== aRentalItem

When a method depends on another method from which preconditions or posteonditlons are to be
repeated, it I preferable not to literally repeat the precondition , but merel y to reference the methods on
which ir depends This practice is applied in precondirion ( I ) The beneRt of such a rderence is that if the
preconditions in the ca lled method change, it IS not necessary lO then update the preconditions in (very
method using them . The postconditions in thi s example arc pretty much what o ne would expect for a
constructor.
As another example, if we define a method

int weirdSum( int addendl, int addend2 )

so rhat .dd,"d2 is asSIgned the sum of .ddtlfJ, and nddmd2 , then .dJrnd2 is mentioned in the postconditions as
follows ,

Postcondition: addend2' = addendl + addend2


DEFINING METHODS 543

• /t:I",1 An in(o rm,1 st,t emont o( wha t the me th od is inte nded to d o


• Don'l spe ify the det."s here the other categones provide them
• prcton.l,"OJlS Condi ti ons On nonloca l variabh:s that the meth od assum es
• Include parameters
• Verifi allon of the e condilions not pron" ed 10 method II e1(
• Po f o"d,ltotls Value of no n· 10ca1 variab les ah~ r execu tion
• Includes parametci
• No tatIon: x' denotes the value 01 variable x after execution

Figure 22.3 Programming conventionS-documenung methods. 1 of 2

The notallon x' refers to the v.lue o( a vanable " at the conclu ,on of a method
The Invariant SPCCdlCS a r('latl onship among the variab le... thal the method doC's not alter ThiS program ·
mer may want to draw altcntlO.n to an invanant . For example, he may want to Sln: S that the class Invariant IS
honored by the method. pecifYlng an Invariant IS equivalent to qallng It among the preconditions and the
pOSlCond,tions.
The return pCCliles the exact nature of what the mcthod IS Int('ndcd to rt-turn Once Jgaln , thiS IS

sp~Clfied in prcCIe terms


Figures 22.3 and 22 4 summanze these poinls
Figure 22 5 shows an example Instead of po tcondllion I, we could have speclfted that the anginal
dements o( garnrBoard are Inv.n.nt because move already rnade should nOl be hanged
A me thod is purdy j,mcl{ou.a1 if it has a rl'tum , no postcondiuons, and us prccondilion refer only to
parameters. In thi asc , Rrl,,", de cribes the cnllre "'ason (or the meth od's eXIStence We make methods
purely functional unless we want (hem to partlctpalt' In an objcct -o rlented design ( \\,hlch I often , however).
When there arc objects of a class at runlm,e-whlch we WJnt in mOSl cases-we need methods that
manipulate the attributes o( the objects and arc thus 1101 purely functional Take, (o r example the method "rta()
EO the class Rtcta"glr. \VIc could denne arta() purely (unctionally b p3Sslng the length and wldlh, as ,n

class Rectangle { . . .
public double area ( double aLength , double awidth ) . . . '

• l"uana"1 , Relatio nsh ip a mo ng no nlocal va ria bles th. 1 th e me lhod's executio n leaves un cha nged
(The val ue, 01 th o Individual va nable< may c hange, however )
• Equivalent to Inclusion In both pr{' · and po~t o ndlllOn<i
• There may also be In vanants among loca l v,nable<
• Rrlurn :
• What the method returns
• Kno lDn ISSIltS .
• Honest ,Iatement of what h. 10 be d one, delecI, that have not been repaired, etc
• ExcqHIOHS
• n,ese arc of l en thrown \vhen the prcc.ondillon..; arc: not Illet becJlI\c dw;; In{he'He," an abn rTllalu) In
exeCUtion

Figure 22.4 ProgrammIOg conventlons-documentlng mel hods, 2 of 2


544 CHAPTER 22 PRINCIPLES OF IMPLEMENTAnON

/ n Intent : Record anOorX at aRo w/aCol if aRaw/aCal blank ; Retu r n ' N' if
• not permitted ; return anOorX i f full row/column/diagonal

1> Preconditlo n s : a nOorX = ' Q ' ORa nOorX= ' X '; 1< = aRowO(:;;3 ; 1<;aCol<=3

* Postco nditio ns (note use of x and x ' )
" Post.O . All preconditio ns are met OR Ey. ceptio n thrown
• Post 1 . gameBoard ' co n tains all n o n - b la nk eleme n ts of gameBoard
• Post2. gameBaardlaRow- l] laCo l - l ] = " OR retu r n = ' N'
• Past3 . gameBoardlaRaw- l llaCo l - l] ! = " OR
• gameBaard ' laRow- l] laCal - l] = anOo rX
* Post4 . There is n o full li n e o f anOo rX i n gameBoard ' OR r etu r n:;; a nOor X
· /
public static char ma ke Mave( c har a nOa rX , ; n t aRo w, i n t aCal) t h r o ws Exce p t i o n {

Figure 22.5 Example of method documentation-tic·tac·toe

This has th e pro perty o f being independent of th e class It belo ngs to . and we would ty picall y make"
, Iallc. We wo uld invo ke this vers Io n of nr<nO as in

. . . Rectang l e . area ( 1 , w ) • • • •

Al terna ti vely, we could de fi ne nrenO with preconditions on the instance va riables 1"'91h and widlh of
R,elnH91" a in

c lass Rectangle { . . .
public double area () . . . . }

This leverages the object· oriented nature of R, InH91,. We would invoke th is version of .renO as on

. . . rectangle.area () • • •

22.5 IMPLEMENTATION PRACTICES

Figures 22 .6, 22 7, and 22 .8 summanze good habits for imple me ntin g cod e. The y arc described in more dotail
in the following scctians, and many of them arc put Into practi ce in, listong 22.2, found in Section 22 . 15. 1i
and also applocd to the R'Hlnl class of our video store example.

22.5,1 Use Expressive Naming

When assigning names to vilriables , parameters. functions. classes, ilnd so on, the most important criteria a~
that the names are expressive and that they convey meaning. They should not include vague, ambiguous
terms. This helps the reader to understand their purpose (recall that Our job includes produci ng ma intainable
work). Consider the following piece of code,
IMPLEMENTATION PRACTICES ~5

• U se expressive naming: th e names of the (unction , th e parameters, and the va nables shou ld indicate
the" PUll>0 e
• m(llllpuinlr(jloal aFlMt, .,... r mrl"r) - poor
• g"&",ROIsrdToExpo,,mt(floll' ,113,,,,, ,", ""Expo"ml) ~ belter
• Avoid g lobal va riab les : consider pa 'ln8 paramelers Inslcad
• rx'rac,(,., a"E" lry ) { labl, = } _ replace]
• ""'r<lc'(IHla"E,,,T)', Employ«Tabl, a"Employt<Tabl,) - belter
Bul Hot wl)(l1 the tlumha of para mrl(r) rxcrrds ± 7

Figure 22.6 Good implementation practices, 1 of 3-naming variables; global variables

• Do n't use parameters as method variables


myMelhod(lnl ,) ( . . . . 10r(i =0, .. - no l
• limit number of parame ters to 6 or 7
• Give names [0 numbe rs
for(i = 0, I < 8927; I I i) - poor: why 89277
Inslead:
inl UM_CELLS = 8927 /1 . ,
for(celiCo unler = 0, celiCollnlcr < NUM _CELLS: I t celiC ounter)
• Introduce variables near th eir first usage

Figure 22.7 Good implementation practices, 2 of 3-parameters; no unnamed numbers

• Initialize all variables


• fe -initialize where necessary to "re set"
• Check loop co unt e rs, especially for ran ge correctness
• Avoid nes tin g loops mo re than 3 levels
• Introduce aUXiliary methods to aVOid
• Ensure loo p termin a ti on
• a proof I ideal- In any case , document reasoning

Figure 22.S Good implementation practices, 3 of 3-initlalizing vanables; handling loops

/ / Example of poor use of naming


int Dolt ( int a , int b)
{
int c ;
c=a*b ;
return c;
}

Whal does llll< fun c llon do] Il mulliplies Ihe IWO pJr.lmtICI'. Jnd re lums the ""u ll , bUI whJI eXJ t1y"
Il, purpo\ 'l it " hard lO le ll hy Ihe name' of th e funcllon or Ihe vanob le ' - lhcy do nOl o n ey "ny mean",!;
Now cono,lder lhl\ li lmpl e fun lion rewritten u~ lng C'<fUC';;lve nJll1c'i
~6 CHAPTER 22 PRIN CIPLES OF IMPLEMENTATION

i nt Co mput e Re ctan gl e Ar e a ( i nt l e n gth , i nt Wi dth )


{
i nt ar ea ;
area = l e n gth * width ;
r e turn a r e a ;
}

Even with ou t co mment s, th e purpose of tht" (unctio n IS now cl ea r: it co mputes th e area of a recta ngle,
lI <i ng the le ngth and wi dth that arc p. scd as parameters.

22.5.2 Global Variables

G loba l van.bles are dat a accesSIble fTom an ywhere in a prog ram . Using g lo bal va ria bles compromises the
pri nCip le o f mJOfrn a liOll h.dll19, w hich we discussed in Chapler 15. InstcJd. w e want to minim ize thei r usc to
reduce the dependence o n o th er part s o f the im pl("m Cn lari o n and to hide implementati o n detail s.

22.5.3 Function Parameters

D on't usc parame ters as wo rking variables th is is not th eir purpose. Parameters sho uld o nly be used to pass
info rmatio n into and out o f a functio n. If a wo rking variable IS nceded . It should be decla red within the
funct ion O th erw ise, unintended errors can be introduced . For example, If an input param eter is used as a
working varia ble. Its original value ma y be mod ified. T hcn if the parameter IS used late r in the fu nc tion with
th e assumption that it contains it s o ri ginal value . an error will occur.
limit the numbe r o f para mete rs to 6 or 7-lt is hard to keep trac k o f parame te r and use them properl y
if the re arc morc than 60r 7 Also. the more parameters are used , ,he more li ghtl y coupled the call ing func tio n
is with the called fu nc tion If so much data need to be passed, reexamine the design and sec wheth er the
coupled fu nctions should be combi ned. or if they belo ng in the same class, With the parameters becoming
pri va te class members.

22.5.4 EXplicit Numbers

It IS no t good practice to use explici t numbers in code. ConSider the follow ing:

f or( i = 0 ; i < 8927 ; ++ i )

It I nOt clea r what 8927 means. Why loo p 8927 limes? Usi ng a number like this hides the truc meaning
o f the loo p. Now consider ,he fo llowi ng,

cons t int NU M_CE LLS = 892 7 ; / / • • • •


for( c e ll Co un te r = 0; ce llCount e r < NUM_CELLS; ++ cellCo un ter )

Th is is much clearer the program containS cells. thcr. are 8927 of them. and we are looping through
all of them.
IMPLEMENTATION PRACTICES 547

n,e other problem wIth U<IO [o( explICIt numbe,.." .r


e<pecially u,ed throughoul the ode, IS that they are
ven dIfficult to find and hange correctl y at a later tlml' o n Ider the exa mple above, ",here 8297 IS used
ex ph ttl In the J", r loo p uppoc;e '297 1 ~ a lso lI,ed In m any o th e r pia cs, and we want to 1nerea e th e numht"r
of «11< to 9 Wle w uld then need to loca te all Occu rrente< of 8927 and change Ihcm 109999 Wlh.tlf Ihe
number 8 27 IS al'!oo used (or Ollle: o the r Pllrpo~{·- for eXOlmplc , the numbe r of names In .l h~ t'? YOLI \vould
have to examine th e o de to dl' lerminc Whl' lhc r 01 parttcular OCLurrencc or 927 mean the number 01 cell ... o r
Ihe nu mber of name' A beller ap proach" 10 u'e a named LOn, lant <uch a< UI'I_CE L "' In Ihe exa mpl e
above ll,cn , In order to hanglo tht number o( u :1I to 9999, 0)11 thal to, reqUIred IS ro ed,t the o ne ')(alcmcnl
k

",here N U '1_ ELL "defined , and all re kre n c, 10 NUI\I_ ELLS ", oil u<e Ihe new value

22.5.5 Initialization and Declaration

22.5.5.1 Variable Declaration

Ir IS good practice to dcclJr(' va nable .. a.. clo C (0 thl'lr hr<.lll'c a') po",blt: If you arc rcadlng a pu:c(' 01 c.ode
you ~rlll then be m o re likel y to hnd J l'ld undc.::'-"'la lld th\.' v.:lnablc, I t rd('r('nct:~

22.5.5.2 Variable Initialization

The reaso n we In lli aliz\.' vJnabh:~ I ~ to take cOlltro l of th t.:m . avold lll g ddallit or garbage va lue . . that tht.: "y.,lcm
as Igns. n ll c; aVOids POLt.:llt lai error.; where J v;:t nablc '''' used and con tainS an uncxpt.: lcd valu\.' It I') good
practice to in itiali Ze (J variab le when Il I') declared, a . . In thL' (ollowlng example

float balan ce = 0 ; / / Ini t ia lize ba lance to 0

22.5.6 LOOps

Loops. ca n be c01l1phcatcd and arc common "'OUfce... of . . e n ou... (adurc..·... TI1C arc.:: thu., 'peclal targch 01
vc n ficJ tl o n McConnell [ I J ... uggCq S the fo ll OW ing question, to I t: an ... wt;..' red a, gllldc(,nc ... to tn.,unng loop
CO lTectne~.;

• I, a whol, loop oelng u<ed Inslead of a for loo p'

• 1< Ihc loop enlered from Ih e lOp?


• Does Ihe loo p oody havl' , o mcl h,ng ,n II ' I, II n" "e mpl Y)

• I. . the loop ... ho rt cnough 10 ( eV I(..: \'/ all al on ('7

• H ave lo ng loop (.onlt.'nt" hee n moved into thl',r ow n fun lion '"

• I, Ih~ loop Iomlted to al 010<1 Ihree I cvc1<~


• If Ih loop IS a Jor loop , doe, Ihe hod y 01 Ihe loop aVO Id mod,fy,ng Iht loop Inde vanablc'

• Doc\ Ihe If)()p alway, lermlnale'


• (( b,tak or (oH lmur arc u,cd arc th..:-v u\l,d (..orrcu ly

They arc dc.,trrhed In more (il-ta dll1 dl(' fO ll ()WII1~ "l' l l tnn., Jnd Ill anv or them J l l' r llt InW rr~(;tI (' an
I",t",~ 22 2. fuund "' '><(l IO" n 15 I and ar plo ed hI Ihe Rnll,,1 la" (,lour vlden 'tOfl' e,.mplc
548 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

22.6 DEFENSIVE PROGRAMMING

n dIe IIw p,"c ti cc lo r nliniml z lIlg bugs is to a ntICIpate po te ntIa l e rror> and Impleme nt code to handle th em
ll'l ~ t(. hn iquc IS Glilcd dcjt11Sil)c progrmtf'"ltIg nc orthe most common erro r sour cs 1\ Illegal data, either (rom
a bad vallie in a (-un tl o n's II1put param eters, or from an external source su h JS f! file, database, or data
communIcatio n lone . In each case the bad data must be detected and a stra legy e mpl oyed to handle il. There
are a numbe r 01 crlec live defen Si ve <[ra<cgies such as ig no rin g the e rro r. slIb<titul ing a default va lue, o r II the
error IS (rom an c.:xternal source, wailin g, (or valid data . These arc di scus'O\cd in ma rc detail in th e nex t secti on.
ExC/P lloli halldl"'9 IS J mechanism lhat paSSl'S contro l to erro r handling code that kn o ws ho w to respond
to lhe erro r. Many I.nguages such as Java and C++ have bu dt · in e xceptio n· handling laclloll es. Exception
handling IS covered In Se lio n 22 .6.2.
O th er meth ods 0 1 dden Ive programrr.in g include bufler o verflo w preve nt io n and "e nlo rclng inten·
lio ns · Eac h is dIscussed al the end 0 1 this sectio n.

22.6.1 Error Handling

Deve lo pers are constantl y faced with the issue 01 what to do with po tentIally illegal data . An example 0 1
illegal data is an account number that docs not correspond to an ac tual bank account. Altho ugh we try to
make ImplementatIons as simple as pOSSIble, the real world is not simple. A large fractIon of programming
goes toward the handlmg of errors A dISCIplined approac h is essential , pick an approach , state it, and be sure
everyo ne o n the team understand and abides by il.
Gi ven that the possibiliry of errors must be dealt with , how does one program a method to handle illegal
input-tor example, a merhod that gives the balance on an account number when the method's preconditions
clearly require that the account parameter be legal l lf all of the aspects of the development process have been
properly practiced, the method's parameters wi ll always be legal whenever the method is ca lled. But should we
program a check of the parameter value in case our design or Implementation is flawed, The answer depends on
the requ irements . For example, suppose there is a system requirement thOlt the continued eXc.."Cution or the
application is paramount. even if the execution is degraded or flawed . In this case, the programmer must deal
with all inputs , even those that ",ake no sense. Techniques for hand long illegal data are described below [ I].
Wait for a legal data value. If the illega l data are from an external source such as allser interface, database,
or commUnication device, onc possibili[)' is to interact with the data Source until the input is changed to a legal
onc before the processing continues. This is possible for much of uscr interface programming, where we can
often ensure that only legal inputs are permitted. If the only allowable strings that can be entered in a text Reid
arc "car:"'rruck ," or "bus," it is easy to prevent the user from continuing until a legal entry is made . A list box is a
common way to do thiS. Even here, however, subtle errors may creep in. For example, the user may cntt.'T date or
birth as I/ I/ SO and age (on 20(0) of 30. It is possible to check consistencies, but the onus i on the designer to
handle all possible consistency and boundary checks (sometimes called 'business rules").
Another example might be when data are transmitted over a faulty communica tion line. The receiving
method may be deSIgned to expect certai n data, but the application is ofte n explicitly required to continue
execution, even when the data arc not legal. Here, the data mllst be checked and errors processed in
accordance with the requirements (e.g., "If the signal is not between 3.6 and 10.9, discard the signal and listen
for the next signal . . . ") .
Sct a default value. Sometimes a default value can replace a bad data value . As an example, consider an
application that monitors heart functions and controls an oxygen supply to a patient. Let's uppose thaI we are
coding a method process (int measurementType, • . . ) where mra,umromlTy/>t must be
poSllive. LeI us assume that Ihis application cannot afford to crash even when an internal mel hod has
been given an illegal integer due to a development defecl. To deal with this, the code would check Ihe inpul
DEFENSIVE PROGRAMMING ~9

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 IS aborted and resc l This IS
most often the COl C 10 applicatIOn s w here sarC:1Y IS a o nccrn and a bad va lue can cau cham, TI,ls ca n al 0

occur In embedded SYSl crn" that manage th"lr Own memory and detect memory corruption If 10gg1Og !

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 III respon>e 10 dlegal data IS dictated by the re-
quirements : abort if afct y.crill cal. use th e plcvi o u rc"u lt.f It !!!o not expected to cha nge. and ~o on ow let us
conSIder methods whose exceptIo nal behaVior IS 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 POS] tive
· , ,
II nO'N do the work
· , . }
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 YOll are throwing;
otherw ISe, fin d an alternative design si nce unhand led excepti o ns crash applicatio ns
• "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 It down in cases
when the con eQuences have been thou ght through.

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 551

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 1 tent policy (or thro,,'ing exceptio ns 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 lIch
enforct.'mcnt of intentions makes road s safer, It IS comm only apphl'd In many l'nglnec:nng dlsopllnes The
followlog Includes cxa mple of Ihe "Enforce Inten ltons" pnnclple In software englneenng

• Us<: qualtflers such asji"al, co,,<1 In C+ +, and abstra<l 10 enforce the orre pondtng tnlentto ns ji".1 c1asse
can't be tnhen ted from ,jintll met hods can'l be ovcmddcn In tnh tnted cia <('5; Ihe va lue ofji.1II1 vanables can'l
be changed If Ihls cause< comptl e ·time error , II means Iha t YOll do nOI fu ll y undersland you r own program
yet, and no harm ha< been done \VIhal we espt lally $l'ek 10 aVO Id arc n.lIlltm e erro"
• Make COnstanls, varianles, an d cla.sc< as loca l a< pOSSIble For cxample, delim: loop counlers withIn the
loop don't glVt' them Wider scope If th iS I) nOt you r Intention

• Usc Ihe Single Ion deSIgn pattem .r Ih re IS to be only one In'tan e of a clas. (see hapter 17).
• Generally spcakl ng, make member. In accc" lble If lhey are nOI !,eclAca ll y Intended to be acces' ed
directly

• Make a1l nbules protecled Ac.cess Ihent Ih roug h more pub lt c acc«sor fu n lI on reqUired (In IJ a .r
makIng attnbules prolcuecl Hlvn On)e IS of ,"bda<,es JcceSS 10 member< r Ihelr ba e IJ"'" whIch I'
oflen undeSIrable )
• M.ke nWlh"ds p,,,,.,, .r Ihey arc for u", on ly by melhods of Ihe >ante IJ"
552 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

o n'\Idcr IIlt ro du 111 & c1J \ 40c \ to encapsulate legJ I parame ter va lu es that prevent bad da la For
exa mpl e. If th e intent io n ror a meth od Clw iUtl lc() is to accept only I' ear," "tru ck," or "bu s" 3 C, parameters, then
It nu ghl be won lWl hilc n Ot to u C be Ju se It Intro du ce th e po s'lbdltY of ill ega l
" 1119 JS 3 pJram <.' tc r
parame ler< It would be belle r to de fi ne a cla« suc h a Spr ", /mJVd"c/, with a priva te conStruCto r and
/.. tory fun c ti o ns.

Sp ecia l izedVeh i cle c r ea t eACa r ( ) { . . . }


Sp ec ializedVe hi c l e c rea t eAT ru c k ( ) { . . . }
Sp ecializedVe hicle crea t e ABus ( ) { . . . }

The method In question can the n ,ake o nly a parameter of th is type. In o the r words, instead of

evaluate ( Str i ng ve h ic l e) . . . / / pr o bl e m wit h illega l st r i ngs

use

ev a l u a t e ( Spe c ial iz e d Vehicle vehicle ) . . . / / par am e ter value cannot


b e illega l

When the posSIble parameter values arc restricted but infinite, a separate class can stili be valuable. For
exa mple, a person's age is an integer between 0 and 105 , let's say, and so a method

ge t Ye ar Of Bi rth ( int age )

may have to deal with errors. In fact , the same error proceSSing would have to be repeated for all methods taking
"g' as a parameter. O n the other hand, a class Agr with a private constructor and a publ ic fac tory method
Age g e tAge ( int ag e P )

would handle erroneous input In a consistent manner, located In the same place as all the other aspec" of age.
Some options for dealing wit h this error are described below. The disadvantage of this method is the
proliferation of additional classes, and the slig ht awkwardness of ca lls suc h as

. . . getYearOfBirth ( getAge ( n ) ) • • •

in place of such simpler calls as

. . . getYearOfBirth ( n ) • • •

22.7 CODING STANDARDS

Applying coding standards across a team improves diSCipline, code ",adability, and code portability. We will
prescnt o ne set 0/ standards as an example. Some of these arc adapted from Scan Ambl.r ( 3). Oth.; s~ncUrds
CODING STANOAPDS 553

can be found at unorporallon's Java He The exact nature of a ~{a ndard is not nearly as Important as the
tact that the tcarn u'\cs one

22.7.1 Naming Conventions


U C J. naming convention for variables. Engineers lcnd to become emotional about their favonte conventl0 nc;.
and true consen us I often Impossible. Nevertheless, convl."niions arc nc cs ary A limited time should be c;;ct
aside for decidi ng on conventions and a method for finaliZing them . For example, a team member can be
d Ignated to draft conventions, c·mail them 10 the other members for comments, then have the choices
finalized by the deSignated person with the approval of the team leader There shou ld be gtlldehnes a. to
when C'xceptlons to convent ion arc to be allowed
The following are example or naming conventi ons In the Java trad inon

• lame: entities wilh concatenated \yords as In IrnglhCylmdcr Thc<;c arc ea y to understand and they con crvc:
<pace ExceptIOns may be pemlltted at the discreti on of the programmer
• 8egln class nc)me wirh capitals. ThiS distlngUl ~ hc s them fro m va nablc:s. orne tools precede the name of
enriries with standard letters or combinations of letters. such as . . (or classes as In CuslOntlr This IS
u clul when the importance of knowing the types of name, exceeds the resuiling awkwardnes,
• Name variables beg inning With lowercase letters . on tant, may be excepted.
• ame consta nt with capital, as In I_AM_A_ ONSTANT (usc static final ) lAMA ONSTANT IS hard to
read; JamA Coll5tant cou ld be confused with a class , ,AmANamr gives no indICati on thal Il is a constant

• Some orga nizao on distingUiSh between vanables local to a method and those of the class ("Instance
vanallles). For example, begin (or end ) the name of instance vanables of classes With an under-co re a< In
_"rn,OjDay to dislinglllsh them from other variables, since they are global to the" oOject, th" I u.ed by
Gamma et a!. [4] but derided by Ambler [5]. A convent io n used In the ca . e study IS to append the suff" I to
Indicate Instance vanable , as In lim,OjD"yl. Each Instance van able is global to each clas. Instance . and
when one IS encountered in a block of code, It is useful to know thiS
• ConSider uSing a notation to dist ingui sh the stallc v.nob les of a class. The ca,e stud y u'es the surRx S, as In
n"rnC.'sEutrBu iIt5 Reca ll that a static vanable IS global to a cia... and It is heipful to know that. vanable
encountered In a block of code IS one of these
• Usegrt , sri , and IS for acce sor methods as In 9,INllm,O, srINII"" O, IsBox() (where the laner returns
a boolean value). Alternatively use "",,,,0 and ,,"m,(51'ltIg), for attribute name (c g., In ORBA-.ee [6]) .
• Augment these wllh standardized addil10nal "getters" and "setters" of co!lecllons, for eXJmple 1I11tr1l"loNamr{),
'''''O!J,F,,,,,,Narn,O, n,wNam,O.
• Consl dc:r a convcnllon for parameter" One o n Vl'n tl o n I to lI~e the' prc~x a, a... III 11"*(1111 nnhllcrg,n . mt
anlnlrrgm j. The case stud y u.cs the: <u(flx P, J' In S"m (11i1 ""mIP. ",I """'2P).

22.7.2 other Conventions

u ~ a conSI~ t om standa rd ((Jr~(!paratlon InCe s lll ~ l e bbnk Ilnc~ arc u~dul (or C;t:para tlll J.C Odl" ... e(.tlolh Within
mtthods. a conSISt "nt "andard IS to use dOllble blank line, bet,.een method, \'(/lIh,,) method, CGn Ider
"~/1dard, such a~ the loll owII1i!
SS4 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

• Perform o nl y o ne o pcrJtl o n pt' r lint'.

• T 1)' to kee p mel ho ds 10 , <In!llc s rc,·n.

• U sc porc nth cses wilh in expresSio n 10 clari fy Iheir me' nln g , eve n If Ihe sy nl ax o f the la ngua ge makes th em
unn c cssary Th i, is In appl. allo n of "If you kno w It, sho w II ..

In namin g clJ~ses , usc ",ingular names suc h as " USIOllltr, unl ess the cxprc!Io'; purpose is to collect o bjects (,n
whi ch case I" 'om,,, mig ht be appro prialc). T o prcve nlthe pro li fe rati o n o f classes, il lS somellmes desirable 10
have . clas, o liecI itS o wn In tan ces This wo uld be do ne Wllh a "alic data me mbe r o f th e class.

22 .S COMMENTS

Comments arc no n<:x t'cut<:d lines in a program whose purpose is to describe the intcnt of the program
Effecti ve usc of comments is impo rtant to understanding code.
Good co mments sho uld nOI simpl y repeat what is o bvio us fro m readin g the code. They sho uld provide
mean ing . explaining how and why a piece of code is doing something. Fo r example,

i -'-+ ; I I i n c r e me nt i

The comment here pro vide no additi o nal inrOmlJtion regardin g what the variable j means and why it is
being incre mented.
Now consider thi s example . using the hlnction dollO we saw earlier in the chapter.

i n t dolt (i nt a , int b )
{
in t C i
c=a *b;
r et urn c i
}

With no commenls and poor naming of the function and parameters, the purpose of Dolt is nOt obvious.
By addin g commentS we can make its purpose clear.

I I dolt - compute and return the area of re c tangle given its length and
width
I I a - length
li b - width
intdolt(inta, intb)
{
tnt c;
c=a*bi
return c;
}

Evrn though thr names of thr function and parameters are still unclrar, thr commrnts c1arify.ts pul"J'OS"
and the mraning of Ihe parameters.
TOOLS AND ENVIRONMENTS FOR PROGRAMMING 555

22.S.1 Documenting Attributes

For rach I." aurobUlt " a'e .,S


purpo<e dnd prov.de all appilcabl~ mvaroan< . Fo r example • •n the class
T/1i111gl,. ,,'e wou ld code omewhat ilke th~ follOWin G

class Tr iangle {
private static final double DEFAULT - TRIANGLE - SIDE = Double . MAX - VALUE ;
II Invariant : 0 < len1 <=Do uble . MAX_VALUE
protected double len1 = DE FAULT - TRIANGLE - SIDE ''
II Invariant : 0 < len2 <= Double . MAX_VALUE
protected double len2 = DEFAULT - TRIANGLE - SIDE ;
II Invariant: 0 < le n3 < =Double . MAX_VALUE
protected double len3 = DEFAULT- TRIANGLE - SIDE ;
II Invariant: lenx + leny > le n z for ( x , y , z) = (1 , 2 , 3) , (1 , 3 , 2 )
Il and (2 , 3 , 1)
• • • •

lor example,

" 1 < _age < 130 " or " 36 < _ l e ngth *_widt h < 193 " .

As a reviewer of thiS book has no ted , onc can wnte a eparalC pnvatc..· or protected mcth od that IS ca lled
by other method when the invarianl n~eds c h~ckin g

22.9 TOOLS AND ENVIRONMENTS FOR PROGRAMMING

It has been ~ald ohen that, a. . a species, we art loolmakcrlO, and thi S 1(,; no less tnlc of oftwa n.'" developers An
increaSing number of tool arc .v.dable lhat help developer<.
Interact.ve developme nt enviro nments riDEs) are Widel y u<cd to e nabl e progra mmer< LO produce mo re
code In iess t.me They Include drag ·and -drop faCilitie s lor forming C UI comp()n~nts . grap hical representa -
tion of directories , debugger<. "wizards: and refa LOrong f.cili tLe (d.<cus cd In hapter 2 ~ )
Profilers such a lProb, can be u<cd to accu mulate statl,tlc o n ode su h as


• Cumulative CPU and c lap<cd lime

• Time <pent by each method

• Cumulative count o f object< generaled

• Number of call,

• Average method time

R~ver~c , enf(lI)ccnng tools are aVJ dablc tholt take sour e code J' Input Jnd produ c ImHted d lumen -
latlon An <:xample of J rcve"c -cng lnc:cnng source ode t 0 1 1 Ii.wadoc Rc vc~c cnglOccnn,.; I' d"lu"cd
mr",: fully III hap I"r 24
~cra l obJo~ I -()n e l1l e d lool, (sut h " Rotlo nal Ro<c . TogethcrlI/ C+ +) gencral~ ' o ur(o (od~ fr m d~"
m()dcl~ 111(."5(: rorward ,enS{lIl 'cnng tools can not h{' c>c pc: t(.'d 10 g('nl'JUtC more d\an lode ,L..dt"u n, \\ !thin
556 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

w i" h Ihe pro~ ralllmtr Illu't wo rk to pro duce th e cventu,l,mple me ntalio n H o weve r, ' 5 o ur diSC USSio n o ( MDA
In I"pter 2 1 sho wed, pl,ns arc under way fo r ,mb,ll ou o dc gc nc rnll o n , p, b"",,,, The <. me tools also
pcrio m"l reverse englOcenng by mc:chani ally pr du !OJ.( ci a, models fro m SOllr c code (hence: th e term "round#
tnp eng meering") .
The history o( tools in other branc hes o( engineering (e . ~ ., CA DI AM ) <Ul::!!cst. th at, de. pitc , rocky
start .nd sevcral (alse directions, pro gramming too ls will co ntmue to Improvc <lg nifi cantl y , that they will
co nt inue to leve rage prog rammm g skills , and th at they will reduce drtld gcry and mec h,n lCa l tas ks.

22.10 CASE STUDY: ENCOUNTER IMPLEMENTATION

• Im pltmcu tation Holt'S A document is mainta ined by


Note to the Student, individual engineers to describe (he current state of
This section contains Implementation notes thcir wo rk.
(or the Encounter case study. The source
code for Encounter is available online so
that the student can inspcct the final product. 22.10_1 programming Conventions

Programm ing conven tions are added to Sec-


tion 5, Standards, Practices, Conventions, and
Several purely implcm~ntation issues need to
MelTics, o( the Encounter SQAP.
be documented, as listed next. We include a
discu sion of whrr' these issues should be
documented. The sections that (ollow con tai n 5.2. 1 Programming Conventions
examples of the documentation content. (t h IS scc tion has becn added to the standard)
The (ollowing conventions will be used .

• Prog rammm9 (o nvttltioru. These can be provided 10


I. Parts of nonconstant names arc dclineated by
the SPMP since they arc part o( projec t ma nage ·
capi t. liza tio n, (or example, Ibi, fsANam, .
ment to a degTee. Thcy could be prOVided in the
SOD although they arc not part o ( the ac tual 2. Class and interface names begin with a capital :
desig n. They could be stated m a separate docu - ror example, Account.
ment, but there are already many documents They
3. Instance variables in classe beg in with a low-
co uld be provided in a document dedic.ted to
crcase char.cter and end wllh "I", (or example,
implementati o n, which would be useful. F,n,lIy,
bainllcc/
they co uld be mcluded in the SQAP Ince they arc
i1direct contributor to quality The Encounter case 4. Static (class) vari.bles begin With a lowcrcase
stud y selected thiS option . character, and end with "S", (or example,
j'llrrrslRtI rtS .
• The impiC17lnllnlio" model This speCifics how the
phYSical file are o rganized (source code, binary, 5. Variabl es defined in, and global to, a method
help files , etc. ). The SOD is a possible repository begin with a lowcrcase chClracter and end With
(or thiS, although the implementation model is not "MO. fo r example, In,,,,,I/ll
actually part of the de ign. A scparnte document IS
6 . Parameters begin with a lowerca~e character and
a po sibilaty A document on implementation
is uc alone would be appropriate. Another passi .
end with "I"', (o r ex,mple, pn'" ipaiP.
biiLty is the SCMP since it is concerned Wllh 7. Final variables hall be wntten in c,pltal,
(onAgUlJtions and version. The Encounter case and sh,1I use underscor . for example
study selected this option. BANK_NAM.E.
CASE STUDY; ENCOUNTER IMPLEMENTAnON 557

5.2.2 Notation for Showing the Location 22.10.2 Implementation Model


of Files
We will uS< UML 10 de cnbe the imp lemenlalion [7].
A description of the impleme ntatio n model ,
wh ich describes how the phYSICal Rles are
5.2.3 personal Software Documentation organized, is added as an append ix to , he
Each enginee r wi ll maintain documentation of his Encounter SCMP.
curre nl wo rk, wh ich is referred 10 as h is Persona l
Software Documl'nlal io n (P D J. This enab les Ihe
cnginc~r to report s tatus at all rimes , and it be- Appendix for Encounter SCMP:
comes pari of the project's arch ive The team or Implementation Model
projec t lead er wil l determ ine how to organize rhe
A part of the Encounter implemenr-atl on model IS
r SD of the lea m. T ypical ly, a perso nal software
docu menl set correspo nds to a task th at has been how n 10 Figure 22 .9
allocated to th e e ngi necr and co nSISts of a sct of
classes. 22.10.3 Implementation Notes for
Encounter: Part 1 of 2

This documcllI is mainlalOed by IOdividual


An example of PSD IS provided in Sectio n
engi neers to describe the current state of their
22. 10.3 be lo w.
work . II should be complete enough to allow

Design model Im!2lementation model


Framewo rkRPG.

'--------------- -----1 RolePlayin gGame


iI RolePlayingGame : --L __ u __ u _ "'j

IRPGame~~-
,
'1.. J utile))
- --
c(file))
,, ~ RPGame .java R PGame .class

IRPGEvent H,-- ~ utile »


-- ~ " file »
~ RPGEvent.class
,, RPGEvent.java
-'
r - -- --, ,
,,, I
GameState H-,, - - ufils ))
RPGame.java
__[_ -'l " file "
-t RPGame .c lass
,, ,
,, ''
11 RPGMouseEventListener
•, I
-- H.- :r " file » ___ ~_ --'i " file »
-------------------------------- -c. RP .... .java RP ..... class

F1&ure 22.9 Design model and Implementation model for Ihe Encounter video game
558 CHAPTER 22 PRINCIPLES OF IMPLEMENTAnON

3. Time Recording Log


the ~n!! 'neer to reporl his or her taNS at
m ~et ln 8s , or to allow another engineer to
take ovcr the work in a rea onable amount EngIneers ma In ta In records of how long it takes
of tIme If necessary them to perfom"l the various ilctlvltieS requi red
by software engineering. The e data are es~n·
ti.1 for th e project, and they prOVIde the engi·
neer wIt h a professional "toolkit.' T,ming dam
1. Introduction can be collected via written fo m.s or software
tools reSIding o n d esktop computers, hand· held
ThIs document descrobcs th e work of Jo hn Jo nes o n the computers, and so o n Engineers have to dc·
class EncounterCharacter. It is under configura ti o n velop a common understanding of the degree of
cont rol with the file name PSD_EncounterCharacter. precision required by the orga nizatio n. No~
The fi le referenced here are stored in the directory that approximate time measurements can easily
Encou nter'IPSD\JJones o n the Galaxy system. become too inconsis tent (or practical usc.

2. Defect Recording Log


Th ese data are to red in fi le Tl mt_Rtcordin9_l..o9
The log in Figure 22 . 10 is maintained in fi le d,frcILo9 . clnd an example is shown In Figure 22 . 1 I .

Phase Repair Tim"


Date Number Type Phase Inj"cted Removed (minutes)

6/ 14/99 142 In terface Personal Personal code 10



detailed desig n reView

Description - omlued checks on name length in EncolmlrrCbnracttr.

6/ 16/99 14 3 Documen tation Code Perso nal code 4



review

Description: incorrect Javadoc description of EucolwlrrClJar"cttr .

• •• •• • •• •• . .. _ . . ,. _ . . . ,. '" • •• • •

Th is table concludes with defects fou nd duron g unit test

Figure 22.10 Example of a defect recording log


Sourc~ HumQhrey, WDtts S. "Introduction LO the Team SOftware Proct>SS: ' Addison-Wesley, 2000.

Time
Oat" Start SlOP Interruptn • . taken Phase Comments
6/99 10,04 10,25 4 + 6 \I Detai led Design Consulted with
am am V.N.
6/99 1,20 4,34 15 + 20 159 Personal Code Defect 14
pm pm review

7/99 • • •

Figure 22.11 A time recording log


CASE STUDY: OPENOFFICE 559

22.10.4 Source Code (without Test Code): Add.ll o n.1 rulcs. The named of me' hods should
Ef/COUntefCharacter follo w commo n prac'ice for namin g gellers (g,'X()),
sellers (wX()) . and predica,c. (" XC), baIXO). ..
The r<ader IS refc ..... d '0 ection 22. 15 2 fo r a itSii ng
of ,h. code. 22.12 CASE STUDY: OPENOFFICE

[ThIS sec' io n pre e nlS examples of Op",OfJi ' docu·


22.11 CASE STUDY: ECLIPSE mentation thal relates to Implem entatio n.]

22.12.1 OpenOffice Standards


No'" ' 0 thc Student,
Thc implcmen' ation of Eclipse is a large body
of code and rdated artifacts. This see,io n No te'0 th e S tudent·
sclcct. just onc vcry small example of stan · There arc many standards assoCiated with
dards as an Illustration. O penOffice dcvclo pmen, W e w tll gwe o ne
mall exa mple.

Eclipse devel o pmen' stand ards and resources Eac h OpenOf[,ce class must begin w.th ,he
ar< I."ed at (8 ). They arc q uo ,ed fro m (8 ) as fo ll ow . fo ll owi ng header from [9 ]
/ * * * * ** * ******** * *** ** ****.*****
*OpenOffice . o rg - amulti - platform
conventions and Guidelines
* office pr oductivity suite
These cover coding standards, naming co nve nti ons, *
and o,h .. guidelines. Fo r exampl e , naming co nven · * SRCS f ile : code , v S
'ioAS arc decomposed as fo llo ws, *
* SRev is ion : 1. 2 S
• Eclipse workspace projects *
* last change : SlIuthor : st S SDate :
• Java package * 2005 / 09 / 02 16 : 31 : 54 S
• Classes and interf.ces *
* The Co n tents of this file are made
• Methods * available subject to the terms of
• Vanables * GNU Lesser Ge n eral Public Lic e nse
* version2 . 1 .
• Plug-ins and ex te nsion p Oint s . •
*
* GNU Lesser General Public License
* version2 . 1
Ne"." we give an example of one of the abo ve. *------------ ------------- ------
-------------------------------
* Copyr ight 2005 by Sun Micro -
* systems , Inc .
Mcthods, Me ,h o ds shou ld be ve rbs, In mixed * 901 San Antonio Road , Palo Alto , CII
ca"" wi,h ,hc Ars, lelle r lowercase, wi,h ,he firs t Jellcr * 94303 , USA
of each Inlt rn al wo rd capi,. lt zcd . Exa mples· *
* This library is f r ee software ; you
runl) : • can redistribute it and/ or modify
runF'~ ~ (J,. * it under the terms of the GNU Lesser
getBd ckqco und() ; * Gen e r al Public Lic e nse v e rs io n
560 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

• 2 . 1 , as published by the Fr ee all Impo rtant aspec" of ,,,ftware dc:vci(>pmcn, wit h


• Software Foundation . OpenOff,cc o r~ , ,"c1udlll ~ ,h e ba<c t"chnology
• UNO, ,he programllling language< suppo rted by
• This library is distr ibuted in th e penOffice org, ,he developme n' of custom com·
• hope that it will be useful , but ponents, and of cou". ,he office apphLJtlon, Wri te r,
• IHTHOUT ANY WARRANTY; wi thout even ale, Draw , Im pre'" hart , Jnd Ma,.
" the implied warrant y of MERCHANT - Th" Developer'< GUide shou ld be co nSidered
" ABILITY or FITNESS FORA PARTICULAR as a growing docum ent wh c rt.' all new A PI conCepti
• PURPOSE . See the GNU Lesser Ge n e ral wtll be dC'scribed in de,atl combIOed wi,h a set of
"Publ ic License for more details . UM L diagrams and exa mple, how '0 u,e ,he,e API,
• Th h Ar\l version I;;' an Init ial Slep for an ongolOg
" You should have received a co py of do umen'a" o n la k and Su n Mlcro<y s t~m' wtl i ,ake
" the GNU Lesser General Public care of ,hiS pro)ec, for ,he Ope nOfncc o rg commu·
"Licenseal o ngwiththislibrary; i f nl ty ., "
" not , wr ite to the Free Software
" Founda t ion , Inc . , 59 Te mp Ie Place ,
The develo per's gUide title page a nd URL arc
"Suit e 330 , Boston , MA 02 111-1307
shown partially In r-' gure 22 . 12
" USA
• ***************** ** *********** /
• • •

Section I (Readers Guide) begins to explain


22.12.2 Developer's Guide the scope of this documenl. The idea is thaI to
add '0
O pcnOffice, 'he developer crea ' es
The following is quoted from ( 10). Notice that compo ne nts using a set of sta ndards. We
the teon "guide" is used here instead of "stan· con,inue to quote direc tl y from the Develop·
dards." Since many developers contribu te to er's Guide with occasional , minor editing.
OpenOfnce, th is is a useful document for
unraveling th e i mpl~mentat ion structure. 1.1 What This Manual Covers

Thi s manual describes how '0


wn'e progra ms usi ng
"The OpcnOfAce.org SDK contai ns now the ,he componen, ,ec hno logy UNO (Unive rsal Net -
new Developer's Guide (PDF version ). The goal of work Objects) wi,h OpenOffice .org , Most examples
the guide is to give developers and solution provi ders provided arc wntten in Java , As well as Java, ,he
the necessary means to use OpenOfllee.org as com· language binding for C++, ,he UNO accc< for
ponentwarc:. usi ng it In their own projects £Ind OpenOffice.org Basic and 'he OLE Au,omallon
extending it according to their needs. The primary bridge ,ha, uses OpcnOfficc.o rg through Microsolt's
target languages are Java and C++, although the usc compo nen, technology COrvVDCOM is descnbed.
of OpenOffice.org Ba.sic, CLI (. NET), Python, and
MS Automation Is treated as well. 1.2 How This Book Is Organized
The initial version of th is guide was a coli abo·
ration work of the 000 core developers and IWO First Steps
external authors. The developers have collected The First S,eps c hap'er desc ribes the
their detailed knowledge about UNO ' and the selling up of a Java UNO development
OpenOffiee.org API.. .. .. The manual will cover ~ n viron m cn t (0 ac h i~\lc th e olutions
I The componen, l<chnology UNO (Un iversal Network Oble IS)
CASE STUDY: OPENOFFICE 561

) " .. r' ,· ~ , 1.,1·... • ·.. " uIII. · ··1H~u~"fllnll"'Tnf"t I IoIplorr, pruvul,.d by [onuo,,' tI~h ",.,.t:'d Intt"mC't

1- ~ ~__~________ ._,__
._~~

SCU'ce code? •

I
.-
• OoNm""U • hI ••
- VentOI' CO"'"'
Contents
1 RQQde(s Culde
. Oeve lo p.,'s G.... ,d. 1 1 Wha t Thl$ Manual COkers
' 10l ,.1'.'."0:.
• JOL 0 ... 19" Guid. 1.2 Ho .... This SOok IS OrgaO/;ed
o JDl DON G.... ld.

- SDIt 1.3 OPBoQ(fjCg,o(Q v ersIon Hist ory


• SOl<. S... ,....~
1.4 Belited docym entatlon
• [ " 4mp t••
• J . .... U"O l.S Convention s
R,f. re n,e
• C++ UNO 1.6 Ac l'oow ledament s
R.f.""O'ICt
• Do... n lo.d
'Tip. 'fI' tnd<.
2 First steps
· lnt"," .. 1 00 s p ou 2. 1 Programming Wi th VJiQ
•E Ima l A..fOU ' CI,
• MI,~ U . n .ov, 2 .2 Fr!Jtld s o f AppllcatlQn for UNO
• D. .... rop •• P'ojecu
• Hllh n9 Un Rul ... 2 .3 Gftt lng S tartelj
· Hev,: l.tt., Ard\' ....
2 .3 . 1 Regu1ff d FIles
2 ,3,2 In stallation Sets

2 ,3 , 3 Configurat loQ
I

Figure 22.12 Contents of OpenOffice developer's guide

you need. At the end of thi s chapter, you


Th ere is much more to the Developer's Guide,
will be equipped wit h the essentia ls re·
but our sample ends he re.
qu ired for the following c hapters about
the OpenOffice.o rg applica tions.

• • •
22.12.3 Sample open Office Code

F,gure 22. 13 is an example of the selected use All haptt'rs prOVide o ne r more exa mples that . how
of UML in this document. It how the inheri · the use of the API in the current de criptlons of this
tance of a pair of classes and the interfaces gllldc. . .
idt:noted with circles) that each of the two
d'5~ ,mplement.
The fo llowi ng sample, Listing 22 I, i. from
[ II J. The aut ho r, comme nts arc III di ffere nt
. ., type and in bold.
562 CHAPTER 22 PRI NCIPLES OF IMPLEMENTATION

com.sun.star.view.XPrintable
get?,;nter
~etPrinter

print

com.sun.star.frame.XStorable
haslocation
getLoc.ltion
i,R•• dOnly
store
"oreA,UrI
"oreToUrt
com.sun.star.document.
Office Document com.sun.starJrame.XModel
anachResource
getURL
getArgs
connectControlier
disconnectCont roller
lockControliers
unlockControliers
hasControlierslocked
Sl!tC urre nf Cont ro tIe r
getCu rrentControlier

com.sun.star.utH.XModifiable
isModified
..tModified

com.sun.star.text.xTextDocument
getText
reformat

com.sun.star.uti\.x5earchab\e
com.sun.star.text.
TextDocument createSearch Descriptor
===
findAIl
«servicl!»
findFirst
findNext
com.sun.star.utiI.XRefreshable
refresh
addRefreshListener
re move Refresh li st ene r

Figure 22.13 UML excerpts from OpenOffice developer's glJlde


CASE STUDY. OPENOFFiCE S63

lJsdnI 22.1: Code excerpt from OpenOffice

I ·*··****·*··~***··*··**·*··
* $RCSfile: ViewSample. java , v $

*SRevision: 1.3$

* last change; $Author : hr $ $Date: 2003/06/3015 : 46 : 21 $
II tt .....ill be • li . t of th•••
* • • •
*** * •• * * *******************. /

u.ort com . sun . star . uno . UnoRuntime;

11___________ implementation___________________

,'0' Create and modify a spreadsheet view .


*1
public cl . . . ViewSample extends Spr eadsheetDocHelper
{
11 -------------------------------
public otatic void main ( Str ing args [J )
{
try
{
ViewSample aSample = n•• View
Sample ( ar gs ) ;
aSample . doSampleFunction () ;
)
catch (Except ion ex)
{
System . out . println ( "Sample caught e xception! " + ex);
System . exit ( 1 ) ;
}
System.out.println(" \ nSamples done . " );
System . exit( 0) ;
}
//---------------------------
public ViewSample ( Str i ng [1 args )
{
..... r ( args ) ;
)

// -----------------------------
1** This sample fun c tion performs all change s o n the view. *1
/I into. . .l daocription
564 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

publi c void doSampleFunct ion () throw s Except ion


{
com . sun . star . s h eet . XSp r eads h eetDocume nt xOoc = ge tOocum e n t ( ) ;
com . sun . star . frame . XModel xMod el = (com . sun . star . frame . XModel)
UnoRuntime . queryInterface(com . su n. star . fram e . XModel.class ,
xOoc ) ;
com . sun . star . frame . XControlle r xController =
xM odel . getCurrentController() ;

I 1 --- Spr eadshee t view ---


II freez e the first column and first two rows
com . sun . star. sheet . XViewFr eezab Ie xFr eeze = (co m. sun . sta r. sheet .
XviewFreezable)
UnoRuntime . queryInterface( com.sun.star.she et . XViewFreezahle .
class , xController);
i f ( null != xFr ee ze )
Syst em . out .pr int In ( "got xFreeze" ) ;
xFre eze .f reezeA tPosition( 1, 2 ) ;

I I --- View pane ---


I I get the cell range shown in the se co nd pane and assign a cell
/ I background to them
com . sun . star . contain er . XIndexAccess xIndex =
UnoRuntime .queryI n terface( com.sun.star.container.XIndexAccess.
class , xController ) ;
Obj ect aPane = xIndex. getByIndex ( 1 ) ;
• • •
I I --- View settings ---
• • •

/ I --- Range selection ---


• • •
synchronized (aList ener) / / exteneive us. of synchronize to prevent interruption
{
aList e ner.wait () ; /1 wait until the selection is done
}
xRngSel . removeRangeSelectionListener ( aListener ) ;
• • •
}
11 _______________________

II listener to react on finished sel ection


private ExampleRangeListener
cl. . . implements com. sun. star. sheet.
xRangeSelectionListener
{
pubUc Str ing aResult;
F''''uc 'lDicS done ( com. sun. star. sheet. RangeSelect ionEvent aEvent )
STUDENT TEAM GUIDANCE FOR IMPlfMENTATlON 5dS

{
aResul t : aEve nt. RangeDescr iptor;
synchron ized ( thia )
{
notify( ) ;
}
}
public void abor ted (com . sun . star. sheet . RangeSe lect ionEvent aEvent)
{
synchr on ized ( this )
{
notify () ;
}
}
public void disposing( com.sun.star . 1ang.EventObject aObj )
{
}
}
11 ______________________
}

The following paragraph inviles readers 10 following documentatio n, using the Encounter case
contribule 10 Ihe develo pe r's guide. This study as .n example,
kind of invilalion helps 10 crcale a cooperative
I . Programming co nve ntio ns
almosphere. Developers arc less likel y 10 feel
conSlncred by standards and guidelines when 2. Implementatio n model
Ihey partici pate in establishing them .
3. Integratio n plan

Make a contribution The prog rmltmiHg cOll vrn tions need no t ~ exten-
sive, but should provi de enough del.il so thaI code
We would like to invite yo u to participa te in this produced by differe nt students exhibit. consiste nt
effort. so as to cover the necds of the commu niry and style.
to hnng in the community' expe rience Please let us It is important to document your Implcmmtation
know wh.1 you would expect fro m Ihe Developer's moci,' so the e ntire team kn ows where files are to be
CUlde, what might be rni sc;ing in the current version, stored and fro m where they are to be retrieved .
which usc cases the gU id e hou ld cover and wh ich An i" fcgmtiol1 pia" is written so you undernand
CXlCnStOns you ca n think of . . the o rder of imple menl.tio n and how modules will
be tested.
12.13 STUDENT TEAM GUIDANCE FOR O nce YO ll have completed the document.tio n
IMPLEMENTATION listed above, usc your detailed design as a gui de and
Implement your project. At a minimum you can
S.fore ommencin!! with the Implementation of Implement key portions of your applicalion to
Yoor student team prole t, you hould produce the fonn a prototype .
566 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

22.14 SUMMARY

Pr gra m o de" rc. lcd lrom designs. In Ihe o bJect · o n ented paradigm , cla«"' fo rm the basi, of the de<lsn
Jnd implementation Cl as~cs arc either domam lasses, wil, h Ori gi nat e from the requirements, JtSlgl1 cli)c;scs,
whi c h o ri ~p nalc from the SDD , o r UltplClf1tlllahOJI c1a~'i;c". whic h Jrc crt:atcd durtng Implementation
Dcfm Wt programrrtltlg is lin approach to rcdu Ing errors h In yolves antlclp,ltIng crrors uch a Illega l cLJta
In function parameters and bad data (rom externa l sou rces lIch as datJ commu nIcation lines There are several

effective strate g ies for dea ling w ith th e dl ega l data . includ in g Ig no nn g th e e rro r, substitutin g a default value,
o r waiting for va lid data Th e philo o ph y of "enfo r ing Intcntio ns IS fu ndame nt al to good , defensive

programmin g.
There are a number of hr51 practice'S to fo llow when im plel11 cnt ing cod e, i ncludl ng lISlng expressive naming ,
aVOid uSing global va riable" nOl usi ng parameters and mel hod va nables, lim iting Ihe numbe r o f function
paramcters, U Ing named co nstants , inIt ializi ng va riables. c heck ing loop counters, and e nsuring loo p tcrm ina·
tlon. Each IS Inlended 10 reduce Ihe likelihoo d or inlroducing errors and make code mo re ma int ainable .
Progrm"mi"g sla"dards are used 10 improve Icam discipl ine, code readab il ity , and code portability.
Sta ndard cover all aspect of cod ing including namln!: co nventio ns, code la youI , usc of brackets, and use of
parentheses Commolls , especia ll y those that observe progra mmin g standards, are an importa nt aid to
understanding code. They sho uld convey meaning , purpose, and intent, and not repeat what is o bVIOUS
from rc.ding the code In particular, • good w.y to defi ne a met hod within a class IS to expliCIt ly specify In
comment It s IHlm l, prccotidiIlOt1 S, poslcotldill Ons , ;,warlants, (Xcrp rio1ls , and b,owtl issues. Poslco ndltio ns deline a
metho d's purpose precisely. The result IS an increased unde rsla ndin g of the method , whi ch leads to a reduced
likelihood of errors.

22.15 CODE LISTINGS REFERRED TO IN THIS CHAPTER

22.1 S.1 Code Listing for Video Rental EXample

The code In listing 22 .2 below illustrates some of the prinCiples discussed in thi' cha pter, applied to th e Rmlal
class of our VIdeo sto re example.

Listing 22.2: Video store application code Rental, Rental/tern classes


/ **------------ ------------
------------------------
* Oescr ibes a OVD
*/
cIa.. OVD ."t.nds RentalItem
{
}
/ **
* Intent : SOD for Rental Framework : http: // . . . . .
*
* Known issues :
* (1) This class is not complete for a first build
* ( 2 ) Relies on log() method to log dev elopme nt problems -- not yet
* created
* (3} Un it test to be moved frommain() and upgraded to use JUnit .
*/
CODE lISTlNGS REFERRED TO IN THIS CHAPTER 567

UpOrtJava.

~o .
••
;
*auact. c1 ••• Rental
{
I I CONSTANTS = = = = = = = = = = = = =
= 99999999 ;
private lInu atatic int
privatellnal atatic int
- -
H1GHEST-ALLOWABLE RENTAL 10
10_WHENJENTAL_ NOT_ IN_EFFECT = 0 ;
privatellnu atatic int TOLERANCE_ON_RENTAL_ID = 1000;
private atatic Str ing F1LE_WITH_NEXT_USABLE_RENTAL_NUMBER =
"RentalNumb er . txt " ;

I I VARIABLE S = = = = = = = = = = = = = = == = = ==
protected int id = ID_WHEN_RENTAL_NOT_I N_EFFECT ; I I renta l
identificat ion
protected Ren talCustomer r entalCust omer = null; I I cust o me r rent e d t o
protected RentalItem rentalItem = null; I I it e m rent e d

1* Class invar iant :


EITHER
the r ental is i na ct ive, id == ID_ WHEN_ RENTAL_NOT_ IN_EFFE CT ,
rentalCust omer == null, and rentalItem == null
OR
-
ID WHEN - RENTAL- NOT
-IN -EFFECT < id < = HIGHEST- ALLOWABLE -
RENTAL_ID,
rentalCus to mer != nu ll , and rentalItem!= null
*1

II CONSTRUCTORS -- -- --
- - --
- - ---
- --
- - --
- - ----
- - - -
/ ********************** ***** *** ******
* Intent: Satisf y class invariant with rental n o t in e ff e ct
• Postc ondi t ions : id == ID_WHEN_RENTAL_NOT_ IN_EFFE CT,
* ren talCustomer == null, and rentalltem == nul l
*1
public Rental ()
/ ************** ********************** /
{
-
id = 10- WHEN- RENTAL NOT- IN- EFFECT ;
rentalCustomer = null;
rentalItem = null;
}
j* ••• ********************************
• Intent: Creat e a s p ecific rental

* Preconditions:
• (1) anID > 1D WHEN_RENTAL_ NOT_I N_E FFE CT
* (2 ) -
anID <= HIGHE ST_ ALLOWABLE_ RENTAL_ ID
• (3 ) aRental Cu sto me r ! = nu l l
• (4) aR e nta llte m ! = null
568 CHAPTER 22 PRINCIPLES OF IMPLEMENTAnON


* Postcondi t ions:
* (1) as for setId( anld)
* (2) rentalCustomer == aRentalCustomer
* (3) rentalltem== aRentalltem
*
* Known issues:
* (1) Exception not specific enough
* (2) No handling of violated precondit io n s

*/
public Rental
( int anld, RentalCustomer aRentalCust omer, Rentalltem aRentalltern)
throws Exception
/ *********************************** /
{
setld ( anId ) ;
rentalCustomer = aRentalCustomer ;
rentalltem = aRentalItem;
checkInvariant();
}
----------------------
// METHODS ----------------------
/************************************
* Intent: A check that the class invar iant is valid; present for
* demonstation only. It is possible that this method is n ot actually
* used.
* Exception: Thrown if the class invar iant is violated
* Known issues: Exception not specific enough
*/
public void checkInvar iant () throw. Except ion
j ****************************** /
{
if ( (id = = ID_WHEN_RENTAL_NOT_IN_EFFECT) &&
( ( rentalCustomer ! = null) II ( rentalItem ! = null ) ) )
{
thrown_Exception( "Invariant in 'Rental' violated" ) ;
}
if ( ( id > ID_WHEN_RENTAL_NOT_INJFFECT ) &&
( ( id > HIGHEST...J!LLOWABLE_RENTAL_IO) I I
( rentalCustomer == null} II ( rentalItem == null) ) )
{
tbrown • • Exception( "Invariant in 'Rental' "violated" ) ;
}
}
/************************************
* Intent: Get the next available number for assigning a rental
*
* Returns: The integer on the only line of the local file
CODE LISTINGS REFERRED TO IN THIS CHAPTER 569

* FILE_WITH_NEXT_USABLE_RENTAL_NUMBER

* postcondition: The integer on the local file FILE_WITH_NEXT_
• USABLE_RENTAL_NUMBER has been incremented

• Exception that exits the application:
* If the file ca.nn ot be accessed or the data is not an integer
*/
pri_t. autic int getNextRentalNumber ()
/***.**** •• ************************** /
{
Str ing nextRentalNumberStr ing = new Str ing ( ) ; / /
Str ing form int nextUsableRentalNumberReturn = - 1000 ;
BufferedReader reader = null;
FileReader f ileReader = null;
DataOutputStream wr iter = null;

try
{
/ / Prepare to read from the file
FileReader = new FileReader ( FILE_WITH_ NEXT_USABLCRENTl.L_NUHBE:R) ;
reader = new BufferedReader ( fileReader ) ;
nextRentalNumberStr ing = reader. readLine () ;
System. out .println ( nextRentalNumberString ) ;

/ / Convert to integer
nextUsableR entalNumberReturn =
( new Integer ( nextRentalNumberStr ing ) ) . intValue () ;

/ / Increment the next available number for assigning a rental


int incrementedNumber = 1 + nextUsableR e nta lNumberR eturn ;
Integer integer Form = new Integer ( incrementedNumber ) ;
/ / and replac e the existing record
WI iter = new DataOutputStream
( new F ileOutputStream( FILE:_WITH_NEXCUSABLE_RENTAL_NUMBER ) ) ;
writer.writeByt es( integerForm.toString() ) ;
}
catch ( Except io n e)
(
System. out .p rintln( e) ;
System. out .println( e.toString() ) ;
}
return nextU sable Renta lNumbe rR etur n;
}
/** ••••••••••• ******,.**.****** ••
570 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

" Intent : Self - test of this class


" Known issue : Not migrat ed to JUnit
*1
public static void main ( Str ing [l args ) throw. Except ion
/ *********************************** /
{
II Create concrete classes because all are abstract
class RentalTest extends Re nt al
{
public RentalTest () throws Excepti on
{ super( ) ;
}
public RentalTest
( int anld, RentalCustomer aRentalCustomer,
Rentalltem aRentalltem )
throws Except ion
{ super ( anld, aRentalCustomer , aRentalI tem ) ;
}
};

class ConcreteRentalCustomer extends RentalCustomer {} ;


class ConcreteRentalltem extends Rentalltern{};

I I Create obj ects


ConcreteRentalCustomer concreteRentalCustorner =
new ConcreteRentalCustorner() ;
ConcreteRentalltern concreteRentalltem = new ConcreteRentalltem() ;

II Test invariant checker first because it is used in testing


// --------------
RentalTest rentalTestO = ne .. RentalTest () ;
II TestO.l
rentalTestO. id = 0;
rentalTestO . rentalCustomer = null;
rental TestO . r entalI tern = null;
try
{ rentalTestO .checklnvariant() ;
System. out . pr int In ( "Test O. 1 succeeded " );
}
catch ( Ex ceptio n e)
{Systern . out .p rintln( "Test 0.1: Should be no exception " ); }

I I Test 0 .2
rentalTestO. id = 1 + HIGHEST_ALLOWABLE_RENTAL_ TD ;
CODE LISTINGS REFERRED TO IN THIS CHAPTER 571

rentalTestO.checklnvariant();
System. out- println( "Test 0 . 2 succeeded" );
}
cat.cb( Exception e )
(System. out .prin tln( "Test 0 . 2 : Exception as expected " ); }

//Test 0.3
rentalTestO. id = 1;
rentalTestO. r entalCustomer = null;
rentalTestO. rentalltem = concreteRentalltem;
try{ rental TestO. checklnvar iant ( ) ; System . out . pr int In ( "Test 0 . 3
succeeded" ) ; }
catch ( Except ion e )
(System. out .println ( "Test 0 . 3: Exception as expected " ) ; }

//Te st 0.4
rentalTestO. id = 1;
renta1TestO. renta1Customer = concreteRenta1Customer;
rentalTestO. rentalltem = null;
try
(
rentalTestO.checklnvariant( ) ;
System. out .println ( "Test 0.4 succeeded" );
)
catch ( Exception e)
(System. out .println ( "Test 0.4 : Exception as expected" ); }

/ / Test constructor s
~ -----------------

/ / Test 1.1: Empty constructor

RentalTest rentalTest1 = ne.. RentalTest () ;


try
(
rentalTestl.checklnvariant( ) ;
System. out . println( " Test 1.1 succeeded " );
}
catch ( Exception e )
(System. out .p rintln( " Test 1.1 : Should be no exception " );
}

/ / Non-empty constructor
/ / Test 1. 2 : Lega 1 co nst ruct io n
S72 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

RentalTest re nta lTest2 =


n... RentalTest ( 1, co n creteRe ntal Customer , concreteR e ntalltem ) ;
try
(
rental Test2.ch ec k~nvar iant () ;
System. out. println( "Test 1.2 succeeded" ) ; }
catch ( Except io n e )
(System. out .println ( "Test 1.2: Should be no exception" );
}
II Test 1. 2 .1: Legal construction with warning
Re ntalTest rentalTest2pointl =
n... Rental Test ( 99999900, concr et eRentalCustomer ,
concreteRentalltem );
try
{
rentalTest2pointl.checklnvariant(};
System.out.println( "Test 1.2 succeeded" );
}
catch ( Exceptione)
(
System. ou t. println( "Test 1.2: Should be no exception" );
}

II Illegal construct ions

II Test 1. 3
try
{
RentalTest rentalTest3 =
D." RentalTest ( 0, concreteRentalCustomer,
concreteRentalltem ) ;
}
catch ( Exception e)
{ System. out .println( "Test 1. 3: Exception as expected" };
}

II Test 1.4
try
{
RentalTest rentalTest4 =
nu RentalTest ( 1 + HIGHEST.J<LLOWABLE_RENTAL_ID,
concreteRentalCustomer, concreteRentalltem);
}
catch ( Except ion e )
{ system. out .println( "Test 1.4: Exception as expected" ); }
eOOE USTINGS REFERREO TO IN THIS CHAPTER 573

I/Test 1.S
~

(
RentalTest rentalTest5 =
...w RentalTest ( 1, null, concreteRentalItem ) ;
}
catch( Except ion e )
(System. out .println ( "Test 1.5: Exception as expected" ); }
II Test 2: of getNextRentalNumber ()
System. ouc .prin tln( "cur rent integer < -- > " + gecNex cRe ntalNumber() );
}

/************************************
* Intent: set the id if the parameter is legal; warn if the number
* of rentals is getting close to the maximum .

* Precondition:
* anId > RENTAL- 10- WHEN - NOT-IN-EFFECT &&
* anId <= HIGHEST- ALLOWABLE- RENTAL
-10
*
* Postconditions:
* (1) id == anId
* (2) i f the rental number is within TOLERANCE_ON_RENTAL_IO of
* HIGHEST_ALLOWABLE_RENTAL_IO, a warning is present on the console .
*
* Exception: if preconditions violated
*
* Known issue: method" log() " to be implemented
*/
pri"atevoid setId( int anId ) throws Exception
/******************************** /
(
i f ( ( 10- WHEN- RENTAL- NOT- 1NJ;Fn:CT < anId ) &&
( anId <= HIGHEST_ALLOWABLE_RENTAL_IO ) )
(
id=anId;
if ( anI d > H!GHEST_ALLO~IABLE_RENTAL_ IO - 1000 )
{ /*tbs:
Log . log ( " setNumber () i n 'Rental' set ' id ' " +
"w ithin 1000 of highest allowed id' , ) ;
*/
System . out .println( "WARNING: Rental IOwithin" +
TOLERANCE_ON_RENTAL_IO + " of highest allowed value" );
}
}
S74 CHAPTER 22 PRINCIPLES OF IMPLEMENTA n ON

.1 •• I I do n ot c han ge id
(
thrown.w Exception( " setNumb er() in Rental tried setting id " +
" o u t of bounds: " + anld ) ;
}
}

}
1 **--
-- --
- - --
- - --
- - --
- - --
- - --
- - --
- - --
- - --
- - --
- - -
- -
- --
- - ----
- ---
* • • • • • • •
* I abstract clan RentalCustom.er
{
}

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

* • • • • • • •

*1
abstract class RentalItem
(
private String title = "RentalIt em title not assigned yet";
public float length = 0; II 'public' for demo purposes

I I Static constants
private static final float MAJCRENTAL_ITEM_TITLE_LENGTH = 20;

/ .**********************************
* Intent: Requirement http: // tbd.tbd.tbd#3.2.DVD.l.l
*
* Postcondition:
* If' aTitle' consists of English alphanumer ic characters i n lower
* or upper case, and punctuation marks!, :, ", or ?, then title ==
* aTit le i f length of 'aTi tIe' < = MAX_DVD_TITLE_LENGTH
* otherwise title == first MAX_DVD_TITLE_LENGTH characters of
* 'aTitle'
*1
privatevoidsetTitle( StringaTitle)
/ **********.*********.*****. /
(
I I Check that' aTitle' consists of English alphanumer ic characters in
I I lower or upper case, or punctuat ion marks!, :, " or ?
bool.... charactersAcceptable = tzu8; I I make false when
unacceptable character found
char ch = 'X' ;
fore tat i = 0; i < aTitle.length(); ++i )
{
CODE LISTINGS REFERRED TO IN THIS CHAPTER 575

ch=aTitle.charAt( i) ; // temporary nam e for clarity

/ / !lake ' char act er sAcceptab le' false if 'ch' unacceptable


// true otherwise
charactersAcceptable = charactersAcceptable &&
(
( ( ch > = 'a' ) && ( ch <= ' z ' ) ) I I
( ( ch > = 'A' ) && ( ch < = ' Z ' ) ) I I
ch == ' !' " ch == ' :' " ch = = .... " ch = = , ?• '
);
}
if( charactersAc ceptable )
{
title = aTitle ;
} // (otherwise leave 't itle ' unchanged )
}
}

22.15.2 Code Listing for EncounterCharacter

Source code for the EncouHI"Cha raC' /(rcias in the Encou nter video game (described In t'Cllon 22 I O) is shown
in listing 22 .3. Source code (or all of the Encounter case tud y is available o nline

Ustlng 22.3: Sample code from the Encounter video game implementation
paetaqe&ncounter . EncounterCharacters ;

/* Class Name: EncounterCharacter


* Date : 01/13/2000
* Copyright Notice : copyright (c) 1999-2000 by Eric J . Braude
*/
import java .awt. * ;
import java . to. *;
import Fr . . . .orkRPG . Char.cters . *;

l.mport T•• tOtiliti.s. * ;

/** Base class for the characters of the Encounter game. SOD reference :
• 6.2 . 1
• <p> Invariants: The values of q ua lVal ueI(J are >= 0
* @author Er ic Braude , Tom VanCour t
• @ve rsion 0 . 2
*/
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.
* <p> 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 S77

/** Construct a new character using the given name and image f i le.
* <p > Requirement: 3.2.EC.l.l (character naming )
* @param nameP Printable name for t h e character .
*@param imageFilep Filename, relative to document base, .... for
* character image.
*/
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.
* <p > 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.
* <p> SDDreference: 6.1.2.1.1
* < p > Invar iants: see the class invar i ants
* <p > Preconditions: qualityP is in qualityTypesS(}
* AND qualityValueP> =O
* AND qualityValueP < = the sum o f the quality values
* <p > 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 .
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"mM-
quali 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 ] ; /1 Copy the
string array .
for ( int i= 0 ; i < qualityTypeS.length ; i ++ ) // 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 quali tyTypeS (]

* @param qua lityp The quality we want the value for .


* @ret urn The value of the specified quality .
*/
pub 1 ic float getQual.ityValue ( String qualityP )
{ ret urn qual.Valuer ( inMxOf ( quali tyP ) ];
}
CODE USTINGS REFERRED TO IN THIS CHAP I ER 579

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 .
* <p > 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 q u alityp The quality we are searching for .
* @re t urn 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 .
* <p > Re q ui r ement : 3 . 2 . EC . l . l (limit on character name length )
* @r eturn 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) ,
• <p>Precondition : qUillHYP is a valid me mb e r of qualieyTYP"sll
580 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

* < p > Postcondition: Quality values are greater than tolerance


* orareD .
*
* @pa ram qualityP The quali ty to set the value of .
* @param 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 <tt>true</tt> 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 () , / / Pr int the name , centered
pos P . x - fIR . otrin<J1fidth (getNne () ) /2 , / / at the character location .
poo P . Y - fIR. g e taeigbt () / 2 ) ;
)
e lae / / File name was provided . Draw the image file .
{ Image chImeg. = CompP . q _ tToolki t () . q_ tlmaq. ( jm. qaFile Nep.I ) ;
int Im"ge"idth = cblmoge. getWi dth ( ChUpP) ; / / Raw size of the image .
int ;m" g e Be igbt = cbI_ge.ge taeigbt( compP) ;
int 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 581

if ( fac:eIAftP )
dravP . dravImaqe ( chImaga , // Draw the image a s g i v e n ,
po.P . x - acaledWidth/2 , po o P . y - h eightPixP/2 , / / scaled a nd ce nt e r e d .
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 , / / scaled and cente r e d .
pooP . x - scaledWidth/2 , posP . y + heightP i xP/2 ,

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 .
* <p > 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(= O. Of ;
f or ( i nt i = 0; i < qualityTypeS . length ; ++ i )
s . - + = qualValueI tiJ ;
return aumM ;
}
} // e nd of En cou n te r Character

22.16 EXERCISES

I In your ow n ,.,..ord, . des r ibc w hat 1 mea nt I y codt, bl.'lIl g "correc t ..

2 Sup po c that you arc about LO code a method W hat .1fe tI'll' ma lo r .;;ourcc:~ dc . . cnbmJ.: fo r you what
th l< method IS to do)
3 Provide an exampl of a domain lac; . a de~ l gn cia.;;,. Jnd an Imp!cmCnt3ltOn ciao;, thal nll gh t be
used ,n the Implementat Ion 01 a bank AT 'I applICatI o n E,plalll why yo u t ho," "aeh cia"
4. Spec ify the '" tCOl , preco nd Iti o n" an d pO~lcon dtt1 0 'h or J (unCtto n th at o m pU lt ... the sqUJrC roo t
of an tn put pa ram eter x
582 CHAPTER 22 PRINCIPLES OF IMPLEMENTATION

5 Explain why Ihe u c of globa l vari.bles works "8alOst the princIple of Inlormatlon hid,ng. C,ve an
example of when this can lead to program errors.
6 . The following functIon returns the correct value, but violates one ol tho implementatIon practIces
described in this chapter. Which llnpl emen tatl on practice is vio lated, and how mlllht II lead to a
problem 10 the future ) How would you Ax the problem)

/ / compute amount of interest and return


float computel nt erest ( float balance, float interestRate)
{
/ / compute interest earned
balance = balance * interestRate;
return balance;
}

7. Describe two to four advantages and one or two disadvantages of enforcing coding standards.
8. For each of the error handling methods described in Section 22 .6. I give an example of when it is
sensib le to use the method.
9. What does the following function compute) How would you modify the function using commentS
and more descriptive variable names to make it easier to understand its purpose]

int compute ( int a )


{
int result = 1 , num = 1;
while (num < = a ) {
result *= 1;
num++ ;
}
return result;
}
II Intent : Compute the factorial of the inp ut parameter
/1 Precondition : 0 < - factorialNumber
II Postcondition : Return facc o cJalNumber!
inc compuceFactorial (inc factorialNumber)
(
inc current - 1; factorial - 1 ;
klhile (currene <- faccorialNumber) (
factorial -- . current ;
current I I ,.
)
return factor 1a1;
}

10. Describe how the pnnciple of "Enforce Intentions" leads to improved code quality. Provide at least
three examples to support your answer.
BIBUOGRAPHY 583

II . ChOOR thr<c of thc "good practices" listcd in th is chapter and dc<cribe exception.1 situations in
which they would not apply

12. Code is rarely perfect. Give thr<e criticism of the code in the case srudies.

Tf".M EXERCISE

Impiementatien
Implement key pans of your application to fonm a protOtype.

BIBUOGRAPHY
I McConnell. Steve. ~CoJ( Co",pklt A Pru cllclll Haltdboot of ~ff1DQft C (trlSlfllchO,. ... 2nd Ed, MICrosoft P r~s. 7004
2 Horstmilnn. Cay. S . "Pracli(AI ObJfCI-Onrnltd DAAlopmrn l 'ft C++ Q,J JUIlQ ," John Wiley & Son\ 1997
.3 Ambler, Scon. "'J1x Objt I Pnmcr TIx Appl,(D!!O" DnlfWP<r'Sew/de /0 Ob)re ! OnC"lla lloltold 11)( UA-lL. " Cambndgc: Umvcl"SllY Press, 2001
.. ~mm~. Erich , RIchard Helm, Ralph Johnson. omd lohn VII S\ldC'S , Drug" PlJ /tCrrtS Elnnm's 0/ Rrusablr Obj«,I-Onntltd Sojhr,m," Add ''ion.
W<slcy, 1999.
S Ambler. ScOtt WYIW ambY'i.oh com ( 1999) [acc('s'icd 1211 3/09 ].
6. Oman P ,J. H3~c:mC'l s tc:r , ilnd 0 A5h,·A Defi nition ~nd T;uconomy fo r Soh\\';:,rc: rvblnl alOab,hty · Unl VC,TSlty of Idaho, M o~co .....
Soh~rC' Englneenng T est l..1bor.. tory Rcpon ,,9 1-0B-TR, 10 838-13 ( 1992 )
i Sooch, CrJdy, J.. mcs Rumbaugh , Iva r J.. cobso n, "Tht Upujied 1\loJcl'Plg UtPl91Ul!/' Vu, C',lIde, Addl.son · We-sI~' Pro(~( lo n.ll. 2005
8. Eclipse ProJC'Ct hnpJIWW\Oo' cc1 ip'C orglcdp-.ch ndex php faCCC55cd 12/13109 ]
9. Opc:nOfllcC' Project. hupJ/www .openofficc.orsldev_docv rourcch cmpl.ltc:Vcodc t acc~~d 121 13/09]
10 OpcnOrfice Devd o pe~ GUide hupll",·,k. 'iC'rv l C~ opcnofRet: o rg/""lk aIDoru mcn m ion/OcvGuldd Opt:nOffice o rgJ)cvdo pel"S_
(",ude (accessed 12113/09).
II OpcnOlfkC' ProJect. hlLpJlapl .openof ICC org/(()Urcc/bro"" (d a pJ odklexa mpINlOcvd opcrsCuid prcadshcctNlcw mplc j.wa}
rev: 1.3&content .lyJX= tclt1!vnd. \',ewcv\ ·mol rkup (accesscd 12/ 13/09 ]
uality and Metrics in
Implementation

• How do you assess the degree of


Plann ing sufficiency of an implementation ?

Maintenance • How do you measure the degree of


robustne ss?
Testing
The Software • What metrics are there for flexIbility?
Developmen t
Llle Cycle Requirements • Reusability melrlcs? Efficiency?
anatysis Rellab;;;ty? Scalability?

Imple'ltlntatlon • How does one assess the degree of


security of an Implementation?

Oesign • How do code inspections Improve code


quality? What about code revIews?

• How does pair programming Improve


code quallly?

Figure 23.1 The context and learning goals for thiS chapter

The qUJ IIl y of an implementation can be mea urcd with attribute,;; SimIlar t those 1I cd fo r asc:;esslI'g J
design. The fi r I p.u,- of thl - chapter descnbes these attribute, The second di!. us "-s c de In .. pc lions an
c.-rfCClivc qllillllY process (o r discoverin g defects before code 10;; tested A~ u ~lIal . 010 t mctric~ dC'S nbt'd bel \\'
are mealllngful onl)' 111 th e context of co mparati ve dal') (rom pa')t proJect'i.. In Jddlt lo n. eac h me tric is most
effective whe n used in co njuncti o n with o the r mctncs rJth e r th"n by It elf
QUALITY OF IMPl£MENTATlON 585

As menlioned in precious chapter<, there are two ides to assessI08 the quality of implementations. One
is the IXrifica lion side, in which quality is assessed bosed on looking at the source code. This chapt.. d ISCUSses
the ""nfication side. This IOciudes code inspection , the subjeCt of the second part of this chapter. Included in
that part is pair programming , a klOd of r.o nllnual inspection favored in agile projects. The other side of
Impkmentation quality is an asse sment of the completed code . That side is ualidalioll-essentially, tcstlng-
which IS the next part of this book.

23,1 QUALITY OF IMPLEMENTATION

The qualities of an implementation Ca n be categorized as shown in Table 13 I. For each category, the two
cxmmes are captured with a rough scale o n whi ch 0 indicates low quailty and 10 high . More precise
measu~ments for these categones are dl cussed In th is chapter
Some of these qualities support other<, depending on the application For example, robust code is less
sensitive to anomalous conditions, and thus makes applICation morc reliable si nce they stay operat io nal

Table 23.1 Rough measures o~of an implementation


ro;;;- of Rough metric
.. . o ... 10 (maximum score)

IsufIIdency Satisfies all of the design specificatIOns for this element

Will cause crash on any anomalous event


Irobustness Recovers from all anomalous events as well as can be expected

IWill have to be replaced entirely if the design or reqUifements change


Iflexibility AS easily adaptable to reasonable changes as can be expected

cannot be used in other applications

usable in all reasonably related applications without modification

Fails to satisfy speed or data storage requirement


.,
satISfies speed or data storage requirement with reasonable margin

Obviously won't achieve required mean time between fa ilure

IObviously will achieve required mean time between failure


can't be used as the basis of a larger version

IS an outstanding basis for a version with much larger scope

~ not accounted lor at a/l


MCurity
-r,; known manner of breaching secunty IS known
586 CHAPTER 23 QUALITY AND METRICS IN IMPLEMENTATION

robuSlness

I / ,
reliability

I / seal bility /
/
_ _ • flexibility

f/ /--- -
efflclency ~ -- - - - - • reusability

Key: usually competes: . • usually supports: )

Figu re 23.2 Supporting and competing relationships among implementation quali~es

lo nger On the other hand, some of these goals compete The I;oals of reliability and Aexibility often compete
because flexibility tends to introduce Increased opportuni ty fo r error. It is difficult, frequentl y impossible, for
a design to cnJO all of these quali ti es at o nce. Figure 23 .2 shows comm on support and contradictio ns among
them oftware engtneers trade off properties by prioritizing qualities Agile development , fo r example.
places a lower priority on tlex,btl,ty and reusabi lity than o n sufficiency and reliability
ll)c sec ti ons that fo llow claboTOltc upon each of th ese Implementati o n qua liti es .

23 .1.1 The Sufficiency of an Implementation

The suffi 1(tIC)' of an Implementation measures the pcrccntag(' of th e requ irements and design specificatio ns
(lctually implemented . Although we expect to Implement all requirements, time lim ita tions often force liS to
Implement in order of pnority, omitting some. Th e suHicicncy of an Implementa tio n can be calculated from
the fo ll OWing formula (which req uires us to have a completely speCified li S! of deta iled requ irements).

Prr rutnge of detailed requirements thtll nrc implcmol ted .

If the SDD IS detailed, the design speCifics classes and methods. Another measure for the . ufRcie ncy of
an implementJtlon I as follows.

P"cOI'ag , of methods speclfi,d III .he drsig" .bn. arc II"pl",,,,,,,d

A rougher m elfiC is (he followi ng.

PercCllfagc oj classes sptciji,d 1/1 .be dCSlgll fh•• 'lfe IIIIplcmm .,d.

A problem with the laner is how to account for classes speCified in the SDD that arc o nl y partially
implemented .
QUAUlY OF IMPLEMENTATION 587

1 input to the method


a Anomalous parameter value
b. Anomalou> glob.1 variables
c. Anomalous- event variables
2. Asses dependent methods
tcas-ure ex tent of compromise

FigUre 23.3 ASseSSing the robustness of a method

23.1 .2 The Robustness of an Implementation

which it handles anoma lous input ( 1.(, . Input whose fo rm or


An implementation' robuSlu rss is th e extent to
content IS unexpected). In the final .nalySls, the wo rk of an application is performed by ItS methods
However. not every method need to be ro bust ,n every way . Fo r example . suppose that. medicine is highl y
toxic when taken in large quantities. A me th o d that o m pUl es doses for Il must be as Tabu t as r>o~s lbl e On
the other hand, • method that takes input and creates a strong for displayi ng an .utomobtle doc> no t need to
be as robusi. There arc tw o avenu('S (o r aSS'C 55ms th <: ro bustness of a metho d, as listed in Figu re 23 .3
T o assess the robustness of a method relative to It S po tenti al inputs, we in vesti gate th e precondili ons.
Fu'St. we a sess their completeness. In o the r words , we e nsure that every assumption made by the me th o d IS
expressed in the preconditions. \"(Ie th e n as ess whethe r the metho d defe nds against possible vIOlati ons of
each precondition . ConSider, for example, the Rcc/tlIlg/r closs in Listing 23. 1
Ho\,.' robu l is the method t tArrn () 7 Let's assume that we do not want to restri ct [h e size of the ]Jon l
inputs.

Ustlng 23.1: A Rectangle class

/ **---------------------------------------
----------------------------- --------- -
./
poblic: class Rectangle
{

-- - - - --------------
//VARIABLES ====---- --------------
-------- ---- ------------- ---

float area = 0 ;
float length = 0 ;
float width = 0 ;

------------------------ -----
//CONSTRUCTORS =====-----------------------------

/* ******************************** *****
./
public Rectang le ()
/********************.***************** /
{
}
588 CHAPTER 23 QUALITY AND METRICS IN IMPLEMENTATION

/ *********.****.***********************
* 1 public Rectangle ( float aLength , float aWidth )
/ ******************.*******************;
{
length = aLength;
width = aWidt h;
}

II METHODs ------------------------------==========
------------------------- - -- --

/ **************************************
* Preo:onditions:
* (l) length > = 0
*(2)width > =O
*
* Postcondi t ions:
* (1 ) area == length * width
*1
public void setAr ea ( )
/ ************************************** /
{
area = length * width;
}
}

Note I , The first question is whether the preconditions are complete. In view of the stated desire not to
restrict the values of 1'''9th and Ividth , the preconditions appear to be adequate. (One is not always com:ct in
onc's intentions. bur the point is thal the y are documented and so ca n be revisited . Undocumented intentions,
o n the other hand, lead to confusion and greater errors.)
Note 2, Next, we assess whether the method allows a reaso nable recovery if the precondition fails . Since
there I no provision for this in the code, the method's robustness is compromised. A check on 1"'9th and width
that leaves a'ta unchanged, and that generates reasonable notices, would elevate the method's robustness.
listing 23 .2 is a more robust version of RtctaH9l,. It restricts the values of fields to what is intended, a
practice that usually makes computing more robust. The objectIon In Note 2 above is also addressed.
Nevenheless, listing 2 is still subject to critICisms, which arc discussed below

Ustlng 23.2: A more robust Rectangle class

1* *--------------------------------------------
---------------------- --------------------
* Rectangle class, including safeguards for limits on area
*
* Known Issues:
* (1) Limits dimensions to floats, not double.
QUAUTY OF IMPlEMENTATION 519

• (2) See known issue (s) for indiv idual method (s) •
*1
public cla . . MoreRobustRectangle
{

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

I I Class invar iant (i ntent: the corresponding area is limited) :


I 1 0 <= length && 0 <= width && ( le ngth * width <= Float. MAX_VALUE)
private float ar ea = 0 ;
private float length = 0 ;
private float wid th =0;

II CONSTRUCTORS ====-==--------------------------
- -_ ._-----------------------

/ **************************************
*1
public MoreRobustRectangle ()
/ ************************************** /
{
}

/ **************************************
* Intent: Robust constructor
* Postcondi t i ons :
* ( 1) If the class invar iant is true, length == aLength && "'idth == aWidth
* (2) Otherwise
* (ilamessagehasbeenloggedtothelogfiledescribedinErrorUtility
* stating that the class invar iant was viola t ed and
* ( ii I the same message appears on the console
*1
public MoreRobustRectangl e ( float aLength, float awidth )
1************************************** /
{
if ( c lassInvar ian tHo Ids ( aLength , aW i1th ) )
{
length = aLength;
width = aWidth;
}
.1..
{
I I Postcondi tio n (2 I
Str ing error Message= "At tempt i n RobustRectangle ( float , float) " +
" to use values that make the ar e a too large . Ignored ";
EuorUt ility . 1ogAndRepoltToConsole ( er ror Message ) ;
}
}
590 CHAPTER 23 QUALITY AND METRICS IN IMPLEMENTATION

uETHODS -
// 1'1 ------------
- - - - - - - - - - - -----------------------
----------------- - -

/ **************** •• *******************.
* I ntent: A single locat ion for checking required class invar iant .
*
* Returns: true if the class invariant would b e valid after construction
* with length == aLength and width == aWidth; false otherwise
*
* Known issue: Does not deal with aLength > Double. MAX_VALUE or
* aWidth > Double . MAX_VALUE
*/
classlnvar iantHolds ( float aLength, float aWidth )
priv.at. boole'n
/ ************************************** /
{
/ / Create Double form to allow check on product of floats
double aLengthDouble = ( new Double ( aLength ) ) . doubleValue () ;
double aWidthDouble = ( new Double ( aWidth ) ) . doubleValue () ;

/ / double form of Float. MAX_VALUE


double floatMaxValue = ( new Double ( Float. M.l'.)CVALUE ) ) •
doubleValue () ;

return
(
aLength >= 0 &&
aWidth >= 0 &&
aLengthDouble * aWidthDouble <= floatMaxValue
) ;
}

/ **************************************
* Precondition : The class invariant
*
* Postcondition: area == length * width
*/
p"'lic void S e tAr e a
()
/**************************************/
{
if( classlnvar iantHolds ( length , width) )
{
area = length * width;
}
ebe//Postcondition (2)
{
StringerrorKessage="Attempt inKoreRobustRectangle .setAreaC) "+
"to use out-of-bound value (s) • Ignored" I
ErrorUtility.lOgAndReportToConsole( errorMessage);
QUAUlY OF IMPLEMENTATION 591

}
}

/* •• ********.*.*.**********************
* Precondition: The class inval iant
* postcondition: length -- aLength
*/
public 9OJ.c:l setLength ( float aLength )
/ ************************************** /
{
/ / Safety check on the precondition
if ( c lassInvar iantHolds ( aLength, width ) )
{
length = aLength;
}
.1 . .
{
StringerrorMessage="AttemptinMoreRobustRectangle . setLength() "+
"touseout-of-boundvaluefor length. Ignored";
ErrorUtility.logAndReportToConsole(errorMessage) ;
}
}

/**************************************
*Precondition:Theclassinvariant
*Postcondition:width==aWidth
*/
public""ic:lSetWidth (floataWidth )
/************************************** /
{
//Safetycheckontheprecondition
if(classlnvariantHolds(length ,aWidth ) )
{
width = aWidth;
}

{
StringerrorMessage="AttemptinMoreRobustRec tangle.setWidth () " +
"to use out-of-bound value for width. Ignored " ;
ErrorUtility.logAndReportToConso le (e rrorMessage);
}
}
}
592 CHAPTER 23 QUALITY AND METRICS IN IMPLEME NTATION

A metric (or each method, No ro bustness = 0, , o me = 05, comp lete = I


A metnc (or classes

L (degree o ( method 's robust l1es< on , ca lc o( 0 to I )


"I/II!III-GJ
Number o( meth ods

Figure 23.4 A robustness metriC for classes on a scale of 0 to 1

A metric (or the ro bustness of a block of code IS shown in Figure 23.4


Let's calculate the robustness of tVIortRobll5fRcclaligit This class has six met hods (we Include construe ·
tors). The null const ructor is guaranteed to leave all va lues zero , so it respect the class In va n anl, and is robust
The cbcckiHvariaHI() method is rob ust The r«t of the methods check o n the precondition but do nothing If
the preco nd itio n is not valid. We can give these the score o( 1'1 . The formu la In Figure 23.4 thus yiel ds the
follOWing robustn«s measure fo r RobllSlRccltmgft.

(I + I + 1/ 2 + 1/ 2 + 1/ 2 + 1/ 2}/6 = 67%

It is considerably more robust than RtCldHgit , which has a low score

23.1.3 The Flexibility of an Implementation

An implementation isjb:ibft if it can easily acco mmo date new o r chan ged requireme nts. Figures 23 .5 and 23 .6
list impl~mentation techniques that increase Oexi bihty .

I. Document precisely and th o ro ug hl y


• Reason, cannot adapt code that you do n't und erstand
2. Name constant.s
• Reason , understandability
3. Hide where possi ble
• Variables and methods
• Reason: reducing complexity Increases understanding
4. Collect common code
• As helper methods and classes
• Reason, reduce complexity

FIgure 23.5 Factors In Implementation that increase flexibility, 1 of 2

5. Reduce dependency on global variables


- and on any variables external to the method
• Parameterize methods
• Reason: allows method to be usod in other contexts
6. Program at a general level
• Reason: applies to more situations
7. Use understandable vari.ble and ",nction names

Flsure 23.6 Factoo $ In that Increase flexibility. 2 of 2


QUAUTY OF IMPLEMENTAllON 593

We dlscuSli the~ factors b.:low and subject the code above (or Rob""RtCla"glt to each factor.
I. J)ooooo..1. The idea is that the more effectively code is documented, the more easily it can be reused.
For example, we can still fault the overall ciass description in MortRobusrRtcla"glt (or lacking su(Hcienl
description o( the purpose of a cia ... One could possibly fault the "variables sectIon as lacking a
description, .Ithough none is needed where obvious.

2. Na .., CO","'"I> When constants arc named rather than being stated explicitly, the code becomes morc
eisily targeted to new u~s . There arc several places in the MorrRobu"Rcc"'"9k code where constants would
have improved its flexibility- for example , naming Floar MAX_VALUE as J\W...ALLOWABLE...AREA.
As another example, instead of the statements
pr ivate float length = 0;
pr ivate float width = 0;
we could state the (ollowing,

private static final float DEFAULT_LE NGTH = 0 ;


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

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

4. Collter Commo"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
of this by collecting the checking o( the invariant in one place, classlnvaria nrHold50. In this respect, then,
the code is flexible.
S. R,d." D,p",d",cy 0" Clohal Variahh This means that each method and each class sho uld be self·contained
so that they can be mixed and matched .
Perusing the methods o( Roh.,rR,c"'ngl" we sec that the o nly method referrin g to an attribute of the
class is "fAr,aO, which refers to arta . In pnnciple, we can eliminato arm as a variable, elImInating "tArtoO
and introdUCing 9,rArraO that returns the area . This is an improve ment in Rexibility , but it could coll ide
with another quality, efAciency . lf the applicatio n requires very (reque nt use ot arta , II may be preferable
to compute it once and refer to II often .
6. Program C""rically Here we ask whether the code is at a suffiCiently abstract level to be usable for
additional or changed reqUIrements. It is possible to approach thi S at the de Ign level by u ing abstract
classes, but our focus here IS o n impl,,",n rafion flex ibility Flexibility depends o n the directron that an
application is taking. For example, if this class is to be part o( a 3D appli alion, we ma y want armO to
compute the area on the mo nitor o( a rectan gle m space , een at an an!;le-that is, taking perspective into
account. Thi s is a rar more generi c computJlI on.

7. U" U"d",,,,"dahl, Varlahl, and Funcrio" Nom" In d,scu sing Rexlbilrty , we indl atcd that vanables and
methods must be understandable (or the code to be Aexlble. In f. t, the very name 01 a va nab le or method
is an Imporlant way of makIng it under<tandabk Names ,hould be as expliCIt a po<,ible witho ut
becomml! cumbe r;ome. Fig ure 23 .7 sho ws examples
594 CHAPTER 23 QUALITY AND METRICS IN IMPLEMENTATION

Poor Betler Bcst


Ome dally Dosagc ma xDady D(J,age
mOO ", InOailyDosaJ!c
o mmonOa Il yDo <ogc

Figure 23.7 Naming vanables to Improve code quality

Table 23 .2 Metncs for vanous attributes of an Implementation


Attribute Metric

1. Degree of documentation a) Percentage of comment lines


b) Percentage of commented lines
2. Extent at named constants Percentage of numerals with names (see Note 1)
3. Hide where possIble a) Standard deviation of class size (see Note 2)
b) Standard deviation of method size
4. Degree to whIch common code is collected percentage of repeated code paragraphs (see Note 3)
S. Degree of dependency on global variables a) percentage of public fields
b) Percentage of protected fields
C) percentage of unlabeled fields

6. Degree of generic programming Percentage of generic classes


7. Use understandable vanable and function names Percentage of names clearly difficult to understand

Memes for ro bustness can be ba<cd o n the attributes of robustness. One can mea 'ure Ihem as in Table 23.2,
probably usi ng an aUlOmalcd process, or manually by tak ing rand o m amples from the code base. (Counling all
Iilles manua ll y IS usuall y impractical).
The foll owin g elaborales o n Ihe ,nd,caled points in Table 23 .2.

OlC l One look for plain nllmbers in the co de and counts thost· not prescnt in a definition,
such as " 135" in the following :

final int TANK_CAPACITY = 135;

Note 2: H igh standard dev ia ti o n means high deviation fro m the average. Measured over a
large number of classes, a deviatio n higher than the usual mean s an unusual variation in class size.
This IS no t necessarily bad , but It docs suggeSl Ihat Ihe largeSi and small«t classes should be
reVi ewed, focusing on their size.
NOI" 3: One considers paraKraphs of code, sclecled al random , and delermines the
percentage of paragraph that arc repeated al leaS! once (or ., leaS! Iwice, etc.).
NOIe 4: The hIgher Ihe perce11lage of public fields compared wilh the normal percentage,
the more global the variables.

23.1.4 The Reusability of an Implementation

ReusabililY of code is the capacity for ilS use in other applications. Making a componenl more Acxible usuall
makes II more reusable. ReusabililY is pOSSIble at the method, class, and package levels, although the method
level is usually lOa granula r. To make a class reusable , the follOWing factors are considered .
QUAU1Y OF IMPLEMENTATION 595

Table 23.3 Metnes for reusability


Attribute Metric
, The matching of classes to a real·world
Percent of classes that clearly match an understandable concept
concept (see Note 1)
2 Level of abstraction Average number of Inheritance levels from a class In the Java library
(see Note 2)
3 oegree of desCriptIOn Percent of classes that are clearly documented (see Note 3)

1 lllC matc hin g 01 the dol" to a rc.,l . wo rld c o n '-.:pt


. '" Important, ot h ('rwI<;<; d cveiopcr'!i arc unl,kely to
1I I1d<,'r.;(J nd It

2 n,c levd of abSlroc ti o n ,hould be h Ig·h Cnollg'I to (OVer many app IK3tlon .. but low enough to allo,",!
sub,tanct' F• r example .f a dev <.:-loplll cnl organ ....... Jtlon c rc;)t cs m,uran C Industry appl, i)llon.;; the: lc.:\c\
of a cia" (IlJtllacEldoradol",,,,,,,,,,Poll . " probahly '00 10\\' and I'0 II t)· ,on h Ig-I1 ali Idr L. Jo;; feU.,a b I I Hy I!l-
on erne d An A"'omol,,I,Poll~ -J cia ...... , 0 n ,I lC· 01 Iler Ilan d \\ ou I(I b C .. ub ... tan ll VC and probJbl y reusable

3 The reliability of code pr mOlC''' rcu(,Jh.hl}' Olhcrwl'l: "0 nc IS Ilkelv to reu<;(" the Ill". It .. hould
contain o mplctc (rror dJeckltl9 . for example In a ') orncwhal Circular proce .. :, c1a"~<..·, that 3re wldc;iy u.. ed
become tN"ted and under-load and thu, morc' wldelv reu:,cd

.Metnc", for rt'us(lblilty can he ba,ed on the attnhule, of rcu,anlil tv Onc an mca!>urc them.J!> In Table 23 3
based on an automated process or bv manual random !>arnpk.. takcn from the code bJ~e ( unllng allltnC~
manually IS usually ,mpra IIca l)
late I This an be calculated on a r.lndom sample: bv laking a vote among tnspector~ for example.'
Note 2, Thc hI gher lhl' number thl.' more hkel}' th<..' cla~, JI1 be reu!> d
NOte 3 The bctlcr a las, I~ descnbed , the mon; Ilkelv It p. to be rCll'loablc Scttlon 23 1 4 dc, nl cd
measures of documentat ion , 31ld lho,c can be used here tOO

23.1.S The Efficiency of an Implementation

Recall that there an: ,\,' 0 kind, of cfflCl<:nc}' prot.:e." 'peed and ,tOr.sgc U'loC Elhcl<..'nC)' requlrl'ment, Ill:l) or
may not be <'peclhc..'d 111 the RS For cxampk. suppo;;;e that on<..' IS specifYIng the reqUirement, lor a Jicndar
appltcatton one should "pcClfy tlml· Illnlb su h a, the appllcJtlon wtli reSl.'t all calendar, \\,.th ne\,'
apPo intments \'lIlhm V. econd \Xlh en crfIClenc ' n.:qll ...emenl<\ Me not ... pe Ihl'd \vc apply Lommon ..en"c
hmns as bcst we can Neither Pi) (' nor runt 15 unlimited In praulce ror (:,,(Jmpk a \'(Ieb '1((: ,hoppln~ Glrt
appltcallO.n may not <,pC'clfy maximum d lay . but It I' ommon o,enw that the uwr .. hould nOt walt more than
a minute for a c redit card approval. excluding Internet dela s
An appropnau: metriC for ')peed dh I('n )' 10, the fraction 01 the ,peed required For C""(ampll' It .111
appilcatlon I:) requ ired to proc.c" J transaC110n In at I1lO,1 half J , etand but Jctually take ... two !>cc.ond.. ,q: an
fairly ~ay thallt<, dr,C lcncy m<'a .. urc 14\ YJ 12 :=25 % It all applicatiOn "cn' t~p;;tcr th an rcqutr ct , \'1.'(.' l,o,' Olild .. lIli
hkc to be able t measure Its ')pccd cfl1cll:nt y The sam fOnl1UlJ i.1pplle" ~'I example If du: appJt Jtl 11
prcxC"Sscs transac..tIOI1' In onc quarter second on avcrag<.:, then II'- CfflCI~IlCV mca .. ure wou ld be ~ I/. ~OO''tI =
It ha~ high 'lual,lY In Ihl,) rc.;pec.t with 100~... being th<: 'UCLe,' ba" Itne
An appropnate mctrt<.. (or c;paLC dh lenLY I' Slm.iar l or CXill1lplc .f an appliCatIOn I" required (I') lI'C no
mOrt. than 2 Hi o( dlc,k \PilCC hut ust's 5 {\ IB th en we (.;Hl fillrlv .,ay tllill It .. ':!orac..e: cfh ICIlCy I~ 2. 10 . IKe:
aJ(aln the (om1ula appll(,'t even If 1I,a~~ excced, requirement .. rorc'(a l11 pll.', If til app llL3tlol1 \,'ere LO U'C onl\
1 MB we: would rate " .. ~loraHc u<\c clflLll'n y a.. 2,' 1 20('''l
596 CHAPTER 23 QUALITY AND METRICS IN IMPLEMENTATION

23. 1.6 The Reliability of an Implementation

ReliabilI ty j , a quality lhat goe< funh er than sufflclcncy and robu, tnc. <. To ' rel y" o n an ap pl.ca ll o n I ~ to be
sure fil"'i t that It docs ,~hat it is supposed to, th iS Include sufn leney, as desc nbed above Rel ,abil ity can be
o n<ldered , 0mClln'es to include robu<tncs<, where the applicatio n behaves appro priately In the pre,e nce of
ano malous Input. An appli c~tl o n that IS su(Rclent and robust may slill have defec ts and lhus be less than
reliable, however For example, an appl,callo n may be required to add any parr of Inlcliers. eac h betwee n -
100,000 and 100.000 It can be sufficient in that It does the job reqUIred and robust ,n Ihat It dIsplays an error
message fo r an y Input nOt an Integer between - 100,000 and 100,000 . However, If the applicallon crashes
aher successful I), computing add itio ns for an hour (perhaps because of unco ntrolled memory use). II IS no t
reliable. Defects affecting reliability arc found by inspection and testing.
The mo,t commo nl y used metnc for reliability is the ",,"II 1"71' b,lw«7IjQl lu" (MTBF) T o measure {\'ITBF,
o ne fi rst defines "fai lure " T YPicall y, this means that the appli cation has to be reStaned Run the application
several times, fo r SIgni ficant durati on , and calculate MTBF as foll o ws:

MTBF = (tolal time up and running)/( number of failures detected In that time)

23 .1.7 The Scalability of an Implementation

An implementation is .ca fablt if it is sumcient for all reasonably anticipated homogeneous growth (i.e ., growth
In the same general direcllon as itS current capability). For example, a melhod that slOres dal. may work well
fo r a data rate of one record per second. If the maximum anticipated data rate is 1,000 records per second, the
method's scalabrl lty IS effectively its adequacy for Ihis growth requirement. We inspect and test the method
With thiS in mind as soon as possible. Inspection and lestlng for scalability have limitations, however.
Scalability can be di fAcul1 10 assess through inspections; early testing at the required scale can be expensive or
even impracfical because of the work reqUired to create a scaled-up test structure.
Scalability melrics measure speeds and data storage to these simulated or accelerated cnvironm~nts

23.1.8 The Degree of security of an Implementation

Applications often include or are connected to networked pans. T he parts may be components of the
executing code (as with Web Services, for example ), they may consist of distributed data, Ihey may consist of
a downloaded Web SIte, or they may simply be accessible through the Intemet or another ne(Work. Often ,
some of the data are confidential For those reasons, security is a significant co~sideration . Consider the
simple example of logging in The application checks Ihe user's 10 and password before allOWing access. We
will assume that these data must reside on a Ale situated remotely from the application . This scenario raISes
many security questions, as listed in Figure 23 .8.
Recall that security considerations can be divided into categories. We can base initia l implementation
metrics on these, possibly weighted, as shown in Figure 23 .9, measured for every unit of code for example,

• StOre IDs and passwords wilhout allowing unauthorized access


• Ensure that data go only to authonzed requesters
• Design so that security is easily maintained a application e"olves
• Isolate security-.ffecting c1asses7

Figure 23.8 Security for Simple Login example


CODE INSPECTIONS AND RELATED QUAUTY PROCEDURES 597

, ConAdenliality, I\t a ure by degre f d' fA I '


e 0 • cu ty: ga'"'"9 J'lallow,J aem, 10 i"Jo""allo.
, onr'Cpu d latlon: rrpud'"li"9 a9"""""
,Integrity, .. IIlrmug Jilin ,. Irll""', u.d"rrI,d
,Authentication· .. urnJY"'9 idnllily
'Authorization. .. 9"i.'"9 di,allowrd IIUns 10 II /ocalio.

o = tasy, t = !'fol rosy but C'onCtipabltl 2 = flol Co"ctivablt

f1Sure 23.9 Metrics for security-hlgh·level metric using security attributes

on classes and relevant methods. Although this categorization helps, the nontrivial part lies in assessing the
liability of the implementation to each kind of security b..ach.
The d ifficulty in assessing the degree of security of an .mplementation is conceiving of breaches. The
' not conceivable" category of Figure 23 .9 does nOt necessarily imply that breaches are impossible merely
that the evaluator cannot imagine one.

23.2 CODE INSPECTIONS AND RELATED QUALITY PROCEDURES

The tOp.c of inspecting project artifacts was covered in general in Section 6.3. Now we will describe a specific
process for inspecting code
Code IOspections are an effective tool for producing high-qual ity code. As with other artifacts produced
during development , code is reviewed by a team of peers whose goal is to identify as many defects as possible
of as high a severity as possible. Inspections are typically conducted after a segment of code is written but
before it is unit tested
Before code is inspected it should be d"k-ch,ck,d by its author. This entai ls the developer reading the
code looking for syntax and other obvious errors. There is no point in having others examine your code if you
haven't carefully looked through .t yoursel f. The code should compile with no errors or even warnings; if it
doesn't, there arc obvious errors that need to be fixed befo .. inspection .
Oner desk-checking i complete, the inspection process commeners. The author distributes the code to
a group of reviewers Sometimes an overview mee ting is held before the actual inspoction . The goal of this
type of meetlOg is to prescnt an overview of the code, presenting its layout and the overall design This helps
orient the reviewers and provide persp<Ctive whi le they read the code .
The team next prepares for the inspection m~cting by having each inspector read the code looking for
faults . The" Rrst POlOt of focus .s to verify that the code exh.bits the qualities listed in Table 23 .1, to the
extent they arc spec.fied in the requirements. In addition , an effective method is to usc a chICk/i,', which
includes speciAc errot> 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 )


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 COllfitlllC statements ,,,ark correctly]

o 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 599

• 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 contlnuously-
rssentially 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".
1. L.,.Ist . I" your own words, describe the meaning 0
each quality
.le ICHC')';an d , ,"'abil,ty
2. Ex p Iatn h ow C)J1( I
can >o me t'mes

be compe ting Impl ement all o n qual ities
an example to ,upport your a",wer
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

• What Is refactorlng?
Planning
-- • How does ref acto ring work at large scales?

• !-tow do you relaelar at the method level?

The Software • Can you reorg anize classes uSing


Development refactoring? Reorganize data?
LIfe Cycte
Requirements
analysis • 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?


Design
• 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.,
conc;,dercd ac; 500n as c;oftwarc:: eng inee r, hCg'l n writ ing co de, andI n cc; , cnlIJI p ~lIt 0 1 010" J ~ dc.: approa ht.· ..
Ie;
R.facto n "j( wa, In trod ULcd 10 a wl dc all d, e ncc hy I uw le l "' IllS la'<le hook I t J
All dc"gn volve,. and 11,,\ " e'pcc lall y lru" lor , o(l,. arc prO)CC h In lhe pa" " ha, o flen n t be n
dftctJv modify ('od very mu h J~ n~cd, 'vulvt" H owever ohJect-orl e ntJtl on , IInprovl-d dc vl'l opm l"nt
li)
enVlfonm nt~. and, f.:\pt: 1;)lIy r diJtlUn rl ~ have m.1 u · d11 \ Incl cil "tlo glv ffCCll vC
P(rhap\ the: \Imple\l dlU"t tralive e Xil llll11 C QI rC'fa((() lI og I" r(nalll/utl In w hl h th e n J Ol t 0 1 J va n ahl e-
'ndu dtn ~ a di1~~ n r pa(,k.a~C' name: an be ( hange d ~ l n" t devel opm ent cnvlro nmcnh allfo m.1l C n..· n ~ l1\ln ,.; 01 ..
602 CHAPTER 24 REFACTORING

d" u"cd below Whe ll Ihe Ilame i, changed , all rclerc nce> to It except for comment< arc automallcally
hanged Jt the ...amc time . Bef ore renamin g be ame Jvailablt", nanling a variable \vas, in practice, an important
declsloll Ihat became hard to aller o nce made and used for a lime If he o r , he wanted a new variab le name, the
pros"rammer was often o bliged to alter so man y occurrcn c: o f th e name 111 multipk- classcc; that it was seldom
worthwhile 10 carry out for a large program . Naming variables is jus t as important J~ In th e past , bur the ability
to rena me vlftually at will has freed some progra mmer time . Ild allowed new flexibililY ·
What fo llows is " second examp le that demo nstrates the tl.vo r of refacto rin g. It IS called "Promote
At'tTibu l C to C lass ," and I use d to co nvert a implc attribute in lO a class . To accommodate the increased scope
of an applica ti o n, we ofte n need to introduce ol new class to replace an att ribu te. Forcxa rn ple , suppose that we
already have a class Au!omobilr w ith inregcr attribute milragr .

class Automobile
{
int mileage;
• • • •
}

W e may decide later that "mileage" for used automobiles, however, is substantiall y more involved than a
si ngle tnt va riable. For example, the auto's motor may be a replace ment , resu lting in a m otor mileage different
(rom a chassis mdeage. In addition , if our application is required to account ('Or fraud , the reported "mileage"
would have to be modified by other attributes such as whether the car had ever been stolen . For these reasons,
we would consider the "Promo te Attrib ute to a C lass" refactoring. Th is would involve introduCing a Millage
class like

L1stl ng 24.1: Mileage class-promotion of mileage field

class Mileage
{
int nominalMileageValue = 0; 1/ shown on odometer
int chassisMileageValue = 0; / / best estimate
int engineMileageValue = 0; / / best est imate, account ing for
replacement
• • • •
public int computeEffectiveMileage () { . . . } / / to obtain estimate
}
class Automobile
{
Mileage mi leage ;
• • • •
}
REFACTORlNG 603

t Rc"",,"o f Il!ld '"


r~

, .
• · o · q. · -.-- ShiftlAIVR
n -.- 1 • •

• __ lie ~~ ••• [ m~lo,ee I


5tr1DQ ~;
I

( e.G I

~n.llM h e ld fEJ
~n21 ~
I M~~~~J~ _________________________ ,
• . j...." (chp"' SDK
!!IUd ·atefewas
O' to''t? tutu.! OCCIITCII"U1 n CGif'!'lel"'(:S 4I'Id st1n;s (forcfS PNIC") ~ · o · <:. .

pula..l..l. c:: c:.l..... tl::lp l o yee. I


StrlDQ ~_;
I

t PreTES )o I( II C..... I
Figure 24.2 using a refactoring wizard-an Eclipse example

Dependi ng on thc progre s of ,hIS appkatlon , eve n the cia S 1\'11/"'9' could be conSIdered worthy of
furth .. refactonng--fo r example . b). extracting ' o me of ItS properties IntO scparate types 0 mdeage classes.
Anotherdi reClion for refactoring I to extract Interface< for it so that lienr code (code that u cs It ) can as ume
that It possesses a given set of method signaturcs such a compu/,Eff, /Il',AI'/<a9'()
Some rdactorin gs are computer·asS! ted This u ually takes the fom, of a "'IZard that interact with the
programmer. Almost all interactive dcvdopment environments are eqUipped With several u h re fac tonng
wlz.rds. For examp le to use Rnla"" In Eclipse, one can place the cursor on the vanable (,n thIS ca e namrl and
press Shilt/Alt/R. The user IS then ho,,' n the window seen In Figure 14 .2 for the entry of the new name ( 10
this case n"m'_ ). The wizard automa ti cally makes thIS change throughout the application exce pt within
comments.
The rest of thIS c hapter Introduce many of the rdactorings descnbed by Fowler, a well as an additional
one, ln/roduCing Mr/iJod, ID Es regularly Include ncw refa tonngs, and" IS a good Idea to explore the e be Id~
the refactorings in [ I ). This chap tN I Intended to !l'VC the reader a ubstantlve taSte for refact o nn g and to
place II 10 a ~oftware englOtcnn!; context
Fowler or!;a ni zc, hI< rda cto ring as 10 Figure 24 .3 TIll' chapter does not attempt to explain all of
Fowld~ refactonngs For example , S,mplifY"'9 LOIIJ,llollal Exp'''!loll and 11101:/119 IIf"J.,d alh ""pI" are n t
<iaborated 10 this book , Jnd the reader IS rderred to r I )
604 CHAPTER 24 REF ACTO RING

I 1l1~ Ref, lOring>


2. ompo IIlg "'et hods
love Features between Obje t,
4 Orga nize Data
5 Dealing with Generalization
6. implify,ng Condi tiona l Exprc sions
7. "'aking methods Calls Simpler

Figure 24.3 Fowler's main refaetorlng taxonomy


Source Fowler ct 81 , RefaC10nng: ImprCNIng the Design 01 EJustJng COde. Copynghl f 1m by Pearsoo Education, InC
Rl'Qfoduced bY petmL$SlOI'l of Pearson Education. Inc

24.1 BIG REFACTORINGS

The refactonng de<cnbed In this section are mai nly at the class level and have more of an architectural impaCt.
They arc thus called "big rdactorings." Fowler describes fou r. 'Tease Apart Inheritance," "Convert rrocedu,"1
Design to Objects: "Scpa'"te Domain from Presentation: and "Extract Hierarchy." Each is described below.
Tease Apart I"brnl."cr can be applied when subclasses of a class proliferate Into multiple combinati o ns, as
exemplified by Figure 24.4 . Effectlvciy, we want to factor the combinations as if convcrting a product such as
9 ( dx3 ) cia ses that describe every combinatio n into a urn such as 6 ( =3+3 ) classes. We do this by
identi fY ing characteristics, which we encapsulate V 13 inheritance and aggrcgation . These arc Em ploy« types
and Sialu, types In the case of Figure 24.4 .
The next "big" rd.ctOring we'll co nsi der, CO,,", rt Prortdu,.1 Dtli9" 10 Obj,el,. is appropriate for use when a
design has not fully leveraged object orientati on by bei ng unnecessari ly procedural This IS commo n for
Inexperienced programmers and eve n for experien ced programmers wo rking in a hurry. For example , as

rJ0 Em~yee
~
<-r
SoftwareEmp MaintceEmp ClencalEmp

I' t..;,. -r'


FullhmeSoftwareEmp FulllimeMainlceEmp FulitimeClericalEmp
PartlimeSoftwareEmp IParttimeMalntceEmp I IParttimeClericalEmp I
IReliredSoftwareEmp I IRetiredM'lnlceEmp I IReliredClericalEmp I

FIgure 24.4 Big refaetorlngs. 1 of 4 Tease Apart Inheritance


SOtJIU Fow\ef tt ai , RefactOf'ln8 Improymg the 0es1iJ"l of ExiSting c.ooe. CoPYTCflI I 1999 by Pearson EOucatloo.. InC
Reot'CdUCed by IJe... II"'O"1 or P~r1On EdUCltion. VlC-
BIO REFACTORINGS 605

.J-0~ ---_--,
IVldeoGame I
stanGamBO
disptayCharactar O
moveCharacterQ I
GameCharacter I

I . '.' t" u

Figure 24.5 Big refactorlngs, 2 of 4-Gonverl Procedural Design 10 Objects


50cIft f(lV.;ier et Il~ Ref.ctOfIng: InlprcMng the DesIgn of Existing COde, Copynght f 1999 by PUrson EdlJCauon. Inc
Rt;400""P\d 1:11' !:rIJssioo of Pearson EducatIOn. Inc

shown in Figure 14.5, a designer may usc a clas such as COH ,ro/ to contro l a vrdeo game (Le., to start and stop
vanouS element of the game). The problem with this IS that cont ro l classes, when needed, should be used to
manage object o nl y by initia ting the" methods, not as a replacement for the work that should be performed
"'rthln an object. When an o bject is requi red to con trol, it should be kept to a min imum : usually a simple,
s,"glr call to a method in an appropriate object that sets off the entire process. Figure 24 .5 shows how
dements of what used to be control, such as mourO, have been relocated to the objects to which they properly
appl y The Instances of CameCharactcr now move themselves . Minimal control ma y sti ll be needed outside
of VideoCame and CameCharacter, but it would in itiate rh o work rather than doing it.
The next "bIg· re(aCloring we'll consi der, Scpnrn tt Domtrlt1 Jrom PrcstH ltJ liotl , is used when a design mixes
control with output fonmalS-ln part icular, when C UI code occurs in the same class as the computational
algonthms or the data repository . For example, as shown in Fib""e 24 .6, a desig ner ma y use a class such as
Accovn' to perform computations but also to produce di pl ay<. Such a design lacks reusability and conceptual

Account
name
balance
•••

displayStandardO
displayHTMLO

:
display 0
Account
nlme
=> balance
•••

display ()

Flcure 2.4,6 Big refactorlngs, 3 of 4 eparate Domain from Presentation


~C4" FQMef 1ft aI RtfflCtOflna imprOVIng the 0esI(I,n Of (xl,lIna Code, CopyTIWlI , 1m by Peirson EOucatlot\, Inc
_CG,,"1d Of PI ''''U'On 01 "UfIOtl E.cSuca1JOn, IOC
606 CHAPTER 24 REFACTORING

Project

=>

Figure 24.7 Big refactorings"-Extract Hierarchy


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

simphcity (ConsIder how comphcated it would be to change just the CUI parts or to allow several displays
for the same account data .) Figure 24 .6 shows how the o ri gina l des ign can be decomposed into the core part
of A CCOIUlt , se parated from classes describing varioLis ways to display the account.
Our Rnal example of a "big" refactoring, Exlmel Hicrarc/,y , applie, when il has become clear that a new or
extended hierarch y of classes IS nceded-in particular, when the classes in the existing hiera rchy are not
refined enough for the task at hand. For example, as shown in Figure 24.7, a designer may use a class such as
PrO)tcl to implement a project management application . We'll presume that the application has become too
soph isti cated fo r a generic project. So, for example, quite different functionality IS needed by software
engineering proj ects vs . entertainme nt projects. As shown in Figure 24 .7 , cXl.Tacting a hierarchy of classes
fro m the original beco mes a needed rdac torin g

24,2 COMPOSING METHODS

The "composing methods" category of rcfactorin gs concerns the process of creating , removing , and
combinm8 methods to SUIt an evolving Clpplication . The various rypcs of mcrhod composition examined
by Fowler are shown in Figure 24 .B. They are e.plalOed bel ow.

• Extract method
• Inllne method
• Inline temp (re move a temporary vanable )
• Replace temp with query (i,e , a function )
• Introduce cxplainlOS variable (to replace complicated expressIon)
• Split temporary vanable (I.e., used more than once)
• Remove assignment to paramel'ers
• Replace method ","h method object

Figurl! 24.8 " Compose methods" refactorings


Sourw Fowter et at . Rotoctot .!IO Improol!l"l8 the OF r,gn 01 ExlStlna ~. COgyr'igtlt I 1999 by Pearson Eclucation. InC..
RepOCluc:td I7f ~6ttmssron Of Pearson Educltion.. 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<quently the functionality involved is needed . As a rough guide, note that the average length of
a method In an 00 implementatIOn is on the order of 10 lines (i.e., not 100 lines). If several methods call
the same block of code, that is stron g reason for ex tracti ng it to a method . When there ar< three such
calling methods, we very often extract as a matter of course. Most IDEs are instrumented with Exrracr
M,rbod.
1.1i., Mdhod refers to the opposite of Exlracl Mrlhod . We replace a ca ll to a method With the actual code
from that method. The occasion to consolidate is reflected by the opposi te of the justificatio n described ,n
Ext,acl M"hod : when a method is so shan or inconsequential that it is simpler to include the code itself instead
of the method call. Another case is when the ove rhead (time 0 ' heap space u cd) of a method call must be
avoided.
1.1i", Trmp refers to the process of replaci ng a temporary variable instead of uSIOg the whole expressio n
that it replaces. One considers this very strongly If, for example , the expression is complicated and has more
than twO tenns. An example is replacing y- (x-z).,,··y by a temporary variable in expression (24 . 1).
[x(y + z) - 'illY - (x - z) + x"yl (24 . 1)

R,placr Trmp wilh aurry refers to using a method ca ll IOstead of a temporary variable. For example , we
might want to save expression (24 . 1) in a temporary variable v and then usc 0 several times, or we mi ght want
to dISpense with a temporary variable and call the method that evaluates thIS expresSion each time we need it.
This would make sense if the variable we usc takes up a lot of space (true for a large data structure but not for a
Aoating point number like the one above). Another factor to consider here is whether or nOt the vanables in
the expression change . The penalty for introducing R,plaCt Tnnp will, a"rry is the time It takes to make the

compuranon.
1.',oduCt Explai"i"9 Variablr is the opposite of R,placr Tnnp will, a",ry. It introduces temporary van abies to
facilitate working with complicated expressions. Although the hiding quality of R,plac, Tnnp wilh Gurry is
usually benencial , it is counterproductive when there is little to hide.
Splil Trmporary Variabl, applies when you use a temporary va riable for purposes different fro m its anginal
One. It consists of introducing one or marc additional vanables IOstead. Cenerally speaking, it is good practice
to us< a temporary variable only for a si ngle purpose.
R()IIov, Alsi9"",rnllo Paramd", nxes the problem of changi ng the value of a parameter this is nOt expressly
designed to be an in/oul vanable. Cenerally speaki ng, it is poor practice to wri te to a parameter unless the
method is speCifically designed for th is, expecting and using the changed values In fact , it 15 usually good
pract ice to make methods parametersji"al (in Java notation) to prevent their use other than fo r the value they
provide.
R,piacr M,'hod W,lh M"bod Objtel is the process of replaci ng a met hod such as dofiliancinlC"lculalionO with
a function call on a dedicated object of a specially desig ned class (Fllla"ela/Calcul.llon ) uch asfinancialCalcu.
la"onl •.rxcCIIltO. The effect of calling ",te.'cO With object filla"ela l alc"lalionl' of a separate class gains
adva~tages when the funCtIonality required has too many effect to be handled conven ie ntly by a simple
functio n call ~I one. Another exa~lpfe is when we need to cou nt the number of times thar functionality uch as
n"ma lcProfilO 10 class SrockH,lprr IS executcd. Instead 01 si mply making " 'II"al,Profil() a method of SlockHrlptr.
we create a class ProfiIE."mnlioli that agsregate SloclcHrlp, •. and we call the method ",mll,O of Projilf>III".'ion
A nn.al.example IS when we want an ulldo capability . If we store the object repreSenting the function , there IS a
pOsSibility for undOing. Otherwise. we couldn't retrieve the funcllon call that brought us to a urrent state and
would be unable to go back.
608 CHAPTER 24 REFACTORING

24.3 MOVING FEATURES BETWEEN OBJECTS

Tim C"I<gOry of refa loring can erns c han ge in lh. placemenl of 10" feature . The,e arc su mmarized ,n
F.gures 24 . and 24 . 10
Atou, '\Itl/,o'/ han ~es the localion of a method fro m o ne las> 10 anolher For example. we may have
cla«c. "'o,"", Book, and O r.h, as we ll as a melhod lhal perfo nn , ordering The app loca"on could be budt
Wilh ",,,ultOr.l,,{&ok aBook ), a mClh od of ( 14" 0"''', However. till> 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" I 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 e"IS'
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,

• Move Me th od
• Trades off method ho ld.ng v<. usage
• Move Field
• Trades off hold ing vs. usage
• Extract Class
• Encapsulate a set of attributes and methods of a class
• Inli ne Class
• OpPosile of Exlrael Class

Figure 24.9 "Moving Features between Objects" refactorings, 1 of 2


SOUIte Fowler ct al... RetiKtCl"II'lg: ImortMng the DesIgn of EXistfng COde, eopJ'l'Iif\l , 1999 by Pe~ Educabon, Inc
Reproduced by permlssIon of Pearson Education, Inc.

• H ide D elegate Hide class dependencie from client classes


• Re move Middle Man
• Opposite of Hid, D",gal,

Figure 24.10 "Moving Features between Objects" refactorings. 2 of 2


SClC.TU rOl-.'" f't II .. RefICtOf'll'W" .iij)fO\ilna tho DI : ii' of Edsma COde, Cov/f1ItIt, '999 by PHrson EOlJCauon. IlC.
AlprodlJt:ed Dv pel,,; ' ['on of Pe.-son Eauc:ation. i'IC..
ORGANIZING DATA 609

;----1
I
Class' I
I
I
Clienl ----.j
I
I
I Class2
I
.. _--- melhod20

delegale Class2
--------
melh0d20

Key: 0; changed delegale.melhod20

FIgure 24.11 "Hide delegates" refactoring


~: Fcw.1e1 et at.. RefGCtoting: ImprovlnE the DesIgn of Exlstmg COde, CoPY'l&ht, 1999 by Pearson EducatIOn. Inc
Re1JOlh'ed by peillussion of Pearson Edutanon, Inc

Climl. Tax preparation

Class2 Personal proRle

Class!. Employer

m,'bod2(). Prepare summary tax page

In summary , Clire l has been saddl ed with unnecessary respo nsi bility. Hid, Dd'9alrs allows Iirnlto depe nd
only on Class2 by aggrega ting Class I to Class 2 (making a Cla sS! objeci an attribute of Cla"2 ). A a result, Grel
now depends only on CIa SS 2.

24.4 ORGANIZING DATA

In the refacto rings of Ih is seclion , Fowler li m Iho e havi ng to do with Ihe location of data in a design o r
implementation .
S'if Elleapsulal, Fitld c hanges direct access of an attribute (c g., pub 1 ic S t ring name; ) to that via
accessors (e.g., pr ivate Str ing name; . . . Str ing getName () . . . ) One would use this
refactoring if one forgets to make or postpone, makin g fie lds private, available o nl y via ac~essor methods.
Using accessors in 00 is generall y good practice becau e it allows co ntrol such as checki ng an as igned value
to ensu re Ihat il is withi n bounds
R,pla" Dala V"lu, wilb Obl,el; A an exampl e, c hange the otlribute pub 1 ic S t ring name to
pub lie Name nam e . O ne wo uld app ly R,pla" Dala Valu, wilb Ob)tC1here when the idea of a name becomes
too complex for Slrill9 . An examp le" whe n it becomes necessary 10 track all parts of a name as well a alia e ,
matTIed nam e~ , and former unmarned o nes.
O,a"9' Valut 10 R,f"rncr b u cd when the va lue of an object's allribute IS beller obtained via a function
(typically, because Oblall1 l1l!! the va lue IS complex) ra ther than ,-.,h an expkll instance or with IIull, as III Ihe
fOllowing example In th e "" version below, the attribute II slon", has the va lue lIull. In the e ond VCrsl n, II
IS a ( " Sl"",,, object created by a "atic mel hod of uSlorna. Thi S ha the adva ntage of entralizlI1l! the rcatlon
of "slomtrobjecls. ",hl c h is often desirable T his advanlage be o me clear when severa l different las e need
610 CHAPTER 24 REFACTORING

ustomtr objcCl<\ In J standard man ner, such liS w h c Tl In'I J nll Jt1n~ a defau lt cu\tomer The undC:"lfable
altcmat ive is to repeat the code that rcates such o bJccts for each of the,e dasse.

class Order { . • .
Cust o mer customer ;
• • • •

• • replaced by • •

class Order { • • •
Customer customer = Custo mer . get Customer ( Str ing • . . . ) ;
• • •

( hul/ge RrfertHce 10 Value IS the opposi te of the previous refacto ring. Thi would be nceded when the
machinery of a refeeellce is fo und 10 be unnecessary. perhaps because the program turns out to be less
comple x than Jmicipated in thi S respect.
Rrplace Array wllh Obi,CI, Arrays have the beneRt of being standard in form and of ha vi ng random access.
However. they arc not as Aexible as specia lly built classes even though both may ha ve essentially the same
contents. When the use of an array loses the balance of its advantages. this rdacto ring makes the convers Ion.
An example is the fo llowi ng.
C hange Company [ ] companiesl . . . . to class Companies{ . . . } . Th is refactor·
ing may be benenci al because there are bener way to access companies (e.g.. why should IBM be
companiesl [3] in particular)). whereas accessing a compa ny by name (e.g .. Compani es compa-
nies2 . . . companies2 . getCompany ( •• IBM' • ) ) may be much morc appropriate .
The preceding rdactorings arc summarized in Figure 24 . 12.
( hal/ge Bid""tlonal Association 10 Ullid",clional, We usua lly want the relationship between classes ( , and ( 2
10 be one-way rather Ihan two -way. For example . ( , refers 10 (2 bUI ( 2 docs not also rder to (, . Olherwise.
we cannot usc onc in another applICation without the other. Ci rcular references are awkward in an)' ca e.
Elllploy« and Em ployer is an example; if the applicatio n is a corpora Ie a ile, we wou ld pro bably want Elll ployer 10
reference Employer. and there may be no need for the reverse. Tho resull is as fo llows.
Em ployer _ Em ployer.

• Self Encapsulate Field


• Change: direct acces or an attnbute to accessor lise
• Replace Data Value with Object
• Change Value to Reference
class Order ( Customrr cuslOtnt'rJ .
,In" O,d" ( pri"at< ( Ul loIII" 9"(""Olll,r(51""g .. )
• Change Reference to Value
• Replace Array with Object

Figure 24.12 "Organizing data" refactorlngs. 1 of 4


souru: Foil! - et ai, Relac:toring; II'I'O't1oMg the oestgn of eo.stin& Codt. COp)'flahl I.. 1999 by P~arson EdlatJOn. InC.
Repf'OO'.JCtd bV LX""h l'on of PeItWl Educ:atJon. WlC.
111

°
CI"'"9' tI,udim:lrollnl As inlioll 10 R,d,rtCliollal is the opposite operation from th~ preceding rdactoring. If
then: i no clear way to e1.iminate the dual asso iation direction e ntirel y, we typically ny to create a third class
to ha.ndle the relat,onsh,p . An example is as follows .

E,llployer ~ EltlploYItI,"IRtlaliol,hip ~ Employtr.


However, if this is Aot feasib le, we apply Cbnllg, tI,tidirteilollnl Associalioll 10 Bidirtcli""al by establishing a
reference in E",ploy" to Employtr.
R,pla" "Magic Nu",btr" wilb Sy,.bol,e olls lall l is the process of using symbo ls for consta nt S wit h in code .
An example is NUM_ WORKING_MO TH S instead of purely " 10." This helps readability, si nce the
reader understands NUM_WORKING_MONT HS but not necessa rily just 10. This process also help
with maintenance, si nce it allow easy changes-for exa mple , c han g Ing NUM_ WORKING_MONTHS
to II instead of hunting for all occurrences of 10. checking lheir context, and changing to 11 where
applicable.
E.capsulal, Fitld i the proce of c hanging accessible variables to pMn l, ones, supplYlllg an accessor
method or methods. For co nvenience, we might intemlo nall y make all variable public when first c reating a
class and then apply this relactoring.
The pn:ceding set of refaclorings is summarized in Figure 24 . 13.
R,plnct RtCord IVilh Daln CIa s is u cd when we need to e"capsu late the data of a class in a database record .
In other words, it suits the application better to deal with records as self·co ntained unit . The reco rds become
objects with private data ne lds and accessor methods. This is similar to the Replae, Da ln Vnl", wilh Objeel
refactoring mentioned above.
Replace Type Cod, will, Class is used whe n a group of ~rtributes of a class essentia ll y specify what type an
instance of the class is. For cxample, in the class 5/'01, the attributes eo""'ryOj ,"n""jnclure, qual"y, and
dcsi9""Name would effectively indica te the type as h igh fashion , IIltem, edia te , or low fashion . Thi s refactoring
applies when it becomes advisable to call out a specific type class (SI,oIFnsl,ion Type with at leasl three valllcs for
the example). T ypically, the type class is aggregated '"ith the o r;g lOa l class.
R,pla t Typ, Code ,vilh Sub Inss, This refactorin g implements the sa me problem as for Rlplnel Type Cod, IV,lh
Class hy using inhe rited classe , each a d iffe rent ty pe, as shown in Figure 24 . 15 .
The preceding refactori ngs arc ummarized in Fig ure 24 . 14 .
R,plact T yp, Code ",il/' Slnlc/Strnle9Y' Thi s refactori ng deals with the same type of issue as that described In
R,plact TYPI Code wilh Class/S"bclass but combines classes into a hierarchy . as shown iQ F,gure 24 . 15. The result
" the aggregation of a type class, such as AeoulllType and inherited sllbclasses su has Re9"I",Aeeou",Type and
IVboltsaleAecounlType. At runtime, the A,outl/Type allribute of Aceo",,1 is instantiated with an object of type
RegularAeeo""ITyp, or WI,oltlal,A ecolmITyp,

• Change Unidirectional Association to Bidirectional


• (On ly If necessary), install backpoinlcr
• Change Bidirectio nal Association to Unidirec tio nal
• Find a way to drop; conS Ider third party.
• Replace "Magic Number" with Can tant
• Encapsulate Field
• public at!rihul~ to ,,,ionlc/newso r
Fl&ur. 24.13 "Organizing data" refactorings, 2 of 4
SOtxu F(M1H et. 81 , Ref3ClO(11l1l: ImproYlng me De51&11 01 tJ(ISllnR cooe, COC)Yrlghl' 1m by Pearson EdUCation. Inc
ltapoollCCId 111 Ptfmtsllon of Pe8rsM EducaUOl"l. Inc.
612 CHAPTER 24 REFACTORING

• Replece Record with Dala Class


o SlmploSI obJoct with privato data flold. accessor
• Replace Type Code wllh Claa.

Accounl
...
Iype

REGU' 6R: Aoco..,ntType


BIG_DISCOUNT: Aooo!.tnlType

Figure 24.14 " Organizing data" relactorings. 3 014


Source Fow\ef' et aJ• Relactormg: ImprOVing the Design 01 ExiSting Code. COf)'frlght , 1999 by Pearson Education, Inc.
Reproduced by peitiilssion of Pearson Education. me..

• Replace Type Code with Subclass

Accounl
•••
=>

•••

type

• Replace Type Code with State/Strategy

Account
...
type

Figure 24.15 "Organizing data" relactorings. 4 01 4


SOUrce' FO'N1er el at . RefactOtlng: ImprOYlng lhe DesIgn of Existing COde, copyr.ght " 1999 by Pearson Education, Inc.
Rept'oduccd by permissk)r of Pearson Educatkln. Inc.

24.S GENERALIZATION

The refactorings in this section exploit inheritance to conven (l deSign and code base from o ne (orm to
another that bett~r suits the si tuation .
Pull Up Firld is used whe n a field (e .g .• ordrr in Whol,salcOrd" and In R,'aiIOrd,,) occurs In severa l slibel. ses of
a class (wh ich we'll call the baS( class). It declares the ,ecurnng field in the base class. helping us to extend the
functionality of the design since the base class becomes more useful as a r«ult . Figure 24 16 shows an example.
Pull Up MtI/'od is th e same as Pull Up F,,/d except that it refe rs to recurrins methods '""cad.
1

• Pull up field
WhoIesaleOrdor RelollQrder
amount amount
• Pull up method

• Pull up constructor body


o Rep lace by super(. ..)
• Push Down Method
o When base class mel hod nol used by mosl subclasses
• Push Down Field

Figure 2".16 "Dealing with generalization" refactorings, 1 of 5


Source: FoWtef et al . Aefactorlng: Impro¥1ng the Design of EXisting COde. Copynght i 1999 by P~arson Education, me
ReprodUCe<! Dv peilUISSlOfl of Pearson Education. Inc.

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
quantity
Order
quantily
• Extract Subclass
discou nt

Iype dlacounl
minimum

• Extract Superclass Employee


name
Manager salary
name
salary Engineer
numSupervlsees name
salary Manager Engineer
skillSel numSupervisees skiUSet

Figure 24.17 " Dealing with generalization" refactorings, 2 of 5


Source FOWler at al.. Relactorrng:; improVing the Design 01 lJOsting Code, Copyrfght I 1999 OY Pearson EducatK>n, me.
RepfoOucecl by pefmlsslon of Pearson Education, IIX".

• Extract Interface :-i';io~l


1-Bln;.bie l IgBlNsmeO I
Manager I gBlRB1eO :
- -7' '_- -
I{/9tSsiafy{) I
name
salary
numSupervisees
Engineer
name
IT'
I
,I
ifI
salary I I
billA ale skiliSel I I
I
billAale Manager Enolneer
numSupeMsels 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 615

Assemblylnslructlons
wrllePrep()
wrileSalely()
wrileWrapUp()
wnleManual()
, ~

BlcycleAssemblylnslruelions BieyeleAssemblylnslruelions
wrileBikelnslruetlons() 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 I 1999 by Pearson Education, Inc
Rcpe OduCe<:l by peilhlSSfotl of Pearson Education, Inc.

eliminating an inheritance. Fo r the example in Fi gure 24.20, Accou/ll can inh erit from another class once the
..factoring is done , resulting in greater Aexi bil ity . Th e refactoring give a sequence of step that ensure a
smooth and safe transition from th e o rigi nal fo ml to th e refactored fo rm .
R,p/ae, DtI,galio/l with J/l h,rita/lC< would be appropria te whe n we wanl to repai r a desig n in wh ich code
becomes understood as having a gene ralizati o n rciati onship such as Emp!oy"/ Pmo/l . \Vle effec I Ih i in code by
mean~ of inheritance .

• Replace Inheritance with Delegation

Record
lastChangedO
reco rd .Ia stChangedO

Account
Account record
taslChangedO tastChangldO

• Replace Delegation wl.th Inheritance

Flcure 24.20 " Dealing With generaliza tion" rcfactorlngs. 5 of 5


5outu; fO\'t1et at • Refactor1l'1i' amprO\llng the Design 01 EXlSlJng Code, COPVTIiht
tot 1 1999 by PeArson EduClJtlon. Inc
ReprO<JU(td by pel lIIiStion 01 Pe&r5On EduUl.lOn. If'\(..
616 CflAPTER 24 REFACTORING

24.6 INTRODUCING MODULES

Cood deSll(n requires modul.rozallon , a process of ('paratlng Its es",ntial clement Whenevcr fc.-iblc . th"
hould be performed in advance H owe.er, it IS very useful to mod ularize aher thc fact a, well - In other
words. to recognize useful modulan Z3 t10n as the appli allon grow..; <and tran sition Into millntc:nance.
Cia se< by them elve, are a mean of modularozatlo n, but an applicatio n can contain huodred, of classes,
and so cia. os need organizing to enable designers 10 manage and appl y them . A useful way to handle
modularity o n thi sca lc is via the Fa ade dcsign pauern . Impl,(YlOl! m3ue,>, the problem can be reduced to
that shown in Figure 2~ . 2 1 , in wh ich the design IOvolves classes U, V, and W, where U references (men lions}
classes V and W . An example is U ~ Transaction, V ~ CllSlOme r , and W =Loan pool. Suppose that we want to
avo id multiple references like this (think of many clas os instead of Just the twO in this simplification , and you
can ImagIOe the re lilting compleXity). la s U must be modified becallse it ,hould no longer reference bo th
classes V and W .
The rdactoring 10 Figure 24 .2 1 is si mple if U docs not need to instantiate V objects or \VI objects ThIS IS
the case when U needs o nl y tatic methods of V or W . (Example, A transactio n needs only a generoc CtlStomer
functionality >uch as ge uIOS average assets of all customers, and the IOtal amollnt in the loan pooL ) In that
case, U references functio nality in F o nly, and F does th e work of translating slich function ca lls into the static
calls on V or W.
The situation may be more involved, however. Suppose that U requires V instances In order to operate
( such as is usually the case when it lran action involves a cuslomer). If we want to protect \1 within a package,
then U has to depend on the facade interface F and 11 0 longer on V directly. Figure 24.22 shows how thi can
be dealt with . First, V IS proVided with an abstract interface VI (Step I) that abstract its public methods.
The Exlrael liller/nrc rdactoring can be used for this. Next. in Step 2, \1 is enclosed 10 a module (or package)

package

,,---G
@}--- -0- --~
:- -~

Figure 24.21 Refactonng by introducing facade

u0)

Figure 24.22 "Introduce module" refaCloring. 1 of 2


REFACTORING IN PROJECrS 617

ITmsctn ~ Cust

Agure 24.23 "Introduce module" refactorlng, 2 of 2

• T msctn has attribute 01 type Cust


• Replaci ng Cu,' em l ; with ICu,' ell" ; OK if . ..
• Cusl has on ly private attributes (, C., usc via metho ds o nl y )
• Tntsctn docs nOt instantiate Cust instances
• T m sctn has me tho d wi th parameter 01 type CUSI
• Replacing my Method(Cllsl) with myMe thod(JCu.sl) OK if . ..
• Cusl has only private attributes (i.e., use via metho ds o nl y)
• T"" eln has method returning type CuSI
• Replaci ng Cusl mylvltlhod(J; with ICll sl myM, II,od(); OK
• T"'seln has method with variable of ty pe Cllsl
• Replaci ng Cu" eIIsl; with ICII, I ell "; Unreso lved as a general mailer

Agure 24.24 Types of references of one class to another

with facade F. The class U must now be modi Red so as to refere nce \f / and F onl y. It is far less of a problem fo r
a class to reference an interface than !O reference a class.
Let's apply thi s to an example , shown in Fi gure 24 .23 , where a transactio n o bject 01 class T",scln depends
on a customer clas GISI.
We can introduce inte rlace ICuSl, wi th Cusl bei ng unc hanged , but we need !O dea l wit h the resulting
changes needed to T"'seill . The de pende nce of T"'selll o n Cllsll re placed with depe ndence o n ICusl. TIlis IS a
slg~ificant improvement because II increases modularity. Th ink of it a fo llows: Imagine T "' ,elll as a bicycle
pump. Such a pump wo uld be of littl e use If it werc ab le to o pe rate o nly on Ajax tires (no t an interface ) but
would be very usefu l if it were ab le to operate o n an y tire sa ti lyi ng the standard va lve interface . Figure 24 .2-1
lists the impl icati o ns of th is c han ge for T ", \Chi and intro duce rem ed ies for most situall o ns.

24.7 REFACTORING IN PROJECTS

As mentioned at the beginning of thi S chapter, rdactorlng ca n be profi lably applied a soon as software
engineers begi n wri tin g code , Figure 24 .25 was Intro duced In hapte r 4 o n ag de metho ds, bUI With o ur
mcreased knowledge of rdilc to rins we now have an o ppo rilinil to reexamIOc it. Re .11 Ih at a~ i l e
methodologies repea t the waterfa ll ,cquc nce ma ny time, bUI with eve ral diffe re n c< Eac h Ie beilin,
With the (functi ona l) code base ReqUIrements . re us u. lly in the fo rm o f IIser ~torie , . The ex ,,"n g
6I 8 CHAPTER 24 REFACTORING

Oblaln high-level Obtain requirements for


requirements noxl perlod's' segmenl

Ref.clor 10
Ref.ctorlo accommodate
clean up new
reqU irements

Modify code and lesl code base


to handle additional requirements

• Typically 1-6 weoks

Figure 24.25 Agile methods-cycle of activities

will have been expre sly designed for Ihe eXisting requirements. It is a tenet of most ag ile melhodologies "01 to
try to anticipate forthcoming rcqulrtl1lcnt . The existing code ba~c m() y thus be unsuited to th,· additional
requirements In one or more ways-and rdactoring wou ld then be clppropriatc in order to accommodate
them . An example is the uscr story for a video Slore applicalion that inlroduces candy sa les (i.e .• nOl just Ihe
management of rentals ), A n('\\' module at the architectural level may be required" and this , In rurn , may
require pulling contro l functiona lity out in o rder to orc hcsrratc the rentaVsalt::~ actiVities.

24.7.1 Refactoring in the Agile project Life Cycle

Figure 24 .25 shows an additional refactoring step the ta,k of cleanup. I\·\osr software addilion and
modification work leaves a "me s" of one kllld and ma gnitude o r olher. An example i a SCI of displayllc-
COI(l110 methods, one (or an existing account t)'PC and two more: for added account types Even If the
application docs nor continue to evolve 10 this direction , the disorganization descnbed I\hould be cleaned lip
to make" more reliable and readable . Rdactoring is thus an esse",ial parr 01 agile design . imp lement.tlon.
and testlllg. It IS part of the expectation for agile projeclS.

24.7.2 Refactoring and Design Patterns

Fowler's refactorlngs, described in [ 11. stand mostly apart from de ign patterns at lea" 111 expilcjl term .
However. refactOrlng is really an integral part of all de .. gn and implementatIon In particular. the need for
refactoring often poinlS to the need for new de ign panerns The cla<slc source for these is (2). in whICh
Kerievsky names most of hIS patterns in one of the follOWing forms .

'Exr~cI < Design Pattern > "


or
EXERCISES 619

' Ext.. MoveIReplacc < irua tion > \Vith/to < DesIgn Pattern >"

Our purpose hen- is on ly to dral\' the reader' attent ,on 10 thi s \Vork . H ere arc some example •.

• Encap ulatc Classes wIth Factory. Help the sO(l\Vare engineer recogn ize .. .
.. when Factory is a better way to construct o bjects that he o r she is dealIng with, and how 10 go
about the conversio n

• Move Embelli shment to Decorator • •

... when the amou nt o( functionality bein g added dynamically to objects of a class is extensive
enoug h to require th e use of the Decorator design pallern , and how to go abo ut the co nversio n
• Replace State.Altering Conditio nals with State
.. . when the State desig n pattern is a berter wa y to handl e eve nts that alter the state of the
applicatio n, and how to make the transition

24.8 SUMMARY

' Refacto ring" refers to a d iscipli ne of replacing code in such a way as to Improve the applicatIon but without
changing its functionality . The improvement can be o( the following kinds.

• A simplifica tio n of th e design and code (removing unneees ary complexity)


• An increase in its reusabil Ity (or o the r parts o( the codc base fo r other app li catio ns

• Improved preparedness of the desig n and code (or increasi ng functionalit y

Refactoring is possible at the archotectural level and at the det.oied code level. II extends the lIfe of
applications because it increases their capacity fo r modiAcation in response to changing requirements.
Some refacto rings can be done wit h wizards upplied woth devel o pment environment
Refacto ring is essenna l to agile devel o pment. This is because It facilitates the evolutio n of applications
so as to include additIonal funct Io nality .
This chapter has eoted severa l classica l refact orings. There are many more . An a t lve research
communI ty explores new rdactoring sec f3], for example

24,9 EXERCISES
I. O ne refactoring is to "sepa rate domain fro m prese ntat ion " Explain what this mea ns, and app ly It to
a ca lendar applicatIon ,
2 Wrote a SIngle that ompute< the roots o( a quadratic cqua tlon Apply "ex tract method" to It.

3. Describe an appl,cation not mentioned In this chap ter- or part o( an application-in wh , h


' Convert Method to Objec t" would he approp roat e

4. Apply ''Extra ct lass" to the (o llowlng


620 CHAPTER 24 REFACTORING

class Rental{
Str ing customer;
Stringdvd ;
• •
lnt customerLlcense;
Str ing director;
Date date;
• • •
}

5. TI, is chapter ci tes the fo llowi ng class diagra m for o,allg, Bid",ctional AssocIation 10 UHld",,'ional:

Elll ploy" <0---- <> Em ploY"''''t Rtiatio",biP <> --> Em ployer


(see Section 24.4 ). Write code consistent with this model that allocates seven emp loyees among
two employers and lists them .
6 . Give an example in which the addition of a meth od to a calendar application would cause the
software engineer to apply P"II Up M,tbod.
7. Explain where Inlrod"a Facad, was used in the Encounter video game case study.
8. Section 24 .7 cited two stages at which rdactoring is used in agile projects. Give examples of each
in the evolut ion of a calendar application.
9. The introductory section of thi s chapter refers to a class Mil,ag,. Show how the refactoring of it
could progress usefully along the directions suggested there.

BIBLIOGRAPHY

I Fowlc.-r, M~nln . HRtJactonl'l9 I".",oai"9 ,he Dn'g" of E"u l '~ CoJe Addlson,Wc-sit-y . 1999
M

2 KcnC""Sky . J<xhu.a .. Rt/acwnf19 fo P.:Jrk"" ~," Addl'>on·Wt"Sley, 2004.


3 Rd~ct on ng http j/~' rdactonng.com! ( Iccc~..ed 1l/ 14/09].
Introduction to Software
Testing

Planning
• Why test early? Why often?

Maintenance
• When and why do you retest?

• W tlat IS the difference between black


r.stlng box and white box testing?
The Software
Development •
Ltle Cycle Requlremenls
analysis • How do you document lesls?

Implementalion
• How do you plan for testing ?

• How do you know when to stop


Design 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

'ionwarc le<t lnl,; i< av~l l datl"n proct<' Execu tll1 g "de (rom th e c u lv "' 1l J"p l l<.~ t lon IS provide I \\ Ith
Input, and the (csullln~ output 1\ ompzll cd wI th thl' (('qulI 'd lllPlil i'(l h <lte; rcp illlq' 01 lll'\ln\('ndccl ... ,elt·
dlecl Indicate') a 'duh , hll ~ , ()r ('rrllr In lhl' 111'r>l c ll\(.-: nt~{lnn dc"gn , ur req UIreme nt' \~/c \ ..qlllt\e the \\(lr I
<kIf<! lO u,vcr 311 lh , . t ·r01' . d -ftn ed by th .. II I L (1[1+ <; ' Jl1d " ,d C I<h<ary 0 1 01 ,,,,-,,<., 1 1l~lneefln!:
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 623

1. Regression
Original lesl (= original
leSI lesl?)
Original
Original
coda
code artifact
artifact
addition 2. Teslof
added """
functionality
""-
Figure 252 The idea of regression testing

Suppose that C is a body of already. tested code in


A
an applTcation A. Suppose that A has been altered
with new or changed code N.

• 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 ....
N
• Otherwise 4ft'I' $ 'woos us
Regression test C

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 ].


/larry ,"" S"Gon' 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
1\
which the application was deSigned o r implemented. ilia k box testing can be performed by <omconc who
needs 10 know only what the apphcatlon i~ reqUIred to produce (He or ,he doe< not need to know ho '" the
application was bUll!. ) This i, analogous to buddinM an automobi le and then testlO!; it by dnvlng it under
vanous conditions
624 CHAPTER 25 INTRODUCTION TO SOFTWARE TESTING

Result
Input determined by...

Actualoutpul
.. . requirements - - -.... compared with
reqUIred output

White box
Va lida lion
... design ------+-t ot expected
elements behavior

Figure 25.4 Bla c~ box and white box testing

Black box tes ting is esse ntial. H owever, to uncover as man y defec ts as possib le, we also need to utilize
knowledge of how the application has been designed and implemented. ContInuin g the automobile analogy,
if the ca r is built with a new design (or its automati c transmission , we wou ld be wise co usc this knowledge ,
srressing multiple gear changes and runnin g rests that foc us on changi ng gears in as man y ways and
circumsta nces as possible. T ests based o n desig n and implementation know ledge arc called wbilt box or glass
box tests. Figure 25.4 illustrates th e d iffere nce between black box and wh ite box testi ng.
White box testing met h ods arc typica ll y performed during unIt testing , which is described in C hap ter
26. Black box test ing is performed both during and after unit testi ng and is described in C hapters 26 a nd 28 .
Tests that focus substantively o n bo th o n the know ledge of h ow an application is intended to operate as
well as how it is construc ted are someti mes called gray box tests .

25.4 UNIT TESTING VS. POST-UNIT TESTING

Software applications co nsist of numero us parts. As with all constrtlcti o n, the sou ndn es of tho who le depends
on th e soundn ess of the parts. This is ill ustrated by the ca nt ileve red bridge in Figure 25 .5.
Because of this depe ndence, we test software pans thoroughly befo re- assembling them-a process
known as "n il 'tsling . Individual methods arc con idcrcd tmits for tC'sting purposes, and so are clas cs. A part as
substant ial as a grammar checker in a word processor is probabl y too large to be conSidered a "un it." At times
we inadverte ntly allow a defect in a unit to remain undetected until the pro duct is compiete. In that case, the
cost of isolating and repairing the defect is tens or hund reds of times the cost of doi ng so wit h in the pRase
durin g which th e defect was creat ed. In other words, there is a very large payoff in d etecting defects early at
the un it leveL

Reliable
Reliable? Reliable?
Reliable?
- - Reliable?
Reliable? Reliable?

Agure 25.5 A bridge made from parts depends on their individual reliability
TESTING OBJECT-ORIENTED IMPLEMENTATIONS 625

• Int~rfac~
testing
validates function. expo cd by modules
• Int~ration _ _ _
_ _ . combinations of module
• S~tem • Robustness
whole appitcation ab.lity to handle anomal.es
• Usability • Performance
user satisfaction
• R~ression fast enough, uses acceptable amount of
changes did not create defects in existing code memory
• Acceptance
customer agreement that conlract sal.sfied
• Installation
works as specified once installed on required plat form

F"rgure 25.6 Some major types of post-unit tests

Unit

Unit
• ••• •

Unit Build

Application
..... -- Application
•• ••• _~) Modufe
on test bed
- on final

(n(erface testing platform


• • • •• system testing
installation testing
usability testing
Unit acceptance testing

Unit Module . testing


• • •••

Unit Regression testing throughout

FIgure 25.7 various non-unit test types

Various types 01 POS'-""" tests arc al 0 administered . F.gure 25.6 sum marizes some 01 the major types.
They are covered in Chapter 28.
Figure 25.7 is a summary of when each of the post -unit testing activit.es.s performed during the praces
of bUilding an applicalIOn .

25.5 TESTING OBJECT-ORIENTED IMPLEMENTATIONS

Object-oriented applicat.ons, when develo ped well . beneA t from thei r organ.zation into c1asse . like an
modularozatlOn , this help' wit h testing because the classes ca n often be tested separately froro-and '"
626 CHAPTER 25 INTRODUCTION TO SOFTWARE TESTING

add,t,on to- bl. k box functIonality . Prior to the advent of 00, modulanzatlon tended to be in terms of
fun tlonalul1Its , deco mposed 1111 0 lowe r leve l functional un its ("stnlctured programmlllg") Thc<e units can be
eparo tcl y tested but o nl y when cleanly de igned. As w.l l be >cen in hapter 211, on unIt testlllg , 00 t<stlllS
In ludes method , lass, and package te. tin g.

25.6 DOCUMENTING TESTS

It require signdkant lime to decide whal lo test, how to lcst , when lO do so, and with what data . In addition,
test results must be ana lyzed to determine what defects they uncovered . We therefore treat each test as an
item of value Tc 1 procedures, tcst data , and test record arc maintained; tests are reused o r modified where
possible . E.xamples of test documentation can be found In Chapters 26 and 27.

25.7 TEST PLANNING

T o ma xi mize the effectiveness of resources spent on testing. a systematic approach is required and a plan
IS devised . Recall that the goa l is to detect as many errors as poss ible at as se riou a level as possible
with the reSOurces available . Typical planning steps arc shown in Figure 25 .8 and elaborated in the rest of
(his section .

25.7.1 Organize "Unit" VS. Non-Unit Tests

The limIts of what constitutes a "unit" have to be defined by the development team . For example, do they
include the testing of packages, or is this to be considered another rype of testlllgi

I . Deflne "units" vs. non-units for testing


2. Dctermllle what types of testing will be performed
3 Determine extent
• Do not just "test until time expires"
• Prioritize, so that important tests are def1nitely performed
4. Document
• Individual's personal document set includedl
• How/when to incorporate all types of testing)
• How/when to incorporate in formal documents;>
• How/when to use tools!test utilitiesl
5. Determ ine input sources
6. Decide who will test
• Individual engineer responsible for some (units»)
• How/when inspected by QA)
• How/when designed and performed by third partiesl
7 Estimate resources
• Use historical data if available
8. Identi fy metrics to b<: collected
• Dc:fine, gather, usc
• For example, time, defect count, rype, and source

Figure 25.8 A plan for testing


TEST PLANNING 627

• When tester has not been .ble to Rnd anot her delect in 5 ( 101 301 1001) minutes of testing
• When all nominal, boundary and out -of-bounds te _t examples show no delcct
• When a given checklist of test type has been completed
• After completing a series of targeted coverage (c.g., branch coverage for unit testing)
• When testing "ms out of its schedukd time

figure 25.9 Stopping criWia (or testing

For object-oriented devel opme nt projects , a common sequence of unit testing is to test the methods of
each class, then the la,scs of cach package, and then the packagt: as a whole . If we were building a
framework , we would test the classes in each framework package first and then move on to the application
packages, bt-cause the laner depend on the form er. Once the "units" and non -unIt tests have been identified,
they must be organized and saved in a sy tematlC manner.

25.7.2 Determine the Extent otTesting

Since it is impossible to test for every possible Situation , the rx ltll l of te ting hould be considered and den ned
in advance. For example, if a banking application consists of Withdrawals, deposits, and queries, Untt testing
could specify that every method should be tested wtth an equal amount of lega l. boundary, and illegal data; or
perhaps, due to their se nsitivity, withdrawal and deposit methods arc tested three times as extensIvely as
query methods, and so on . Test cases are se lected both from normal expected operation, as well a from those
judged most likely to fail. SloPP;lIg enl,,;a are established in advance; these are concrete cond Iti ons upon wh Ich
testing stops. Examples are listed in Figure 25 .9 .

25.7_3 Decide How Tests Will Be Documented

Test documentation consists of teSt procedures, input data , the code that executes the test. output data,
known issues that cannot be attended to yet, and efRciency data . Test dnvers and utilitie are used to execute
unit tests. and these are documented for future use. JUnlt is an example of a unit test utility (described In more
detail in Chapter 26). JUnit·like and various profeSSional test utilities help developers to retaIn test
documentation JUnit classe . in particular, tend to be maintained along with the applicatIo n.

25.7 _4 Decide How and Where to Get Test Input

Applications are developed to so lve problems in a speclRc area , and there is often a et of test data special to
the application . Examples are as follows ;

• Standard test stock market data for a brokerage application

• Standard test chemICa l reactIOns for a hemical engineenng appitcalton

• Standard FDA procedures for the pharmace~ltcal Industry

• Standard test input for a compiler


• Output from prevIous verSIons of the applt atio n

The procurement process and usc of su h doma.n-,peCtA test Input mu t be planned ,


628 CHAPTER 2S INTRODUCTION TO SOFTWARE TESTING

25 .7.5 Decide Who Will Be Involved in Testing

UnIt t<' slIng i usu,II), performed by develope rs tn. m.nner o f their own cilOoslng T estIn g beyo nd the unIt
leve l i, planned and performed by people other than the devel o per- u uall y an tnternal Q A o rganlZ<ltto n
UnIt test arc m.de .v.dablc fo r Inspec tion and for possIble Incorp o ratI o n into hIg he r-leve l tes ts, Some post-
unit tes ting requires QA engineer; to understand th e design, but mos t o q~anlza ti o n s do not support this
carability , and so the y . sign QA to hig her-level , blac k box testing o nl y . Some o f the inde pende nce of QA
can be caplllred by havtn g development engineers unit-test eac h other's code. It can al 0 be attamed by QA
assuming an oversIght re po nsibdlty, ensuring that unit tesllng is performed tho roug hly by de velo pers.

25.7 ,6 Estimate the Resources Required

Unit te ting is o ften bundled with the development process rather than being called out as a separate budget
ite m. Good leaders fos ter an altitude that the rcliabiHty o f un its is essential , and they allow developers
suf Acicnt time to alta in reliable un its, Testing beyond the unit level is an identifiably separate item , usually
assocIated with the project's budget but sometimes a part of QA's whole budget. Employing a third party for
teslln g IS sometimes used-including offshored resources-and must be budgeted for.

25.7 ,7 Arrange to Track Metrics

The develo pment organ izatio n speciRes the fonn in whIch engineers record defect counts, defect types, and
time spent on testing . The resulting data are used to assess the state of the application , to forecast the job's
eventual quality and completion date, and as historical data for future projects . The data also become part of
the organization's hi stori cal record .

25.8 TESTING TEST SUITES BY FAULT INJECTION

Suites o f tests and test plans can be eva luated, and there arc ways to improve them . MutatioH !(sti"g , in
particular, validates testing sUItes rather than the code under test itself. Suppose that we have developed a
suite of tests for all or part of an appl ication . Fo"ft injection is the process of deliberately inserting faults into a
program , Mutation testing is a kind of fault injection whereby we change the source code in small , controlled,
and deliberately incorrect ways to detennine whether the resultIng mjected errors are detected by the test
suite. Examples are changing a true to a Jalst and a ">" to a "> = ". If our tests continue to pass despite fault
injections, this exposes weakness In our current tcst suite . We can infer that the test suite is probably failing to
find defects that we did not insert . By working on fault insertion, it is possible to estimate the number of
defects that our test suite is faili ng to And.
Mutatio n is said to have originated by R_lipton in a J 971 class . It is computationally intensive, which is
one reason it took some time to become active as an area of research and practice.

25.9 SUMMARY

Software testing is a validation process, the purpose of which is to detect as many defects of as high a level of
seriousness as possible , Defects are detected when the software under test is provided with input, and the
resulting output does not match the expected output.
Two basic principles of software testing are "test early" and "test often," "Test early" means that as soon as
a software part is implemented it should be tested. This ensures that defects are detected as close to their
introduction as possible, making them easier and cheaper to detect and correct, "Testing often" means
EXERCISES 629

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
unit Testing

PlannIng • What parts of the code should be


~ subjected to unit testing?

• How do you go about unit testing?

T...... • What is statement coverage? Branch


The Software coverage? Path coverage?
Development
Life Cycle • 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 631

Key: • ·speclfies· Implementatlon.time


specification

Example:
get D VD tlt/e
Desig n document
(SOD)
1i·ltllemlnlatlon
Requirement
Domain unll
document
classes (cede lor i1i."~ or claD)
(SRS)
Examp Ie:
·'t
Enmple: shall be
Example: void sa/OVON.mel ... )
possible to add 8 DVO
to the vkJeo store's me/hod addOVO( " . )
inventory» ~Pr8condl'ions: ... _
Postcond,llons: ... •

FIgure 26.2 The source of units for unit testing

tested together. This is what we will ca ll pOS I-"IIIllrsliH9 and is covered In C hapter 27 The rest of this chapter
describes specific test methods a nd stra tegies employed in unit testing .

26.1 THE SOURCES OF UNITS FOR UNIT TESTING

The first step in unit testing is identi fyi ng Units and determining wh al they are intended to do . These arc
obtained from the SRS or the SOD . They may a lso be ele me nts 100 minor to specify in the SOD . Figure 26.2
illustrates this for the video store exa mpl e.
For units arising from design , we ma y not possess ex pl icit requ ire ments against which 10 perform te ts.
An example is a test for the class Cm"rOla,aCIII, introduced for the design of ou r video ga me; none of the
original requirements specifica ll y involves CamrChamrlll per se. Separate specifica ti ons shou ld be wrillen for
all design classes oncc the desig n is crea ted . When Ihese are nOI wrinen , as is often the co e, lest cases have 10
be devised against the functionality Ihat the class is supposed (by Ihe lesterl lo pos c s Figure 26 3 ill ustrale
unit lesti ng agai nst reqUire menls a nd against design .

26.2 UNIT TEST METHODS

Both white box and black box mel h ods are ul ili zed during unll Icstl ng Some of Ihe principal te hni ques
are shown in Figure 26.4. As described In h ap ter 25, white box testing IS conducted with knowledge of
the design and impleme nlatio n of Ihe unit under lesl. The while box unit Ie I fo us o n the Internal cod~
structure, testi ng each pro!:ram statement , every deCision point , a nd each indepe ndent path Ihrough th e
code. Black box mel hods focu nn tesling the unit w lthoUI u"ns its IOternal structure Tc hniques u. ed 10
conduct black box unit lest' Include eq uiva le nce parllt ionlng and boundary va lue ana lysi<, IOP'C Ihat are
explained In detail below
There has been , and con tinue, to be, resear h o n Ih e relations hi p alilong these te tlOR Iyp<"> SIO c they
often overlap a nd a lso leave va n ou' ki nds of gaps An examp le of p. t research is dc, nhed by Rapp' and
E J. W "yuke r [ I J. '" which paths are selec ted on Ih ba<;' 01 w here v.nable, are deAned vs. where Ihe are
u$ed . Nevertheless, the types d,scu,sed form a Rood , tart ins point and pra tica l ba<is
632 CHAPTER 26 UNIT TESTING

i2} Design
3.2.EC.l .2 Dualities of ElKX>unler GameCharacler: An abstract class
chsracters with attributo name ... ,
Every game character has the
same set of qualities. Each quality
"- "- \
Test this class ... j
shalt be a nonnegative fica ting .,. against this requirement
point number with at teas tone
Characters
decimal of precision . . . .

\ GameChsfscter
"- .....
-- "-
\
L

"
Test this method ... I EncounterCharacters
... against thIs require ment -j ,
"- EncounterCharacter
t.. adjUS1OuaJityO
Figure 26.3 Relating tests to requirements and design

26.2.1 Statement Coverage

At a min imum, every statement in a program must be executed at least once during unit testing. Ir a line of
code contains a defect, tests that nev", execute the line will not detect the defect. Untested statements are
thought by many to be a major cause of latent defects.
Consider the function co",p.t,Fi", 0 shown in listing 26. t . We will usc a directed graph, ca lled a progra",
(0""01 graph , to graphically represent the control paths of the program . Figure 26.5 contains the program
conrrol graph of comp.tcFi",O, where each node in the graph represents an executable line of code, and each

White Box Methods

• Statf:ment coverage
Test cases cause every line of code to be execllted
• Branch coverage
Test cases cause every decision point to execute
• Path coveragr
Test cases cause every independent code path to be executed
Blad Box Methods
o Equivalence partitioning
Divide input values into equivalent groups
o Boundary value analysis
Test at boundary conditions

figure 26.4 Methods for unit testing. categorized by black box and white box types
UNIT TEST METHODS 633

False

False

Figure 26.5 Control flow graph of computeFineQ, with numbers keyed to Listing 26.1

edge represents the transition between lines of code. In the graph we repre e nt decision poin ts uch a If, ",/,il"
or for statements as a diam o nd, and all other executable statements as a ci rcle.

Ustlng 26.1: COmputing a fine for a late rental

int computeF ine (int daysLate, boolean pr intOn)


{
1 int MAX_FINE_PERIOD ~ 21, fine ~ 0;
2 i f (daysLate < ~ MAX_FINE_PERIOD ) {
3 f ine ~ daysLate * DAILY_FINE;
}
4 logFine ( fin e) ;
5 i f ( printOn~~TRUE ) {
6 printFine(fine);
}
7 return fine;
}

In order to satisfy statement coverage, tes ts are devised ,,, lth Inpurs that e nsure eo h linc of code IS
cxecutcod at least once As s hown in Tab le 26 I , o nl y o ne tes t is nece>'"!)' to sa ti sfy sto te mc nt co crage 01
",..p..kFi"t() (but not truly comp le te overage , as we shall eel .
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)


{
1 int MruCFINE_PERIOD = 21, fine = MAX_FINE; / / defect fixed
2 i f ( daysLate <= MAX_FINE_PERIOD) {
3 fine = daysLate * DAILY_FINE;
}
4 10gFine(fine);
5 i f (pr intOn == TRUE) {
6 printFine(fine);
}
7 return fine;
}

To satisfy branch coverage , one or more tests are run with appropriate inputs to ensure that every
statement is executed at least once and every branch decision is executed at least oncc. The two test cases in
Table 26_2, for example, satisfy these conditions .
The execution path of each test case is shown in the program cont'rol graphs 01 Figure 26.6 , with the
bold arrows depicting the contTol Aow.

26.2.3 Path coverage

An even stronger form of test coverage is path coutrage, in which all distinct code paths a", executed by at least
one test case. By distinct code paths we a", rderring to the complete set of sequences of branches and loop
UNIT TEST METHODS 63S

Table 26 -2 Tests SUfficient to sa tisfy branch coverag


e
Test Case • daYSLate printON Path
I 1 TRUE 1-2-3-4-5-67
2 60 FAlSE 1-2-4-5-7

Test Case #1

False False

False False

FIgure 26_6 Branch coverage of computeFmeO. with numbers keyed to Usting 26.1

traversals, even if the y d iffer by just o ne small part of the path . This type of testing detects errors that only
occur if a speciRc path is executed . Path coverage subsumes statement and branch coverage. As an example,
c","puItFi"r(J contains two If statemen ts, each with two branch decisions · true and false . Therefore compu/rFin,(J
has four distinC1 paths through the function as Illu trated In Figure 26.7.
Four test cases would be reqUIred to test all the distinct paths of compu/rF,",O, one fo r each path , as
shown in Table 26.3_
As the number of branches and loops increase, the number of distinct paths grows exponentially. It
.r
qUJckly becomes impractical to test them all. Fo r exa mple, the number of decision poi nts IS 30, the number
of distinct paths is over 1 billion . It is therdorc necessary to limit the number of paths to test_ A commo nl y
used method of maklOl! the tests Viable whde gal nln !! IgniAca nt conAdence is to compute the number of
linearly independent paths, or baSIS paths, through the code under test ThIS can be thought of a the minimum
number of paths that can be combined to generate every po Sible path , and i the minimum number of paths
that hould be tested
636 CHAPTER 26 UNIT TESTING

Path #1 Path #2 Path #3 Path #4

1 1 1 1

False False False False

False False False False

Figure 26.7 Distinct paths of computerFineO, with numbers keyed to Listing 26.1

The Il umbe r of basis paths ca n be ca lculated by computing the cye/omnlie eompltxity [ 2]. which has its
roots 10 graph theory. The Am step in computin g the cyclomatic complexity is to represent the code with a
program conrrol graph. Then the cyclomatic complexity (CCl is calculated w ith the fo ll owi ng fo rmula:

CC = e - n +2
where e = the number of edges, and n = th e number of no des.
As an example , listlOg 26.3 contains an upd ated vers io n of eornpulrFi""O that has input an array
containing the number of days late fo r a list of DVDs. In o rder to process the list, afor loo p is introduced,
adding an addi ti onal decision POlOt in th e function Figure 26.8 shows the corresponding program conrrol
gra ph for this eompul,Fi""O.

Table 26 • 3 Test cases for all tile distinct paths of computeFine()


Test case • daysLate prl ntON path

, , TRUE ' ·2·3·4·5-67


2 60 FALSE '·2·4-5··7
3 , FAI SE ' ·2·3·4·5·7
4 60 TRUE '-2·4-5·6·7
UNIT TEST METliOOS 637

10

F"lgUre 26.8 Program control graph for computeFinesO. with numbering keyed to Listing 26.3

26.3: updated function--computeFinesO

int computeFines ( int d a ysLate[], int numDVD, booleanprintOn)


{
1 int MA>,-FINE_PERIOD = 21, int cumF ine = 0;
2for (i=O; i < numDVD; i++) {
3 fine = MAX_FINE
4 if (daysLate[i] <= MAX_ FINE_PERIOD) {
5 fine = daysLat e [i] * DAILY_ FINE;
}
6 logFin e ( fi n e );
7 i f (pr i nt On == TRUE) {
8 pr i ntFin e (fine);
}
9 cumF i n e += f i n e ;
}
10 r et urn c umF i n e ;
}
638 CHAPTER 26 UNIT TESTING

To cal ulale thc cyclomalic COIl1P!cXIIY of comp"'cFiHtS() , we rcrcr to Ihe program co ntro l graph In
Figure 26 .8 and no te thaI Ihere arc 12 cdges and ' 0 node$ Therefore, C IS ca l ulaled as follows ;

C = 12 - 10+2 = 4

Tills lell us Ihal Ihere arc four basIS palhs. To ge nera le a spe lfic scI of basIs path< , Ihe foll o wing SICPS
can be foll owed.

I. tart wilh Ihe stralghl path Ihroug h Ihe code (all cond i\l ons lrue).
2. SCI Ihe firsl cond 'lion 10 fa lse, kee ping all Ihe re I lrue.
3 Resel Ihe firsl co ndillo n 10 lrue, Set Ihe second condil io n 10 false , keeping all the rcSI lrue
4. Continue, se lling Ihe next cond itio n false with all the rcst true.
5. Stop aftcr the last condition has been set fal e.

ThaI IS, each basis path varies o nly o ne of Ihe conditions at a time. Note that the condition nodes in thiS
function are 2, 4, and 7, which arc the for statemenl and the IwO if stalcments. Usi ng Ihis algorithm , the four
baSIS paths for (omp"'cF,",,() arc as follows ;

Basis Path # 1; 1· 2· 3· 4·5·6·7·8·9· 10 all true


Basi Palh #2 ; 1·2· 10 for Slalement false
Basis Path #3 ; 1·2·3 ·4·6·7·8·9· ' 0 first if statement false
Basis Path #4 ; 1· 2·3·4·5 ·6-7-9· 10 second if statement fal se

The corresponding program control gra phs arc shown in Figure 26.9.
Four test.s arc then devised with appropriate inputs to ensure that each baSIS path is executed once, as
shown in Table 26.4.

26.2.4 Equivalence partitioning

The challenge of testing is the selection of a test sct. For example, a funclion such as (ompuI< Fi"c(),
which takes a simp le integer parameter day,i.A'c, ha s all of 2" = 4 bill ion possible input values . Any test
SC I IS a truly \ln y subset of the collection of all possi bilities. and so we want il to bc as represe ntative as
possible.
EqUivalence partitio ning IS a black box test method in which paramcter values arc divided into
nonovcrlapping selS that constitute the complete set of possibilities (" partitions"), with the values in each
partition expected to produce similar rest results . (( we can identify such a partitioning, we ca n have some
confidence in a test that selects one value per equivalence partilion as test input. Equivalence panitloning i
also used in system testing, which is discussed in Chapter 28.
The potential input values for a test can be thought of as points 10 para",clcr space: an "-dimensional pace
with one dimenSIOn per parameter. For example, if we arc testing a method intended to compute the area of a
rectan gle, the parameter space is two -dimensional, each widlhnCHglh pair is a point in two-dimensional spact'.
As another example, suppose we want to test that the video Store function discussed above COII«:tiy
computes the flne on late movies. Suppose that the store's penalty depends on the number of days late.
usual but also on whether the movie is a new release, old release, or ·one·of·a·kind: The parameter space
Basis Path #1

1 1 1 1

5 5
- -

Figure 26.9 Basis paths for compuleFinesQ c:


z
=<
§
3:
~
~
0-
W

'"
1>40 CHAPTER 26 UNIT TESTING

Table 21> • 4 Tests that cover a ll basis pathS


Test Case I daysL.ateO numDVD pnntON Basis pat h

1 11,5,141 3 TRUE 1-2·3·4-5·6-7-8·9-10

2 11 ,5,141 0 TRUE 1-2·10

3 11 ,5,601 3 TRUE 1-2·3·4-6·7-8-9-10

4 11 ,5, 141 3 FALSE 1·2·3-4-5·6-7-9·10

can be thought of as consisti ng of the poi nts shown in Figu re 26 . 10. The parameter space is not limi ted to
kgal va lues; it incl ude values that are no t perm itted F'gure 26. 10 lIggem the shape of this pa rameter space.
uppo e rh.:n th(" store's Rnc calcul ation requiremt'nt is as (ollows:

The Rne shall be $2 per day fo r the firs t 5 days and $ 1 per day after that, up to th e value of the
movie. The value of all new releases shall be taken to be $20, o nc-of-a·kind releases $ 15, and old
releases $ 10

The parameter space decomposes into correspo nding regio ns such as "new re lease between 0 a nd 5 days
late," each haVing the fo llowing pro perty .

1lJ( applicallo" b,hautS in II similar marHl(r jor nil lJalu(5 hI web r(9,on .

The-se are ca ll ed r4u ilmlmcr partilio"s, o r cc[uil1alrll ct cln sses.


C rea ting equivalence classes ca n be demanding. T o (ocus o n onc region In Ollr Vi deo sto re example, we
expect that the algorithm behaves in the same way fo r all of the paramete r points in the ' I(W "fcasr/6- 15 days Ia/,
part ition shown in Figure 26. 11 .

Each element represents a pair. (Days late, Movie name)

new releases ,,, ....·1 1111111111:"::111111 :::::


••• • •
• ••••
,,
,,
,
,,, •,
•• ::::: 111111111111 :.:: 111111 :::::
old releases ,,
• ,,,
. ..!~ 111111 ... ....·

11111111111 ... ,, ,
• ••••
one-of·a-k1nd • • • • •• •

•• • • • ••
•• • •• ,
,
...-....-..- ..................._.- ........... •...... -........ -................. .......:>-
~

-5 o 5 10 15

Days late
•.g., (6 days late, "Casablanca-)

fl&un! 26.10 Parameter space for COIllputeFlneso


UNIT TEST METHODS 641

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
I
-5 o 5 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
642 CHAPTfR 26 UNIT T.ESTlNG

10 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

i f (( numDaysLat e > 5) && (numDaysLate <= 15))

H owever, a common error IS to wnte code like the (allOWing

i f (( numDay sLate > = 5) && (numDaysLate <= 15) )


If we were to uSe o nl y a value of 6 10 lest this equivalence class, Ihe boundary error would no t be
delected.
Values equal to and o n cilher side of a boundary hou ld be lested . In Ihe example above, we arc
tnlcrested in leSi ing the eq uivalence class wilh values in Ihe range [5 .. 15 ], inclusive. Test cases shou ld be
executed Ihat include the following values for PI"tnDaYSu,lr as inpul ' 4, 5, 6, 10, 14, 15, 16
In ge nera l, one identifie boundaries as follows, the principal sources for unit testing being cia s
Hwananrs and method preconditions.

1. Identify all of the variables involved , global and local.

2. Identify their limits, individually and in combination (example, the co ndition 2< x+y<7 identifies 2 and
7 as boundanes for ny).
3. Test for combinations of these variable/combination/values. Testing all combtnations is ideal but when
this is Impractical , wc select those that appear most likely to fail or we select combinations at random or
bo th.

NOle th.t 2 betng a boundary for x+y implicales the straight line x+y; 2 in the x-y plane as a boundary.

26.3 TESTING METHODS

Unit testing typica ll y stans by teSiing the melhods of a class. In this section we discuss how to carry this out in
an orderly way. incorporating the methodologies covered in the prevIOus sec tio n.

26.3.1 Checklist for Testing Methods

Humphrey [3] recommends the checkllSls in Table 26.5 for perfo rming method tests.

26.3.2 organizing Test cases

By now you may be overwhelmed by the sheer number of different types of tests . Several t t over
cs types l ap.
For example, a test with normal inputS may have statement coverage branch cov-rag d h
,. . . .. . .... c, an pat coverage.
One way to Slmpltfy and organize the Untt tests IS to lISt the testin g types as in Table 266 d L _ h
" d I d' I
In d IVI ua tests aceor Ing y .
. , an to numucr t e

26.3.3 Stubs

A method frequently depends on class« other than the one containing I't Th'
• IS pre ents no probl 'f h
needed c1ass« have already been built and tested. Otherwise, we use stand. ' . h L em I t e
inS Wit tnc same name but with
TESTING METl100S '43

TIllIe 26,$ Humphrey's unit-testing checklist, categorized black bOxor Whlte bOx In the context 0 f a me!hod test
operatIOn Comment
1. verify operation at normal parameter values a black bOx test based on the unifs requirements
2. verify operation at limit parameter values black bOx
3_verify operation outside parameter values black bOx
4. Ensure that all instructions execute statement coverage
5. Check all paths. Including bOth sides of all branches path coverage
6. Check the use of all called Objects white bOx
7. verify the handling of all data structures White bOx
8. verify the handling of all files white bOx
9. Check normal termination of all loops white box: part of a correctness proof
10.Check abnormal termination of all loops white bOx
11.Check normal termination of all recursions white bOx

12. Check abnormal termination of all recursions white box

13. verify the handling of all error conditions gray bOx

14. Check timing and synchronization gray bOx

15. verify all hardware dependencies gray bOx

just enough substa nce to support the method under test. These are call ed slubs. For example. suppose that we
want to test the ,,,,'0 method in the R",lal class of the video store application framework . It depends on the
classes R",'alI'tm and R,"laICuslomtr as shown in Figure 26. 14. \Vle therefore create stubs for these two classes as
shown.
Simple stubs like these are not .ufAcient beyond the method-testing level. As we will de cribe in
Chapter 27. in that case we require artifacts known as "drivers" as well.

26.3.4 Exam ple of a Method-Level Unit Test

As an example of a unit tcst . we will test for the fo ll owi ng detai led requirement for the Encounter cas. study.

3.2.EC. I.2 Qualities of Encoun ter characters. Every game character has the same se t of qualities.
Each quality sha ll be a nonnegative floating POlOt number with at least o ne decimal of precision
These are all initialized equally so that the sum of their values is 100. The value of a quality can not
be both greater than zero and les. than 0.5 For the Am release the qua lities shall be (Oil tt,lmli" • •
sl'''''M. ,."I/'9mCt. palltllrt . and sl""'9 Ih .

An approp"ate test ,et for a method adjusIQllalily(Slrlll9 4,mlilyP. floal vallltP) , gIven next Thi method
sets the qualtty named by 4ualiryP to valutl' and ad;u IS the rema ,n ing qualt ties so that the proportIon of
the remaining avaIlable points rema,ns the sa me Within each of the "on ranKt boundnries: ' Ollts d~ rang~:
644 CHAPTfR 26 UNIT TESnNG

Table 26.6 Checklist lor unit tests an example showing which


tests fulfilled each question
Test type Tests

1. Within bounds? 1, 12, 14, 15

2. On boundary? 12,3,5

3. Out of bounds? 6,3,4

4. Covers all statements? 9

5. Covers all branches? 1

6. Covers all paths? 1, 10

7. ASsertions tested? 12

8. Use all called objects? 6

9. verifies handling data structures? 8, 7

10. Handles all flies? 12

11 . Tests all loops with normal terminations? 12

12. Tests loops with abnormal terminations? 7

13. Tests all normal recursions? N/A


14. Tests all abnormal recursions? N/ A
15. Tests all error conditions? 11
16. Tests all synchronizations? N/ A
17. Tests all hardware dependencies? N/A

Rentalilem Rental RentalCustomer


neededByRentO
----- - ----- neededByRentO

./
........- - - - - - - dependence

Rental

. . . . --------<'0' ,estin~g;---------//
stubbsd

fl&ure 26.'. USing stubs to test a method


resnNG METHODS U5

Unit test 01
sdjustOuafllyO

Within range On boundary Out of range

fIIU/'I! 26.15 Partitioning iJdjustQualityO at the top level

Within range

Does not result in zero Results in zero

concentration stamina •• • concentration stamina •••

FIgure 26.1 6 Partitioning adjustQualityO-" within range"

and ·within range" categories, we try to obtai n systematic coverage by seeking represe ntatives of eaeh
equivalence partition . Figure 26. 15 is typical of a systematic deco mposi tio n of the input space into
equivalence partitions.
The next levels of partitioning are shown in Figures 26. 16, 26. 17, and 26 . 18, and the actual test ca es are
listed below.
A resulting test suite is s hown in Table 26.7.

On boundary

Parameter :;:; zero Parameter:;:; total current points

concentration stamina •• • concentration stamina •• •

Fl&ure 26.17 Partitioning adjustQuality(}-"on boundary"

Out 01 range

Above upper limit Below lower limit

=t
CXlI1Cantration stamina ... concenlration slamlna ...

26.11 Partitioning adjustQuallty(}-" out of range "


~6 CHAPTER 26 UNIT TESTING

Table 26.7 A test suite for adjuSrQualityO

Key to unit tests of adjusrQualltyl} (Details for each test follow this table)

1. Within range

1.1 adjustQualiry(} does not result In a zero value

1.1.1 quality parameter ;; "concentration"


..'
1.1.2 quality parameter ;= stamina "

• • •

1.2 adjustQualiry(} does result In a zero value

1.2.1 quality parameter = '"concentration"


1.2.2 quality parameter ;= "stamina"
• • •

2. parameters at range boundaries

2.1 zero parameter

2.1.1 quality parameter == "concentration'"


2.1.2 quality parameter ;; "stamina'"
• • •

• • • •

2.2 parameter value = current lotal points

2.2.1 quality parameter =; " concentration"


2.2.2 quality parameter ;= '"stamina"
• • •

3. Parameters outside range

3.1 Above upper limit of parameter values

3.1.1 quality parameter = "concentration" ; total points ; 100; parameter 101


.. .
3.2 Below lower limit of parameter values

3.2.1 quality parameter = '"concentration'"; total points = 100; parameter -101


.. .

The following a", th e details for each of the tests.


Test 1.1.1
1"""" (Ideally, choose these at random between 0 and 100 to sum to an amount les than 100.)
Concentration 10, Sl<Imin.10 [ 1/ 4 of the non-"concentration" points), lntelligence 10, Patience 10, Strength 10,
Eucuk' .Jjw,IQ..lity("colICfII,r.,i"". " .0) (Ideally. this value is chosen at random Within bounds guarantttd
not to rC!SUlt in a zero "coO'C('ntr.ltion" value.)
TEST-DRIVEN DEVELOPMENT 647

&".<11'1/ .... ,""" Concentration 20 + 10 = 30, Stamina 70/4 = 17.5, (Note, remains 1/4 of the non -
·concentration" points), Intelligence 70/ 4 = 17.5, Patience 70/ 4 = 17.5, Strength 70/4 = 17.5,
Tests 1.1.2, 1.1.3, '" are similar, using the other qualities Instead of concentration.
Test 1.2. 1
I'PIII, Concentration 20, Stamina 20, Intelligence 20, Patience 20; Strength 20,
Extoll<;adiustQualiry('"conC"rtltmtioll". 99)
Exprcl<a output , Concentration 99, Stamina 0 ( 1/4 result replaced by zero), Intelligence 0 ( 1/4 result
",placed by zero),Patience 0 (1/4 result replaced by zero), Strength 0 ( 1/ 4 result replaced by zero),
Tests 1.2.2, 1.2.3, ... are similar, using the other qualities instead of concentration .
Test 2. 1.1
I.pu" Concentration 0, Stamina 25 ; Intelligence 25 ; Patience 25, Strength 25 ,
Exrcu't , aaiu"Qualiry(",lamilla", 7' )
Exptclta outpu" Concentration 0; Stamina 99; Intelligence 0 (result of 1/ 3 is set to zero), Patience 0 (result
of 1/ 3 is set to zero); Strength 0 (result of 1/ 3 is set to zero)
Tests 2. 1.. 1.2, 2. 1.1.3 , ... are similar
Tests 2.2, 2.3 , . . . pertain to other extremes. For example,
2.N aaiu"Quality() called with parameter equal ing a current value
Input, Concentration 0; Stamina 25; Intelligence 25; Patience 25; Strength 25 ,
EXtcutt, aaiu,tQualiry('", lamina ". -25)
Exptclca ou'put, Concentration 0; Stamina 0, Intelli gence 33; Patience 33; Strength 33-,
Test 3. 1.1
Input, Concentration 20, Stamina 20, Intelligence 20; Patience 20, Strength 20,
Extcu't, aaius,Qualiry("conctn'ration". 81)
Exptctra output, Message to error log stating that adjlls,Qllaliry() was called with out ·of·range input;
Concentration 100; (20+81 set to 100); Stamina 0; (after concentration is set, there are no remaining quality
points to distribute); Intelligence 0; Patience 0; Strength 0
Tests 3. 1.2, 3. 1.3, ... arc sim ilar
Tests 3.2, 3.3, ... are similar to test 3. 1
Test 3.N . 1
Input: Concentration 20, Stamina 20, Intell igence 20; Patience 20, Strength 20;
Ext, u't: adill s,Qllal,ry('"conctnlralion". -2, )
Exprcltd OI'P"t: Message to error log stating that IIdjllStQ llalily () was called with out-of·range input;
Concentration 0; (20-2 1 se t to zero ); Stamina 25; ( 100/ 4); Intelligence 25 ( 100/4); Patie nce 25 ( 100/4);
Strength 25 ( I 00/4).

The remaining test set is ge nerated in a sim ilar manner


The relevant partS o f the code fo r adi llslQ llaliry arc part o f th e class EncolI,II"Chllracfcr , give n in listing
26 10 found in Sectio n 5. 1

26.4 TEST-DRIVEN DEVELOPMENT

All dfective me thod for pe rform,"!! un it testin g IS to co nduct te nng in par.tllel with implementatio n. In fact,
in dfective way to "Ulld qualllY in to an impleme ntation i< to specify the tests that an implem entation mll t
pass be/orr writing the cndc After wnlln j.( u h a test, o ne add. to the impl ementat ion lIntil the teSt '" ceeds
648 CHAPTER 26 UNIT TESnNG

Th" " called ItS l-dmlCll droc/opm"'1 (mDl TDD is ofte,; a"oclated with ag ile devel o pm e nt, but ,t IS useful
w, lh,n any developmenl process The general sleps Involved in TDD arc as follow s:

I. Write a leSI case for some code lhal " yet 10 be IInplcmcnled
Envi ion what lhe code is suppa cd 10 do. Dependlllg on how tho roughly this part of th e code was
previously designed , a bit of dCladed de<lgn may be required Tests arc tYPically c reated to test only a
relalivcly small amount of code as lillie as several lines.

2 Run the lesl case to verify it, which fa ll .


The first nln of the Icst shou ld always fai l, since the code to make it pass has yet to be written . If it does
pass, there Iii; a bug in the tcst case and It needs to be fixed .
3 Wrile only as much code as necessary to make the leSl pass.
In th is wa y il clean implementation emerges with minimal extraneous code.

4. Run the lest case .


lf il slill fail s, go back to Step 3 and fix Ihe problem in the implementallon. It il passes, the test ca e is
complete. If there is morc Implementation to be done, repeat these (our steps .

Figure 26. 19 summarizes this process .


There arc many advantages to mD, includi ng Ihc following :

Stalement coverage-A natural by· product ofmD is thaI after the lests arc wrilten and pass, every line
of code is executed by al IcaSl one tcst . Thus sta tement coverage is satisfied .

Cleaner code-As we men tioned previously, only as much code as necessary is written to make a tcst
pass. TI"Iis results in an implementation that tends to be clean and contai ns little extraneous code.

Rapid feedback-Once a seclion of code is wrillen , it is immediately tested , providing instant feedback
as to its correctness. TI"Iis leads to quicker development time a,s bugs are easier to identify and correct.

Suite of unit tesls-After a test is wrillen and passes, It is saved along wilh olhertests being developed. In
this way a suite of unit tes~ iscreated and can be used for huurc te sting activities uch as regression tC'Sting.

II is common to perform mD within a testing framework such as JlI"'t, which we describe next.

, . 2. Write a test
case (wiliiall)

_-+I 3 . Wrile/flx code 10 Test passes. more


pass test tests to be written
rest falls

4 . Run test case

Test passes, no more


tests to be written

FIgure 26.19 Test·drive developlilent-the activities


TEST·DRIVEN DEVELOPMENT 649

26.4.1 using JUnft for Unit Testing

]U.1t is a public·domain te t framework widely used to "wnte and run repeatable tests" [4]. It is implemented
In and u ed for testing Java programs It supports lInit testing with tools lor test result executio n, reporting,
and error handling .
uppose, lor example, we have a Calculator class and we want to write a test lor a yet.to·be coded
ubtract method. 11 we are uSing TOO, the Rrst step is to write a unit test lor the enVisioned method. By
convention. when testing a clas X, tests arc placed in a clas TtS'X and every method perlorming a test 01
method mmmm {) is labeled ItSlMmmm O.
listing 26.4 is a Teste alew/ator class that co ntains One test called IrslSub'racl.

26.4: JUnit class for testing Calculator

~rtjunit.framework.TestCase;
public: c:l . . . TestCalculator extends TestCase
{
public: void test Subtract ()
{
=
Calculator c new Calculator () ;
/ / Test 1: Nominal Case
double r = c. subtract (2.0000000001, 3.0000000002) ;
assert:Equals ( -1.0000000001, r, 0) ;
/ / Test 2: Corner Case
r = c. subtract (Double . MA)CVALUE , Double . MA)CVJlLUE) ;
assertEquals (0.0, r, 0) ;
• • •
}
}

By ~xamining testSubtract we can imagine the code we must wntc to pass the test :

I A subtract method that takes two double arguments and returns a double result.

2. An implementation of a subtract method that subtracts the second argument from the Rrst and returns the
result of the subtraction .

To fulfill our envISioned method, we write a subtract method such as in Listing 26 .S.

Llltlna 26.5: Building subtractO method for the class Calculator


package EB . calc I

public class Calculator


{
650 CHAPTER 26 UNIT TESTING

public double subtract(do u ble n1 , do uble n 2)


{
ret u r n n 1 - n 2 ;
}
}

,
..' nrrul

-----_. ----- - .. -

-
1I!I . . . . ~R2',.

I I u
•- •
- '"

Figure 26.20 Outp~t of JUnir for a simple test

The result of runn ing T estCalcul ator in J Un it is the wi ndow in Figure 26.20 showi ng a g reen bar (for
"passed") .
T o illustrate what hap pens when a tes t fails. we wi ll fo rce a d efec t with a new subtract that erro neo usly
converts to float , as in Li sting 26.6.

Ustlng 26.6: Example of a test that will fail

package EB. calc;

public class Calculator


{
public double subtract (double n1, double n 2)
{
float subtract ion = (f loat) n1 - ( f loat) n2;
return subtraction;
}
}
TEST·DRIVEN DEVELOPMENT 651

~;;;;; e~e" ed ... , 000000000 1" butwa s '- I 0'


al EB calc TestCalcutalor.testSublr.ut(TestCalculalor Java.! ' )
at sun retlect.Nallve MetnoClACcessorlmpl tfft'OkeQ(Nattve MethOd)
at sun reneclNatJvelrllettlOdA.ccessorlmpl lnvoke(lJnknown Source)

Figure 26.21 Junit display for a failed test

Re-executing the testSubtract unit test from


Listing 26.4 results in aj Uni t response like that shown in Figure 26.21 , with a red bar indicatin g failure .
In o rder to run multip le unit tests, j Un it imp le ments th" TtSrS",r, class. Suppose that in additio n to the
T,srCa/cuiaror/Ca/cu/aror pair we also have a T,srCo"wr,,,"rorICo,,cnrttl" ror pair, as shown in Listings 26 .7 and
26.8, respective ly. If we run j Unit us ing t he TtS rAll class show n in Listing 26 .9, bo th of these tests will be
execu ted .

Ustlng 26.7: Test for Concatenator class

import junit.framework.TestCase;

public class TestConcatenator exte nds TestCase


(
public void testconcatenation()
(
Concatenator c = new Concatenator () ;
Str ing str ing = c . concatenationOf ( " abc ". "def " );
assertEquals ("abcdef ". string) ;
}
}
652 CHAPTER 26 UNIT TESTING

Listing 26.8: Concatenator class

public class Concatenator


{
public Str ing concatenat ionOf (Str ing as t r ingl ,
String aString2)
{
return aStr ingl . concat (aStr ing2) ;
}

Listing 26.9: A TestSuite example, combining tests for Calculator and Concatenator

import junit . framework . Test ;


import junit . framework . TestSuite ;

public class TestAll extends TestSuite


(

public static Test suite()


{

TestSuite testSuite = newTestSuite ( " A simple test suite example " ) ;


test Sui te . addTestSuite (Test Calculator . class) ; / / Add all test s
from TestCalculator class
test Sui te . addTestSuite (TestConcatenator . class) ; / / Add all
tests from TestConcatenator class
return testSuite ;
}

26.5 CASE STUDY: ENCOUNTER VIDEO GAME

26.5.1 Code Ustlng for Encountercharacter Class

listing 26. 10 IS the class EncolmtrrCbaractcr from the Encounter video game.
CASE STUDY: ENCOUNTER VIDEO GAME 653

10: EncountefCharacter class from the Encounter video game

1* Class Name: EncounterCharacter


• Date: 01/13/2000
• Copyright Notice: copyright (c) 1999-2000byEricJ. Braude
* Edit history:
* 24 Dec 2003 Er ic Br aude Edited to simple stand-alone version
• to show unit test of adjustValue ()
* 24 Jul 2000 Tom VanCourt Cached character image rather than
* recreating it on every repaint.
* 13 May 2000 Tom VanCourt Moved saveQualityValues , getOldValue
* and oldValueI from Player Character
*/
ioIpOrt ). ava. aw t . * ;
.
ioIpOrt)ava.l.o.. *;

1** Base class for the characters of the Encounter game.


* <p > Requirements: SRS 3.2. EC
* <p > Design: SDD 6.2. 1
* <p> Invariants: <01 >
* <li> encounterCharacterS contains all objects of this class
* <li> The values of qualValueI [1 are >= 0
* </01>
* <p> Design issues: <ul >
* <li> Character images are switched freely between right- and
* left-handed forms. That means that sword fighter swill swi tch
* hands; scabbards will swing back and forth; scars, tattoos, etc.
* will move around, hair styles will f lop back and for th, etc.
* It's good enough for now, though.
* </ul>
* @author Er ic Br aude, Tom VanCourt
*@versionO.2
*1
public cl ••• EncounterCharacter extends GameCharacter
{
1** Total quality points at initialization .
* <p> Requirement 3 . 2 . EC. 1. 2
*/
public atatic tlnalllo.t OUAL_TOTAL_INIT = 100. Of ;
// Symbols used when other classes refer to specif ic qualities.

/** Symbol f or one of a charac ter ' s quali ties * /


publ.1c ataticflnal String OUACCONCENTRATION= "concentration";
654 CHAPT1:R 26 UNIT TESTING

/ **Symbol for one of a character's qualiti e s */


public static lind Str ing QUAL_INTEL LIGENCE = "in te lligenc e " ;

/ ** Symbol for one of a character's qualities * /


public static lind Str ing QUAL_PATI ENCE = "pat ience" ;

/** Symbol for one of a character's qualities * /


public static final St ring QUAL_STAMI NA = "stamina" ;
/** Symbol for one of a character 's qualities * /
publl.c static final String QUAL_STRENGTH: "strength";

/ ** Qualities that each Encounter character possesses.


* <p >Reg: 3.2. EC. 1. 2
*/
protacted static final Str ing [1 qualityTypeS =
( QUAL_ CONCENTRATION, QUAL_STAMINA,
QUAL_INTEL LIGENCE, QUAL_PATIENCE,
QUAL_ STRENGTH
) ;

/** Root directory for graphics files. */


static find String FI LE_ROOT = "edu/bu/braude/SWEngExample/";

/* INSTANCE VARIABLES * /
/ ** Values of the qualities. <p > Requirement 3.2. EC. 1. 2 */
protectad float[ 1 qualValueI : n•• fIoat [qual it yTypeS . length 1 ;

/** Quality values before the last engagement


* <p> Requirement: 3.2.AR.4.6
*/
protectad float [ 1 oldValueI = n•• fIoat[qualValueI.lengthl;

/** Name of GIF file containing the character image.


* The character in this image is assumed to be facing left.
* Select this character's height, relative to heights of other
* char acter s,
* by padding the to~ and bottomwith transparent pixels. No padding gives
* the tallest posslble character.
*/
prohct.ad String imageFileNameI: null;

/** Displayable image for the character. Initialized when used. */


pri.Yata Image chImage I = ma.ll;

/* CONSTRUCTORS */
CASE STUDY: ENCOUNTER VIDEO GAME 655

/ ** Allocate initial total qualitv oints . .


" <p > Requ irement . 3 2 E - p . equally among the quall.t:les.
"/ . . . C.1.2 (qual:ltyvalue initialization)
~uct.1 EncounterCharacter ()
{ Lupn ( ) ;
for( int i = 0 ; i < quali t yTypeS . length· ++ i)
qualValue . I til = QUAL_ TO TAL_ I NIT / qu'ah. tyTy peS . length;
saveQual:ltyValues() ;
}

{"* Construct a new character using the given name .


<p > Requ:lr emen t : 3 . 2 . EC . 1 . 1 (char act e r naming )
* @param nameP Printable name for the character .
*/
protected Encount erChar ac ter (St ring nameP )
{ this (nameP, null ) ;
}

/ ** Construct a n ew character using the give n name and i mage file . I


* <p > Requirement: 3 . 2 .E C.l.l (c haracter naming )
* @param nameP Pr intable name for the character .
*@param imageFileP Filename , relative to docume n t base,
* f or the character image file .
*/
protect.d Encoun terChar acter ( Str ing nameP, Str ing imageF ileP )
{ thia ( ) ;
setName (nameP) ;
imageF ileNameI = FILE_ ROOT + imageF ileP;
}
/ * KETHOOS * /

/** Adjust qual ity values , normally retaining a co n stant total.


* Synchr o nizat ion holds qualityValueI constant even with other
* threads running .
.. <p > Invariants: see the class invariants
.. <p > Preconditions : qualityp is in qualityTypesS [1
.. ANO q ualityValueP >= 0
.. AND qua lityValueP <= the sum of the quality values
* <p > Postcond itio ns: qualityp has the value qualityValueP
.. AND the rema ining quali ty values ar e i n the same proport ion as pr ior to
.. invocation , except that values less tha n some tolerance are zero .
.. <p> SOD : 6 . 1 . 2 . 1 . 1
.. <p > SRS : 3 . 2 . EC . 3 . 2 : " Conf igurab ili ty of Encounter character qua li ty
.. values. "
"@param qualityp Quality whose value is to be adjusted .
656 CHAP! fR 26 UNITTfSnNG

* @param qualityValueP The value to set this quality to .


*/
public ayncbronizad void adjustQuality (Str ing qualityP,
float qual i tyValueP)
{ / / Value of the quality to be changed
float quali tyValueM = qual Value I [indexOf ( qual i tyP) J ;

/ / Save the sum of the values


float or iginalSumM = sumOfQualit ies ( ) ;

/ / Set the stated quality to the desired amount,


/ / adjusted to the threshold value.
setQuality(qualityP, qualityValueP);

/ / If the caller adjusts the only non-zero quali ty value,


/ / divide the adjustment amount equally among all other quali ties.
if (or iginalSumM == quali tyValueM )
{
float quaU tyDiffEach = (or iginalSUmM - quali tyValueP)
/ (qualityTypes.length - 1);
for(int i = 0; i < qualityTypes.length; ++i )
if( ! qualityTypeS[ iJ . equalsIgnoreCase ( qualityP ) )
setQuality(qualityTypeS [ iJ, qualityDiffEach ) ;
} ala. {
/* Compute factor ("proportionM" ) bywhich all other qualities must
change.
* Example: if the valueswere 1,3 , 5 (i . e . sum9) and the first
* qualities changed from 1 to 2, then "3" and "5" change from B/9 of
* the total to 7/9 of the total, so each should be mul tiplied by 7/B ,
* Le., by (9 -2 )/(9-1).
*/
Coat proportionM = (or iginalSumM - qualityValuep ) /
(or iginalSumM - qualityValueM ) ;

/ /Adjust remaining qualities, retain i ng their mutual proportion


for(Uiti=O; i<qualityTypeS.length; ++i)
if( !qualityTypes[iJ.equalsIgnoreCase (qualityp ))
setQuality(qualityTypes [iJ, qualValueI[ iJ * proportionM ) ;
}
}
/** Get a copy of the list of names of quality values.
*@returnworkingcopiesofnamestringsr eprese ntingqual . t '
*/ ~ ~es .

public aUtic Str ing[ 1 getQualityTypes ()


{
CASE STUDY; ENCOUNTER VIDEO GAME 657

Str ing ' [] r eturnListM


. = // Copy the s t rlng
. array .
IIZ1I St r l.ng [ quaIl tyTypes . length J ;

for(1Ilt i = a'; i < ~ali<YTypeS . length ; i++) // Copy each string.


returnL1.stM[ 1] = new String( qualltyTypes [i]);
dturD returnL1.stM; // Retu rn the copy .
}

/* * Returns the value of the specified quality .


* <p >precondit ion: quali tyP is a valid member of qualityTypeS [J
* @param qualityp The quality we want the value for.
• @return The value of the specif ied quali ty .
*/
pablicf!olt getQualityValue (St ring qualityp)
(
return qualValueI [ JndexOf( qualityp ) ] ;
}

/** Quality values below this threshold are set to zer o to


* avoid having the game go on for an indeterminate amount of tim e .
*<p>Requirement:e.g.3.2.EC.l.2 ( 10werlimitonnon- zeroqualityvalues )
*@return Tolerancevalue
*/
atat.icflndfioatgetTolerance ()
{ HturnO. Sf;
}

/** Returns the index of the the specif ied quality .


• <p> Precondi t ion: qual i tyP is in qualityTypeS [ ] ,
* give or take capitalizat ion .
*@param qualityp The quality we are searching for .
*@return Thequalityindex.
*/
protlctlcl.tatic int indexOf ( Str ing qualityp)
(
//Default to "missing" value.
iIIt r e tur nlndexM = - 1 ;

// Search quality name table and not e t ,he i nd ex value.


fo,. (illti =O · i < qualJtyTypes . length; ++1.)
1f (qua l1ty~s [i] . equalSlgnoreCase(qualityP» {
return lndexM = i;

}
zoetum returnlnd e xM;
}
658 CHAPTER 26 UNIT TESTING

/ ** Set default max imum number of characters in names of charact e rs .


* <p >Requir ement : 3 . 2 . EC. 1 . 1 (1 iroi t on char acter name l e ngth)
*@return Maximum number of characters allowed in a character name
*/
protect odint maxNumCharslnName ()
{ return 15 ;
}

/ ** Preserve the current quality valu es . * /


publl.csynchronizedvoid saveQualityValues ( )
(
for(i nt i=O ; i < qualValueI . len gth ; i++)
oldValueI [i) = qualValueI [i) ;
}

/ ** Set a quality value without regard to the values of other qualities .


* Truncate any value below the threshold value down to zero .
* Synchronizatio n prevents cha nges to qualityValueI while other
* threads ar e using it .
* <p >Requirements : 3 . 2 . EC . 2 ( l ower limitonnon- zero qualityvalue s ) ,
* <p>Precondition : qualityp is a valid member of qualityTypeS [ )
* <p>Postcondition : Quality values are greater than to l eran ce or are O.
*
*@param qualityp The quality to s e t the val u e of .
* @param valueP The valu e to set t h e qua l. ity to .
*/
publicayncbronizeclvoid setQuality (Str ing qualityp, Coat valueP)
{
i t (valueP
< getTolerance ( ) )
qualValueI[ indexof (qualityp») =O . Of ;
.1_
qualValueI [ i ndexOf (qualityP) I =valueP ;
}

/** Computes the sumo f the quality values .


* Synchronization mak es sure t h at a n other thr ead wo n' t c h a n ge
* qualityValueI wh il e th is th r ead ispart -way thro ugh computing the
* total .
* <p > Requireme nts : 3 . 2 . EC . 3 . 2 (proport ions among quali tyval )
* <b r > S RS 3 .2. EC .3. 1 Ll.vl.ngp0l.
., . nts ues ,
* @return The sumof t h e player ' squalities , a value 0 or great
*/ er .
publ1cayl>cbronlzodfloat sumOfQualit ies ( )
{
float sum!! = O. Of ;
CASE STUDY' ENCOUNTER VIDEO GAME 65.

forCint i=O; i <qu.. llCyTypes . length ; ++i)


sumM += qual ValueI [ i J ;

retum sumM;
}

} / / end of EncounterChar acter

26.5.2 Unit Tests for the


Encountercharacter Class
For si mpl,ci ry , thi s unit re t includes teS t data
with the method . Normally , ho,,'cver, the
ote to the Student: Input data and the expected output are rc ·
The format of this docllm ent is derived from tri eved from a Ale .
the IEEE Standard lor Software Test Docu -
mentation This document applies to the tes t· 3. Test Procedure Specification
ing 01 one class. JUnit was not lIsed in tillS case
but could have been . TI, e unl! test' for E"co",,'rrCbnfllCltr arc IOltiated by
execut ing the ",mil O method of EncounlrrClJn rncttr
The parameter su pplied to mni" O speCifiC the fl le
UNIT TEST FOR THE
to wh ich th e rc ult are wnncl1
ENCOUNTERCHARACTER CLASS

1. Test Design Specification This is a si mple procedure . H owever, the


procedure becomes can iderably more com-
The unit te~l (or Eli collnlerClJnraclrr co n 1St .... of rwo plex when sourCe flies and u er interaction arc
public methods as follows. involved For example , this will be the case in
unit tes tin g the class E" o""'trG",",
ItSIE"co""lrrOlflracltrM"hod.O teSt- cach of the
methods in rurn
4. Test Results Documentation
ItsIE"co""'trChararl,, 1a sO test< <cquen cs of
methods The test re lilt documentatio n o n"5r, of the te t
log , tt·<t incide nt report , and test su mm ary report
The,c methods ca n be executed by E"co",,',,-
Cha"",d, mamO method or by an external ob)cLl 4.1 Test Log

2. Test Case Specification


Till I< an ac ount of the tt' 1', result. et, the
The i.est cases for £"(0""'''( /",,"(/tr are bu d t 1111 0 eX' l1lrle helow
InIEHco""'trCha"'<I,,Mtlhoa.() alld 'tl'£"'.""'''( /"''''(-
IrP( 1us.(J
660 CHAPTER 26 UNIT TESTING

1l\1~ IS co ntained in RIc Etlcolmlcr bllradt,_ » » setQuoIIlYO Test I nominol volue


Tnl_Lo!l_dllY _molllh-J,tnr doc ««<
Ac tual Ooal = expecled Aool.
» » selQuolityO Tesl 2: nominal value
4.2 Test Incident Report
««<
Actual Aoal = expecled Aoal.
This Includes any occurrences or noteworrhy > > > > adj ustQuahty() lest 0: verify that values
~vc:nrs that occur during te ting Sec the exam- add 10 100 « « <
ple below AClual Aoat = expected floal.
> > > > adjustQ uali tyO lest 1: ve ri fy values sum
to 100 afrer adj u l,ng « « <
Thi s IS co ntained In file E",oulllrrCl}fIrtlClt,_Ttsl_ Actuol Aoat = expected Aoar.
1n""Jntf_da)' _molll" Jcnr doc > > > > adjusrQua l,ty{} tesr 2: verify values ad-
jusred as commanded « « <
4.3 Test summary Report AClual floal = expected Aoar.
» » adjusrQuo li ty() tcS! 3: verify low va lue
This IS contained in fi le reve rts to zero « « <
f" co,m l,rCharael"_T",-Sum'M'Y_R,porCdQ)'_ AClual Aoat = expected Aoal.
lI1otllh-ywr. doc > > > > odjustQuality() ICS! 4: veri fy values sum
EX<lmple of a Test Log (Seclion 5 of the Per· 10 100 ofrer odJusring < < < < <
sonal Software: Documentation ): ACluol Aoat = expected Aoat.
EncounterCharacler_Tes,-Lo!:-, C lass test :
26JuU999 » » Class ICS! ge-aq-so « « <
Mel hod tests: 100.0 < - - Ob lained
> > > > GetChorocler T est I: nom,nol vo lue 100.0 < - - Required
««< » » Cl055 test ge·aq·aq-gq ·so: part I
querry < - - Obtained «< «
querry < - - Required 20.9876 < - - Obtained
> > > > GetCharactcr Test 2: Outside porame· 20.9876 < - - Required
ler values « « < » » Closs test gc ·aq-aq-gq-so, part 2
ddoultNamc < - - Obrarned «< «
ddaultName < - - Required 100.0 < - - Oblained
> > > > EncounlerChoractcr Test 3: limil po· 100.0 < - - Required
rametcr values < < < << » » Class lest for Ihe invariant '_q uaIValue
1234567890 12 345 < - - Obtained [iJ >= 0'« « <
1234567890 12 345 < - - Requ ired true < - - Obta ined
Expect one name rOT each charactcr tn'e < - - Required
Querry
defaultName
1234567890 12345 The leS! log example doc:s not show failed t~ts.
» » i ndexOfO Test I: valid quolity nome These can be delailed in Ihe log, transmitted 10
««< a separale fi le, and con ge nerale monilor leXI.
Actual tntc:gcr = expected in teger.
» » lndexOfO Test 2: volid qualilY name
««< Example of a Test Inc,dent Report ( eelion 4 2
Actual Integer = expected integer. of the Pe"onal Soflware Do ume nrion ): f"co.,.;"
Cbarael"_T" '_/lIcidtlll_26_Jul_199. dO<'
CASE STUDY: ENCOUNTER VIDEO GAME 661

Th( test was allemptcd With version 7.2. I of E. Braude in version 6.5.2. They are due to ~
&. o"."rCbarael" using version 2.3 of the TrslUliiilits expanded in later versions of EHeO"HltrCbaraCltr.
package . On th e first try , the test fa ded to run . Example of Unit Test Source Code:
We think that t his wa due to the fact that we did The fo llOWi ng code, for the EHcowHlrrCharaCltr
not really have version 2.3 of Ttl/liIiiilit! . When class, includes self- test methods.
we ~Ioaded this package , the test ran without The class TtslEx<cwlioH is used to execute the
Incident. un it test . It contains a static method pri.,RtportToFik()
whose parameters , in Javadoc notation, are as
fo ll ows.
This is a good place to mention mistakes made * @param - FileWriter - Destination of report
dunng testing. These are particularly prevalent
when user actions are required, and it is im-
* output.
• @param - String - A description of the test.
practical to rerun the e ntire test. * @param - iot - The expected correct result.
* @param - int - The actual result .
Example of a T est Summary Report (Section 4.3 * @return - void
of the Personal Softwa re Docume nti o n): Elleoll.'''' * @exception - None
CbaraeICT_T lSI_Summary _26_111'_' 999 doe There are no preconditions. The postcondi-
This test was executed by Joh n Jones at 2:00 tions afe that a fi le has been written to the destina -
P.M. using release 1. 1.6 of Sun's virtual machine . tion indi cated by the FiitWril" input parameter. It
Subject to the anomalie in the test incident report , conta ins the test description input, the expected
the results were 100 percent pass o n the bui lt -in unit result , and the actual result, each clearly indicated.
t<st methods. These met hods were inserted by The test code is shown in Listing 26 .11 .

listing 26.11: Control for testing EncounterCharacter

1** To test th is class


* @param argsP destinatian .of methad test lag, class test lag
* respectively
*l public static void main ( S t ring [J ar gsP )
{
II Default files an which ta write test .output run tests &
Str ing methadOutputF ileNameM = "methodOutput. txt" ;
Str ing classOutputF ileNameM= "c lassOutput. txt" ;

i f (argsp ! = null && argsP . length == 2) I I use defaults if input



lmpraper
{ methadOutputF ileNameM = argsP [OJ ;
classOutputFileNameM = argsp[lJ ;
}

I l l . EXECUTE TESTS WHICH DO NOT REQUIRE HUMAN INTERVENTION


I I Test methads individually , then test class
try
{ testEncounterCharacterMethods(methodOutputFil eNameM);
662 CHAPTER 26 UNITTESTING

testEncounterCharacterClass(classOutputFileNameM) ;
} catch (IOE xc e ption eP)
{ System . out . println (eP) ;
}
//2 . EXECUTE TESTS WHICH DO REQUIRE HUMAN INTERVENTI ON
Frame [) imageTests: { // Display test cases
new testCharacterImage ( // Missing image
new Enc o unt erChar acter ( " GuyWi thNoImage" , null ) ) ,
new testCha ra cterImage( // Image is present
new EncounterChar acter ( "E lena ", " e lena . gif " ) )
} ;
for( i nt i = 0 ; i < imageTests . length ; i ++) (/ / Display each t est window
image Tests [i) • setSize (400 , 250) ; // Adequate size for char acter

imageTests[i) .setVisible( true ) ;


imageTests[i) . show( ) ;
}

try { // Let user examine windows


Thread.currentThread() .sl eep(30*lOOO ) ;
} catch ( Exception exc) {
}

for ( int i = 0 ; i < imageTests.length ; i++) // Shut the windows


imageTests[i) . dispose();

System.exit(O ) ;
}
/ ** Tests this class by executing its methods in combination
* @param destinationP Location to write results
* @exceptio n IOException I f there's a problem opening or accessing
* destinationP
*/

Class testing is covered systematically in combinations of methods The code testing


Chapter 27. It consists largely of testing EncOImrtrCbarncftr is given in the cas< study th<ie.

26.6 SUMMARY

Unir .r"ring ' e IY J fte '


f is conducted by softwa .. develop<" either In conJ'unction w'I th or .1m m ed lat I .
a Unit 0 code. Units are typically Ih< methods and cla"es of t L • soft B L L r Imp <menll ng
,,- wa.. . Ot" W",re b · d bl k b
methods are utilized. ox an ac ox
EXERCISES 663

Thl! Ilrs! tl!P in unot testmg is Identifying units and dl!termining what they arc intended to do. This
comes from one of several sources, the SRS, the SOO . or else a motivation tOO minor to specify in the
DO. For methods arising from design, we may not possess explicitly stated requirements against which to
pl!rform tests.
A systl!matic approach is required to effecti vely implement unit testing. In this way, as man y errors as
possibll! at as serious a level as possi ble can be d iscovered within a practical time period and usi ng a prac tical
amount of labor. The Arst ste p is o rga nizing the testing-typicall y methods are tested Arst, followed by
classes and packages.
The extent of testing should be considered and defi ned in advance. Test cases are selected from one or
more categories of tests, both fro m no nnal ex pected operation and those judged most likely to fail. Stopping
criteria are established in advance; these are concrete conditions at which point this particular testing process
will hi! considered done.
Depending on the problem space of the software , there is ofte n a set of test data that is pecific to the
application . If applicable, obtaining and usi ng this data must be planned .
Unit testing is typica lly conducted by deve loper , as they arc the most fa miliar with the structure a nd
organization of the code under test. H owever, un it testing is sometimes conducted by a separate organizat io n
such as QA because of their object ivity . Th is requires extra time fo r the new o rganization to learn the
software desig n so they can successfully executed the tests .
As with other phases of development . metrics are co llec ted during un it testmg. Metrics collected
include number of test cases, number of tests per test ty pe , a nd percentage of fai led teSts.
There are several d iffere nt types of white box and blac k box testing metho do logies empl oyed during
UOit testing. White box methods include statem e nt coverage, branch coverage, and path coverage . Black box
methods include equivalence partilionin g and boundary va lue analysis .
When testing the methods o f a class. a strategy is required to ensure proper test coverage. Humphrey
recommends u ing a checklist that includes Ite ms such as usi ng no m1al parameters, parameters at their boundaries,
illegal values, handling of error conditions, path coverage, loop termination , timing, and hard,,'are dependencies.
After the individual metho ds of a class are tested , the class as a whole is tested . All of the class methods
are tested in combina tio n. Th is is because the methods of a class are freque ntl y interrelated as they may alter
the values of common class attributes. Focus i placed o n eque nccs likely to be comm o nly used and
sequences that appear most likely to contain defects. If an ohject of a class transitions th roug h several states,
s!ate·based testing is emp loyed .
An effective method fo r performing unit testing . a nd to build q uality IO to a n Impleme ntation, i to
specify the tests that an implementation must pass btforr wri ting the code After " 'fi ting a te t, one adds to the
Implementation until the test succeeds. This IS called ',s ,·dr",,,, dwt/op,""" (TOD ). T OD IS ofte n associated
wi th agile developme nt, but it is usefu l for a ny deve lopme nt p rocess.

26.7 EXERCISES

t. In your own words, d escribe t he difference between white box and black box te ting . Why is each
Important and ncccss ary ~

2 Why do you think unit lesting is u,ually co nduc ted by lhl' d~vcloper ,vho Impleme nted the unit]

3 a What is eqUiva le nce pa rt lt ionlng~ \~hy I It Im portant to partitIOn th e te t ,po e into


eqUivalence cla sses ~ rlease usc your own wo rd, in re<ponding
b For lhe followll1 /l fun cll o n, de "be five d iffe re nt les t a,cs Jnd for ca h des nbe the type 01
test case II represents The applica tio n i, ha,cd o n Myer, tn ang le prohlem [5 ).
6~ CHAPTER 26 UNIT TESTING

Il x, y and z are the lengths of the sides of a tr iangle . This funct io


class if ies the

Iitriangle and returns either ' ' scalene " (all sides unequal ) ,
, , isosceles" (two sides

Il equal) or "equilat eral " ( all sides equal) . If x, y and z don't


form a tr iangle

II (Le. either (a) x, y or z is <= zero, or ( b) ( x +y ) < z) the null


string is returned

IIAssumption: x,yandzareinascendingord er ( i.e. x <=y <=z) soyou


do not need

li to test for this


char. triangle ( int x, int y, int z)

• • •

4. Explain why testing every line of code for correctness (i.e., 100 percent statement coverage) is
generally insufficient for ensuring that a program is bug-free . Give an example of a defect that can
go undetected by tests that have 100 percent statement coverage.
5. Why is path coverage a stronger form of testing than statement coverage7 Give an example of a
defect that would be detected by path coverage but not by statement coverage.
6. Draw a program control graph for the method adju' IQuality() of listing 26 .4 in this chapter. What
is its cyclomatic complexity' Explain your response .

7. Write the code for a class Accou"t with attribute balan", accessor methods, and method add() . Assume
that Account has states Sound, Empty, and Arrears, and that these are implemented using the State
design pattern . Write a complete set of unit tCSlS for Account, including statc·oncnted tests.

8. In test·first development, why is it imponant to execute a unit test to ensure that it fa,l s before the
code it is testing is actually written ]

9. You intend to implement a Recta"gl, class using test-first development . Suppose the class is defined
during design with the following characteristics,

• Constructor with parameters length and width


• Methods getL..:ngthO and getWidthO to retrieve length and width
• Method to calculate area of rectangle

Write. unit test class to test the as yet unwritten class Rt<ta"91t Next write the cod t I
" e a ,mp cment
h I.us.
tee
BIBUQGRAPHY 665

unit Tests
Perfoml full unll te ts on two signi fica nt methods of your applica ti on. State how long individuals and
th~ whole team spe nt o n de velo ping eac h part of these tests. and how the proce s yo u used could have
been improved.

Evaluation criteria,
( I ) Degr~e of clarity of th e plan
(2) Ext~nt to wh ich the plan and test include all relevant aspects of the unit tests
(3) Realism of the self·evaluatlon data and improvement plan

BIBLIOGRAPHY

I Rapps, Sandra and Elaine J W(:yuk~r. "SclC'C IIIl ~ Software Test 1)313 Usmg Datil Flow In (o rm all on," IEEE Trnnsnctto"S on SojlJD,m
&.g'''''"''9. Vol. II . no. 4. 1985 . pp 367-375
1 McCa~. T J.,·A CompleXity Measurc,- IEEf Tr"tI~lCllOtl5 "n 5"jlll.tI(( E"9H1etrltl!/. SE·2, no .. ( 1976), pp 308- 20
3 Humphrey, WaItS S , "MtJI'I49 1119 rl,( Software P'ocr<~ (SEI Srnri m SO/IU)n rc £"9'"(("" 9)," Addr so n·Wt."s lC'y. 1989
4 jUnll org WW'W jun.t org [acccs.:.ed 12/ 14/09 J
S Myers Gle nford J 'Tht Art of SO/I U1.trt TrS fm9." John Wiley & So ns. 1979
Module and Integration
Testing

Planning
• How do you test a class?

• How are stubs and drivers used for


Maintenance testing?

Testing • What are attribute-oriented lests lor


The Software a class? Class invariant-onented
Developmen r lests? State-based tesls?
Ule Cycle Requirements
analysis • What IS mtegratlon?

-
Impleifbl nt8tJon
• What is big bang Integralton?
Incremental? Bottom-up? Top
down? Continuous?
Design
• How do dally bu ilds facilitate
continuous Integration?

• What is interlace testing?

Figure 27 .1 The context and learning goals for this chapter

This chapter dlscuo;",co; tes ti ng beyond Unit IC')llllg-to the module level and to the Inl cgr\luon of
modules. Vil e bc:glll by discussing class tl.-sung. Cia'S tc')tmg I con,\1dcred by some to be beyond lImt It''Stln~
and by o thers not so
Integration IS the process of assembhng partS to (om, a whole As 3 phYSIcal illustration of thl< o nn.pt .
consider Flgur( 27.2, which IlIuslra tC' the Integ-ration of J ~uspcns l o n bridge . The order of Inlcgr.1tlon and the
STUBS AND DRIVERS ..7

Assembling Ihe parts inlo a whole

Figure 27.2 The meaning of "Integration" -an analogy from bridge·building, steps 1 through 6

manner In which rhe part are te red toget her IS critical for rhe co n,tructio n of the bridge For exampl e,
as cmbling ir in the wrong order wdl lead to longer construcrion times, o r worse, a defecti ve bndge u h
issues are equally important for the integration of sofrwa re sy tern,
likeall engineering artifact , software systems must be bui lt fro m parts. Each part is deve loped and unit ·
rested separately. The whole i then assembled , /''',gralloll is the process of assembling these parts and te ting
the result to ensure that they work together correctl y. A part of a software system to be Integrated can con ist
of several lines of code, a whole method . a class, o r an en tire subsystem
Aglie melhodo logies use co nti nuous integration and dail y budds as much as possible. We dIScuss th ese
on this chapter.
An example of a class tc t IS provided In ne case study sectio n. In ano ther, an integratio n plan"
descnbed. Both of rhe'e apply to the Video game example u,ed ,n thIS book.

27.1 STUBS AND DRIVERS

Consider the coordination issue, a,sociated w,th Integrati ng the parts of an application show n in Figure 27 .
~eral of the part depend on each other yet mu'i be put together ,n some order. \Y/e u'c ,rub, an d drivm for
thiS purpo e
Simple stubs Were Introduced ,n haptn 26 We e 'amine th em ,n more depth here for Integration
t"'"ng, and we also int roduce drivers The left·hand co lumn of F'gu re 27 4 <ta'" the proces, by sh \ mg the
tvtntual, dc" red conllgura tl ol1 01 three Item' or an applicat,on that InU,t be l11teg raled (The item ' ca n be
classes or package of cla<se, ,)
If our goal IS bottom · up Integ ration (dcstnbcd In detad I·n e tI n 27.33 ) thl'n we nN reate the Item
alone 111 Iter BU-A and le,t It thoroughl y alo ne However, a !lood ,,;t of Ie'" tri e< to repr du e Ihe mall/wr ,n
which the Item wil l be used For that reason , we create a "ub (step aU-I>), 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

668 CHAPTER 27 MODULE AND INTEGRAnON TESTING

Computes pariS 01 a tax return


Home Office Use associated with the use 01 pari
01 the home (or business
purposes

uses

Tax Retum uses

Creates an entire tax relUm for many kinds


of personal and business situations

Computes the depreciation on


Depreciation various types 01 equipment

Figure 27.3 Stubs and drivers-motivation from a tax return example

Eventual I Boltom-up : Top-down


I
conliguration I development I development
I I
I or integration I or integration
I I
I I
.------, I Item 2 __- .... I
'-~-::l Item 2
Item 2 : BU-b I
driver I stub
I I '--
I I uses
I I
I I
I I
Item 1 uses I uses I Item 1
I I
I I
I I TD·C
I I
--' -..,
Item 3
:
I BU·A Item 3
I
I
I TD·a
Item 3
I I stub
I I
I I
• •

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 669

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)
d deleteFromEncounterCharacters(EncounterCharacter encounterCharaC1erP)
ge EncounterCharacter getEncounterCharaC1er(Strlng nameP)
gq float getQualltyValue(Stnng qualityp)
gs float getSumOfQualitlesQ
gt float getTOleranceQ
10 Int IndexOf(String qualltyp) throws Exception
II InsertlntoEncOunterCharacters(EncounterCharacter encounterCharacterP)
m Int maxNumCharslnNameO
sq setQuallty(Strlng qualityP, float valuep)
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<t a quality - adjust qualot.es - get the quality

There are, in fact , IOAnitely many sequence> 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 C<1!ego rized as either
most likely or least likely to expose a defect. Otherw.se, the sequence IS consigned to the "neither" category.
All of the "most likely" tests are then executed , together with as many of the "neither" category as possible.
n,e "least likel y" are executed if there is time.
The process 01 adjusting quality va lues in the Encounter video game is relatively complicated. The
following is an example of a sequence apparently more likely than many to harbor defects.

g'-"l -aq-'q-aq-gq II g" characler - sri a quality - adjusl qualilirs - sri a quality - ad!,'" qua/.Urs - g" quality

\'(Ie will assume that the methods have been tested IOdividually, and we'll concentrate o n sequences of
methods that aflect the others. Figure 27.6 shows how the methods in the example chosen rdate to each
other through their effect on variables. Steps I and 2 affect the value of the conw,'rolion vanable. Step 3 affects
the value of " ""gl/'. In Step 4 . the "amina variable is an input to the adju"Qua/ity() method, which uses this
value (and the current value of co"crJltrntio~l ) to change the value of Cotlct'llration . Thus, each method in the
sequence sq-aq-,q-aq affects the outcome of a later method. The interaction among seemingly simple method.s
can be quite complexi
The case study of Chapter 26 shows these tests in action . The sections that follow discuss ways to tame
this complexity 01 choices.

27.2.2 Attribute-Oriented Tests

Attribute -oriented tests focus on variable changes, and create method sequences that effect them . A simple
example for an Acco""t class is to have the balance grow and shrink to zero. To do this, we could execute
t he sequence ",Ba/aH"( 50); addToBalan,,( 70) ; d,ducIFromBa/a"er( 120); g,'Ba/aller() . \'(Ie va lidate the predicted
balance. The example in Figure 27.6 can be designed as an attribute test, focusing on the variable
(O"'"ltraflon .

1. ge: c = getEncounterCharacter( -PlayerCharacter")

3. agoc.adjusIOuaiity( "concentratlon-l 0 ) concentration

4. 5g: c.setOuatity( "stamina"40 )

5 . agoc.adjustOuatity( "concentration"10 )

6. gg; c.getOuatity( "COncenlration") --retrieve data to validate

Figure 27.6 selecting melhod sequences ror unll lesting


TESTING A ClASS 671

27.2.3 Testing Class Invariants

As described in Chapter 22, class invariants are constraint among the attributes of the class that must remain
nut alter the execution of every method. A class invariant te t conSists of executing a seque nce 01 methods
and validating Ihat the invariant remains lrue. For example, suppose that a rule of the bank is that overdrafts
~re capped at $1 ,000, including the assets in the customer's avings, and IOtal assets per regular account are
capped at $10,000,000. The invariant of the Accolml class would be something like the lollowing.

-1000 <= checkBalance + savingsBalance <= 10000000


We would initially set the variables to amounts that honor this invariant, such as chrckBalanCf = - 3000
and SQvin9sBalanCf = 2500. Then we would execute a sequence 01 methods such as deposl( 300); wilhdraw(500 );
deposil(50) and check that the invariant is still true.
Languages such as Eillel and Java are equipped With functions that test the validity of assertions. An
assertion is a statement that can be true or fa lse: lor example , "x = = y." Assertions are often invariants.

27.2.4 State-Based Tests

As we have seen, the instances 01 a class ca n often be usefully thought 01 as transitioning among states in
response 10 events. We should therefore test such classes in terms of' their state. For example , let us test the
class Enco,,"lrrGame. Figure 27.7 illustrates the first steps In the testing of the application's state transHions .
The complete state· transition test is shown in Figure 27.8.
The numbered steps denote a typical event sequence for causi ng a meanin gfu l sequence of events. One
lest would thus consist 01 sti mulating the system so that it transitions through thi s sequence. The tester would
also introduce events that do not apply for panicular Slates 10 ensure that indeed they do not affect the
application .
To design and execute state·oriented testing requires significan t time, especially because extensIVe user
inputs are required. Tools arc available that record user interactions with the system and that can reproduce

test step 1
Preparing
Verify that the game is
initiallv in Preparing state
(by checking on the class
Player member gameS/a/e/).
dismisses
qualities menu

Wailing

flcur. 27.7 State-transltlon test sequences, 1 of 2


seve. A5'<WtJon 10( Compuong Madtinery, nup'VIww acm orll... pe(lmarVQUOSliOn cgmorm. PUTQ
672 CHAPTER 27 MODULE ANO INTEGRATION TESTING

test step 1
test step 2
........... .--/
Preparing I~
Verily that the game Is
Dismiss the quality Initially In Preparing slate
menu, and verily that (by checking on the class
the game Is in Waiting member gameStatel).
Player
slale. dismisses
qualiries
menu
test step 3
"- ,./
Move the player
character to an
adjacent area, and
verily that the Move to
adjacent - - -
game is still in area ---'
Waifjng state.

Figure 27.8 State-transition test seQuences, 2 of 2

these actions In addi ti o n, assertion checkers ca n be embedded ,n the code to verify that the system is in th e
slate it is supposed to be.

27 .3 INTEGRATION

Thi s section discusses and compares various types of Integration , and is summarized in Figure 27.9. It starts by
co mpanng b ig bang inlegration with the inc remenlal style that IS generally recommended ( when it's
po sible), The extreme (orm of Incremental integration is COll titlU OUS integrati on. The last c1assincl:Ition
d iscussed is between to p · down and bottom · up sty les. Projects o ften mi x these ,"teg rati o n and testing styles,
depending on the n3rure of rhe projec t

Big bang integration

Test Incre".entallnlegration
modules
IndMdually

Figure 27.9 Module and integration testing


INTEGRATION 673

IApplication I
'/

Module Module Module ••••• Module

c-
Unit Unit Unit ..... • ••• • • • • •• • • •• • Unit Unit Unit

figure 27.10 Big bang integration

27.3.1 Big Bang Integration

Big ba.gintegration consists of creating modules in parallel and th en assembling them in one operation . A
form of this is illustrated in Figure 27. 10 Although big ban g testing redu ces or eliminates the need for test
drivers and stubs. thi s beneAt is usuall y far outweighed by the complexity and co t of fault isolation. Since
many modules are integrated at o nce. i t IS frequ ently difAcult to locate the source of defects .
As an example, consider a sys tem that moni tors th e health of at ·ri sk patients as th ey go about their daily
lives. As illustrated in Figure 27. 1 I . the application ca n be th ought of as deco mposed into a m odu le that

Individual Health
Monitoring Applicalion

Health Data Diabetic Cardiac Emergency


•••••

Transmission Analysis Analysis Notification

Unit Mobile • • •• • • ••• • •••• Unll Ambulance Unil


Phone

Fleur. 27.11 Big bang Integration of a health monitoring system


674 CHAPTER 27 MODULE AND INTEGRATION TESnNG

Module 1
uses
uses
Module 4 Module 3

uses uses

Module 2

Figure 27.12 Module sell-dependency-conslder Its effect on Integration

handle the collection of data fro m patients, o ne that analyzes data for sp('ci flc diseases, o ne that handles
emergency notiRcations such as calls to the po lice, and a o n. it makes a g rea t deal of sense to develo p these
modules separa tely For example, \\'!hy no t develop th e diabetic analysIs in an orga nizat ion specia lizing In that
Acid, an d ha ve emergency no ti fica ti o n d eveloped by a company with expe nence in writing such software
reliably Some modules may be effectively written b), skilled teams worklllg anywhNe , geograp h ica ll y
speaklllg. Although continualllltegra tion , described below, is preferable in gene ral , it ma y not be practical in
a case like thi Each h ig h · level mo dule and its subsidiaries ma y ha ve to be devel o ped separately, and then
IIltegrated III big bang fas h io n.
The Integration and .estin g of mo dules illustrates the wisdom t,f desig ning so that dependenc ies arc
noncyelic. In o th e r words, we try to avoid architectures in which a mo dule depe nds o n itself. Figure 27. 12
illustrates suc h an architecture. We can't fully test an y pair of mo dules al o ne, O ur o nly c ho ice is to use stubs or
to test all of th em together, which multiplies the po tential for hard· to·R nd and hard -to-Ax defects.

27.3,2 Incremental Integration

owa days . software integra tion typica ll y proceeds 10 an incrcmt. ntal manner in whIch softwa re modules are
developed and assembled into progressively larger parts of the system, This is known as i"a"""".1 i""gra'io"
( I ). Gradually building the system means complexity increases incrementall y, making it easier to isolate
integra tion problems Incre men tal integration ommences when the first tWo pans of an application arc
developed, and continues until all its part s have been integrated into a complete sy tern , at which time system
testi~g comme nces. Stub and drivers arc employed during this process.
Throug ho ut th e integration process, software "builds" may be crea ted that foml the e merg ll1g ystem , as
Illustrated in Figure 27. 13. Befo re adding new mod ules, integratio n tests arc executed agai n t each build,
ensuri ng th at the build ",arks correctl y. Figure 27.2 Implies that mo dules arc developed and integrated in
some o rd er, but does no t sugges t how the o rder is determined , We u ually determine the Integration order b)'
ba ing it on the desig n of rhe sy tern . Two common met ho ds are bOl/om-up and lop-dOlPH , and eac h must
account for dependenCies between the modules mak ing up the desig n.

27.3.3 Bottom-up Integration

Suppose that an application consists of the modules and dependenc.es as hown III Figure 27, 14.
In bottom-up Integration , modul« that are most depended o n are developed and inte"rated ., •nrsl. Th en
the modules that depend on t h em are integrated next, .nd so on In FIGure 27, 1-1 , this implies th.t Module 3 i<
developed first , si nce it is at th e "bottom" of the dependency tree Modules I and 2 arc integrated nat with
-.
,. .'.
.•. ~. ; ••.h-
.
~
"
~-'~

.... ..

RII!'d

BuIld

Un!! Uni!

Uni! . .... .. .... • •• • •

Figure 27.13 Incremental integration with builds

Module 4

\ uses
Module 1

uses
uses
Module 5 Module 3

uses

Module 2

FIgure 27.14 Example of module dependencies

Module 3 since they depend o n II. Modules 4 and 5 arc integrated lasl. Integrating in thi s manner is illustrated
In Figure 27. 15. An advantage to th is approach is that It reduce< the need for stub si nce dependent modules

are available when needed for integration


Let's consi der how we mi ght perform bottom ·up integrat ion testing o n the Encounter vi deo game.
Figure 27. 16 shows the relationship among rhe objects of the Encounler ",chlleC[ure ,
We have three modules (package ) to Int<:grate. and need to determine which modules depend on
which. The direction of th e aggre!;ations uggesr an appropriate order, 0 show n in Figure 27. 17. Figure
2718 Ihows the resulllnK "using" reiatlon,llIp between the po kases .
676 CHAPTER 27 MOOULE ANO INTEGRATION TES TING

Third or fourth

Module 4 Module 5

usos Third or fourth


uses

Module 1
Module 2

uses uses
- -I First or second

Figure 27 .15 Bottom-up integration

EncounterGame

EncounterGame
.. Iacade ..
getTheEncounterGameO
getStateO
--< setStateO
Er'I»'Hlt&rChar8cters

lr
c
1 handleEvent()

EncounterCast EncounterEnvironment
.. facade-
getTheEncounterCastO I*-
getThePlayerCharacter() EncounterEnvironment
getTheForeignCharacterO .. facado ..
setLocationO

Area

Figure 27.16 Module relationship in Encounter

X depends on Y 50 create and lest Y first

Figure 27.17 Dependence and Integration order


INTEGRATION 6n

EncounterGame

uses
uses
EncounterEnvironment

__------ uses
EncounterCharacters

F"tgUre 2.7.18 Module dependencies in Encounter

EncounterGame Second

uses
uses
EncounterEnvironment

uses
EncounterCharacters

F"rgure 27.19 Bottom·up integration testing in Encounter

Next, we apply the principle of bottom · up integration to derive an integration order. Th.s tell s us to firs t
te5tthe integratio n of EncoII"'trEnoiromn,,,' with E" Oll"'tr /larnrlcrs , and then to integra te E"colln'trGmnr. Thi s is
.lIustrated in Figure 27. 19.

27.3.4 Top-Down Integration

Top ·down Integration is the opposite of bottom ·up, Modules at the top of the depende ncy tree are developed
first, with integra t.on proceed.ng down the tree . Th.s rype of Intq;ranon requires a cons.derable use of stubs
since dependent modules are nOI yet ready for Intcgrallon . The advantage of top·dow n '"tegTalion i that
modules at the top of the dependency tree arc typ. ally h.gher level fu nctiona hty of an aDpl. allon , su h a
user interfaccs, and are te ted early in the .ntcllratlOn ~y Ie. n,i< prov.des an early fee ling for the appli ation ,
1110lolin8 time for .mportant mod.f.cation,.
F,gure 27 20 shows the lop ·down .ntegration order of En ounter. Th.s tell s u to Ar t te t the .ntcgrallon
of EnCO""'rrG"mr w.th E.ICollnlrrEnviro","tIll , and th en to .ntewale E"(Ollllln Ch"", 1m.
678 CHAPTER 27 MODULE AND INTEGRATION TESTING

EncounterGame Ar51

uses

uses
EncounterEnvironment

uses

( second) EncounterCharacters

Figure 27.20 Top·down integration testing in Encounter

Top-down Implementati on . '"t<gratio n, and lCSling has a long hiSlory. In the very early days of
computing, programmers reveled in the exci ting thin gs the y could do WIt h softwa re. Programs tended to
explicitl y Iransfer co nlrol rapidl y fro m one place in memory to anot her so that th ey became very difficult to
,h,
debug and extend. In a famous letter to the editor of the (o,"m ull ica"oll. oj A( M [ 2], DijkSlra suggested the
begin nin gs of what he and ot hers deve loped inlo ,'ruc'u"a program11tillg . This called for a hierarch y of functions,
with hi gh · level functi ons cOll1i ng lower level o nes. Thi s remai ns an important part of what software- engi neers
do. T op· d ow n integratio n calls fo r the deve lopment of th e hi g hest leve l functi o ns, ca ll ing stubbed subsi diary
(unctions.
Return ing to the analogy wit h bndge co nstructio n of Figure 27.2. in top -dow n think ing-and
integration-we view and test first in th e large ("suspensio n bridge") and o nl y th e n begin to fi ll in the
rest in increaSIng level of detail Continuing the analogy. we'd test a mod el of the suspension bridge fo r wind
. nd simulated load reaction, maklOg gross assumptions .bout th e parts of the bridge (the analog of stubs )
O nl y then wo uld we test the parts.

27.3.5 Sandwich Integration

Sandwich Integratio n is a process by w hich o ne integrates from the bottom and to p more o r less at the same
time , introduci ng stubs for the intervening classes as o ne does this Suppose. fo r example, that we wa nt to
integrate (h e class Forri9nCharacttr, which is at the lowest level in Encou nter, and EnCOUHltrGamt, which is ar the
highest, without havi ng to worry about the intervening components for now. T o have FO"'911Charac1" and
E"colmkrG~mt coexis t, we can introduce stubs (or the intervening classes. For example, in Figure 27.21 , we Ars t
have Fortl9n Cbaracttr work with a stub (or EncolmlrrCbaracttrs , then one (or E"CO,mlrrE,1IJi,."mmcH', then E"coulflcrGatftt.
We don't count the Introduction o( stubs as true integration, so the only step th at's trul y integration i n this
exa mple is the last. It integr.ltes from th. top and bo tto m Simultaneo usly.

27.3.6 Continuous Integration

(oll ,illuou, ;II" 9ral;01l is a ty pe of .ncremental integr.ltion in which small amo unts of code are added to rhe
baseline (the currentl y state of the application ) on a very freq ue nt basis. Intervals arc often. freque nt.s da.ly
(see Section 27.4 ), and the newl y integrated code does not neces arily correspond to a completed met ho d or
DAILY BUILDS 679

EncounterGame

uses
uses
\

EneounterEnvlronmentSTUB

b
.- uses

EncounterCharaetersSTUB

a uses >1ForeignCharaeter I
Figure 27.21 sandwich integration testing in Encounter, in order a, b, c

class but can be smaller. As long as the code is unit-tested and does not introduce errors in the baseline , it can
~ integrated into the baseline. Continuous integration is one of the twelve practices of Extreme Program-
ming (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

weekly builds biweekly

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
680 CHAPTER 27 MODULE AND INTEGRA nON TESTING

Run
Regression
tests

development development

Freeze Confirm baseline or


/0 baseline rever! /0 previous 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
ItS ls
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
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

VSCustomers DVDsRented

DVDCustomerAccess fE-
.'.c.,OO,. o ..n

Figure 27.24 Video store module interfaces


IPflERFACE TESTING 611

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 f II oWing:
rerss . t exposes meth ods ' uch as t h eo
: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 .


682 CHAPTER 27 MODULE AND INTEGRA nON TESTING

An Interlace Test:
DVDs
DVD gwtw • new DVDI "Gone With 'he W.ncf"):

DVDAccess 1/ GOI access 10 the fO~8de object


-facade-
DVOAccess dVOs '"'
DVOAC.0e55.getTheOVOACO)ssO:
void stockDVD(StringaDVDTilie ):
Rentalltem getDVD( intaDVDID): II Now run the tests
dVDs.stockDVDI gwtw ):
Rentalltem getDVD( StringaDVDTilie ):
AontalUem rentalHem ~
String describeDVD( IntaDVDID ): ge,DVDI "Gone With the Wind") :

String describeDVD( SlringaDVDTnle ):


/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 683

II Check that aDVDRentalCustomer is an actual customer


DVDCustomerAccess theDVDCustomer Access =

DVDCustomerAccess
( I h . getTh e DVDC t ()
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, IS a test fo r th e Enco"n ler llaracler class and comple te the Encou nter case study in
Chapter 26 .

Ustlng 27.2: Tests for EncounterCharacterclass


public static void testEn counterC hara eterClass ( Str ing destinationP )
throw. IOExcept ion
(
/ * 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:
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
EncounterCharacter ( "CharForTestCl " ); I I method "ge"
eClM. adjustQuality (QUAL_STRENGTH , 40.0f); Il aq
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" ,
eC2M. sumOfQuali ties ( ) , 100. Of ) ; I I so

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
I truthM tzue ) ;
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 615

-@par_ dest inat ionP Location to,",r ite results.


• tellcept ion IOException 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),
EncounterCharacter eCPuncM= new EncounterCharacter ( "a +b" ) , // bad chars
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 <qualityTypeS . length ; ++i )
tzy (TestExecution . reportToFile( outM,
" inde xOf () Tes t 1. " + i + ": valid name: " + qualityTypeS [iJ ,
indexOf(qualityTyp eS[i J ) , i) ;
} utch ( Exception eP )
{TestExecut ion . r epor tToF ile (outM , "ind exOf ( )Testl : validname: compar e " ,
" i nd exOf ( '" + qualityTypeS [i J + "' ) ", "w ith e xp ected " + i ) ,
}
/* Tests for indexOf () for an i nvalid quality n a me . */
tcy {TestExe c ution.r e portToF~le( outM ,
" inde xOf () Test 2 : i nv alid name: zorch ",
i nd e xOf( " zorch " ) , --1) 1
686 CHAPTER 27 MODULE AND INTEGRAnON TESTING

} catch ( Except ion eP )


{TestExecution.reportToFile( outM ,
"indexOf () Test 2: valid name: compare " ,
l'indexOf (\ ' 'zolch\ " ) ", , 'with expected _1" );
}

1* Tests for setQuality () *1


II Set up for test
EncounterCharacter hank = new EncounterCharacter ( , 'Hank" );

II Nominal value
hank.setQuality (QUAL_STRENGTH, 10.3f ) ;
TestExecution.reportToFile(outM, "setQuality (} Tes tl:nominalvalue",
hank.getQualityValue( QUAL_STRENGTH), 10.3f ) ;

II Out of range value


hank.setQuality ( QUAL_PATIENCE, -6.2f);
TestExecution.reportToFile(outM,"setQuality () Test2:nominalvalue",
hank. getQualityValue (QUAL_PATIENCE ) , O.Of ) ;

II Value below close-to-zero threshold.


hank. setQuality(QUAL_STAlIINA, getTolerance () * 0.9f);
TestExecution.reportToFile(outM,"setQuality()Test3:valueclosetozero",
hank. getQualityValue (QUAL_STAMINA) , O.Of);

II Tests for adjustQuality() .


II Set up for test and verify: Values should be 20 each.
EncounterChar acter harvey = n.. Encounter Char acter ( , Harvey' , ) ;
I

TestExecution.reportToFile( outM, "adjustQuality() test 0:


ver ify that values add to 100' , , harvey. sumOfQualit ies ( ) ,
100.0f ); II Nominal adjustment
II strength 30 rest 70/ 4 each
harvey. adjustQuality (QUAL_STRENGTH , 30.0f );
TestExecution.reportToFile(outM, "adjustQuality() test 1:
values sum to 100 a£ter adjusting" ,
harvey.sumOfQualities(), 100.0f ) ;
TestExecution.reportToFile ( outM, "adjustQuality () test 2:
values adjusted as commanded' , ,
harvey.getQualityValue(QUAL_STRENGTH), 30.0f);

II Adjustment resulting in a zero value


harvey.adjustQuality( QUAL_STAMINA, 99.0f };
TestExecution.reportToFile(outM, "adjustQuality(} test 3:
ver ify low value reverts to zero' , ,
harvey. getQualityValue ( QUAL_STRENGTH), O. Of ) I
CASE STUDY: ClASS TEST FOR ENCOUNTER

// Conclude
outM . close () ;
System . out .p rintln( " \nMet h od tests of EncounterCharacter
class conc luded . " );
}

/ **Classtotest repainting of characters. Createsawindow, whichwillcontain *


* several copies of the character image .
*/
pd.... t.e .t.atlc cl ••• testCharacter Image eztend e Fr arne
{
/** Instance attr ib\lte that remembers which character image to
display. * /
pri_t. EncounterCharacter characterI;

/** Basic constructor -- cr eate a window for test ing some char acter ' s image .
*@param characterP Character whose image is to b e tested .
*/ testCharacterImage ( EncounterCharacter characterP)
{
"ljor (c haracterP.getName()) ; // Do all normal Frame initialization.
characterI=characterP; // Rememberwhichcharacterwe ' retesting .
}

/ ** Repaint the display areaof the frame .


*@param drawP Graphics context for drawing the c haracter.
*/

public ..oidpaint (Graphics drawP)


{
Dimension frameSizeM = getSize () ; / / Size of the window area .
iJlt widthUnitM = fr ameSizeM . width / 5 ; / / Co nv enient divisions of window .
iDt heightUnitM = frameSizeM . height /5 ;
character I. showChar acter ( this, dr awP , / / Dr awn small , fac ing right .
n •• Po int (widthUnitM , heightUnitM) , heightUnitM , tab. ) ;
char acter 1. showCharacter ( thio, drawP , / / Dr awn large , facing left.
now Point(widthUnitM*4 , heightUnitM*3), heightUnitM*2 , tru. );
char acter I . showChar acter ( thia, dr awP , / / Dr awn lat ge , fac ing right .
now Point (widthUnitM*2 , heightUnitM*2), heightUnitM*2, lala. ) ;
character 1. showChar acter ( thi., drawP, / / Dr awn small. facing left .
n •• Point (widthUnitM*3 , heightUnitM*4) , heightUnitM , tru. ) ;
}
) / / End of tcstCharacterlmage inner class
688 CHAPTER 27 MODULE AND INTEGRATION TESTING

27 .8 CASE STUDY: ENCOUNTER INTEGRATION PLAN

APPENDIX FOR ENCOUNTER SCMP:


INTEGRATION PLAN
The irH cf,( ratlon lC tlOg a.;sociated with thiS
Integra ti on plan a urnes that the Ind,yidual
c1asse, have been tested (as above ).
Note to the Student,
We need to de eri be the order il1 wh ich the
applic.'ltion is to be IIltegr.lted . The S MP is 2. Construction of Integration Baselines
an appropnate location for this descnption ,
since it describes configurations of th e itera·
tions and builds. ThIS could be placed in the Referri ng to the va rious integration techniques
SPMP, but it contains design and implemen · discussed aboye, which o ne IS th is, It is largely
tation detail, which are nor rea ll y projec t bOllom · up if you take Ihe ",tS relationship for
management irems It could be placed in the the hiera rchy. The til o""lrrGo"" package IS then
SDD , but the integration plan is nOt a design at the top. If the integration process we re to be
but a way to get to the implementation of the co ntinuous, a descnption of a dail y build pro·
design . A document o n implementation issues cess would be prOVided , perhaps along with
alone is a possibi lity . Another possibility is the some sense of the order of the integration. This
SCMP , si nce it is concerned with conRgura· is normall y associated with an agile process.
tions a the produc t comes toge ther. The
Encounter case study selected this optio n.
TIl e three successive bUIlds fo r re lease 1 of
Encounter arc show n In Figure 27.26. TIle first
budd conS ist of th e GamtC/ulrn Irrs fra mework pack ·
Jgc and th e Ell cotmtrr bartlctrr5 package . Th e second
Hi story of versions of this document:
build uses rhe fir.; t build. It consi ts of the E"co""I"E"·
11 / 1/98 E. Braude, Initia l Draft 11irolUllf l11 pJckagc, irs corresponding fram ework. and
the ("St build . The third build refers to budds I and 2.
4/4/99 E. Braude, Re vised
It consi"it of th e EllcolmlcrGamc pa ckage,
8/23/99 R. Bostwick, Documents reviewed and its corre ponding framewo rk, budd I, ond build 2
rccomm enctJtions made

8/ 24/ 1999 E. Braude, Recommendatio ns 2.1 Integration Build 1


integrated
Build I i illustrated in Figure 27.27. Budd I imple.
8/26/ 1999 E. Braude, Reviewed , comme nts ment. the Gam,Charnel", frame work pockage and the
exponded EII Colmter Imractcrs package.

1 . Introduction Imc rfacc testing (see Sectio n 27.5) is performed


on this module by identifying all of the methods
Dunng the integration process , the softwa re for that its classes make public. (1\·lethod not
Encounter is co nstructed in sta ges or builds. Thi s needed by other modules should be made
appendi x describes the configuration of the first private to avoid unneeded te. rs of th, kind.)
three builds . Integration testin g i. b •.sed on these The design is such that these methods are ,,11
builds The last build i the basis for sy tem p.rt of the f"CO""lrrC,,,, cia ..
testi ng .
CASE STUDY: ENCOUNTER INTEGRATION PLAN 619

Build 3
EncounterGame

>l EncounterGame
Build 1
-'
EncounterCharacters

EncounterCast
j
Build 2

./
EncounterEnvironment

\ I;
EncounterEnvironmenY1!
.
""
Figure 27.26 Integration plan

Inlegratkm Plan r,
0
1
GameCharacters
Err.;Q.ltlt~

«framework package»
r _"""
e,"'(J'''o{",N'''''',.r\~2
GameCharacter -'
&...-....e-,."..Q" . ... I

Encounter Characters

EncounterCharacter

EncounterCast ~ PlayerCharacter
. facade -
- singleton -
ForeignCharacter

Figure 27.27 Build 1 for the Encounter game


690 CHAPTER 2; MODULE AND INTEGRAT ION TESTING

Integration Pip"

1 r'>L!( . ... I
GameEnvironment
~
I (J'!CO 'IW C • A
,. •

GameAreaConnection ;<;
t
GameArea I~
1<
L ~
GameCharacter
GameLayout

~
~

Area

EncounterEnvironment EncounterCast
«facade » ~I
«Iacade~'
~

EncounterEnvironment

Figure 27.28 Build 2 for the construction of Encounter

At Ihe conclusion of build 2, Ihe framework!


2.2 Integration Build 2 application decompOsi tion is show n in Figure 2;.29.

Build 2 is shown in Figure 27.28 . Bu dd 2 conSlSlS of The fll CoIIII,,,Gllm, package and its Ro/,P/ayillgGarro,
the EH CO lltlltrfu pjrollmhlt package and the GtlmtEIIIJlr- framework package arc no t present because the a~
part of budd 3.
0"'"'''/ framework package . logelher wil h Ihe first
build. The GamcEHPlfoHmcnt and the En Co lmttrEtlVirorl -
,""" packages use the build I Gam,Charac'tr and 2.3 Integration Build 3
f" colm'"Cas' classes, respective ly. Courtyard, dun -
geon , and liVing room are examples of areas. Some The fi nal build, build 3, IS illuslraled in Figure 27.30.
of Ihesc areas are connecled . For example, there is a Budd 3 consi Is of Ihe fllco""" re""" package, ItS
connection between Ihe dressing room and Ihe Ro/,P/aYIHgGmnt framework pa kage, build I, and
courtyard bUIld 1_
CASE STUDY: ENCOUNTER INTEGRATION PlAN 691

Characters GameEnvironment
. framework package _
- framework package.

EncounterCharacters

EncounterLayout

Figure 27,29 Status of Encounter after build 2

~--------------------1

L-f!ol~~~~ng~arn~~ _____ _____ ______ __ ____ _______ ________________________________ _' ____ ,


I 1
I RPGMouseEventListener RPGame GameState !
I
I notifyOfEventO P>-- handleEventO handleEventO I
; f\ I

i
I £ ~ __ _ _ __ ______ ____________ • !
-~-----=-_£".:==~-=-=-:...-=.:=~---=--=~:.--=--:.==--.:.===--.::--== --------- --- -"l
II~ «singleton» Engaglng
' Wal'tl' nn I
~

handleEventO handleEventO I
I Engagement
I ----'
I
I
I1_ _ _--...: '---_ __ __-L..._--, !
Reporting Preparing I
I
handleEventO handleEventO I
EngagementDisplay I
I
I
- .--- --.- -,,- - -- - ----- - ----- - ,- - -- -- - - - -;---------------..
: EncounterGarne :--1
L ____ __ ___ _ ____ _ _ _ _

I
Key: Domain class I
Figure 27,30 Build 3 for Encounter (Includes bulla' and build 2, not shown)
692 CHAPTER 27 MODULE AND INTEGRATION TESTING

27.9 SUMMARY

Int08"'tion rders to the process of assembling the pans of an app licatio n and testing their Interactions 10
ensure that they work tOKether correc tl y . The parIS that arc integrated can be as small as a few IIIK'S of code or
as large a ;} subsystem.
Two overa ll strategies for integra ting th e parts are IIIcnlrlrntal and big bmtg In incremental integrati o n, th e
system is built step by step in relatively small increments. As soon as a part of the applicatio n is developed it is
Integ rated into the basel ine. In big bang integration . the parts of the system are developed first and then
are ",tegrated toget her in o ne tep. This approach ca n lead to man y problem s and i usua ll y avoided if at
all possible.
A com monl y u ed tech nique is to build and test the entire code base on a reg ular basis. Earl y in projects the
interval an be weekly, but atthe tail ·end it can be daily. Co nducting daily builds ensu res that any problems that
arc uncovered can be isolated to recentl y added code . si mpli fying defect isolation and reso lution
The Facade design partern can be used to facilitate interface testing between modules . A facade stub
object IS created that implements the public interface of a class or packa ge O ther modules test their interf"ce
wi th that module, and the facade object checks that it is being ca lled correctly and retu rns a predetermined
respo nse. Once the interface is tested, the faca de is replaced wi th the real modu le and the modules are tested
further.

27.10 EXERCISES

I . In your own words, describe incremental integrat io n. Name and explain two ben el1ts of
incre menta l integ'ration .

2. In your own words, explain how a project schedule is affected by the method of integration used on
the projec:.

2A. Consider the health monitorin g application described in Figure 27. 11 . Describe wit h examples
how yo u would integrate it bo tto m· up and how you would test the integra tion process.
3. In yo ur own words, describe how boltom·up integration works. list and ex pl ai n two advantages
and dISadva ntages of bottom·up integration .

3A The case study in Section 27.8 does not deSCrIbe a continuous integration process-but
suppose that the document did prescribe one instead. What would that document say7
4. In your own words, describe how to p·down integrati on works. list and exp lain two advanta es and
disadvantages of top ·down integration. g

5. Consider a poi nt·of·sale system th.t is under developme nt. Assume that th-.... h ard ware p Iatfarm an d
device drivers that control it are brand new. The rest of the software 's b . d fr
. . Wh " I emg porte am an
eXlStmg system . at appropnate method of mtegratio n might you rec d be
om me n used and
wy7
h •

6. In your own words, explain how daily builds facilitate the isolation f d ( .
a e ects In a build.
7. Figure 27.31 shows the architecture outline of an application th t ' I h
. b k P 'd I fo .. a 51 mu ates t e movement of
customers In a an . rovi e a pan r bUilding and integratin g th O I"
IS app ICtltlOn .
BIBLIOGRAPHY 693

BankSlm
BankCustomers

~
.facade- I BankCustomer I
Pending Events
executeNextEventO
Number

~
ufacade»
getNumberO
BankLayout

BankLayout
-facade »
BankEvent
Teller
BankEvent
ccfacade'l
IQueue I executeO

Figure 27.31 Architecture of bank simulation exercise

TEAM EXERCISE

Integration
Obtain proj ect speci ficati o ns from two other team s in the cia . s. Speci fy informa.lly a new appl icatio n
that contains significant cl ements o f these applicati ons. SpI' cify an integratio n plan to build thi s new
applicatIon .
Evaluatio n cri ten a:
( I ) Degree of clan ty of th e pl an
(2) D egree to which the pl an conlaln an appropriate o rder

BIBUOGRAPHY

I I>czu . M auro, dod Mlchill l Y(JunH, ., 0/111'£'" Tl\l'''!/II''11 ;\~U lyfl' p ' ()( t1 C, Pm,,,,,,,, jlllJ Trdmlllun," John \'(' ,I c)' ~ S('IO, 2008
2 U.,kstra, Ed'8C'r, - ( ,I') To t .. teme n, on" den:d " "rm(u ' " COWI III'HIlj, dhOn( 0/ ,/'t AeM Vo l II no 3, I (\8 Pf' 1-t7- 1"1l
i t...J,."m. no. M . ~ Ild R W Selby. ~ llow M. ro<\oit nUl ld~ ~oft .....arr .· ( O,"I'Ut" '( ""O"~ o} I/It Ar M v I 40 no O. 1997, PI' . l - b l
Testing at the System Level

Planning • How do functional and nonfunctional


lesting differ?
Maintenance
• How do you conduct performance tests?

Testing • What is load I stress event testing?


The Software ReliabilIty and availability testing?
Development Recoverability testing?
Ule Cycle
Require: 118"15
analysis • How do you lest usability?

• How do you validate secunty?

• How do you test when requirements are


sparse or even Ronexistenl?

• What Is acceptance testing?

• How does one lesl In agile processes ?

• What are compatibility, installation. and


serviceability testing?

• How do alpha and beta releases relate to


teshng?

• When Is testing automated?

Figure 28.1 The context and learning goals for this chapter
TESTING AT THE SYSTEM LEVEL 695

• p~rfonnance . ..
Tcst peed of appl,cation
• LoadlSli <55 ..•
Test against heavy event Ira ffic
• Rdiability and Availability ' "
Determine percenlage up · lIme
• Recovcnbility ...
Test ease with which application recovers from cra h
• Usability ...
IXrermine degree of user sa ll sfaclion .
• Security ...
Determine susceptibility to intended and unintended breache
• Compatibility .. .
Application compatible with ot her systems as required
• [nslallability . . .
Test ease of installation
• Serviceability . . .
Test ease of keeping up· to-date at customer si te

FIgure 28.2 Principal system tests

SySltm Irs ling follows integration teslIng . It consists of black box test. that vali date the en tire system
against its requirements. Once all other system tests arc successfull y com pie led, Ihe application is deemed
ready for the customer's acceptance testing (Section 28.4 .2). These are related to the requirements and to
metrics in that each test measures one or more metrics.
System tests are most often conducted by an independent group such as Quality Assurance . During
system testing, compliance with both the functiona l and nonfunctio nal requirements is validated. Recall fro m
Chapter 10 that functional requirements specify services Ihat an applicatio n must provide (e.g., ''fhe
application shall compute the va lue of the user's tock portfoliO .") . Nonfunctional requirements, o n the o ther
hand, descnbe a quality or behavior an application must possess. Examples of no nfunctional requirements
include performance , usability , and compatibility . Figure 28 .2 summarizes various types of nonfuncll onal
systems tests. Since system tests ensure that the requirements have been mel , the y mu t systematically
validate each requirement specified in the SRS , including each of the usc cases.
Whenever possible, system tests are performed on the applkation "Inning in its required environment
This is not terribly complicated ('or an application that is intended to run on a PC, such a a ca lendar program ,
although even for simple platforms we sti ll have to be concerned with complicating issues such as the versIons
of the operating system . However, many applications ca nnot be fully tested in their eventual environments.
This certainly applies to space-based applications, for example, with somc times d,sastrous consequences The
Mars Climate Orbiter spacecraft i a case In point. It veered of( course , resuillng In a lo -s of hundreds of
millions of dollars. According to Cable Network News, the Investigatin g board's chairman reported that

the root cause o( the loss of the spacecraft was a laded tran,lat ion of English units into mctTlc
units and a segment of g round . based , navIgation . related nll' ion so ftware .

T csting for thiS and other requlreme nls had to take place o n a grou nd -b.-cd Ie t bed.
In analogy to the two pronc lpal forms of rcq ulre m c nt ~.f'lll Iiollallnis leSt the fun 1I 0 nai rcqulrtmcn!> of
the system, and nonJullclionll/ INl s the qua"lle, and behaVIor o( the sy<tem The ac cptan e test'. validating that
696 CHAPTER 28 TESTING AT THE SYSTEM LEVEL

the- req ui re ment ha ve been ful fl llcd, makc up th e 111 311'1 functiona l tes t ~ct. The main nonrunctlonal tests arc
In luded in the <u ",mary of Figure 28.2. , Ild ,rc di sc ussed In th e re< t of this c hap tn
This chapter prOVides a number of mctrics as,;oclJtcd wllh these lest, It al 0 dlscusscco smoke le~tln8
( cctio n 28 .7.2 ). a kind o f rough regrcs>lon te<t. a nd tes tln ~ In th e presence of lig ht we ig ht (incomplete or
eve n nonexisten t) requ irements.

28.1 FUNCTIONAL TESTING


Functional system tes ts focu o n ho w custo mers will use th e pro duct in real li fe Use cases a rc a primary source
of functIOnal requirements As an example of testing a usc case. reca ll the fo llOWin g Encounte r usc case. EHgag(
For(igt' ClJart1CI(r , from the customer req uirements.

I . Encou nter displays th e fo reig n charac ter in the same area as th e player's.

2. Encoun ter exc hanges quality values between th e two c harac ters.

3. Enco" nter d isplays the results of the engagement.

4. The user h ilS the "OK" buno n.

5 Encounter di plays player's charac ter in a rand o m area.

To test th is. we may begin playing the ga me unt il an engage ment tokes place and is o bserved. as In Figure 28.3.

Currenl lif e 001,'11, !IT !I

Test Slep
-.:....:..2.:.•:. .:. :3. and
CUl1'entonJue
so

~ 80fof, lasl encoul'ller"


10 0

Step 5
-

Figure 28.3 System testing of Encounter video game Engage Foreign Character use case
FUNCTIONAl TBTING

As p.111 of te ting thi Us" case, we <eo that In tep 2 quality values are exchanged. We tum to the
detailed requirem e nt< (or qua lity va lues and va hdate eac h. The (ollowing is an example , taken from the
Encounter SRS .

3.2.EC.1.2 QUALITIE OF ENCO UNTER C H ARACTE RS

Every game c harac ter has the sa me sct o( qualities. E.ch quality shall be a nonneg.ti ve Aoa ting-
point number w ith at least o ne deci mal of precI sion . These a re all initialized equally so th.t the
sum of their values is 100 . The value of a q u. li ty ca nnot be bo th grealer than 0 and less lhan
0.5. For the firs t release , the e qualities wi ll be CO)Jn'" frallotl , mttlligttlct, patitllct, sfa1tlHltl , and
strmgth.

This can be decomposed as fo llows,

3.2.ECI .2 . 1 Every ga me charac ter has the same se t of q ualities. Each quality sha ll be a
no nnegative Aoati ng ,pOi nt number with at le.st o ne decimal o( preCISion .

3.2 .ECI .2 .2 Th ese a re a ll initial ized equally 0 that the urn of thcir val ues is 100.

3.2.ECI .2 .3 The va lue of a qua lity canno t be bOlh gTeater than 0 and less than 0.5.

3 .2.EC I .2 4 Fo r the fi rst re lease, these qll.1 itie wi II be (Olletll lrali oll , ;IItrlligrllcr, pal;ntcr , ,'amllla , and
strmglb.

• 3.2.ECI .2. 1 is validated by goi ng through each quality o n the srI quallf;'S ,,' indo,,' and ensuri ng th.t each has
a deCImal value , as shown in Figu re 28.4 .

• We validate 3.2 .ECI .2 by c hecki ng o n Ele na's quahties as the game begi ns

; Elena quality uJldate .'~"\'~

Total life points: 60.0

Concentration
Stamina
120 .0

OK
- ,

Fl&ure 28.4 System testing of Encounter Video game testing with GUI for setting qualities
698 CHAPTER28 TEsnNG AT THE SYSTEM LEVEL

. Elena quality update ' )( . fiend status ~ •


-,

I I
I
Total life points: 25.563635 I Curre nt life POints 25 16364

1 Current value:
Concentration
Con centration 0.0
1°.4 1
Done '
Inte lligence
- I Patience ~ Before last encounter:
1.3454546
lL _ _ _ _ _ _ _ __ __ __ _ _ _ _
. --

Figure 28.S System testing of Encounter video game testing via GUI for setting and viewing qualities

• Validatin g 3.2.EC. 1. 3 ca n be do ne by redllCing Elena's poin ts o n a quality to less than 0.5 . The result of
se tting stamina ( 0 0 04 and showrn g thal Encounter actu all y sets th is imcrnall y to 0 is s(--e n in Figure 28 .5 .

• \VIc validate re qui rement 3.2.EC.I .2.4 by e nsunng that all pro mised qualities arc present and th at there are
no additio nal quali ti es. We co ntinue testin g in thi s manner for the res t of the use cases and functional
requ iremen ts.

Met n cs fo r fu ncti o nal testing are lIsually based on the requirements, and include the fo ll owing ,

• Nu mber/percent of detaded req uirements partially, and no t fu ll y real ized


• umber/percent or detailed requirements no t realized at ell!
• Number of hi gh ·level req uirements no t implemented, as pe rceived by th e Custo me r

• Number of detailed reqll1remenl not implemc!llcd, as perceived by the customer

28.2 NONFUNCTIONAL TESTING

Thi s cction dcsuibes several common types of nonfuncti onal testing : performance, load/s tress, reliability
and availability, recoverability, lIsability, security , compalibili ty , installation, and serviceability test ing.

28.2.1 Performance Testing

Perfonnance testing vahdates that a system meelS Its specified perfonnancc requirements b b h
y 0 servIng t e
throughput, or speed of the system. Throughput rerers to the number o f transactions that can be _" .
·
given amount a f time .
. 0 f a transaction
Th e meaning . d epen dson t h c: type of .lpplication that 's L- . procesScu
d F 111 a
• • 1 UC:Ing tes te . or our
Video SlO'" apphcatJon, speed could be measured by the l1umbe r of-vldeo rentals th.I can b- P d '
.... rocesse per mmute.
NONFUNCTIONAlTESnNG 699

For a ~31 · tim~ communication system , peed nllght be measured by the number of data packets that can be
p~ and forwarded ~r econd. Good requi~ments w,lI have avoided vague statements about ~rfonnance
such as 'customer ,csponses should be acceptably fast ' uch vagucness causes problems because the stakeholders
can harbor very different interpretation of ' fast : For the video store application, a well·wronen ~rfonnance
requirement is 'The appl, ation hall be able to successfully handle a load of 1000 rental requests per minute.'
Te t environments such as Eclipse's Test and Performance Tool Platform ( ee Section 28.6) identify the
packages, classes, and methods with high execution times, as well as those invoked frequently .
Mernes for performance testong are u ually based on perfonnance requ,rements, and include the fo llowing,

• Number/percent of speed requirements not satisned


• Number of memory use requirements not satisned
• Number of s~ed requirements not sati sfled, as perceived by the customer
• Number of memory use requirements not sa tisned , as perceived by the customer

28.2.2 load/Stress Event Testing

The purpose of loadlstress testi ng is to subject a system to incrcasi·ng loads and to tress it in various other ways to
detennine its breaking point. Another way of stating th os is 'under what load does the systcm start to breakt
Examples ofthe types of loads used are maximum number of users supported , maximum number of transactions ~r
second, and maximum data transfer rate. Once the points of failure are determ,ned we can understand whether the
system meets its load ·related requirements. Knowing these limits also allows us to examine the system desi gn to
understand those pans of the architecture that arc susceptible to stress, and use this for future plann,ng.
A good requirements document speCifics the performance of the applicati on under precisely stre ed
circumsta nces. As an example, suppose we have the fo ll owing performance req uirement.

Th, sot, shall halldl, custOll"r v,sits with a maxi",,,m of fD stcollds wait "m, "ndtr th, followillg conditions. VISIts
occur in a Pois son (probability) distrih,,"on with at, avtrag, of fDO ptr IIIill"t, Each ordtr is ai' avtrag, of 2
books, distrib"t,d IIonllally with a stalldard dwia tion of 1 .

An example of a loadlstress test based on th is requirement is the fo llowing.

Visit th, sil, for 10 mill"ttS with an aotrag' of 100 c"stomm ptr mill "t,. Each ord,rs at, a"trag' of 2 books, w,tb a
standard dwiation of L

Rtcall that the Poissoll distrib"tion si mul ates arroval times at a queue, the st""dard dwiation measures the
extent to which data varies from the mean . For examp le, a variance of zero ,n the orders of the above
requoremen! would mean that exactly 100 customers ca ll every minute O nce we va lidate the system ca n
handle this load , we increase the number of cu tomer vi it ~ per minute to determine the point at which the
application exhibits a probl em.
In many cases, loads and strcss limit arc no t ex ploc,t1}' spe oil ed in a requirements document In th,s ca e,
the project manager, QA, o r management decides o n the rargets to be attained based o n the lollowing factors

• User and customer ex pectations


• Technical lim'ts
• Costs of improvement
700 CHAPTER 28 TESTING AT THE SYSTEM LEVEL

• Le8~1 advice
• larkct ond ili ons

• 4xpt'ncncc with past products

• Comparisons Wilh competitors' products

T ools such as Eclipse's T est and Performance T ools Platform (TPTP see Section 28 .6) provide the
number of objec ts rca ted at nlntimc and the amount of memory they consume. V arious gra ph ica l devIces art:
prOVided th.t sho" a "thermometer" reading o f memory consumption (min to ma x) by mo uSing over a sequence
diagram of h.nction Invoca ti ons. Tc'S tcrs seck ma ximum and near·ma xlmum rea dings . The sequence diagram
can be ge nerated fro m the test execution . TPTP shows how many objects refere nced a give n object at runtime.
MetriCS for loadlstress testin g include the fo llowing ,

• 'umber/ percent of load/stres requirements not satisfied

• umber/ perce nt of loadlstress standards (industry or company) not satisfied

These can be decomposed by types of loads and stresses.

28.2.3 Reliability and Availability Testing

It IS an implICit requirement fo r every application th.t it be available for usc! Sometimes it is acknowledged
that the system will have defects or th.t it wi ll not be able to survive defects in its environment (e.g ., the
opera ting sys tem) and will crash at times. Rtliabi/ity "lid a"ai/ability assess and measure the extent of this.
Relia bility and avai lability arc ty pically measu red by the mean time between fa ilures (MTBF). T o obtai n
MTBF, a defillition of "failure" is first specified-for example, a crash of the appl ication that requires its reload.
Several different levels of failure ma y actually be defined and used. To compute the MTBF. a tester start.s the
application and notes the time. He orshe then executes the appl ication using, ideal!y, random scenarios until
the system fa ds. The elapsed time is computed. This process is performed repeatedly; the MTnF is the average
of these times.
Obtai ning a very reliable value of MTBF involves hiring people to use the applicatio n according to some
controlled rules and procedures. Gathering these data for man y hours requires significant compensatioA for
testers. Naturally. one tries to gather the data while users are using the application for another purpose.
However, the other purpos~r purposes cannot be permitted to bias the results. A related technique is to
have a large body of users exercise the applICation in advance of its official release (see Section 28.4.3
concerning alpha and beta releases). To obtalll an MTBF, it is necessary then to estimate the number of users
and the lime they spend using the application. As many know, the gathering of this kind of data continues
even after a prod uct is shipped. as in the pop·up message "Please send us notiRcation of th is fail ure . .. •

28.2.4 Recoverability Testing

Many otherwise excellent applications crash from time to time, The reasons may be beyond the control of
developers, such as power outages. A good SRS specifics what should take place when an application crashes. A
common require ment is that, whC'n restarted , the application returns to its state at the time of tht: crash. This is a
rrc01JfI'ab,lily rcqul,,,"ml. Anothercommon requirement is for a designated log ~Ie to conta',n a . I . f h
. . n exp anahOn 0 t C
crash s cause (ratherlike an airplane s black box). As an example of a recovery techn 'Ique con d h"b k •
• $1 C'f( e ac StOP
technique employed by Tom VanCourt on the Encounter video game The code ,' s ho . L'
. wn In I tlllg 28. 1.
NONFUNCTlON.Al TESTING 701

28.1: Recoverability in Encounter video game


INbliC: .tatic: void main( Stringl] argv)
{
try {
// Create the main applicat ion wi n dow .
1!n&1 GameMain gameFr ameM = new GameMain ( ) ;
g ameFrameM . addWindowListener ( new windowAdapter () {
public void windowC losed ( WindowEvent e )
{ Sy s te m. exit(O) ; }
public void windowClos ing ( WindowEvent e )
{ gameF r ameM . dispose ( ) ; }
}
) ;

// Set frame to a workable size . The size given here is only


// approximate , since the frame can be resized and the layout
/ / manager can adapt the content over a wide ran ge of sizes .
// Ad d in approximate amou n ts for window frames , etc .
gam eFr a meM . resize ( GAME_AREA_WIDTH + 25 ,
GAME_AREA_HEIGHT + THUMBNAIL_HEIGHT + 25 ) ;
gameFrameM . createGameUI ( ) ; // Set up the user interface .
gameFr ameM . show ( ) ; // Display the win dow .
gameFrameM . validate () ; /1 Display the win d ow co n te n ts .
gameF r ameM . toFront () ; // Start in front of other wind ows.
} catch ( Throwable thrownException ) {
// Backstop exception handler : Catch any exceptions not already
I I hand l ed elsewhere and try to get debug informatio n fro m them.
/ I Runt imeExcept ion obj ects , in part icular , can be thrown by
// any method wi thou t hav ing been dec lar ed in a ' thr ows ' clause .
System . err . println( thrownException . getMessage() ) ;
thrownException . printStackTrace( System . err ) ;
}
}

The effect of this odc i to trap excep tion, not hand led elsewhere and report them before the
applicataon stops. One can tc~ t for thl at :hc system leve l by entering ill ega l valell's suc h as 10 '0 for strength
value of a qlll1lily . M e trics for 10acVs tre.- tc ~ tin g include the fo llOW ing:

• Number/ percen t of rc ove rabil,ty reqUireme nt > nOt <a t, sr,ed


• Number/per ent o f recovera bllity 'tandard~ (II1du<try or company) not <a t i~flcd

• Mean lime to re pai r ( I ' ., to rcua 1n a Jotlvcn nilln in g StiltuS)


702 CHAPTER 28 TESTING AT THE SYSTEM LEVEL

• Frequcncy of auto· recovery compared with thc deslrcd auto ·recovery frequency
• tcan recovery time

• Mean r('S tart time

28.2.5 Usability Testing

U,./lIlily ''' 1119 va lidates an application's acceptability to Its users. Thc primary goa l 01 u ability testing is to
ensure that the application sa tisfies Its stated u ability requirements. These should be provided in the SRS In
quanrified tem1 S, toget her with the manncr in which the deSIred quantities arc to be measured. Kit [ Il lists the
overa ll critcna in Figure 28.6 as csscnrial lor usabi lity tcsting.
For example, wc might reqUirc rhat a random sample of 30 users of our home finance application rate the
application o n a scale of 0 to 10, as shown in T ablc 28 . 1. An inspection of the accessibility results shows that
our application scores about 12 percent lower than the industry average-some cause (or concern . Our
va ri ance is lower than that found In industry, however, which means that the sampled users agreed more on

• Accrssib,/,ly
How easily can users cnter, navigate, and exit '
• For example , mea ure by average time laken to ...
• RcsponslIJnltss
How rcady IS the application to allow the uscr to accomplish specified goals?
• How often IS CUI display accurate (pe rce ntage)?
• How quickly arc user actions ack nowledged?
• How oftcn is the application rcady for user actio n?
• EfficifflCY
Degree to which the number of required steps for sclected functiona lity is minimal
• "Minimal" calculated theoretically
• For example , measure by minimal limclav('ragc time
• Compr<hcn,ibilily
How easy is the product to understand and use with documentation and help,
• For example, measure time taken for standard queries

Figure 28.6 Key attributes sought in usability testing


so..n-to. Kit. &1Waro. SOftware Testing in !tie Real Wor1O Impn:Mng the PrOCt"SS. Addlson·Wesley, 199$

Table 28.1 An example of usability scores


Industry Industry
average average
Quality Score Vat1ance score vat1ance
Accessibility 8.1 2.1 8 .2 3.5
Responsiveness 9.3 3.2 5.0 3.0
Efficiency
+
5.6 2.0 7.2 1.1
COmprehensibility 2.3 O.S 6.0 0.3
NONFUNCTIONAl. TESTING 7Cd

thIS seo"' .than u ~rs t pically as",e on the usabiloty of a UI. This tell< us thot a smaller percentage probably
acru.lly dl Ioke uson g our applocatlon than i u ual.
The appropriate ample sIze depends On the desi red probability of an erroneous conclusion. If we want a
smaller probabiloty o( Cllor, we need a large r sample. Usability data can be collected on a controlled or
uncontoolled environment. In a contro lled envi ronment , subjects arc o bserved and data like the following are
obrainerl:

• Average time for the u er to comple te deSig nated functI o ns


• The rate of user errors on desig nated interactions
• Average time take n to learn new function

• Average time taken to complete d eSignated tasks (e.g., crea te a letter in a word processor)
• The results are compared with required , compan y, and industry no rms. Users arc very sensitive to
applications with which the or experience deviate much from what they arc used to .

In designing usabili ty questionnaires, the challenge is to obtai n data that enable engineers to remedy the
most serious shortcomings without exceeding the lim its of user ' time and patience Alling out questionnaires.
Usability data can be expensive to collect because users often expect compensatio n fo r the time and trouble of
providing detailed feedback. For example, a client of o ne of the authors develops software for a device used by
physicians. The company provides a free dinner and signiAca nt mo neta ry compensa tion in return for viewing
and commenting on screen sho ts and demonstrati o ns
Turning now to uncontroll ed environments, Figures 28 .7 and 28 .8 show the beginnings of the Purdue
Usability Testing Questionnaire [2], which provides useful data from which to assess the value of and
potential improvements in a set of CU ls.

28.2.6 Security Testing

Security testing co nsists of id enti fy ing securi ty defects and measuring the extent of an application's security .
Recall that some princi pal aspect of security are those Ii ted in Figure 28 .9. We can base securi ty testong on
these. The I.esting ca n be performed by using or imulating interception of traffic (called "sniffers"), usi ng
software that attempts to break systems, such as sc rip ts that repea tedl y try pa<sword break -ins, and by uSIn g
people of varied skill leve ls to try delibe ratel y breachong the desig nated security aspects . At the hig h end of
this spectrum o f skills are people wi th experie nce '1, acking." A hi gh leve l o f Sc urity clearance i< required fo r
them . Usi ng hacker ca n prese nt majo r problems whe n an external co nsultong company i the o nl y alternati,'c
and especially when the experie nced people have bee n invo lved in unautho ro zed activi tIes in the pa t
The OPtto Sou,Ct Security Testooog Methodology Mml u"' (OSSTMM ) is an Opell standard me th od o logy (or
performing secu ro ty tests [3]. OSSTMM focu<es o n the technica l detail . o f which Iteon need to be tested ,
what to do during a sccuroty tcs t, and when dlffcrent type< of securi ty test. shou ld be plTformed. A checklIst
for confide ntia lity testIng in in forma tio n secu rit y, parti y ada pted from OSSn,1M , includes the fo llOWIng
actions_ o me arc part of non -securot y lest lng as we ll , a o ne co ntlnue< to re ognize thnt many se urity
breaches SImply exploit a defect In the ohware

• Validate conflde nlo al d atabase 10 alo o ns


• Scr e n all dat.bast:s for co nfide ntoal co nt en t
"g
n

Purdue Questionnaire ~
11><>1111'/7 ofDf6<r- Soj/vtIT. s,SIPU Ad " U
g1
"""on.
O""'POrlQnI:. Ut not mclud.d in th&.t onlul. but could b. intorpOfaud ;""0 '"
'"
oCpE.nU

iil
:;j
Z
PIe ... raIe th. u.ability of the system. "~
J!
m
II>
o Try 10 respond 10 all the items. -<
II>
• For Items tlw ate not appbcable. use NA ;ri
o Make run: the •• 6elch are 61!ed in. System: Email I. : ;:
• 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.
o To mail III your result•• chck on: Mail D.,.
t2
m
r

Syrtam.l_ J Email I,,, r~_ _ _ __

commenlS and your et:naJl address to the bOK

-~
r/.
..".-, -- ..--.,....
-.
.
.
..
r j- _,",.",.~

~~;'.;..t.1- . .",,_r~ RF:TURN TO REFERRINO PAOE


"'~'-'~-~'-

1. \,;um rAU"",u:1' 1 1 3 4 5 6 7 NA
- - - - --

I. Is the control of cursor compatible with movement? 111 bad r r r r r r r good r


2. Are the results of control enb'y compatible with user expectations? GIl bad r r r r r r r good r
3. Is the control matched to user skill? ,. bad r r r r r r r good r
4. Are the coding compatible with familiar conventions? lD bad r r r r· r r r good r
5. Is the wording familiar? bad r r r r r r (' good r
FIgure 28,7 Purdue usability questionnaire fragment. 1 of 2
Soufu Plldue usability T6 Ung Qu<tStJonnake. httPJ IWww.acmOfil- perlmanlQUfStloocgi1Iorm., puTQ
-- 2 11 S J[ ot u-S II'!
6. Is the assignment of colour codes conventional? C bad r: 0 0 () (j 0 C good ()
7. Is the coding consistent across displays. menu options? C bad 0 0 0 0 (j C C good C
8 Is the cursor placement consistent? C bad (j (j (j (j 0 r o good 0
9. Is the display fOllllat cO!lS1stent? C bad 0 0 0 0 0 r C good C
10 Is the feedback consistent? C bad 0 C· C 0 0 ('. r good r

11. Is the fomlat within data fields consistent? C bad (J 0 r () C 0 r good C


12, Is the label format consistent? C bad (J 0 C (J C r C good 0
13 Is the label location consistent? C bad r: 0 0
" r· () r. C~
good C
14. Is the labelling itself consistent? C bad 0 0 0 0 r: c C good C
15 Is the display orientation consistent? -- panning vs , scrolling. C bad (J 0 () () 0 0 r good r
16 Are the user actions required consistent? C bad C 0 0 0 C 0 o good ()

17. Is the wording consistent across displays? C bad 0 0 C r C 0 o good 0


18. Is the data display consistent with entry requirements? C bad C (", 0 0 0 (", o good 0
19. Is the data display conSiStent with user conventions? C bad C 0 0 0 0 0 o good 0
20. Are symbols for graphic data standard? I::J bad 0 0 0 (", 0 C- O good 0
21 Is the option wording consistent with command language? I::J bad 0• 0 0 0 0 0 o good 0
22. Is the wording consistent with user guidance? C bad 0 0 0 0 0 0 o good 0
- z
0
Figure 28 ,8 Purdue usability questionnaire fragment. 2 of 2 z
."
c:
.source P\KOue vsabdity Tescng QueslJoMaire. httDl /WYM acm Ofg!- perlmanlquestion cgi1form",PUlQ Z
!:l
(5
~
r-

~-
~

~
706 CHAPTER 28 TESTING AT THE SYSTEM lEVEL

• ConRdenti.lity
• ",ffers vahdate that d.ta passed not vi sible to unauthonzed p.rtles
• Hlrc profession. 1 hackers]
• Nonrcpudiation
• Experiments to va lidatc
• Integrity
• Alter data .nd validate consequences
• Authentication
• Hire profeSSional hackers)
• Authorization
• Hire professional hackers)

Figure 28.9 Testing (or security

• Valid"te cookies

• Content, types , expiration , and encryption

• Check for buffer overflow protection

• Check for memory leaks

• Test for illicit site navigation

• Validate Sign -inS

• Include default IDs and passwords

• Check protection against illegal and out-of-bounds input (not necessarily input that allows breaches)
Merrics for securiry testing include the following .

• Number/percent of specific security requirements not satisfied

• Number/ percent of security standards (industry or company) not satisRed

• Confidentiality: Average time required to gain disallowed access to informa.tion


• at a specified level of security

• by testers of a specified degree of training and expenence

• NonrcpudiatlOn: Average time required to repud iate agreements

• Integrity: Average time required to alter data in transit , undetected

• Authentication; Average time required to verify identity

• Authorization : Average time required to gain disallowed access to a location

28.2.7 Compatibility Testing

Many applications arc designed to work with other applications. For example a word pro h II
. . . . . Ceisor t at a ows
the Insemon of a ~prcadshcet must be compatible With the spreadsheet application Anoth I .
. - . fr I -h . . .
application that obtainS data om peop e Wit mobile deVIces of variou.s brands Com
or examp e IS an
'b ' I' . _
, patr I Ity testing IS
NONFUNCTIONAl TESTING 7m

s.milar to integrat.on te ting III that it tests the interactions between parts of an application. The difference .s
that the Interfaces are typ.cally developed by different organizations, and developers normally can't change
the applications with which they mu t be compatible .
An important subfield of compatibility testing is assuring that the application operates w.th deSignated
past ver<.ons of software on which it depends . This includes versions of the operating system. An example is
an online learning env.ronment, wh ich must work with various versions of Windows as well as with UN IX.
Compatibility with future versions can be planned for to some extent, and it is sometimes possible to si mulate
upcoming changes. Testing must include combonations of versions.
Metri~ for compatibility testi ng include the following ,

• umbe r/percent of speCific compatibility requirements not atisfied


• Number/ percent of compatibility standards (industry or company) not satisfied

28.2.8 Installation and Installability Testing

An installation test validates that an applicati o n can indeed be install ed. An instal/ability te t is a more general
concept in that it tests via installation test cases whether an applica ti o n can be installed o n a va ri ety of
configurations. Installation tests whether an appltcation ca n be successful ly .nstalled o n its targe t system .
These are binary canlcan't tests Many types of errors can occur during insta llatio n, espec.ally du c to the
djfferences in hardware and software platforms. Applications are often required to execute o n multiple
hardware and software platforms. Multiple platforms typically require separate tests. For example , .f our v.deo
store app lication were required to execute on Windows and Macs with Internet requirements, we wou ld
devise tests that ensure the satisfaction of the requirements on each of these platforms. Although we try to
develop applications that arc plat fo rm independent, thi s has limitati o ns. Fo r example, we may need to te t
with separate bar code readers for Windows and Mac platfo rms . Installatio n tests would be ide ntica l for the
most part but would contain Windows·specific and Mac·specific parts.
Once we have tested that an appltcation can be installed correctly, we run a second tier, co n ISting of
installability tests that measure the level of d iffiwlty of installing the application . As computer u ers we are all
too famdiar with how easy or how hard it is to install an app lication . Installability tests thi s proce S and the
aspects of the application that make this easy or difflcult.
Metrics for installation and insta ll abilty testing include the fo llowing ,

• umber/percent of speCific in tallability requirements not sa tisned


• T.me required to install o n deSignated platform by custo mers with designated amount of expert en e or
education
• Time required to co nnrm installation intcgrity via a standard test seque nce

• Number of d e fec t~ found durtng .nstallation, with "defects" carefull y defined

28.2.9 Serviceability Testing

Serv.cing an applicat.on .s the pro css of repainng or enhanci ng it This could include visiting the itt and
sending a full or partlal replacement ovcr the Internet.
An applicatjon '~ strVlCcah,lity refers to the ease or dtlfi tllty w.th wh. h it an be kept opera t.o nal In the
face of changes to .ts envlfonmcnt. For example, an expert system appltca t.on reltes o n Its knowledj:e base
typ.cally in the form of a \et of rule., whKh may be straightforward to moddy Another exampl e b the ca<e
708 CHAPTER 28 TESnNG ATTHE SYSTEM LEVEL

with which an appJ. Juan that nlns o n o ne versio n of an opcra tlnH sys tem can be made to run on Its successor
<rv,ceab,llt te tS execute scenanos such a wapptng databases Scrv,cca btl,t y IS re lated to matnta,n ·
abilIty-the case or dlfAcu lty with which an appl,ca tio n ca n be maintaIned The dtffercnce IS that crvlCtng is
a planned, expected , and pred,ctabk- proc.s,.
Metncs lor serviceabihty tcsttng tnelude the follOWIng ,

• umber/ percent of spcCllk scrviccab.!lty requirements not 311shed

• Number/ percent of serviceability stand ard (,nduStry o r ompa ny) no t allsf,ed

• Time reqUIred to sC r"\' lce actions on deSignated platfo rms

28.3 TESTING WITH LIGHTWEIGHT REQUIREMENTS

Th is secrion di scusses tc tln g in the co ntext of requirements that range from being not written duwn at all
(Section 28 3. t) to betng o nl y partially expressed in writing via the user stories of ag tl e processes (Secti o n
28 .3.5 ).

28.3.1 Testing in the Absence of Requirements

i\4ost of the softwa re engineenng literature emphasizes the importance of requirements a nd the execution
of testing against th ose requiremen ts. Hi g her CMM levels arc bestowed only on those organizallons that
wnte down reqUirements thoroughl y (see Chapter 6 ). However, man y real · world applications have
Incomplete or even nonexistent requireme nts docume n ts. Our concern in thi s chapter is how to rest such
applications .
Even when requi remen ts do exist in written form , the)' generally cannot prOVide a very good feeling for
[he apphcation compared with running code. This is like the dif fe rence between drawin g detailed plaAs for a
house and living in the house after it is built-they arc simpl y not the same. In fuct. if we want to determine
whether a hou.se that is already built satlsnes needs, it is more useful to ask the occupants thaa to inspect the
architect's drawings. Figure 28 . 10 summarizes the reasons for res't ing wit h little or no reference to a
re::quirem ents document .
Suppose that yo u have been asked to test an applicatio n for which there is no requirements
document. Where do you begin ) In the next sections, we'll describe a starling poi nt, a h,haDiora' ",odel of the
applica ti on .

• PrOVides a "feel" for the application


Even complete , wnnen req uirements do not accomplish this effectively
• The Requirements document omits implicit ones
• The ReqUirements may -
- be incomplcre
- be inco nsistent With the code
- be missing
- never have been written down at all
• You can't access the requirements because the product is from d third party
Vendor software that you must test before using

Figure 21.10 Reasons to test without basing the tests on written requirements
TESTING WITH LIGHTWEIGHT REQUIREMENTS 709

28.3.2 Models for Software Testing

To tcst an applicatIon 10 the ab cnce o( \vell -wrltten reqUIrements, the tester needs a .cnsc o( how thc
applicanon is meant to beh. e and how it actually behaves. ThIS IS ca lled btl,.1IIo",/ moddillg . Mo t o( us have
alread had a behavioral modehns expericn e In dealing with an unfamdl3r application. Although we may
road the manual or follow a tlilo nal , we often si mpl y ' play around" with the application . Th, s cCtl on conCerns
dLClplined ways to "play around" with the goa l of fi ndlOS as many defects, as serious as po sible, in as little
nmo as possIble. ThIS is not the black·and -white proces of requirements-based tesllOg, and it is someti mes
called 3n "arl: Good artist . however, arc extremely well -dis iplincd, and good testers are too.
Onc approa h to forming the concepts of an as· built (already constnlcted ) applicati on is to u e the
software design models that we covered in haptcr 15 These are the uS! .It modds, clnss modds , dtllnJlow ,"odds,
and slalt mo.lds. These arc valuable (or creatIng desi gns o( applicat Io ns yet unbuilt , but they are less 0 (or
modeling already -built applications. Table 282 indicates whcn these deSIgn model could apply to
behavioral modeling of already-bu ilt applicat Ions
ThIS suggests that a different or modified model shou ld be soug ht , as di scussed next.

Table 28.2 Applicability of various deSign models to black box testing of as-built applications
oeslgn Model Applicability to As-Built Black BOX Testing
use case Model Apply use cases to identify the main, unbranching behavior
Class Model Typically not especially useful for black-box testing
Oata Flow Model Possible if the tester recognizes principal functions
State Model Possible if the tester recognizes states that the application
transitions through

28.3.3 Constructing Directed Graphs for Black Box Testing

w. will use the concept of dlrtcltd gmpiJS in what fo li o"" . A directed graph is a Rgure consi ting of node ,
together with arrows between certa in nodes, called tdglS , illustrated in Figure 28 . II The meaning o( nodes
and edges depends on the conlext in which they art app lI ed

node

edge

Figure 28.11 Directed graphs


710 CHAPTER 28 TEsnNG AT THE SYSTEM LEVEL

1 3 ~--- 4

Actions
• Launch text document processing
• Enter leX1
• Hit liIe / save
• Enter a file name and press save

An action Edge Indicates sequence


(only one in this case)

Figure 28.12 Initial directed graph for OpenOffice

O ne approach to modeling as· built applications is to sta rt from what appears best to be a beginn ing
point of th e application , and then keep track of the paths from th ere In directed gra ph form . Each node
represe nts an act io n performed by the user o r the appli cati o n (someti mes a seque nce of such act io ns instead).
Each edge leads to the next possible act io n. Edges arc labeled ",hen necessary to distin gu is h options. This use
of nodes and edges IS neither data flow nor state/ transition. It can be tho ug ht of as a control flow in that each
node represenlS a point at which the applicarion i in control.
As an exam ple, let's perform th is for the word processor of the open source ofRce suite OpenOfRce. Besides
servi ng as a means forblack box testi ng, a directed graph is a means of ge tting to know the application. Figure 28. 12
shows the ~glnning of a directed graph for executing OpenOfRce's "Writer.' its word processor.
Si nce thero is no branching in the example o f Figure 28 .12, there is no need to label the edges to
understand the seque nce of actions. In Figure 28 . 13, o n the o ther hand, there is such a need. Branch points aro
labeled as nodes like any other (which makes these diagrams different from o thers we have studied in this book).
Figure 28 . 13 shows a continuation o f the graph ing process. The numbering serves o nl y to label the nodes and
docs not denote an o rder. The la~ls on edges are used to assist in d ifferentiating among branching o ptions.

1\----- s:::- save-


bold save
Actions 4
headings
1. Launch text document processing. ~

2. Enter text
3. Hit file I save as
4 . Enter a file name and press save [Pred icate
7
5. Convert 3 line to headings at levels I . nOde) F
2. and 3
6. Bold some lext T
8
7. File exists?
8. Hit save ' "already exists" pops up , yes

FllUre 28.13 Elcample of a directed graph for OpenOffice


TESTING WITH LlGtfTWElGHT REQUIREMENTS 711

- - --
1 - . save -
"
--- - -~
·• .. headings
Palhs: •
- -> bold " " '" save
Actions '.
"
1. Launch text document processing. /
2. Enter lext /
3. Hil file ' sa VB as
IPredicate
4 . Enter a Ii Ie name and press saVB
node] F
5. Convert 3 line to headings at levels ' .
2, and 3 T
8
6. Bold some text
7. File exists?
8. Hit save '"already exists' pops up ' yes

f"tgUre 28.14 Using a directed graph for testing-openOffice example

• The most .,xpected path s with no e rror o r a no maly condit io ns


• Th., most expected paths with error or anomaly co nd iti o ns
• The paths most likely to Yield defects

Figure 28.1 5 Selecting paths in directed graphs for testing

28.3,4 Using Directed Graphs in Testing

Tests are de igned via sequences that traver e mult ip le no des. A reasonable goa l is to crea te enough of these
to cover all nodes. (Attempting 10 cover all pnl/, co .. blllalioll' exposes more defects but usually leads to a
combinatorial explosion in the number of poss ibilities.) Figure 28 . 14 sh ows Ihree paths that cover all nodes ,
The number of eque nces made of these path s ca n be extreme ly large . The tester can be elective among
these as in Figure 28 IS , h owever.

28,3,5 Testing for Agile Processes

As mcnlloned in previou c hapters, continual tes ting IS an IIlteg ral part of agi le proces os, especiall y via
utilities such as JUnll and N Unit Allh oug h suc h tests focu, on a method under constnlction , a growing ,
cumulative set of unit tests ca n e ffe c ti vely te,t large parts of an app lica ti o n as it grow .
A sU ite of jUnit te t , grown mel hod by metho d and class by la, (as In hap ter 27), rn a be part!
usable for functional testing ( , e , to check that the rcqullcme nls have been . at"Red ) H owever, Invariab ly
there will be reqUirements for whl h th 'yare not a pp ropria te , uc h a th o.e that reqUire user intera tl On
The follOWin g kinds of teS lin g arc ca rn ed o ul for a!,l dc rroJ,:c t\ In the sa me wa y a, for non . ~gdc ones

• onfunctlona l tcst lll g (pe rfo mla nce, 10aeVs trc", cvcont, rc ovcrab ,hty, lIsab ili! , SeCliftry, o illpatibil itv
,"stallatlon , servlceabdit y)

• Accertancc tc,tlng (a cnlr. I part of Ih ' a~ d c approa h )


712 CHAPTER 28 TEsnNG ATTHE SYSTEM LEVEL

28.3.6 Qualities of a Good Tester

We have described various tcchnlques fo r t hc blac k' I)OX te.Sttn - g 0 r 's bu I It applicallons. A good tester,
U ·

however, goes well beyond them In hIS or her efforts In tryi n!: to ferret out defect that could be encountered
_.,111 an t time
w hen many people usc the appilCJllOn ror J sign ' ., per. Il aps In u nant, c,pated ways. He orsh. .shou. ld
be an Independent th,nker and should not be part of the tea m that deSIgned or ,mplemented the appllcat,on
under test. Thi IS bcc~u~c ('ven the most Independent pc:r o n involved In dcc;lgn or Implemcntatl~n develops
a vlS,on of the app hcall o n that , eve n when excellent " likel y to overlook or misunderstand ISsueS . The
following arc o rne of the qualities of a good tester:

• Willingness to learn goals of applica tio n


• Wdlingness to pu t self in uscr shoe<
• Dcterrmned
• Dogged
• Fearless
• Imagi native

• "Outside the box" thinker


• Curious

• Meticulous

Let's translate these qualities into the testing of OpenOfr,cc. T o fi nd as many defects as possi ble within a
fixed amount of time , the tester would need sufficient detenninatlo n to go beyond the obvious ways of using
the application This is because the com mon procedures will probab ly have been exercised many times and
thus have been debugged . The tester would need dogged nes< to stay with h, or her intuition concerning
lurking bugs even when it yields few initial bug finds . In the nonnal usc of an application , users tend to be
relatively gentle . For example, the y avoid hitting a cont ro l-X butto n while a fi le is bein g saved, o r pressing
many keys in rapid succession, including functio n keys. A tcster, on the o ther hand , need the fearlessness to
stress th e application In such a manne r.
There is another sense in which testers need to be dogged: ge lling actIOn on the defects that they And.
Kaner [5] notes that Anding 'lnd obtai ning action o n discovered defects i significantl y mo re important than
simply fi nding them. H is pOint i that the time spent discovering a defec t i wasted if the defec t is never
repatred. It is certainl y the task of QA to ensure that qual iry is present. and this includes en uring appro priate
actio n o n def(·e ts.
T t'Sters need enough imagination to think of many different ways of usi ng the appl ication . The)' need to
· think out ide the box· because defects arc usuall y found in execution paths that arc not obvious. For example,
in testing the OpenOfAcc word processor, a good tester would pursue sequences very different from the nln '
of·the- mill opm fildtdillsavt sequencc_A more de111and ing sequence is opm fllrl..,ld 10 1i""ISt' Somt Ii"" '" II<InOll5
I)cading Inxls/StJlJt in Jocafjcnt f Iset Somr linC'S 10 parious bulitts/wUf itl 10caiioH 2l rcfrirot .
~d testers are C\~riOus. They a~ required to wonder aboUl the I,m its of the application, repeatedly asking
"Wha, ,f I were to - .. I An example IS "What ,f I were to load a non-OpcnOftlee document a d th •
, n en . ..
Testers need to be meticulous in that thcy must kcep CJreful records of the steps folio" d d'
...·e to Iseover Ol
defect, and gather detailed information to include in bug reports.
TESTING SHORTLY BEFORE RELEASE 713

28.' ~STlNG SHORTlY BEFORE RELEASE

Every project ha, a hi tory of testi ng lasti ng almost as lo ng as the projec t Itself. H owever. the period JUSt pro or
to relea,ing the appll aloon has specia l testing characteristics. which are described in thIs sectIon.

28.4.1 Soak Testing

h is common to conduct loak 1<s/on9 ncar the end of the system testi ng phase. During soak testing the
applicaroon IS executed In an environment that simulates as closely as pos ible the way a tYPIcal customer WIll
use the sy tem under no rmal load . The soak lest is conducted for an extended penod of time for eX.IIOple ,
twO weeks. rest scnp~ are used so that the testing can continue for the entire duration wilhout intemoption .
The purpose i to uncover problems such as memory leaks and timong.related is ues that only manofe<t
themselves after the sys tem is run for a substantial peri od of time . The goal of soak testing IS to reduce, as
much as po ible, initial custome r complaints about problems-not necessa nl y sen ous but annoying o n<s;-
encountered when they exerci e the appl ,cation in a manner not exercISed before. Ideally. soak testS are run
by committed customers, otherwise by QA .

28.4.2 Acceptance Testing

In principle , the customer contracts with the developer to build an application . At ome POonl, the developer
claims to have fulfilled his or her part of the contract, the cuStomer validates this , and then pays for the
application if satisfied . The customer performs thl validation by means of ncaplalla 1<sls In pnnclple , these arc
most important for all concerned . Acceptance tests can be executed by the custo mer, or by the development
organization-in ome sorr of clearly demonstrable manner on behalf of the customer. Acceptance tests arc
lYpically driven by the SRS . A subset of the system tests i selected that valodate maJor funerional
requirements and selected nonfunctional requirements.
It is a realiry of software de velopment that deli ve red applocatlons contaIn defects. If a con tra t were to
stale that software will not be paid for if a defect IS found , very few compan Ies would ro sk deve loping software.
Defects therefore have to be factored into contracts There arc several ,,'ays to deal WIth this, mostly legal In
nature, that relieve the devel opment orga nIzati o n of a degree of responsibility .
Recall that soltware ~an meet all its requireme nts ye t nOt meet the II"dl of the custOmer. o ntrac ts
attempt to navIgate the gap between customers, who want appl, cation . that arc satISfactory to them (" ' rot te n
or not ), and developers, who need to work WIth wcll ·dcflllcd ends. Acceptan c testong IS planned and
tonducted accordingly. Metrics for acceptance leStong are a subse t of those covered so far In thIS hapter, by
mutual agreement between the customer and devel oper, made In advance.

28.4.3 Alpha and Beta Releases

Th,s sectIon concerns ap pll ato o ns Intended for usc by a large number of pc pic A oftware product versIon I
rtl"",d when it os officially turned over to CUStomers. This usually take. place dorectly after a ceptan e te<h
Quallhcd releases may take place prio r to the fina l reica<e In many case , Int ernal pro pectlve u<cr< as well a,
CUstome rs, arc will,ng to parrlclpate in the y< tem teslong proce« Th, process 0< on tro ll ed b afpl", relea c
and "'Ia releases, as dIfferentIated by Figure 28 16
Alpha rtl,am are g Ive n to In · ho use user\ o r to a high Iv e lective and tru<ted group of ex lerna I u<ers lor
early prcrelea~ use The purpose f alpha rclca<e, 0< to rrovldc the devclol'ment organl zatoon f.edba k
and defc t Informat Ion (rom a group larger th an the teStNS, without afle tlnB the reputall n of th e
unreleaso:d product FolJowlnr< the d, ssem,natoon o f alp ha rclco>cs , I,,'n "Ira'" arc ~ Iven Out 1 he e arc
714 CHAPTER 28 TESTlr.jG AT THE SYSTEM LEVEL

/"-/'0"" a"d hig/I/Y !M"J "sc,..


• Multiplies tes tlll g
• Prcvlcw~ custo mer rea c ti on
Alpha
• BeneAts thlrd -pany deve lopers
• Foresta ll co mpetitio n

c/ected cU5tomers
• Multiplies testin g act ivity
Beta
• Obtains c usto me r reactio n

Figure 28 _16 Alpha and beta releases

give n to part of the custo mer co mmun ity wi th th e unde rs tandin g that they re po rt defects fo und . Alpha and
bet. releases are also used to co nv mce potential custo mers that th e re rea ll y is a product behind th e
vendor's pro mises.
A prinCipal motiva tion to be alp ha testers and beta testers is to gai n advan ce know ledge of the product.
Developers can gam informati o n about the appl ication (typica ll y its AP ls) so that th ey ca n begin to d evelop
applications that use It. Users can begi n to fo rm decisions abo ut purchasing the application o r gai n
• •
t!xpen(" ncc uSing H.
Metncs fo r alpha and beta testing include the metrics mentio ned so fa r 10 th is c hapter, in principle.
Alpha and beta tesllng are generall y not focused o n particular attributes. ll,ei r products are bug reports,
which arc ge nera ll y ca tegori zed Metrics include mos t of those already mentio ned in thiS c hapter, as well as
th o se with a simpler ca tegorization such as the fo ll owi ng:

• umber of majo r defects detec ted within the firs t x days/weeks/mo nths

• Number of no n-major defec ts detec ted within the Arst x days/weeks/mo nths

28.S CASE STUDY: ENCOUNTER SOFTWARE TEST DOCUMENTATION'

Note to the Student: g reat deal since it improves their ability to


Th is document describes the overall testing make applications more reliable .
of Encounter. The document uscs the IEEE
Standard 829- 1998 Software T cst Documen -
tation (STD ) headings (in'roduc'ion. 'tS'plan.
H IStory of version of th is document:
ttSt JrsigH. Icst CdStS, Itst proceJwrn . trst .ttm rro"s-
lIIillal "port. ,,,' log. 'tS' incid.. , "port. 'tS'
' UIII- 1111 /98 E. Braude, In itial Draft
lIIary ) and refers to the various particular t~sts
(i ntegnUlon tests, system tests, acceptance 4/4/99 E. Braude: Revised
tesfS, etc.). These, in fum , are described using
8/23/99 K Bostwick· Documents reviewed and
th~ same IEEE SID headings. Thos~ involved recommendations made
in testing appreciate fhe documentation a
I R(produced wit h permiSSion ,
CASE STUDY: ENCOUNTER SOFTWARE TEST DOCUMENTATION 715

8/2411999 E. Braude: Recommendations game. IEEE standard 829- 1998 for Software Testing
integrated Documentation is used at every I~I of testing.
Status: to be completed The test philosophy for the Encounter video
game is summarized in Figures 28. 17 and 28. 18.
1. Introduction
Although the SOD is not explicitly a require-
This document contains the STD for Encounter and ments document, it efkctively imposes require-
its role-playing game (RPG ) fra mework. The catego- ments on the implellientation. Sometimes these
ries of testing addressed in this document include unit • requirements are spelled out in a separate doc-
integration, system, acceptance, and installation test. ument. The case study in this book does not
ing. This document describes the testi ng required to contain such a separate document.
validate the nrst three builds of the Encou nter video

-
Test Type Approach Corresponding document sections
-
White and black box; method and
Unit SRS scction(s): 3.2 Classc.IObj,el.
class tests, tcst agai nst detailed
SDD sectio n(s): 6. D,'ajt,d dt<jgll •
requirements and design.

Gray box; mostly package· level; SRS sectio n(s): 2. Outrall dt<criPlioll , 3. 1
orien ted to builds ( I, 2 , and 3), Ex/ental hlltrjac(S , va lida te representative re-
Integration test against architecture and quirements in 3.2 Classr.IObj,cls
high-level requirements. SDD sectio n(s): 3. D,compo.ilioll dt<criPljOIl , 4.
D,p,"dmcy dtScripljoll , 5. IlIltrfac, dt<criPlioll .

SRS sectio n(s): 2. Ou,,,,11 dt<criPllolI , 3. 1


Extcnlnl ju lujaas , validate represe ntati ve re-
Black box, all packages; whole quirements in 3.2 Classt<IObj'CIS, 3_3 Ptr-
system (Build 3); test against JonnnJl mluirrmruls, 3.4 DrsigH constra;,ds, 3.5
t
System nonfunctional requirements, . r· Sofllva" ,y,'tm
allribult< , 3.6 Olh" "4I1irr",,,,',
chitecture and hi gh-level SDD ectio n(s): 3. D,composlljoll dtScriPllolI , 4 _
requiremen ts. D,pmd<lICY dtSCriPlioll , 5. IlIltrfa , dt< criPllolI :
va lidate represe ntal ive requirements in 6_
D,lait,d dt<igll .

Figure 28_17 Approaches to system test and their documentation, , of 2

Black box, all packages: whole system (Build 3), test SRS scction(s): 2. Outrall
Acceptance against high-level requirements and detai led drsrn'pljoll, 3.2 Clams!
rt:qUlremenrs. Obi' Is

Black box, ail packages; whole <y tcm (Bui lds for SR section(s): 2 Ol'(rall
lostailation customer specoRc o nngurarions), test against hlgh - dt<criPllolI , 3.2 ta ss'"
level requirements and detailed requirements. Objrel

Fleur. 28_18 Approaches to system test and their documentation, 2 of 2


716 CHAPTeR 28 TeSTING ATTHE SYSTeM LEVEL

2. Encounter Video Game Test pa koge and the Encoun ler harael'" package It de ·
Documentation scribes how to verify thai the player and foreign
c haracters Ca n be retrieved . modi(,cd, and dIsplayed
n,e5 I 0 for En <>tin ter and th e RPC f", mewo rk covers thro llg h the singicton Enco""I"C"" object
lCSt planning. speCifica tion, and reporting . TI'\crc arc
separa te tcst plan for unit, mt'cgnm on, ystem , accep - 2.2.1.1.3 Test Items The classes and method< '"
tance, and ",stallatio n te ling. Each test plan reference< th e G",", harael", a nd E"cou",,,Ch.,. I", packages
its test design, rc t case, and test procedure spc IRca· arc te. ted throu g h the EncountcrCast sIng leton .
lions. The' tcst reporting documen tation consists o( the
tCSt 108, incid~nt report , and summary report.
2.2.1 .1.4 Features to Be Tested The features
tested by the tes t desig n speci ftcation Budd 1_ TD ar"
2.1 Unit Test STD based o n the reqUIrements with", the SRS and SDO,
as listed in Figure 1810.
Refer to th e separate UOit test document .

2.2.1 .1.5 Features Not to Be Tested


See the case srudy in Chapter 17.

Inevitably, infinitely many points simpl y can't


2.2 Integration Test STD be tested for. but identifying particular issues
that will not be tested for sometimes helps to
The 5 I 0 fo r Integration testing consists of the
clarify the test ing process.
separa te STDs for budd I, build 1, and build 3, as
described next. Refer to Appe nd IX A in the SCM P fo r
an expla natio n of th e construc tio n of th e build The testing of th e feature s associated with th e
• in tegration baselines. T csts will be Ident iRed acco rd · EncoutlltrEnu"onm mt and EncounlrrCamt packages and
Ing to the convc: ntlo ns shown In Fi&'Ure 28. 19 . their fra meworks is deferred until the build I and
build 2 integra tio n testing .
2.2.1 Build 1 STD
2.2.1 .1.6 Approach The approach to the ve rifica·
2.2.1.1 Build 1 Test Plan tion of build I consists of verifying that the characters
of the ga me can be ret rieve d and displayed through
2.2.1.1.1 Test Plan Identifier Build 1_ TP the Si ngle to n EncounterCast o bject. Th e method and
interface tests verify that the re quire d (public) inter.
2.2.1.1.2 Introduction This test plan covers the face methods of th e Encounter Cha racters package are
integration test for the G. ,",Ch. ,.cl'~ framework av. dable from the EncounterCast si ngleton.

Test Document Identifier

Test Document Document Identifier


Build I T est Plan Build 1_ TP
Build I Test Design Spocificallon Build 1_ TD
Build I Test Case Specifications BUIld 1_ TC I toBu ild 1- T C ..
Build I Test Procedure SpeCifications
Build I T est Logs
-
Build 1_TP I toBuild I TP . ..
Buildl _ LOCI to Buildl _ LOC "
BUIld I Test Incld"nt Report
Build UnRep I to BUilcMJnRcp . ..
Build I Test Summary Report
BlIIldl _SlImRepl to BuildiSumR"p ...
Figure 28.19 Test document file Identification
CASE STUDY: ENCOUNTER 717

Document Section Requirement Title


SRS 2. 1.2.2 User interf~ce for setting quality values
-
3. 1.1.2 User interface for sening quality values

3.2.EC Encounter characters

3.2 .FC Foreign characters


--
3.2.P Player characters

3.2 .PQ The player quality window

SOD for RPG framework 3. 1.2 Characters package

5.0 Interface description

SOD for Encounter 3. 1.2 EocounterCharacters package

4.2 Interprocess dependencies


-
5. 1.2 Interface to the Enco"PlltrCharacltrS package

Figure 28.20 Features to be tested in build 1

2.2.1.1.7 Item Pass/Fail Criteria Pass/fail crite- 2.2.1.1.11 Environment Needs Depending
ria are based upon satisfying the corresponding upon equipment avaiiabil.iIY, either an IBM PC,
requirements in the SRS and SOD. Sun SPA RC workstalion , or an Apple iMAC hard-
ware configuration can be used. The Eclip e In te ·
2.2.1 .1.8 Suspension Criteria and Resumption
graled Development Environmenl (IDE) should be
Requirements (N/ A) used for Ihe build 1 testing.
2.2.1 _1.9 Test Deliverables The documents
listed in Figure 28 . 19 are to be delivered to the 2.2.1.1.12 ReSponsibilities Sally Si lver and Jose
conRguration management group at the completion Hernandes from the SQA group are responsible for
of the build I integrati on test. managing. preparing , and execullll8 Ihe bUIld I inte-
grati on test. In addition , the Encounler development
2.2.1.1.10 Testing Tasks The testing tash on -
group addres es lechni cal quest,on and respond to
sisl of the foilowlIlg steps:
teSI inCldenl reports. o nAguration ontrol stores aU
I. Load build I and Ihe pa ka ge Build_ I. te st documentation and data.

2 Execule build I Ie I procedures from Ihe malllO


2.2 .1.1.13 Staffing and Training Needs The
mel hod of Bu ild_ ITest ,n package Budd_ I
SPMP speciAes the ovcra ll stafRnl( and tra,ning need,
3 Wme lest report documentall on In accord.nce for integration rel.i tln g
wllh Sect,on 2.2 I I 9
4 Slore ail te<l documentallon and dala ,n a cord - 2.2.1.1.14 Schedule The chedul e for lIlle!(ra-
an"c w'lh Sect,on 2.2 1. 1.9 uncler ~o n 'guratlon tiOI1 tcstlng ,S 111 luded ,n the P"IP, 'uion 5
management. VC,",'OIl and hi gher ( t"Ct!CH\ Iq d" tI",CI\ (lu.'
718 CHAPTER 28 TESnNG AT THE SYSTEM LEVEL

upd~tlng of the PMP to rene t the arc hitecture 2.2.1.2.3 Approach Refinements • •

selected )
2 .2.1.3.2 Test Items The functlonaJ.ty to be
te ted is conta ined ,n the pcone.tlons for the
TI,e ca e studies in this book do not include follow ,n g publi c met hods of fl1 CO""ltrCasl.
the updated SPMP.
E"co""ltr asl g"n"fl1coll11 I' rCns l()
Gam,(I,a,acltr 9"Th,Player(haracl, )
2.2.1.1.15 Risks and Contingencies If the SQA
tcam is unable to execute tests, or the numberof defects
Ga ,",Characler g" Th, FortigllChaTaCI,r( )
causes an unacceptable number of system failuTes. then void stlPlay,rO,. ,acl,rQual,ty(SI,illg 4",,[ity,jloal oa[.,)
Alfred I\lurray of the Encounter development team w,lI
be aSSIgned to the budd I integration test. oo,d stIFortigllC/UI,"clerQ""I,ty(SI,,"g qua[ity, jloal
oalu, )
2.2.1.1.16 Approvals The completion of this test jloal geIP[ayerC/'araCltrQlIa[,'y()
requires the approval of the SQA Manager, the Encoun-
jloal 9" Fort1911C/,aracl,rQ"al,ty()
ter Development Manager, and the CCB Representative.
These arc tested in accordance with Fig-
2.2.1.2 Build 1 Test Design ur~ 28.21.
2.2.1.2 .1 Test Design Specification 2.2.1.3.3 Input Specifications: see Figure 28.21
Identifier . .
2.2.1.3.4 Output Specifications: see
2.2.1.2.2 Features to Be Tested The test for Figure 28.21
build I w,lI get the f llco""lerC,,sl object and the player
and foreign characters, change the va lues of various 2.2.1.3.5 Environmental Needs ThIS testing is
quahtics, get these va lues, and (hen verify their performed with the Gam,Cba ,acl,'S and fll co,ml,rCbar·
co rrec tness. actcrs packages alone.

Phytr Foreign
input Inp ut
Qu.llry v• .luf: v.lut Othu Action

InCCBr3t1on
Tnt.

81.1 N/A N/A N/A Vcnfy by n.lmc

Bl.l IA N/A NlA Get fortlsn Verify by name


char.lcte r

BI.3 Conccntr.ltlon 30 40 N/ A Venr output valun __


Input v.llu('<.

B1.4 Sloamlnoa 30 40 N/A Verify OUtput .".. Iu« ••


InflUt valuC'S

Bu • • • • •

Figure 21.21 Integration test Inputs, outputs, and actions


CASE STUDY: ENCOUNTER SOFTWARE TEST DOCUMENTATION 719

2.2.1.3.6 Special Procedural Requirements: 2.2.1.4.4 Procedure Steps Po pulate the Ale
None Build I_test_data with input data and expected out-
put values fo r Ihe qualiti es in the following fonna t.
2.2.1.3.7 Interface Dependencies: None
< quality name > < illput > < expected output>

This section dcscri~s the ",Iarion hips among < quality name > < input><cxpected output >
lhe various inlerfaces . This becomes signin .
• • •
anI for fulUr., bUilds, but is not an ISsue for
build I. 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
This identines the class/method from wh ich the defect tracking system for Ihis defect
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 Bu ild U cst3
2.2.1.4.2 Purpose T o sct up a tesl of build I wilh
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 tracted during the execulion of tesl 3 by an alann in
a class with a si ngle method, mainO, is to be co n· the building, and could no t record the re ui ts It was
structed . and tests 1, 2, 3, . . arc to be executed and decided no t to inte rrupl or repeat the test seq uence,
the results compared. and to conducl test 3 as part of Ihe tesling for bui ld 2.

Result Defect reference

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)


720 CHAPTER 28 TESTING AT THE SYSTEM LEVEl

2.2.1.7.4 Impact It \ ,s d~c ldcd th, t the Irl IdcnL(s) d "played th roug h the Enco"n ltrEnviro",mml object,
repo n ed above were n Ot serl ou enough to rcqum.: a an d Ih ,1' the o nncctlon< among them arc con ,sLent
repe t, tlon of lh b lest. 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
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.

2.2.1.8.2 summary TI,e bud d 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 be tested is co ntai ned in the fo ll owi ng publ ic fun c·
h,ndled by the regula r defect repair process. tio ns of Ellcolm f(rEIIVffOtHlltn l .

2.2.1.8.3 variances co build I teq incident re port. GnmcArm 9c1TI"DrmillgRoomO

GnmcArm gCIThcO""9tO" O
2.2.1.8.4 Comprehensive Assessment • • •

• • • •

Add itional remarks supplyi ng details c an be Enco ll PlltrEnvi rOl' ,"ril l 9(1 ThrEt'ICO UH IrrEllvi r(l",molr()
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
described in Figure 28.23 .
2.2.2.1 Build 2 Test Plan These tests will ve rify 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 721

nlO~nl~nts of EH O".t" chara ters wllhin the


~nvlron",ent . The integralion leslS verify that the require·
ments of Encounter, as stated in the SRS, have
2.3.2 System Test Design been satisAed.

~ syslem lests are designed to verify the The acceptance te IS arc slored in the Accept·
architecrure by executi"g and verifying se. ."crT", package, and include the usc cases.
quences of "'Ierface methods The Initialize usc case IS sh own In Figure 28 .24
and is executed by the mai"O method of the class
2.3.3 System Test Cases Initia lize in the Acctpt."erTts' package.
Syst~m T est I The E"rounltr Fortig., CJJarn use case is shown
Itr
in Figure 28 .25 and is executed by the ",.i"O metho d
I. Move player character into dllngeon . o f the class Acctpta"ctTts t l"itia/izt .
2. Move foreign character into courtyard.

3. Move foreign character into dungeon . 2.4.2 Acceptance Test Design


The use cases indicated in Section 2 4. 1 are to be
4. Execute an encOllnter in the dungeon . 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

main player :Player dress ing


:Encounter·
character: quality room:
Game
Pia er Character window Area
User 1a· . .. create" I

1 b. -create .. ~

2. -create-
I 'y
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


722 CHAPTER 28 TESn NG ATTHE SYSTEM LEVEL

:Encounter :Encounter freddie: engagement:


arne Cast Foreign En a ement
Character
1. 1 displayForolgnCharO :Player's
main
1.2 d,splayO character
~ 1.3 .. create ..
2 execuleO
:Engagement
I 2. 1 S.IP~ye.aua ll1yO
Di~a
2.2 seIQua/l1yO

I 2.3 selForolgnOualityO

3. 1 .. create ..
2.4 selQuall1yO
I r 3.2 dispiayAesul10

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

2.4.3.1.4 Initialize Acceptance Test 4 . ..


2.4.3.1.1 Initialize Acceptance Test 1
1. S1~n up game
2.4.3.2 Test Cases for Encounter Foreign
2. Supply main characte r wi1h 1he fo ll owi ng qual. Character Use Case
ity values , In the order show n:
Strength , 30, then Conce ntratio n, 20. 2.4.3.2.1 Encounter Foreign Character Accep-
tance Test 1
3. Move the main character to the counya rei

2.4.3.1.2 Initialize Acceptance Test 2 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: 4. Cause the fo reign characte r to enter the drawi ng
Strength , 30, Concentrati on, 20, and room.
Patience, 30. 5. Ve rify that an e ngageme nt has taken place
3. Move the main c haracter to the courtyard. 6. Observe the e ngageme nt window showing the
results .
2.4.3.1.3 Initialize Acceptance Test 3

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, 2.4.3.2,2 Encounter Foreign Character Accep-
Strength, 30 and Concentration, 20 tance Test 2
3. Move the main character to the dungeon .
I. Set the main character's ' stren<»h"
o~ va Iue to ;.'0.
CASE STUDY: ECUPSE 723

l . Set the foreign c harac ter' "strength" value to 20. The installation tests shall consist of the accep·
3. love the ma in chara ter to the dungeon . tance tests conducted o n all of the above platforms,

4 Cause the fore'g n character to enter the dungeon .

5. Verify that an engageme nt has taken place. 28.6 CASE STUDY: ECLIPSE

6. Observe the engagement window showi ng the W e continue to use Eclipse for a case study, as in past
resul~ . chapters. There are many systems for automating
tests; and to appreciate the kind of capabilities that
(The player's strength va lue sho uld be 40, and they provi de, we focus o n the Eclipse Test and
the foreign character's 10 .) Perfo rmance Tools Platform (TPTP), The fo ll OWi ng
is quoted and adapted from the o nline documenta·
2.4.3.2.3 Encounter Foreign Character Accep- tion for TPTP [ 6),
tance Test 3 '" TPTP is a sui te of "test, trace and monitoring
tools ," It addresses the "test and performance life
cycle , fro m earl y testing to production app lication
2.4.4 Acceptance Test Procedures mo nito ring, including test editing and execution ,
Acceptance tests shall be carried o ut with two desig. monitoring, tracing and proAling, and log analysis
nated representatives of the customer present These capabilities." TPTP addresses many of the issues
representatives shall carry out all testing wi th the di cusses in th is chapter, includi ng the col lection
assist.ance of the vendor. Whenever possible, events of metrics ,
should occur as a result of the random processe of the The TPTP profili ng tool can be u cd to profile a
game instead of being sti mulated. An example of th, s 's Web application , including memory use and exe U·
the arriva l of the fore ig n character in an area , A log of tio n time (the two ma in performance metri cs), The
all tests shall be maintained by the customer repre· ize of the hea p as the execution progresses is an
sentatives and ig ned by all panics; an y sig natory can example, TI,e profiling process all ows the user to
enter dissen ting statemen ts in the log , select parameters as well as output formats such as
graphs,
2.5 Installation Test STD TPTP can be used to record trafAc at a Web
application, In particu lar, it e nables loops within
These are tests verifyi ng that the applicatio n which a test engi neer ca n embed a test . te t parame ·
executes correctly in its required hardware and ters varying fro m pass to pass, TPTP has built · in
ope'f3,ating system environments, facilities for maki ng logs of the te t re ult for
exa mple , a grap hica l output showi ng reque t that
take the longest time.
The installation test s for Encoun ter co nsist of St.'vc:ral "agents" ca n be set to monitor various
executing the system tests on the fo ll owong hardware aspect of the execu ti o n, These ca n be thollgh! of as
conAgurations, processes a tong in para ll el with the executi o n of the
app lication under scn,tiny. Besides heap and stack
1 IIlM .compatible PC w,th at leas t 32 megabytes usage data , TPTP ca n be used to vie,,, the II age of
of RAM and 100 megabytes of d, sk space objects l-rom varoous cia ses. It can account for all of
the objects of a class that come onto being dllron!!
2. SUN SPARC mode l mmm with at lea t 32
execution, allOWing a trace into th e exe lIt ion TIm
megabytes of RAM and 100 mega bytes of disk
can be di splayed ,n the fo rm of r an of a ,cqut'nct'
space
diag ram For example , ,t may happe n that 0 man
3 Apple ,MAC mode l 1234 or later w,th 32 mega · ,n stances 0 1 the 'm'9 cia s exis t at runtim e that the
bytes of RAM and 100 megabyte s of d, sk space applicat , n' performance i, compro mISed
724 CHAPTER 28 TESTING AT THE SYSTEM LEVEL

n,e key to man y analy <5 I the Iden Ion Method Invocallon, ca n be compared, as In
of unll<ual parts, su h as a usc of memol)' by a process Figure 2826. In thIS exa mple, dI splay parameter<
that c eeds by far th ose lI>ed by o thers . have becn chosen so as to aVOId dISplaying methods
TPTP proVIdes a means for prosramme'> to invoked a negligIble nllmber of tImes (7].
insert "frag ments of Java code that ca n be invoked at Method execullo n limes ca n be displayed as In
specIfied POints," the Java closs ... " This i< ca lled F,gure 28 .27.
"l s ln~mnll(Jliotl It includes monitori ng (or "method TPTP includes the abilll)' to generate test cases
entl)', method exil, ca tch/ fi nall y block . and cia s and test procedures from higher. level descriptIons,
loa ding," \X/ ith sla'lC instrum entation. probe arc as wel l as the ability to record CU I interactions. In
Inse rted before execlltion. These have 10 be o ther words. the application is execu ted and the user
rem oved often by hand-before the application interac ts WIth CU ls. When the application IS exe·
ca n be deployed . Th is can introduce errors via cuted again in plnyba k mode. the user's same CUI
pro bes Inadvertently left in the code. With d)'llnmic actions arc automatically performed .
inslnlmcntation, moddled cia scs can be ubstllutcd T ests arc often o rganized In hierarchies. For
(or unmoddi c:d ones at runtime . This avoids the example, to test a word procc sor, we would test
manual c1can ·up process, but the application must "child" teSts for Rle handling capab,lit,es, editing
be execuled in a speCIal mode to use il. Listing 28.2 is capabilities. display capabilities, and ot hers. The Rle
example output from a class Order that has been handling tests break down into subsidial)' tCSts, and so
taocally Instrumented with method entry and exit on. Managing tests within such hierarchies is a signif.
probes [7) icant challenge, and tools like TPTP lacilitate this.

Listing 28.2: TPTP output trace of entry and exit of Order class
Entered: Order.main
Start
Entered: Order.<init>
Exited: Order . <init >
Entered: Order .placeOrder
Entered: Order.getSupplierList
Exited: Order.getSupplierList
Entered: Order.connectWithSupplier
Exited: Order.connectwithSupplier
Entered: Order.sendOrder
Entered: Order.constructOrderForm
Entered: Order.checkProductAvailabilit
Exited: order.checkProductAvailabilit y
Exited:Order.constructOrderForm Y
. Exception:Order.sendOrder! Toomanyitemsre ested.
Ex~ted:Order.sendOrder qu
Exited:Order.placeOrder
Finish
Exited,Order.main
CASE STUOY: ECUPSE 725

Method Invocltlons
....
"" .000
........-
llS,ODD

•0c " ....


11 ....
"'0_
.s- .....
~
0

-• ' .000
0

, .....
Q
'.000
E
Z
' .000
' .0lIl
,-
.-
'.000

Methods

Figure 28.26 A comparison of method invocations In Eclipse


source. Eclipse Test and Performance ToolS Platform ProrecL reprOduced WIth permISSIon,
htt+fJ /WNW edipse.orgItptplplat1omv document!JprObeklvprot>eklt.html

Method Execution Time (In seconds)

Figure 28.27 Graphical comparison of methOd execution time In Eclipse


~ [dipse Test and PtriOf'lnance 10015 PIilUOfm PfOjOC.t. JopI"oducca wlUl permISSIOn,
I'&UlTJIWww.edipse OfIll~platformidon'menIJlPfoDelllliptObekit hlmt
726 CHAPTER 28 TEsnNG AT THE SYSTEM lEVEL

28.7 CASE STUDY: OPENOFFICE need n."V I('"W , I t is pO~ltive progrc!)s that is cs~ntja l to
keep th is projcc i moving lorward •

Note to the tudent, 28.7.2 Smoke Tests


QA for o pe n source project' is characterized
by user involvement, as exempli Red in this
Smo ke tests arc superficial tests c hecki ng that
case tudy.
c hanges to the baseline ha ve no t resulted in
cataserophic errors. A smoke lest is a reduced
The OpenOfRce teSti ng missio n tatement is at regression test. "Insta llatio n tests" here are no t
httpilqa.openofRee.org/, ''To provide an easy way fu ll inscallation tests
for voluntee r to find , update and bettcl' de Rne issues.
and to deBne tc"t processes to validate a build 01 the
The fo llOWIng is quoled and ed ,ted fro m the
Olfice SUIte."
si te give n at [ 8].
"Smoke Te ts (a lso ca ll ed Shakedown tests)
28.7 .1 Open Contribution to Quality va lidate a build of 000. These arc not fu ll y . fled ged
Assurance test CJses, but \'Ie may use them to create (est cases in
th e future , Your ideas are welcome." The c consist of
1ueh of this section is quoted o r adapted from
the fo llowing, quoted fro m th e reference .
h up';I q a .openof Rce .org/hel pi n g. h tm I.
Th,' latter "describes ways in which anybody ca n Insta llatio n T es ts. In ta ll 000 in both sta nd ·
he lp make OpenOffice.org better, even no ndevelopers. alone and ncrworked environments
OurCUTTcnt focus isonconAnning issue that an: marked
File type Test. T es t th at 000 can open and
WIth the Aags 'unconfirmed' and 'defect.' O ur goal is to
correc tl y display specified fi le types. Ca n open!
r<-"Spond to new Issues po t<.°d by users a soon as possible
execute a Java app let (sa mp les avai lable ).
as we ll asclcarout the backlog of unconfirmed issues that
currently resides in thc IssllcZilln database. File Actions. T est that 000 can create and
However, we recognize that there is a lot m OTC save different types of files . Ca n sen d mail using
to Quality Assura lKe (QA) than just reviewi ng and an external mail program .
i o lati ng is u(s. In the future , OpenOlfice.org (000)
QA will invol ve te<ting docume ntatio n a nd develop · Insert Actions. T e t that 000 can insert spec.
iRed ac tions into a text document.
In8 tes t software. If you arc super e nthusiastic, leel free
to sta rt wo rking on some basic demonstrations of test Edit Actions. T es t that 000 edit actions func.
cases, regression tests, QA spccifkation documenta- tio n as speCified with a text document. T est that
tion . or any other idea you think wou ld be val uable to em and paste integrate with ex tern al editors
Improving the qualIty of 000. and 000.

View Actions. Test that 000 view actions


It IS indicative of the scale of OpenOfRce that ftlnction .s specified .
settling 100 issues a day (over 36,000 per yea r)
Format Actions. Te t that 000 fom» t ac tio ns
is considered "insignificant." funCtion as pecified .

Tool S/Options . T est that 000 tool. options


EveI)' little bit 01 contributio n counts and is in· fun tion correctl y.
valuable. For example, if we have 100 Interested volun·
teers, and thcya ll work o n o ne issue per day, we would be Print . Test that 000 Prints, text do ument to
able 10 cover 100 issues per day. As insignificant as that a default printer.
may seem ""hen compared to the number of issues that Hdp . Test 000 help Content. and fu nc llo n<.
CASE ST1JOY: OPENOFFICE 727

28.7.3 QA Priorities The following is quoted and adapted from [II ].


1ne qadcvOOo project proVides a te t harness to
~ proce:du ~ de:scribed here ,s designed to execute test cases wri l len in different prOgr.Jmming
en$U~ that t he: most ,mportant issues are languages, like ac+ + , Java, Python, or BaSIC. These
test cases are responsib le for validating the functionality
woritcd on first. Its somewhat mechanical
fonn i n~essary in aD open·source environ. and reliability of speCified APls. The test harness
me:nt since no single manager i making con. (written in Java) is responsible: for setting up, running,
tinual decisions. and controlling the test processes and threads:
"The test harness and a nearly complete set of Java
and Basic ICSt cases for the OpenOffice.org API are at
Table 28.3 reAects the OpenOffice QA pnorit . [ I I ] as well as the desired value set for the test runs and a
,es (taken, with minor editing , from the source given set of test documents used by the test cases "
in [9J.
QA contributor procedures are given at the 28.7.5 Automated GUI Testing
source in [ 10].
'The automated C UI testing provides a test frame·
work with test scripts and an application (TtsrTool) to
28.7.4 Automated Product Source Code QA
test alm os! the w hole of~ce application automati ·
cally. The TtsrTool scripts are wrinen ,n BAS IC with
This section d escribes a test harness for exe - some additiona l functions especially for the o ffice .
cu ting OpenOffice tests. The TrsrTool communicates via TCP/ IP with the
office app licatio n." [ 8 J

Table 28.3 Example of priorities in Open Office


Rank Task IssueZilla (lZ) Search Tips

1. New issues posted for the current month or today. Look at the 'Untouched" issues hnked at
http://Qa.openoffice.org/issuelinks.html
Also try searching IZ with Issue Type set to
"Oefect" and Status set to "Unconfirmed,"
where the fiel d(s) is set to "[Issue CreatlOnl" .. .
2. Follow up on unconfifmed defect issues with the "oooQa" Try searching IZ with only the following fields
keyword . Ideally. start with the oldest "oooQa" issues and set: Keywords set to " oooqa" ... Limit the
work your way to the most current. If the issue is older search to a particular time frame .. . .
than 3 weeks and the Issue does not follow the guidelines
listed in the "How you can help?" page, leave a comment
to the user Indicating you are clOSing the Issue for now.
but If they can provide more information to help
reproduce the issue, they can reopen the Issue at their
convenience.
3. Close out issues reported against versions of 000 that Try searching IZ with Issue type set to " Defect."
are no longer current. Status set to " Unconfirmed," and the
Do a Quick check to see whether the issue is verlfable. If Component and Version fields set to your choice.
the Issue cannot be verified, send a message to the user
to see whether upgrading to the latest version of
OpenOfflce.org resolves the Issue. II upgrading 10 the
latest version resolves the problem, close the Issue. If
the upgrade does not resolve the problem follow the
000 QA " How you can help?" guidelines.
728 CHAPTER 28 TESTING AT THE SYSTEM LEVEL

28.8 SUMMARY

nee integratio n tesling is omplclcd, th e appli ca ti on a~;) w hole I ~ tes ted T hi s i~ known as system testi ng.
y<lc m tes ts arc blac k box tests th at val idate th at the applica tio n mee tS it. ,ta ted requirements Both
fu nctional and nonfun (i onal req UIrement.!> arc lC It' d.
Appl icatio ns arc freq ue ntly distributed in-hou c fo r te ting (alpha t es t in~ ) and 10 partt ci patlng
usto mers to try o ut with a lear unders tand ing of liS <tatus as undergOi ng (tn al 'c 'i ng The la lle r IS ca lled
bc 'a testin g.
Accc prancc tes ts are executed by th e cuslOmer ah er systt"ITl fes ' arc success fu ll y comple ted . Their
purpose is to demonstratC' to the cu lOm(', th at th e JppllcJtio n run s sa ti sfac toril y on Its target hardware and in
Its intended Orlwarc environm ent , such as th e operatin g sys t<..' m. Acce pt an <:: les \" s Me usually a subse t of th e
system tesrs.
j\~a ny rca l· world appl ica tiolls have incomplete or even nonexistent requin:mc nts documl"nts. T c:sting in
th e Jbsencc of well -wrin en requirements requires th e tes ter to obtai n a sen c of ho\,{ th e appl ica tio n behaves
and how it i meant to behave. This is called bt'haoioml modtlmg . A n approac h to tes tin g in thi s srtua tio n is to
S'art fro", wha, appea r; best to be a beginning poi n' o f the applicatio n, and th e n kee p ,rack o( ,he fun c ti o nal
path s fr o m th ere . Directed graphs arc used to document ,hese path s. Te t, are devised to execute a set of
pa,hs ,hat altai n a kind of coverage
In o rd e r to be effec ti ve at Rndin g defec,s, a good software tes ter mus' be de termined , dogged, (eariess,
imaginati ve , curious, meticul ous, and must think "outside the box ."The les ter's gOoll is to discover ddects that
c.a n mani fes t wh en an appl ication is used (or a significant tim e by user , perhaps In unanticipated ways.

28.9 EXERCISES

Answer th e following exercises in your own words.


I. Why arc black box ' cS tS (rath er than white box tests) used in system testing )

2. What is th c purpose o( acceptance testin g and wh y is it nl'cessary 7 Cive an exa mple o ( an


applicatio n and a defec t that co uld go undetected in system tes ting yet be c au g ht by acceptance
tes ting .

3. A compan y is develo ping an applicati o n, and th inks it has d iscove red a novel way to speed up its
tes ting cycl e. It decides to dispen se with sys tem testing, and in tead deliver th e appl icati o n to
customers just after integrati on testing is complet ed. The company will lherefore rely on its
custo me r; to discover problems in the appl icatio n. Wha, arc the ad vanta ges a nd d i ad vantages of
this approach) Be speCi fic and ex plain your answer.

4. What is the purpose of soak testing) Gi ve an exa mple o f a defect thi s ty pe o f tes tin g is likel y to
uncover.

5. Load and sfrtS5 tC'sting is often conducted on indiv idu a l units dllring unit and in,eg~ t Ion
• . • • •
'
IU
. I
testin g. n
thIS teslIng, unllS are subjected to hi g h levels 01 stress [ 0 e nsure ,hat th ey do h 'b'
. . no t ex I It an y
problems. Why IS It necessary 10 conduc, system-level stre« 'c, ,, even if all of ,·h
are success1uI7 . e '"'' t t'"'-'SO t e IS

6. Describe the various levels of testing to whic h you wo uld sub)'ec t ,he' I' . d .
. . .. "pp Icallo n escnbed In
E-xerclse 7 In Chap,er 27. Indicate which o f the clas es and pac kages ( ho . h fi
wn In t e gure ) would be
BIBUOGRAPHY 729

involved in each. (Many more classes wi ll be involved in buildi ng the completc application. but
you are not required to show these.)
7. For Nch of the black box testcr qualities listed in Section 28 .3.6. give an example of how that
quality could be counterproductive if take n to an extreme.

BIBUOGRAPHY
t Kit, Edward, £JjlfL.'\Qft Ttjtlrtg ,PI II" Rcal World l,"pro,,,,,; ,Ix Proem, Addison. Wc:sley. 1995
2: Purdue Usab,hcy T CUing QuC'Stlonna ire, hnp Jlold"ww.acm ,orglpcrlma nlques llon ,cgI1form . PUTQ [accessed 121 15109]
3 Herzog. Petcr, OSSTMj\'I - Open Source Security Tc:stlOg ''''!ethodalat,,), Manual httpJlwww.lsccom org/projcctvOSSlmm shlml
[accessed 12I 15109 J.
... Snnlv~san Deslkan , and Goplllaswamy Ramc:sh. Software TCStHlg. Pnnclples and PraCtiCes , Pearson Education. 2006
5 Kiner, Cern, J;ICk. Falk, and Hung Quoc Nguyen, T Nli"g (olllp",'tr SO/IIlIQrc, John Wiley & Sons, 1999.
6 EclIpse T~, t ~ Performance Tools Platform ProJect . hnpJlwww.cc\lpse.org/lpt.p/ [accC..Sscd 11 / 11 /2009].
7. Eclipse T e"Sl & Performanc~ T 001<; Platform Pr.ojecL htlpJlwwwed.psc.o rg!tptplpladormldocumentslprobcklvprobekit.html
[accessed 11/ 1112009J.
8 OpenOfAc~ Project. hakedown Test SUlle · hllp J/qa opc nofAcc.org/tcstcasc:/mdc)(.html (.lcccsscd 11 / 1112009].
9. O~nOfAcc Project . · 000 QA Issue Revl cw PriOntl~." hnp j/qa opcnofficc o rg/ prio rltlcs.hlml [accessed 11 / 11 / 20091
10. O~nOfficC' ProJect. "A Quick Stan CUlde to contributmg to this prOJeCt. ~ hltpJ/qa .openorAce.org/W'W"Wslagingil askslqlllckstan .
html [.ccess.d 11 / 11 12009J
11 OpenOfS« Project. "Automated product source code QA: hupJ/qa.openofRcc orglqadcvOOo_dodi ndex.html (accessed 12I IS/09}
Software Maintenance

Planning • What are the units of software


maIntenance?

• What are the differences between


corrective , adaptive , perfective , and
Testing preventalive maintenance?
The Software
Development • What are some management challenges in
Ufecycle maintenance? Process challenges?
Raquir8J'L8nt&
analyaIs
• What are the rna," technical Issues?

• What is the maintenance process ?

• How do patches work?

• What standards are lhere for software


maintenance?

• What is reverse engineering?


Reengineering?

• What maintenance metrics are available?

Figure 29.1 Tlle context and learning goals for this chapter

Software systems continue to evolve after their initial release. The l'ttainlt'HflH Ct o f a software sy trm
consists of those activities performed upon it aftcr it ;s released. The IEEE glossary [ I ] deAne< ofcware
maintenance as follows:
TYPES OF SOFTWARE MAINTENANCE 731

TI,. proctSS oj mod,Jyi"!l a SOJlwart 'y,'m or eo,"poHrnl afler d,/i",ry 10 corr,el faults , impro", p,rjO"",,HCt or olb.,
a/lnb.ttS, or adapi 10 a eha"9,d ,H"oroH,"rnl.

Maintenance is an activity of trul y il!nincant proportions, consuming an estimated 40 to 90 pe,cent of


the total life cycle co ~ of applocations (see, for example [2] and [3]) . Perhaps the most famous maintenance
effort involved the year 2000 (Y2K ) problem, for which maS<lve work was performed modifying applications
to handle the years of the new millennium . This was maintenance because it ensured that applications already
delivered continued to provide their intended fu.nc tionaloty.
As software systems evolve over tmHo", the y require co ntinuous ma intenance in order [0 remain useful.
Lehman ([ 4] and [5]) claims the existence of several laws of software evolut,on borne out by extensive
experience. The nrst, eOH IoHu iH9 ehaH9', s tates that if a program IS not cont,nually adapted to ongoing needs, it
becomes less and less useful over time . According to the second law, "'Crta''''9 eomp/"",y, as a program is
changed over time, it complexity increase unless ,,,ork is done speCifically to alleviate this. An example is a
maintenance action that increases coupling between modules . Lehman's two laws are relaled . As oftware
evolves, it is modined by engineers who may be competent to make each change but may not completely
understand the overall desi.g n and implementation . TI,is is not surprising, give n the sheer magnit ude and
complexity of many applications, As a result , the applicat,on's structure and maintainability decline. Il is for
these and other reasons lhal software maintenance of several varielles is necessaty '
The addition of new features and functionalilY to an application is n::a ll y a kind of dcvc1opment-
typica ll y of the application's next release . Nevertheless, the process IS somelimes included in the "mainte ·
nance" rubric , especially when the new features are very much ,n the spirit of the application's curre nt
functionality and when they are small by comparoso n. This type of mainte nance i explained in this chapter.
In many ways, agile projects can be viewed as being In "maintenance" mode from the beginning . This i
because agility relies on adding to a code ba e a procc s that has much in commo n with ma,ntenance

29.1 TYPES OF SOFTWARE MAINTENANCE

This section introduces the unit of maintenance . It also names and describes vanous type of m.,ntenance
activities.

29,1 ,1 Maintenance Requests

Maintenance organizations manage lheir work by identifying task . Ideally , the c sh ould be of comparable
magnitude (imagine the Inappropriateness of a li st of c hores that Inc ludes "buy bananas" and also "build
house"). Each such unit of maintena nce is ca lled a MaoHlrnaH" Rtqutsl (MR) in IEEE term inology We try to ize
MRs to be of a regular mag nitude , but the amount of code needed for each ca n vary and the Impact can vary as
well. A phYSICally small code c hange may have a major effect on an application . One way to keep MRs at
comparable effort is to decompose them into c hild MRs .
An MR is either a "paor or an ".hmoe''"tlfl It IS a repair when it co nce rns a defect relative to the existing
requirements, An enhancement MR is one of two types. The first in troduce a feanlre no t called for in ,he
requirements at dclovery t,me, the second type of enhancement c han !!c~ the design o r implementation , wh,le
keeping the functionality unchanged. ThIS is known as refactori ng , as Introduced in C hapter 24 . Refa tonng
usually improves the deSign ,n order lO redu ce comp leXity a nd Increa e efficiency , and it is a re pon e to
Lehman's seco nd law of Increasing co mple Xity Figure 29 .2 summan zes these distinctio ns.
A common categorization of MRs IS defined by L,cintz, Swanso n, et al (6). (7). who reRne the,e twO
types of malntenan e IntO twO .ubcategories, a' ,ummarized ,n Figure 29 3 and explained ,n the rest 01 this
seCtion
732 CHAPTER 29 SOFlWARE MAINTENANCE

• Repair
• FIXing defec t
(relative to existing requirement s)
• Enhancement

• cw reqUIrement
• C hange desig n o r Im picment atio n
(no func to onal hangc )

Figure 29.2 TYPes of mai ntenance

Corrective
Repair - defect identificatio n and rem ova l
Adaptive
- changes resulting fro m operati ng
system . hardware, or DBMS chan ges
Pc rfective
Enhance - changes resulting from user requests
Preventi ve
- changes made to the software 10
make it more maintainable

Figure 29.3 -:)Ipes and subtypes of maintenance


SOUrce Uentz. Benmltt P., E. BUitOrl SWnnsoo, and Gerry E. Tompl(J1"IS. "Chat<1cterlstlcs 01 Applications Software Maintenance," CQmmunlcaUons of the ACM
(CACM), no 21 . 1978, P 406 471 .

Maintenance Reguest 78

Problem When the player changes the va lue of a quality, the computatio ns are specified to keep the total
invariant , but they do not.

Exa mple. If the qualities arc

' 1""9Ih = 10, pa,i",ct = 0.8, and ",du,anet = 0.8 (sum = 11 .6 ), and the player adjusts "''''9 ,h to I I , the result is
slrclIg fh = 1 I, palimcc = 0 and mduranct = O.
These do not sum to I 1.6.

Figure 29 .4 Example of corrective maintenance request

29.1.2 Corrective Maintenance

Correc tive maintenance is concerned wi th the repair of defec ts relative to exist ing req uirements. These
defects are typically d iscovered b y CUStomers as they use a software product. Each defect must be analyzed.
priOritized, and repaire d, and fixes incorporated into new sofh\>'are revisions. As an example defect, consider
th e MR for the Encounter case study show n in Figure 29.4.
MR 78 requi res the maintainer to determine th e cause o( the defect. One possibility is an error on the
code, such as in the method adJustQu.lityO, which is responsible for adj ustong quality values when one of
them is changed b y the user. Another posSibi li ty here is that eXIS ting requirements (or Encounter characters
are defect've. Actually, th e latter is the case, because the requ ireme nts mand.te the follOWing ,
TYPES OF SOFTWARE MAINTENANCE 733

• The user hall be peml ined to sel any Quality 10 any va lue les than or equa l to the curre nl ,um of the
qualitic .

• The remaining qualities retain thdr mutual proporti on:,.

• No qualit shall ha ve a value both grealer than zero and less Ihan 0.5 ,
• The sum of the qUJ.litte~ remains Invarianl.

can be Seen in the example in MR 78 , Ihese ca nnOI all be salisfied Since the defect is in the
~quirements , ill S the cu lo mer's preroga live to make o r permit the c hange, O ne wa y 10 do th iS is to relax the
last ~quircment to the followin g ,

Isum of qualities - 0.5 * (N - 1)1 <= (sum of qualilies)' => sum of q ualities
where N i the number o f qualitie and x' IS Ihe va lue of x after Ihe adjustmc nl proce

Th is modiAcation keep Ihe effect of di _cou ragi ng the player from changi ng quali ry va lues 100 muc h o r
too many times becau e point ma y be 105 1 wheneve r Ih,s is Gone ,

29.1.3 Adaptive Maintenance

Adaptive maintenance i concerned wllh ada pIing the software 10 changes in the operating envi ro nm ent uch
as a new operating system relea se or a new versio n of hardware. As oft'\"arc system s evolve , It IS inevitable
that changes in their externa l environment will take place. An example i if '\Ie were to port o ur Encounler
video game caSe study to an iPhone. It ma y seem awkward to classify adap ti ve ma intenance as a kind of re pai r,
bur this is appropriate if o ne views an app lica tio n as a liVing cntity . In ordt'r to r('mam leg itimate, the
application must adapt to rea o nabl e chan ges in its e nviro nment.

29.1.4 Perfective Maintenance

Perfective maintenance is the develo pme nt and Im plementallon of u er reqllesl suc h as new feature
enhancements. Recall Lehman's Rrst law- Ihat ys tem s mu t con tinuall y adapt to o ngoi ng needs o r become
less and less useful.
As an exa mple of a perfecti ve maintenance reque<t , <uppose that thl' markelin g de partment ha de ided
that to make the Encounler vi deo ga me mo re atlfactlve and markelabl e, player require more tangi ble reward
for their skill. They wanl th e e nt ire loo k of th e ga me to be enh anced whenever Ihe player a h,eve, a new
level. The art department wi ll <uppl y the corres po ndin g graphi CS, and Ihe mainle nan ce orga n IZati o n is ta ked
with a modifica tion to accommodale lhi ' addi ti o nal requireme nt . a, «alcd in Figure 29.5. A so lutio n to till<
MR is dIScussed later In till' c haple r

Maintenance Request 16 2

Modify Encounter so th at the game begin' w"h area, and o nncl.!lo ns 111 a oordlnated <ly le \XIhen the
player achieves leve l 2 <tatu', all area, and connc tll)n< ifre d, <played In an e nhanced coo rdinated ,t Ie,
which IS <peclal to level 2 The art d epartme nt will rrov lde the req uired "nail .

Figure 29.S Example of a perfectIVe maintenance request


734 CHAPTER 29 SOFlWARE MAINTENANCE

29.1.S Preventive Maintenance

Preventive mJlntcnan c cone<; ,c;;ts of c hang ing J c;;oftwJrc applt a ll on In order to m&lke It eas ier to maintaIn
'n,e need for preventive maintenance can be deduced from Lehman' <econd low As 0 program evolves over
lime, hange made through correc ti ve , adap ti ve, and perfective millAlcnancc requests cause the system to
become Inc reasing ly compl ex unless action rakcn to prevent it. Preventive maintenance Involves
IS
proactively rdaclonng the sy'\tcm to reduce its comp leXity. It IS Jlway~ a good Idea to pe rform preventIve
maintenance on an ongoin g baSI
An example or
preventive mainlcnllncc is to recog ni ze and anticipate Industry trends Suppose, (or
exampl e, that we sell a Windows ·based word pro cssor ond that we reco!: nl ze that word proce sors arc likely
to m1grare, In pan , to the \'(Ieb, A preventative maintenance action would be lO alrcr th e word processor's
architecture so that selected pans arc mo rc readily moveab le to the Web
Metncs can be used to identify lIrcas thilt need improvement. For example , by examining ddect mc(rics
It may be determined that a certain software modlilc has a hig h number of defecrs reported agalOst it After
flirt her inve tlgation It may be detem,ined that many of the defect are a rc ult of changes made wh,le prior
defects were repaired This might lead to a conclusion that the desig n of that modu le IS 100 complex, and thus
not ca, ily modified. As a result , mointenance work moy be perfom,ed to redesign the module to make it
Simp ler and morc mainta inable, without changi ng its hlOctionaliry , Subsequently , we would expect fewer
defect to be filed ogainst the refactored module.

29.2 ISSUES OF SOFTWARE MAINTENANCE

Software maintenance preseOls a unique set of cha llenges. Ben nett [8) has categorized them as manage·
ment (what to do and who wi ll do it), process (what procedu re to fo ll ow), and techOical (design and
Implementa t ion).

29.2.1 Management Challenges

Senior management tends to focus o n delivering new products, which are a Ou rce of revenuc (or COSl
savi ng if internal) and provide a quantdlablc return on investment. Funds spent on main .. enance , however,
are usually not si mple lO justify. The cost of maintenance is high , and unless the maintenance organization
ca n charge for their services, th e return on investment IS much les clear than for delivering new products .
As a resllit, maintenance teams can often be understarred and lInderfunded . maklOg an already dtfficult job
even harder.
oo ner or later, the need for organized maintenance i recognized by management and resources are
allocated !o it. Sometimes an. individual or a group or is assigned to repilir tasks ;lnd a se . pal'are group to
en hancements, Incorporated In new update or releases As software moves from shnnk . wr. ppc d d eI'Ivery and
big -bang integration to online deli very, cont lnuOliS '"tegratlon and security upd,tcs tlle tr:cn d h as be en
U ,

toward more frequent version updates ra ther than major releases_The management of rno fr d
. . " re cquent up ares
IS more demanding thon that for major relcoses Simply because !he act of relcase .
I more
freql1ent Th'I .IS
analogous to thc difference between managing a daily newspaper and a monthly magazine .
The management of maintenance involves the assessment of benefits the calc I ' f
' u atlon 0 cost and the
allocation of rcsourc~s, mainly pcopl~ . Table 29. 1 how examples of COSts MRs .. '
" . a r~ p non II zed bose<! on
ana l y~ like thiS However. maintenance requests arc often worked on in gf'OllPS s .
by coneent"'tinS on related MRs. !nce malntalners ·'V. tl'me
~ ,
ISSUES OF SOFTWARE MAINTENANCE 735

Table 29.1 Example of an es~mate for Implementing a maintenance request


Estimate Estimate
ActMty (person-days) Actlvlty (person-days)
1. Understand the problem and 2- 5 6. Compile and integrate Into 2-3
Identify the functIOns that must be baseline.
modified or added.
/-
2. oesign the changes. HI 7. Test functionality of 2-4
changes.
3. Peliorm impact analysIs. 1-4 8. perform regression testing. 2-4
4. Implement changes in source 1-4 9. Release new baseline and report 1
code. results.
S. Change SRS. SOD. STP, and 2-6 TOTAL 14-35
configuration status.

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<lgn . ur. no t deciSion differs from projec t to project
and MR to MR
736 CHAPTER 29 SOFlWARE MAINTENANCE

A~ an exa mple, "UPPO)C that \'\fC \\IJ llllO ('nh.mel' ~he F n toulllt: r video ),(Jmc with tht: p rco;cncc of \cvcral
mon""" rJlher Ih an JUSI o nt oWe wo,dd prohably kee p Ihe Lurre", overa ll dC<lgn and add to II because the
overa ll 'ame rl' m a ll) S th e )JI1l(' In SPirit ilnd h CGlU"C th t· urrCJ11 archltc lUre " capJbk· of Jbs.orblng the
add itio nal apal>dity . O n th e o lher hand . If we arc reqUired to rurn Encou nter 1111 0 J rea l' lIme 31) game In
w hl h Ollr cha rJclt'r engages In v;:mouS "'Jy4; with the monster u~'ng wcapon) and they arc: Jblc to pursue each
o th er wllhm area, and from area to arca , we would reexa mine- and pr bably alt('r- thc c:xl) lIng arc hitecture
This IS because the COmbJl aspec ts wuuld domi ni.lt e the cXI"lIng ) la lC a~pcc{)
Tesllng IS a sig nl ficJ llIlechlll ailS ue Si mpl y focuslOg tes t on changed or added pans takes time enough
because pecial ttst plans l1Iust o ften be devised for this purpose. But fo u cd te'ling IS no t enough . The
posslbdl ty of npple e(fecls reqUIres th at we execute exte nsive regressio n teSlin g to cn, ure th at changes have not
compromls(.'d th e app lication's preexlsllllg funct ionality Thi s i a major factor In th e hi gh CO'Jo l mai ntcnance or
29.3 MAINTENANCE PROCESS

A ","i"lnl""e, pro css dennes Ihe flow of MRs through an orga nlzallo n Figure 29.6 dlustrates a tYPica l
ma intenance process in J large project, where the th icker lines indica te th e nominal path The additional
(thin · lined) paths show o ther ways In which MRs ca n be generated and retired.
In th e process shown In Figure 29 .6, customers prov id e co mments on enhancements and defect
through the help desk . Th ese are wrillen up as MRs. O rga l1lzatio ns ha ve a limited number of resources to
work o n IR, . mean ing that some of the proposed enhancements and repo n ed defects are eit her delayed
or nevcr implemented . .vtalOtenan cC' engi neers must therefore priOrit ize;.: i\1Rs. A Inag( proc(ss IS ofte n
empl oyed [9] th at includes the: re-vic\" of all proposed ffi (l/ntcnJncc reque sts and the prioritization of their
importan ce to th e bU. ln ess and to customers. Triage starts with an ofRc lal orga nizall o nalun il, wh ich may be

- - - Marketing
nominal
Written
MRs

Proposed
MaIntenance
Customer manager MRs
Help desk

- Approved
MRs

MaIntenance Current source Change control board


engineer & documentation

Modified SOurce
Rejected
& documentation MRs

Figure 29.6 A typical maintenance process for a large project


SO'lf(e GtaQnk.s reprMQ'd wlltl ~ Irom COrm
MAINTENANCE PROCESS 7T1

a single person or a committee. deciding which MRs will be Implemerned and aSSIgning them a relat.ve
pnority . This unIt is often referred to as a Cbal1g, COl1lrol Board (CCB) ( 10). It co nsists of stakeholders.
selected from various organizations such as development . user documentation . marketing , quality assurance
(QA). and customer uppOrt . Each organization brings its ow n perspective, and collectively they decide on
MR priority.
The group conducts an Impaci a,,"lysis . which as esses the scope of the changes to the product's artifacts
that are necessary in order to Implement the MR. Each group represented by the CCB provides input into the
impact analysis. Maintenance engineers prepare an estimate of how long it will take to implement the MR.
and its impact on the system. including code and system spccl~cations . The user documentatIOn group
determines which user manuals, if any. are affected and require updates. QA determines how much testing is
required to validate that the MR is implemented correctly. and also to validate that problems aren't
inadvertently introduced into other parts of the system. In the case of repair MRs. customer support
may need to determine the impact on customers of the MR and whether there are any possible workarounds
that can be employed in lieu of repairing the defect. Using all this information as input. the CCB estimates the
number of resources required , the cost. and the risk of implementing the MR. It then decides whether to
accept or reject it; and if accepted. assigns it a relative priority. MRs approved by the CCB are then retired by
technical maintenance staff. New software versions and documentation are generated and available for
customers. For efficiency reasons. multiple MRs arc often grouped together and released as part of a single
maintenance release .
The number of artifacts affected by the implementation of an MR is va riable . Figure 29.7 illustrate two
extremes. At one extreme , the defect is in a requirement that requires changes in the SRS, the architecture.
and so on, all the way through to the code that makes the system operable in its intended environment. At the
other eXITeme. a defect could be present in the code for a method and the MR could affect that method
implementation but nothing else.
The minimal · impact case occurs, for example, when the programmer has failed to follow a standard i~
naming a local variable, o r when an unused variable is removed. In the worst case, however, every part of the
process is affected. Even for a defect in the code o nl y, the impact can range from minor to major. A seemingly

Maximal impact Minimal impact


Maintenance:
I mpact a I
Requirements Requirements
Df1f8C1/nlected 116'8
Del ect MR

,1
Architecture
Architecture

Detailed design " Detailed design "


Interface specs
Interface specs

Function code
Function code
Defee. Injected 116,..
7
Module (e.g .• package) code
"-
Module (e.g" package) code

System code Key 5 denoto. System code


I"""",

Fllllr. 29,7 The Impact of a maintenance request- two extremes


738 CHAPTER 29 SOFTWARE MAINTENANCE

Add: ·chsnge app6srsnC6 when


Requ irements -----
plsyer achlaves new levels·

Arch lleclU", __
--
:::.
Accommods/e ability /0 change
g/obalappearanC6: USB Abstract

Oetalled design - - -- Factory dsslgn par/em

Interface specs --- - -- Add Interlace me/hods

~/
Function code
for Layout package

- - - - - --
----- as
Add classes and methods

Module (e.g .. package) code -- per de/ailed design

Modify gameplay
-----
System code ----- --- - control code

Figure 29.8 The impact of a maintenance request-a n example

SImple change such as an increase," the SIze of a compile-time C ++ array could have major ripple effects
throughout the application.
Maintenance Request 162, described ,n Figure 29.5 , aHects ewry aspect of the process, as shown in
F'gure 29.8. Recall that this new requirement-t he concept of mu ltiple game levels-is a signiRcant addition .
It leads to changes in every phase in the process_
When an application is designed with traceability in mind, the documentation of maintenance actions
can be manageable. Otherwise, the consequences can be extremely expensive.

29 .3.1 Root-Cause Analysis

After a defect MR is repaired, a process sometimes known as root-caust aHniym is sometimes conducted. This is
an iterative, problem-so lvi ng process ai med at determining the underlying reason Ihat a defect has occurred.
Once the root cause is understood , process or other improvements can be implemented to prevent similar
defects from recurring in the fueure . Root -cause analysis is performed via the change control board or its
d~ignee as part of the maintenance process. For each defect , the team asks a series of questions to narrow
down the root cause of the problem.
As an example, suppose that after an initial investigation it is detennined that the reason for a particular
defect is due to a requirement being missed by the test plan. The roOt -cause analysis process is then invoked
to determi ne the unde rlyi ng reason that the requirement was missed , and once determined, to ensu~ that
other requirements are not omitted in the future . The following series of questions illu trate the iterat,ve
narure of rOOt-cause analysis (9), [II].

I. The requirement is no t t<sted for in the test plan .

2. Why? It appears that the requirement was cha nged after the SRS and test plans were completed.
3. W hy? The customer communicated wit h the product marketing group their desire for the ch.nge, but
th is was commun icated o nl y to development. The rest of the tea m was unaware and therdore didn't
update the SRS and test plan .
MAINTENANCE PROCESS 739

~ . Why~ Product marketing thought this was an .solated change that wouldn't affect product te t.ng, so
they communicated it only to development.

S. Why) Product marketing didn't underst:and that all changes to leatures must be communicated to the
entire team .

Once th. root catlse is understood , the product marketing department can implement appropriate
changes to its proc ..ss that prevent th.s type of problem from recurring .
As root causes are detemlined, metTics are recorded to keep track of them . To provide consistency and
make it easier to track and ana lyze, it is helpful to deRne a list of root causes from which the team can choose .
Rakitin [9] suggests the fo ll owing list.

1. Function was missing from SRS


2. Function was incorrectly specified in SRS

3. Design problem-design was inadequate or inappropriate


4. Design problem design review didn't catch it
S. Code problem code was inadequate
6. Code problem code review didn't catch it
7. Inadequat .. Untt testing
8. Inadequate system testing

9. Installation/e nvironment/versio n compatibility issue

A metrics analysis is periodically performed to identify the most common root cau es. The result are
used to create a plan of action to eliminate these types of defects from recurring For example, if it is found
thaI many defects are caused by Cod, prohlrm cod, rwi,w d.d" 'I ca lch iI, a review of and improvement to the code
review process can be implemented.

29.3,2 Patch Releases

Patches are used in two ways. The Ar t way concerns gelling new or replacement software vers.ons or parts to
users. The second addresses delay< in impleme nt ing an MR .
In Ihe first way, patches arc permanent replacements of parts of the application. They often take the
form of a set of fi les, sent via the Internet. that replace object code already written . In th.s case, the challenge
are for the customer's organization to ensure that patches arc appropriately installed. Many customers
conduct their own system tests of patches that ' 5, 111 their ow n environment.
The second way concerns the handling of defect MRs thot require s.gnincant time to remedy It al,o
concerns defects that hamper a customer's use of the ys tem and so must be remedied quickl . A rap.d Ax is
not always possib le. To take an extreme example , in a m.lirary application with which one of the authors
was once involved , nine months cou ld elapse between the .dentiAcation of an MR ond it complete
implementation and docume ntation l l n these case patches are modifications or addition s to the object code
that either nx or work around a defect. FiBure 29 .9 showl a way .n whic h the'" patche an be organ.zed
w.th.n the develop me nt orga ni zatio n It demon strates the nom.nal , "ofAcial" path taken for a pat .. h on the
740 CHAPTER 29 SOFTWARE MAINTENANCE

1. Get malntenance-!r8Quest

2 . Approve changes
:r
3. Plan changes
Assess
Coordinate
impacl Execute
I
with
patch
4. Change code and documentation

Implement.J Test changes


4
Document
Release Update documentation
patch removal

Figure 29.9 Patches In maintenance workarounds

Advantages Disadvantages
• May be a complete solutio n to the problem • May duplicate work
• Keeps customers satisfied - patch a"d final fix both implemented
• Enables continued operati on and testi ng • Temporaries sometimes ne ve r replaced
without prese nce of th e defect - pro per fix deferred fo reve r
• Avoids masking other defects • Complicates fi nal fix (where appltcable)
• Enables test of fix - must rem ove
• Complicates documentation process
• When too ls used for insertio n, ma y com .
promise code base

Figure 29.10 Advantages and disadvantages of maintenance patches

left-as well as an informal process f.or ge uing the patch into the application on a temporary basis on the
right of FIgure 29 .9 .
The advantages and disadvantages of patches include th ose li sted in Figure 29. 10.
The comment about "masking" refers to the fact that allowin g defec ts to remain can make it difficult to
detect other defects whose effects arc hidde n by the effects of the nonrepaired defect .

29.3.3 Software Trouble Reports, Maintenance Requests, and COlTection Reports

It is simplest when a single test leads to an MR that is worked on as a SI ngle ac tion , but the proce s is often not
so simple. Mai n tenance requests emerge fro m reports of trouble experienced with the application (often
called sofl ware tro"bl, reports). There may be several pieces of evidence for a si ngl e MR or, Conve rse l)" several
MRs th.t grow out of a single trouble report. E.ch part of the work on an MR that IS worth d ocumenting I
recorded in a so ·called correction rtport . To deal with the prol ifera tio n of correction reportS, We may need to
identify a child MR of the MR under conSideration . This organIzation is shown In Figure 29. t I.
IEEE MAINTENANCE STANDARDS 7.1

-;., ::t,
I, Malnlenance
Request
~ Sollware Trouble Report
STR 902834
1293

Correction Correction Correction


Report Report Report
1293.1 1293.2 1293.3
Maintenance Maintenance Malnlenance
Requesl Request Request
1293.1 1293.2 1293.3

Figure 29.11 Software trouble reports. maintenance requests, and correction reports

29.4 IEEE MAINTENANCE STANDARDS

The IEEE ha published standard Sid t 2 19· 1998 [ 12], which descri be. an iterallve process fo r managi ng and
executing software maintenance activities. It is gea red to large projects. but it is instruc ti ve to examine this
sta ndard as a speCific and de tail e d example o f a mainte nance proce s for projects o f a ll sizes. Its table of
contents showing the pertine nt secli o ns I Ii sle d In Figll": 29. 12 .

I Prob lem ide n tifka tion 4 Imp le me ntatio n


1.1 Input 1.2 Proce ss 4. I Input
1.3 Contro l 1.4 O utpul 4 .2 Proce ss
1.5 Quality faclo rs 4 .2. I Codill9 and It lill9
1.6 Metrics 4 .2 .3 Risk alialysis alld rroirw
2 Ana lysis 4 .2.4 Tts l-rtadillfSS rwiw>
2. I Input 4.3- 4 .6 o nlro l, O"tp"! , quality
2.2 Process fac to rs, rnerrics
2.2. I Fea sibility analysis 5 System tes t
2.2.2 Dtlailtd analysis 5. 1-5.6 Input, process, control, output,
2.3-2 .6 Con lro l, o utput, quali ty quahty fa tors, metncs
factors, metncs 6 Acceptance test
3 Desig n 6. 1-6.6 Inpll !, proce. <, control, Ollrpllt ,
3. 1-3 .6 In put, proces', contro l, quahlY fa tors, melnCS
output, quahty factors, me ln s 7 Delivery
7. 1- 7,6 In put , process, contro l, output,
qua hty fac tON, metnc,

Alure 29.12 IEEE 840-1994 "Soltware Maintenance" ta ble of contents


SoIXGf"1EE£ l td ~'994 Reptoouced WlUl "cumtSskln
7.2 CHAPTER 29 SOFTWARE MAINTENANCE

The sta ndard deA ne. seve n p hases t hat an MR flow< th roug h . each orrc pondlng to a scction '"
Figu re 29. 12. as fo llows,

I . Problem/mo d iRcatio n id ent iRcati o n . classiRcation. and prioritizatio n

2 Analysis

3. Dcsign
4 . Im plemen tation

5. Regressio n/system tcsti ng


6. Accep tance testi ng
7. Delivery

Note th at th cse ph ases are si mila r to the phases of th e develo pme nt p rocess. Eac h of th e phases has six
attribu tes th at desc ribe th e actio ns and data associ ated w ith th e m,

1. In put

2. Process
3 Control
4 . O utput

5. Q ual ity fac tors


6. Me trics

Figu re 29. 13 su mma rizes the relationsh ip betwecn t he p hases and attributes. The foll OWi ng sectio ns
describe how a mai ntena nce req ucst flows thro ugh each phase.

Phase ANributes
1. Problem identification
a. Input 1I1e cycle
2. Analysis art~acts lor this step
Process required for
3. Design this step
4 . Implementation c. How the process is
controlled
5. Syslem tes! d. Output I~e cycle
artifacts
6. Acceptance

7. Delivery
PrIX .s. quafl1y
lactors Involved
Metrtcs lor this

FIpue 29.13 Six attribUtes 01 each maintenance request phase


IEEE MAINTENANCE STANDARDS 7.3

Table 29.2 IEEE 1219·1998-Malntenance phase l '• problem Identification


a. Input • The Maintenance Request (MI\)
• "ssign change number
• Classify by type and severity. etc.
b. Process • Accept or reject change
• Make preliminary cost estimate
• Prioritize
• Identify MR uniquely
c. Control
• Enter MR into repository
d. Output • validated MR

• Clarity of the MR
e. Selected quality factors
• Correctness of the MR (e.g., type)
• Number of omissions in the MR
• Number of MR submissions to date
f. Selected metrics
• Number of duplicate MRs
• Time expected to confirm the problem
SOUrce: IEEE Sld 1219-1998. Reproduced WIth permIssion

This section describes and explains Steps 1-4 in Figure 29 . 13. Steps 5-7 arc si milar to the regular testing
and delivery process. Testing in particu lar emphasizes regressio n testing to ensure that exi stin g functionality
has not been compromised.

29.4.1 Maintenance Problem Identification

In this initial phase, MRs arc identified . claSSified , and assigned an ininal prio rity ranking . Table 29.2
summarizes the process (or the identification phase of maintenance requests
"Problem Identi fication" In the Encounter case study, for exampl e, wa perfom,ed by the marketing
department. They solicited and exam ll1ed user complain ts about the co mpl icated way In whi ch Encounter
game characters exchange quality va lues as a result o ( engagements

29.4.2 Maintenance Problem Analysis

Table 29.3 summarizes th e ana lysIS phase (or maintenance req ue ts.
Maintenance problem s range (rom the Simple to the deeply halle nglng. Fo r example, suppo e that we
want to provide the En ountcr ga me player with addin onal image op tl on< (or the main playn This appears to
be a straightforward request, however, the ex tent o( mainte nance request> like thi S is often underestimated
The ana lys; process is deSigned to uncove r the rca l work 111 ca rrying out modifica tio ns and additions For
example, we might dete rmine that the InCrN cd number o( Image opti o n, req Ulf(: a o mple tc reworkll'lI o(
the way In whic h th e Images arC di <p laycd and c ho en
As an example , let's analyze Malnte nanLC Request # 162 (or the ca e <Iud (see Fi gure 29 ) to
~ tlmate the resou r e' reqUired to dCl lgn and Impl ement It W e \" ill u<C the Ab,tract Fa tory design
patte rn (o r the deS ign o( th is MR , . , dc, nbed In ha[lter 17 Modifica ti o n to the oblc t modd to
accommodate these, and the new I.,sc> arc req,"rcd O n c th c>c modificati o ns arc matie, it al'pe . .... that
744 CHAPTER 29 SOFlWARE MAINTENANCE

Table 29 • 3 IEEE 1219 • 1998- Maintenance phase 2'• problem analysis


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

• Conduct technical review


• Verify ...
c. Control . .. test strategy appropriate
. .. documentation updated
• Identify safety and security issues
• Feasibility report
• Detailed analysis report. including impact
d. Output • Updated requirements
• Preliminary modification list
• Implementation plan
• Test strategy
e. Selected quaJlty factors • Comprehensibility of the analysis
• Number of requirem£:flts that must be changed
f . Selected metrlcs • 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
f ' S .lY. an or
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<ements

Flcure 29.14 Using linear regression to estimate the effort for Implementing an MR
7~6 CHAPTER 29 SOFTWARE MAINTENANCE

Table 29.4 lEE E 12191998


• - Malntenance phase 3• design
• Original project documentation
a. Input
• Analysis from the prevIous phase

• Create test cases


• ReVise . ..
b. Process
• • requirements
· . . Implementation plan

• Verify design
c. Control
• Inspect design and test cases
• Revised ...
· .. modification list
· .. detailed analysis
d. Output · . . implementation plan
• Updated ...
· .. design baseline
· .. test plans

• Flexibility (of the design)


• Traceability
e. Selected quality factors
• Reusability
• Comprehensibility

• Effort in person·hOurs
f. selected metrics • Elapsed time
• Number of applications of the change
SOUrce I£EE std 1219- 1998.. ReptodLICed WIth permtSSlOn.

29.4.3 Designing for a Maintenance Request

Table 29.4 describes the design phase for MRs.


A design handling MR # 162, for example, follows the Abstract Fac tory design pattern. which consists of
modifying the ori gi nal Encolll1tcrfHl.1ironmmt package. The original documentation for thiS package is shown in
Figure 29.15
Instead of creating Area and EncounterAreaConnection objects directl y, the modi Red appJ.cation will
do so through methods getAreaO and getAreaCon nection(). These are method of a new class, EnViron.
mentFactory. Client code of the EncounterEnvironment package need have no knowledge of the rype of Aroa
and AreaConnectlon objects being built, bocause all creatio n requests arc channeled through the particular
EnvironmentFactory object aggregated by EncounterEnvironme nt. In other words, there will be no need to
write separate conrrol code for the various levels. At runtime, the client code selects an object of the
appropriate EnvlronmentFactory subclass. For illustrallon pUrposes, the object model in Figure 29. 16 shows
Area and AreaConnection classes for three game· playing levels only (not for the larger number planned)
A plan is reqUired for migrating from the old design to the new . Figure 29. 17 shows such a plan. !t
Integrates the p.ns in • way that allows their testing, one at a time. \VIc .Iso try to keep existing parts
operational while introducing new pans in order to allow the switch only when We have conRdence '" the
new pans.
IEEE MAINTENANCE STANOMCUS 7.7

GameEnvironmenl

GameArea}=> --+I GameCharacler


GameAr88Connection

I
Area EncounterAreaConnection

EncounterEnvironment

I EncounterEnvironment I
Figure 29.15 EncounterEnvironment package (before modification)

1 .. n
'-1 Client I
EncounterEnvironment

EncounterAreaConnect/on

Level 1Area LeV912Area Level3Area

I I \
I I
Level 1AreaConnection Level2AreaConnection Level3AreaConnection

- create ..

Figure 29.16 Abstract Factory applied to Encounter video game

TIllS plan beg ins with the ex isting design. th en adds and tests parts that do not di rupt the existrng
implementation such as ty pes of areas and co nn ectio ns. Before th e last step. the redesig n i ready to execute
the Abstract Factory impl ementat ion. each of the pa ns hav rng bee n thoroughly tes ted In th e fi nal tep. the
new crea tio n process is fi nall y "rurned o n" and tested

29.4.4 Implementing a Maintenance Request

Table 29.5 shows steps and docu mentation for the Impl ementati o n of mai ntenan e req ue t<
....
t

Pha se 2: Introduce Subcla sses of Area and .. . Connection 2


."
rri
-<>1Encol.lnlerEnvironmenl I '"
~

~
VI
a
Start: Existing Model
I
~ EncountsfAreaConnecrion
t:,
I ~
[ EnoountarEnybonman1 I Level lArea Level2Area Level3Area
'";:m
:p
-z
f-----../ """ I ~
:p
., EncounterAreaConneJ:tJon z
leval1 AreaConneclion lovsl2AreaConnectlon Level3AreaConn9Ction
hl

Phase 3: Inlroduce The .Builder Class and Subclasses Final Phase: Aclivate buildAreall and bulldAreaConnecrlonll

EncounlerEnvironmcnl Env(ronmontF8ctOry EnvironmenrFac'ory


gelAre.() gelAroa()

Area Area ~
,--
,
EncounlerAreaConnecllon ~ Encount9rAreaCoonection I ~
T
A
Lev"" Area Lovel2Area level3Area LevellArea l evel2Aroa Level3Area

•,,, -.: , ~
,
,, ,
,, , " ,,
, ,, ,,
,
Ley~ 1AreaConnection l evelZAreaConnection l evel3AreaConnection l evelt AreaConnection Level2AreaConncction l"eveI3Area~ eellon
,,
,,
, , , ,, ,
,, ,,
- "' , , ~
,,
,,
,

LeVI" FIICIoty L.....I2FacfDlY Level3Faciory Levell Factory level2Faclory Leve13FaC1DlY


~O goIA1880 getAreaO gotAre.O geWe.() getAreaO

fl&Ure 29.17 MlgratJon plan lor level-based graphics


SOFTWARE EVOLlJTlON 7.'
Table 29.5 IEEE 1219· 1998- Maintenance phase 4; Integration
• Original source code
a. Input • Original project documentation
• Detailed design from previous phase
• Make code changes and additIOns
b. Process • Perform unit tests
• Review readiness for system testing

• Inspect code
• verify .. .
c. Control • • • CM control of new code
• • • Traceability of new code

d. Output • Updated .. .
· .. software
· .. unit test repcrts
· .. user documents

• Flexibility
• Traceability
e. Selected quality f actors • comprehensibility
• Maintainability
• Reliability

f. Selected metTles • Lines of code


• Error rate
SOUrce" IEEE stO 1219-1998 ReOfoduced WIth permlSSlon

The response to maintenance reque sts can invo lve a sig nificant amount of development , and th is
may actually introduce new d efec ts. The mor m/, is th e number of defects cr ea ted by thos m a", tenance dfort
per unit of eflort (e.g . person. m onth ). The measurement metho do logy for these new defects has to be
precisely defi ned-for example , "th e number of defec t< of medIum eve rity found within th ree mo nths of
deployme nt." Suppose , for exa mple, that th e handlIng of MR " 162 de ribed above co n<ume twenty person ·
days and pro duces ten defec ts, th en the error rat e for thi s MR would bt, 10/20 = 0.5 defec ts per person · day,
The remai ning m ai ntenance steps arc 'ystem te tin g, acceptance testi ng , and updati ng the project
documentati on . The procedures followed for the e are si milar to th ose for regular development.

29.5 SOFTWARE EVOLUTION

Systems th at have been maintained for a signlr.ca nt amount of timt' arc referred to a /'9"')' sy /nll Thi, teml i,
often used. more panlcularl y, for 'ystcm that most peo ple wou ld like to rep l.ce but would be expcn .. vc to
replace. As previou<ly no ted, <oftware system s that are subjected to repeated lll'fIltenance aCllvi lle< bt'coll1 c
larger and more comp lex, and ma intai ning th em can be a c hallenge. ome of th ese c hall c n g~, Jr~ •• fo li ow,

• Soflware compleX Ity due lO o nllnuous mai ntcuanc c- ' 1; ., Increased coupling

• Inef(l(.lencles due to oldcr tec hno logy


750 CHAPTER 29 SOFlWARE MAINTENANCE

• La k of a cur.lle do umenlatiOn
• rigin.1 developers who fully unoerstond the systems ore no longer avatloblc

A the complexity of legacy sy<lems increase , so docs the cost of maintaining the m Organlzallons are
faced with the c hallen ge of how to rcdu e com by making sy,tcms more malntamable . A good approach,
especially for YS lcms with little or no documentation or w ith ou tdated documentation , IS to start with rwtrS(
tl1gU1CCntl9 This IS a te hnlClllc in which a sys t{'m is I'nalyzed to identify ItS components and thelT IOt(r-
relationships From thl information its design and specifica tions arc recreated . That is, we start w ith a low
level of abstraction (sou rce codcl and c reate a higher level of abstraction (design and documentation ).
Another common technique is '('"9111((rI1l9 , where the sys tem IS restructured in order to Improve H5 design and
maintainability . The re-e nglnee nng process ofte n sta rt s with reverse eng ineering

29.5.1 ReverSe Engineering

Soft\Y'are products under maintenance have a wide va ncty of possible hi stories, many existing applications
are poorly or Inconsistently documented, and not very well understood. This leads to inefficiencies as
maintenance engineers attempt to Implement MRs on systems they do n't fu ll y understand . Reverse
engineering brings such a system to a consistent , documented, understood sta te. Two components of
reverse engineering arc "doCllm",'allo" and dcsi9" " COvcry [ 13 J. Redocumentation IS typicall y the first step in
reverse engmeering in which documentation describing the system is generated from cxi ling source code.
Several commercial tools arc available to assist in th is purpose, which ca n, fo r example , reformat the source
code to make It morc readable or extract comments to form documents.
O nce the necessary documentation IS available, the next step is desig n recovery. This I the process of
analyzing the available documentation and know ledge about a system in order to understan d its desig n. Once
successfull y completed, improvement to the design and the system can be impitmented . T ools are available
to generate UM L class diagrams fro m source code, for example. Th is usuall y produces a very complicated
diagram. The diagram can be used to build the key parts of the UML by hand or by erasures. Suppose, for
example, that we were to lose track of the UML for the Encounter video ga me. \Vie could Rrst ge nerate the
UML for all of the code. After that we could start with a key class such as EncounterEnvironment , identify all
classes that it relates to , select some am ong th ose to retain , and then repeat the process with those or stan
with other known classes.

29.5.2 Reengineering

The short·term goal of maintenance IS to fix a probl em or install a feature as soon as possible. The lo ng.term
goa l is to position the changlOg system so that it continues to work efficiently Jnd with reasonable cost per
MR into the future . Due to increasing complexit), and the escalation in cost per MR. we periodically take a
fTesh look at the entire architecture and design of the system. Making c hanges to the architecrure fTOm the
tOP down is the maIO task of ""'9 i ",m"9 . As defined by hlkofsky and Cross [ 13J reeng' . . h
.. " . . . . Ineenng IS t e
examination and alteration of a subject sys tem to reconstitute it in a new fann and t·h b
.. c SU sequen r
impkmcnt-ation of the new fann . Sometimes the rccnglnccrcd sys tem •
support new requ I're mems t h at t h e
older system was unable to implement. The overall goa l of reengineering is to c I cat".....• sys t ('m [ h at IS Ies
complcx, and ultlmatd y . easier to maintain and less cos tl y.
As an example of recnginecrlng, suppose that the video stOre appilcation IS reqUired to - k h 'd
• ~hlC t c non ·v, co
Items that customers purchase at the store (candy, paraphernalia etc ) In the absenCA of .
. . . ' . . ... rcenglneenng , we
might add vanables to the C. , 'omrrclass so that when c.,,'omrrob)cct< are storcd th.ese add' t Id
• I lana ata arc stored
at the same time. In all likelihood, this approach will eventually produce a hard· tO·Ill· t I"
.. In am app .cation.
MAINTENANCE METRICS 751

DVDs

DVDAccess
./ac.C»...
DVDRenlaJs

DVDRenlal
VSCustomers

DVDCustomerAccess H
"'facade~ D D •

Figure 29.18 Original video store architecture

DVDs
DVDRenials

DVDAccess
wfacadelO -t<> DVDRentalAccess
to .. facade,.

nonVideoltel1 ts

VSCustomers
NonVideoAccess
.. facade ,.

.facade.
YidaoStore

• to be completed•
Key: reenginccrcd parts: I I
XX

figure 29.19 Reengineered video slDre architecture

Now lei's consider a recngi neering approoc h Recall the exisling video <lore architeclllre , as hown in
Figurc 29. 18.
Tracking non · vldeo purchascs docs nOI properly At InlO ony of the modules shown , Jnd con cqucntly a
"Off Vid,o(Jcms package IS mtroduced Si nce Ihe busi ness of Ihc 'tore now onsists of morc Ihan renr.ls. a cparate

managemenl module i strong ly indicated . We will label Ihis module vldro loft. In addition . it now becomes
appropriate to Introduce a facade object for Ihe DVDRnllais pa koge Th, rCSul1 in rhe reeng1l1ccred
architecture shown in Figure 29. 19

29.6 MAINTENANCE METRICS

Since mamlenance con um es a large fTa tion o( I,(e y Ie 051 . illS pJrll ularl important 10 qUMHify il
and benefils NOI all orgaOlzallons have rhe sa me goal, in pur uinl: rnomlenan c rl-.",nI 2.lio", Arsl
determme the m.,ntenance go.ls (or Ihe appl,callon . then , de tor trcale metne< thaI measure their de~ree
752 CHAPTER 29 SOFTWARE MAINTENANCE

Table 29 • 6 Maintenance metric selection by goal


Selected Corresponding Metrics (The numbered metnes are
Goal Question from the IEEE)
Maximize HOw many problems are • Fault density ~
customer affecting the customer? INumber of faults found in the applicationVKSWC
satisfaction "Faults" are defects found during testing or operation.
KSLOC - thou sands of lines of noncom men ted source
statements
• Mean time to failure = The average time it takes to obtain a
failure . of the application measured from startup .
• BrealcJfix ratio = {Number of defects introduced by maintenance
actlonsII/Number of defects repairedl

How long does it take • Fault closure = Average lime required to correct a defect. from
to fix a problem? start of correction work.
• Fault open duration =Average rime from defect detection to
validated correction.

Where are the bottlenecks? • Staff utilization per task type =Average person-months to (a)
detect each defect and (b) repair each defect .
• Computer utilization =Average time/CPU time per defect.
Optimize effort Where are resources Effort and time spent, per defect and per severity category • • •

and schedule being used? • • planning


• • • reproducing customer finding


• • • reporting error
• • • repairing
• • • enhancing

Minimize defects Where are defects • Number of entries and exits per module
most likely to be found? • Cyclomatic complexity
• Ratio of commented lines/ KLoC
(KLoC = thousands of lines of source code, including comments)
-'-

of success in attai n ing th o e goa ls. Tabl e 29 .6, bosed o n a tabl e by Stark and Kern [ t4 ] , illustrates this b y
sh owing h o w three di ffe rent goals indicate the u e of different m etrics.
"The definition of "fail ure" for th e applicatio n under teSt depends on what th e customer pereeives as
fai lure, and ra nges from app lication cras h es to specific types of problems. For a fi nancia l application, for
example, any calculation resulti ng in a discrepancy of a dollar o r m o re cou ld be defined as a fai lure. In any
case, the definitions should be explicit.
Let's consider how metries ca n be used to manage a maintenance activity . Th e fractio n of co mmented lines i n
the ouree code h elps to pred.ct th e relative magnitude of a maintenance effort. For example, suppose that the
application bei ng m ain tained co nsi sts of three modules (Accounts Received, Timesheet, and Sick Day Recorder)
each with the size and com menting data shown by the respective black and white dots in Figure 29.20.
Compared with the AccounfS rcccivtd and T.mrshrtf m odules, the Si k Day R,rord" module is liable to
produce the biggest mai ntenance ch allenge because .t .s larger and has J larger proportion of uncommented
lines 01co de. The Accounts R,crivabl, m o dule is likely to be the least expe nsive to maintain because it .s the
smalles t and has a h igher than average proportion of co mments. Th e proportion of comment lines ca n be
obta i ned usi ng a uti l ity program or by counting from a random sample of pages of code.
MAINTENANCE METRICS 753

I I
0 t I I
I I
Percentage 01 0 I

I
I I
comment lines I I
(higher value = lower I I
I I
maintenance effort) 0 I
I
I

• • I
I
I
I
Size

I
(lower value = lower I
I
maintenance effort) I I 0
I I
I I I I
I I I I
I Accounts I I Sick day I
Module: I I Timesheet I I
I received I I recorder I

LOWEST HIGHEST
EFFORT EFFORT

Figure 29.20 Predicting relative maintenance efforts

T o manage a ma in tenance effort, grap hs like the one In I-ig urc 29 .2 1 arc useful. These s how new, ope n,
and closed MRs.
According to the c han in Figure 29 .21 , a large number of reque ts for repair and en hancement arnved in
the nrst twO yea rs, resu lting in a peak backlog during th e seco nd yea r. This backlog was eventua ll y worked off
The pronle in Figure 29.2 1 is a typica l o ne , w hether the comparable time scale are years , mo nths, or weeks.
T ypica ll y , th e maintenan ce ma na ger t-rics to account separately for fau lt and en han ement, so that the
mte cost of the application , as reqUired, can be tra cked .
To manage an orga nization's effective ness in handling the maintenance workload , a graph '" has th.· One
in Figure 29.22 can be used. The graph shows the average number 01' weeks that a maintenance request (whether

800

700 o # MR's received


- - - - - - - - - - - - - i . # MR's completed
600#
• # MR's cancelled
#
500#

400+f"

300#

200#

100

2000 2001 2002 2003

Alure 29,21 Measuring maintenance productivity


754 CHAPTER 29 SOFlWARE MAINTENANCE

t For example, In April, the o ·FOOng~ MAs


If weeks
open average enhancement MR
had been open (or 8 weeks.
• Enhancemenl MRs
10+

o
o "
o .. " o
5+ o
o o o

Figure 29.22 ASSessing maintenance operations

a repair or an enhonccmcnt ) has been waiting for resolution, measured from the time it was first r~portcd. It shows
a converge nce to on average dciay of about one week for repairs, and roughly four weeks for enhancements.

29.7 CASE STUDY

The folloWing is an excerpt fro m the OpenOfnce there is time ). Here is a general rule of thumb for
documentation that illustrates 0 means of handling priorities,
defects and e nhancements.
P I-Ope nOfnce cannot be used fo r testing or
development.
ISSUE HANDLING AS A QA TECHNIQUE IN P2-0penOffice crashes o r basic feotures do
OPENOFFICE not work.

The 1,,",Zilla (IZ ) tool is an accesSible li st of Open . P3-Bugs that usuall y involve a feature not
Of nee "issues." These indude defects and en · working as expected .
hancements. OpenOfRce publishes guidelines and
P4-Bugs that do not offect basic features and
protocols for dealing with issues. The following is
usuolly have workarounds.
quoted f"rOm o penofnce.o rg. Priorities ran ge from PI
(very urge nt) to P5 (will be considered when PS-Very min o r annoyin g bugs.

ISSUEZILLA STATISTICS

Note to the Student,


Bugzilla allows graphical forms 01 data, which supplement tables such as that shown below. The core of
bug tracking is a hislory of new>, 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<",d) within each major part (e.g., ,preadsbttt) of OpenOf6ce.
Tab le 29.7 Examples of statistics available using Issuelilla

Project State changes 08/ 02/04 07126/ 04 07/19/04 07/12/04 07/05/04 06/ 28/04 06/21/04 06/14/04 06/07/04 06/01104

Api reopened 0 1 1 1 1 1 1 1 1 1 1
Api started 2 101 99 98 94 97 93 95 100 99 97
Api unconfirmed 1 15 14 13 14 23 21 15 11 13 13
Api new -4 74 78 82 85 70 71 64 59 61 67
ap' Result 191 192 194 194 191 186 175 171 174 178
Chart reopened 0 0 0 0 0 0 0 0 0 0 0
Chart started 0 47 47 46 46 42 40 40 38 40 43
Chart unconfirmed 1 4 3 1 1 1 3 2 2 2 0
Chart new 0 3 3 3 3 3 3 1 3 2 3
46 46 43 43 44 46
chart Result 54
- -53 50
- 50
- - - - -
2
-
2
-2
database access reopened - 1 4 5 6 5 5 5 5
database access started - 1 30 31 29 29 28 30 30 31 31 31

database access unconfirmed 6 35 29 27 25 23 22 20 17 23 22

database access new - 1 72 73 75 74 86 96 96 58 61 59

daUJbase access Result 141 138 137 133 142 153 151 108 117 114

~
§
.......
...
756 CHAPTER 29 SOFTWARE MAINTENANCE

T.,hlc 29 I ,how, defect , taLU at a summa ry leve l It " a u,oful furm for pro JcU leade"h.p when
J "c" .n~ the matum of rc cnt MRs. ther form, of th e data <how defcch and fea tures (".ssues") grouped
,K ordi n); to module, TIllS enables a develo per to work n <evc ral related f<SUC S at more r Ie,s the same t.me ,
Jnd It enahle, a leader to a seS5 th e health of a module and the work of team,

29.8 SUMMARY

Software sys l e m s CO llt'l11UC' to l'volvt' after th c lr Inllial deve lopment and rel ease o(tware mainte nance
co nsist o f those aCllv .t ies that are performcd o n the sy, tem after .t< release, such as rcpa or of defects,
Implemen tation of enha ncements, and adaptation to changes In the enviro nmen t
The hallen ges of software mJ,,\lenance full into three mam arc", management , procc«, and techOlca\.
"1anagcmcnl must undC'rsrand th e comple xit y and va llie o f maintenance and prOV ide adequate support .
Impl emcntong Jn efficient maintenance process helps rcdu e the complexity T ec hn. ca l challenges In lude
th e desig n of regres ion te sts to ensure that Implemented malntcnan C requests do not havt" unintended '§I de
dfcc!> o n olher parts of the system .
A tYP ical ma.intenance process starts with eu tamers provi din g co mm ent on enhancementS
and defect s through the help desk . The care wrinen up as Maintenance Requ e ts (MRs ) MRs are
reg ularly rcvie,y"d and prioritized , often by a change control board (CCS ). The CC B . composed of
stakeholde r g ro ups suc h as development , use r documentati o n, marketing , quality assurance , and
customer support .
An impact anal ysi i performed on incoming MRs that assesses the sco pe of the change to product
artifacts that arc required in order to impiement the MR. Each group represented by the CCB prov.des
inpUt.
Root·cause analysis is a process conducted after complet ing the repair of a defect MR. It purpo e is to
determine the underlying reason that a defect has occurred . This information is then u ed to .mplement
process improvements so that si milar defects are prevented from occurring on the future .
IEEE Std 1219-1998 describes an iterative process for managing and execut.ng software maintenance
activities. The standard defines seven phases that an MR flows through , similar to the pha ses that Occur during
new product development, MR identification and prioritization , analysis, design , .mplementation , testing,
and delivery. Each phase has six attributes associated with it that describe the activitie and data for that
phase, input , process, control , output, quality factors , and metrics.
As software systems evolve , they become more complex and less understood. Freque ntl y, much of the
original documentation is lost or outdated, and man y if not all of the o ngonal devel opers are no longer
available . Reverse engineering is a process that reconstructs system documentation, such as cnhan ed, mort"
readable code, or class diagrams, from existing source code . An understand ing of software arc hitecture and
de ign is then constructed from the new documentation .
Periodically, organizations take a fresh look at the whole design of a ystcm , with the goal of reducing
its complexity, increaSing its efficiency, and making it more cost effective to maintain . Changong to the
software architecture and design to meet these goals is referred to as reengineering. This IS especially needed
for older systems whose design has deteriorated over time.
It is common for organizations to define specinc malOtenance goal and then de t or create metri
that measure the organization's degree ofswccess in attaining those goals. For example. of a goal is to ",tn i mi~
defects. metrics would be collected to measure the complexity of the code. with a goal of retactonng tho
areas that have the highest complexity.
EXERCISES 151

29.9 EXERCISES

1. DeRne the term · sohwar-e maintenance" in one entcncc.

2 D~cri~ in your own words four types of software maintenance. Is there an example of a
maintenance request that might overlap two of the categories1
3. Give examples of corrective, adaptive, perfective, and preventive c hanges for the Encounter case
study.

4 . Suppose that a proposal is made to change the le ngth of an array in an application to accommodate
requirements that were not previously satisfied. What activity is reqUIred before actual changes in
the code can be made)

5. Describe a practical scenario in which the rather lengthy maintenance now illustrated in Figure
29 6 might need to be circumvented)

6 . A propo al has been made to implement the following requirement for the Encounter ca e study,
which was initially designated optional.
PlayerCharacter Requirement [desirable] ("Player character image") The player shall have the
option to choose the image representing her main c haracter from at least 4 elF files

a. What type of maintenance request (MR) is this)


b. Provide an impact analysis for this MR.

7. Which of the following would require reengineering. Explain .

a. Convert a simu lation of the operations of a bank into an automated bank security ys tem .
b. Add to a simulation of the operations of a bank so that it handles the moveme nts of security
personnel.
c . Modify an online tutoring ystem 0 that it ca n to provide multiple-choice quizzes at any time to
permit tudents to asses their understanding of what they are currentl y reading.

8. There are many co mmercial rever e engineering too ls that automatically genera te docu ·
mentati o n from source code. Using Inte rnet resea rch , Identify two suc h tools and descnbe
the types of documentation the y generate , Explain h ow the documentati o n c1arines the source
code

Maintenance
(a) Obtaon projec t specdica tl o n, from twO o the r teams Ir. the la" Propo e at least une 01 c. h of the
fo llOWing type, o f mo dification" orrec tl ve, adaptive, pcrfee.ivc , and preventive
(ill Anothe r learn Will have proposed four ~uLh modir, tlo n< to your pro)c l. Develo p an Imp3 t
asses~ment on your prOJect of each 0 1 the< mOOlnCatlOI1<
758 CHAPTER 29 SOFlWARE MAINTENANCE

( ) NegotlJte with the tca m proposin~ modifica tions to your project to make them reasonable In terms
of the resources required , then Implement these modiAca tions.
(d ) Implement, tcst, and measure your modifications

Evaluation cri tena:


( I ) Degree to which the propo cd modifications arc of the types specified
(2 ) Completeness of yo ur impact assessments
(3) Degree to which the modifications have been tested

BIBLIOGRAPHY

I ·,EEE St3ndard C losSilry or Soft""'Jr(' EngmC'cring Tc:munology,· IEfE Sid 6fO 12 · 19 90, Dccc:mbcr 1990
2 Foster, ) . Cost FJClo,,", In Softwa re M.,imcnancc, Ph D thesIs, Umversity of Durham. NC. Computer Science Dept, 1994 . as noted
on [9)
3. Pigosk •• Th oma .. M . Practical Sojfll."Jrt Ma'"'1'lt4lfCC en, ProClted for A14Jlfagmg
Your SofrlD~rr !.mrs,.".ett', John Wiley &; Sons, 1996
.. LLhman, M , "Program .. , Life Cycles, and the: Laws of Software Evolulion," ProcrrJ'"9s IEEE, No 19, 1980, pp. 1060-1076
5 Lehman , M . "Progr3m Evolution Inlo m1311 on Procc~'SinJ.: Management: ProcttJilf9s fEEf. No. 20, 1984 , pp 19-36
6 Lentz, !knnt'n J> . and E. Bunon Swanso n, "Sofh"nrr Mn i"fnlaflCt MDrur9011ntl," Addison·Wc:slc:y, 1980.
7. Llcntz, Bennctt P., E. Bunon Sw;)nson, and G<:ny E Tompkins, ·Char"ctcri'stics or Apphcallon5 Softwa re: Maintenance,·
0!ft"'111'11 {"aho"~ oj the ACAI (CA CM), No 21 , 1978, pp. 466-471.
8. Bennet!, K.,"Soh",arc Malntcnance, A T ulOnal: Softw3 rc Engin("cn ng. IEEE Com/lIlla Soclrty, November 1999, as notcd In [Dorfman
.lnd Tha yer. 19'-)9 J
9 Rakltl n, Stcvcn R.. "SofhDtJrt Vcnjicallon a"d Validation fot PraChlrontr1 lind MII"agrn:," Artcch H ou~c Publishers. 200 I "
10. McConnell. StC'Ve. "'Rapul Dnxfo"",ml To".ing Wild SojhDlH( 5<IKJuIN," Microroh Pr~s . 1996.
11 Arthur, lowcll J. , Improving Sohwarc QU.1liry An Insidds GUide to TQM. John Wilcy & Sons. 1993.
12. "IEEE Standard for olrwarc j\'1amtcnance,- IEEE SlJ 12 / p·199Jf, 1998.
13 Ch,korsky. 8hotLJ , and James H Cross II . "Rt'Vcrse Engmeenn~ and Dcslgn Recovery: A Taxonomy," IEEE Sof'lI'Ort, Vol. 7, no. I,
1990, pp 13-17
I.. Stark , Cc-orgc E , 3nd LOUIlOC C. Kcm, aA Sohwarc Metric Sel for Progr"m Maintenance Managcmcnt,- )(}uTMI of SYJf""S lIMd Sof'~IIIT.
No 24. 1994 , pp 239- 249.
1S. Opc:nOfAcc. hup:I/qa.opc-nofncc:.orgt. z_slatl.ak,hlml lacccsscd November 18, 2009).

You might also like