Docsity
Docsity

Prepara tus exámenes
Prepara tus exámenes

Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity


Consigue puntos base para descargar
Consigue puntos base para descargar

Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium


Orientación Universidad
Orientación Universidad

Applying UML and Patterns - Craig Larman (2ª edició) (Anglès), Apuntes de Informática

Asignatura: Enginyeria del software, Profesor: Jordi Ribas, Carrera: Informàtica i serveis, Universidad: UAB

Tipo: Apuntes

2012/2013

Subido el 09/01/2013

avan-102
avan-102 🇪🇸

4.5

(4)

13 documentos

Vista previa parcial del texto

¡Descarga Applying UML and Patterns - Craig Larman (2ª edició) (Anglès) y más Apuntes en PDF de Informática solo en Docsity! APPLYING UML ANO PATTERNS An Introduction to Object-Oriented Analysis and Design and te Unified Process Free Book for Everyone "People alten sk rme wbichr is the best bosk ho introda e them to 1be world al DO design. Lver since l came acrom1 68. Appiyiag UA cd Parteraa has beca my unsetererd choco” —Martin Fowler, autos, VW Dinilod and Refartarina CRAIG LARMAN Foreword by Phúliipe Knrcirmor Sample Unified Process Artifacts and Timing (s-start; r-refine) Sample Unified Process Artifact Relationships Discipline Artifact Iteration^ Incep. 11 Elab. EL.En Const. CL.Cn Trans. T1..T2 Business Modeling Domain Model s Requirements Use-Case Model s r Vision a r Supplementary Specification s r Glossary s r Design Design Model SW Architecture Document Data Model s s s r r Implementation Implementation Model s r r Project Managemen t SW Development Plan s r r r Testing Test Model s r Environment Development Case s r : System enterItem (id, quantity) ... Process Sale 1. Customer arrives ... 2. Cashier makes new sale. 3. ... Use Cases System Sequence Diagrams make NewSale() Sale timeStamp Register ...11 ProductCatalog . . . domain concepts system events Domain Model Use-Case Model Design Model : Register enterItem(id, quantity) : ProductCatalog spec := getSpecification( id ) addLineItem( spec, quantity ) : Sale . . . use-case realization with interaction diagrams conceptual classes in the domain inspire the names of some software classes in the design makeNewSale() create() Register ... makeNewSale() enterItem(...) ... ProductCatalog ... getSpecification(...) : ProductSpecification ... the design classes discovered while designing UCRs can be summarized in class diagrams Cashier Process Sale Use Case Diagrams : Cashier 1 1 . . . . . . Captured-on TABLE OF CONTENTS Use Cases Within the UP 75 Case Study: Use Cases in the NextGen Inception Phase 79 Further Readings 79 UP Artifacts and Process Context 81 7 Identifying Other Requirements 83 NextGen POS Examples 84 NextGen Example: (Partial) Supplementary Specification 84 Commentary: Supplementary Specification 88 NextGen Example: (Partial) Vision 91 Commentary: Vision 93 NextGen Example: A (Partial) Glossary 98 Commentary: Glossary (Data Dictionary) 99 Reliable Specifications: An Oxymoron? 100 Online Artifacts at the Project Website 101 Not Much UML During Inception? 101 Other Requirement Artifacts Within the UP 101 Further Readings 104 UP Artifacts and Process Context 105 8 From Inception to Elaboration 107 Checkpoint: What Happened in Inception? 108 On to Elaboration 109 Planning the Next Iteration 110 Iteration 1 Requirements and Emphasis: Fundamental OOA/D Skills 112 What Artifacts May Start in Elaboration? 118 You Know You Didn't Understand Elaboration When... 114 PART III ELABORATION ITERATION 1 9 Use-Case Model: Drawing System Sequence Diagrams 117 System Behavior 118 System Sequence Diagrams 118 Example of an SSD 119 Inter-System SSDs 120 SSDs and Use Cases 120 System Events and the System Boundary 120 Naming System Events and Operations 121 Showing Use Case Text 122 SSDs and the Glossary 122 SSDs Within the UP 123 Further Readings 124 UP Artifacts 125 10 Domain Model: Visualizing Concepts 127 Domain Models 128 Conceptual Class Identification 132 Candidate Conceptual Classes for the Sales Domain 136 Domain Modeling Guidelines 137 Resolving Similar Conceptual Classes—Register vs. "POST" 139 Modeling the Unreal World 140 Specification or Description Conceptual Classes 140 UML Notation, Models, and Methods: Multiple Perspectives 144 Lowering the Representational Gap 146 Example: The NextGen POS Domain Model 148 Domain Models Within the UP 148 Further Readings 150 viii TABLE OF CONTENTS UP Artifacts 151 11 Domain Model: Adding Associations 153 Associations 153 The UML Association Notation 154 Finding Associations—Common Associations List 155 Association Guidelines 157 Roles 157 How Detailed Should Associations Be? 159 Naming Associations 160 Multiple Associations Between Two Types 161 Associations and Implementation 161 NextGen POS Domain Model Associations 162 NextGen POS Domain Model 163 12 Domain Model: Adding Attributes 167 Attributes 167 UML Attribute Notation 168 Valid Attribute Types 168 Non-primitive Data Type Classes 170 Design Creep: No Attributes as Foreign Keys 172 Modeling Attribute Quantities and Units 173 Attributes in the NextGen Domain Model 174 Multiplicity From SalesLineltem to Item 175 Domain Model Conclusion 175 13 Use-Case Model: Adding Detail with Operation Contracts 177 Contracts 177 Example Contract: enterltem 178 Contract Sections 179 Postconditions 179 Discussion—enterltem Postconditions 182 Writing Contracts Leads to Domain Model Updates 183 When Are Contracts Useful? Contracts vs. Use Cases? 183 Guidelines: Contracts 184 NextGen POS Example: Contracts 185 Changes to the Domain Model 186 Contracts, Operations, and the UML 186 Operation Contracts Within the UP 188 Further Readings 191 14 From Requirements to Design in this Iteration 193 Iteratively Do the Right Thing, Do the Thing Right 193 Didn't That Take Weeks To Do? No, Not Exactly. 194 On to Object Design 194 15 Interaction Diagram Notation 197 Sequence and Collaboration Diagrams 198 Example Collaboration Diagram: makePayment 199 Example Sequence Diagram: makePayment 200 Interaction Diagrams Are Valuable 200 Common Interaction Diagram Notation 201 Basic Collaboration Diagram Notation 202 Basic Sequence Diagram Notation 208 16 GRASP: Designing Objects with Responsibilities 215 Responsibilities and Methods 216 Responsibilities and Interaction Diagrams 217 Patterns 218 iX TABLE OF CON T EN Ts GRASP: Patterns of General Principles in Assigning Responsibilities 219 The UML Class Diagram Notation 220 Information Expert (or Expert) 221 Creator 226 Low Coupling '229 High Cohesion 232 Controller 237 Object Design and CRC Cards 245 Further Readings 246 17 Design Model: Use-Case Realizations with GRASP Patterns 247 Use-Case Realizations 248 Artifact Comments 249 Use-Case Realizations for the NextGen Iteration 2.52 Object Design: makeNewSale 253 Object Design: enter-Item 255 Object Design: endSale 260 Object Design: makePayment 264 Object Design: startUp 269 Connecting the UI Layer to the Domain Layer 273 Use-Case Realizations Within the UP 276 Summary 278 18 Design Model: Determining Visibility 279 Visibility Between Objects 279 Visibility 280 Illustrating Visibility in the UML 284 19 Design Model: Creating Design Class Diagrams 285 When to Create DCDs 285 Example DCD 286 DCD and UP Terminology 286 Domain Model vs. Design Model Classes 287 Creating a NextGen POS BCD 287 Notation for Member Details 296 DCDs, Drawing, and CASE Tools 298 DCDs Within the UP 298 UP Artifacts 299 20 Implementation Model: Mapping Designs to Code 301 Programming and the Development Process 302 Mapping Designs to Code 304 Creating Class Definitions from DCDs 304 Creating Methods from Interaction Diagrams 307 Container/Collection Classes in Code 309 Exceptions and Error Handling 309 Defining the Sale--makeLineItem Method 310 Order of Implementation 311 Test-First Programming 311 Summary of Mapping Designs to Code 313 Introduction to the Program Solution 313 PART IV ELABORATION ITERATION 2 21 Iteration 2 and its Requirements 319 Iteration 2 Emphasis: Object Design and Patterns 319 From Iteration 1 to 2 319 Iteration 2 Requirements 321 X TABLE OF CONTENTS 29 Modeling Behavior in Statechart Diagrams 437 Events, States, and Transitions 437 Statechart Diagrams 438 Statechart Diagrams in the UP? 439 Use Case Statechart Diagrams 439 Use Case Statechart Diagrams for the POS Application 441 Classes that Benefit from Statechart Diagrams 441 Illustrating External and Interval Events 443 Additional Statechart Diagram Notation 444 Further Readings 446 30 Designing the Logical Architecture with Patterns 447 Software Architecture 448 Architectural Pattern: Layers 450 The Model-View Separation Principle 471 Further Readings 474 31 Organizing the Design and Implementation Model Packages 475 Package Organization Guidelines 476 More UML Package Notation 482 Further Readings 483 32 Introduction to Architectural Analysis and the SAD 485 Architectural Analysis 486 Types and Views of Architecture 488 The Science: Identification and Analysis of Architectural Factors 488 Example: Partial NextGen POS Architectural Factor Table 491 The Art: Resolution of Architectural Factors 493 Summary of Themes in Architectural Analysis 499 Architectural Analysis within the UP 500 Further Readings 505 33 Designing More Use-Case Realizations with Objects and Patterns 507 Failover to Local Services; Performance with Local Caching 507 Handling Failure 512 Failover to Local Services with a Proxy (GoF) 519 Designing for Non-Functional or Quality Requirements 523 Accessing External Physical Devices with Adapters; Buy vs. Build 523 Abstract Factory (GoF) for Families of Related Objects 525 Handling Payments with Polymorphism and Do It Myself 528 Conclusion 535 34 Designing a Persistence Framework with Patterns 537 The Problem: Persistent Objects 538 The Solution: A Persistence Service from a Persistence Framework 538 Frameworks 539 Requirements for the Persistence Service and Framework 540 Key Ideas 540 Pattern: Representing Objects as Tables 541 UML Data Modeling Profile 541 Pattern: Object Identifier 542 Accessing a Persistence Service with a Facade 543 Mapping Objects: Database Mapper or Database Broker Pattern 543 Framework Design with the Template Method Pattern 546 Materialization with the Template Method Pattern 546 Configuring Mappers with a MapperFactory 552 Pattern: Cache Management 552 Consolidating and Hiding SQL Statements in One Class 553 xii TABLE OF CONTENTS Transactional States and the State Pattern 554 Designing a Transaction with the Command Pattern 556 Lazy Materialization with a Virtual Proxy 559 How to Represent Relationships in Tables 562 PersistentObject Superclass and Separation of Concerns 563 Unresolved Issues 564 PART VI SPECIAL TOPICS 35 On Drawing and Tools 567 On Speculative Design and Visual Thinking 567 Suggestions for UML Drawing Within the Development Process 568 Tools and Sample Features 571 Example Two 573 36 Introduction to Iterative Planning and Project Issues 575 Ranking Requirements 576 Ranking Project Risks 579 Adaptive vs. Predictive Planning 579 Phase and Iteration Plans 581 Iteration Plan: What to Do in the Next Iteration? 582 Requirements Tracking Across Iterations 583 The (Invalidity of Early Estimates 585 Organizing Project Artifacts 585 Some Team Iteration Scheduling Issues 586 You Know You Didn't Understand Planning in the UP When... 588 Further Readings 588 37 Comments on Iterative Development and the UP 589 Additional UP Best Practices and Concepts 589 The Construction and Transition Phases 591 Other Interesting Practices 592 Motivations for Timeboxing an Iteration 593 The Sequential "Waterfall" Lifecycle 593 Usability Engineering and User Interface Design 599 The UP Analysis Model 599 The RUP Product 600 The Challenge and Myths of Reuse 601 38 More UML Notation 603 General Notation 603 Implementation Diagrams 604 Template (Parameterized, Generic) Class 606 Activity Diagrams 607 Bibliography 609 Glossary 615 Index 621 xiii FOREWORD Programming is fun, but developing quality software is hard. In between the nice ideas, the requirements or the "vision," and a working software product, there is much more than programming. Analysis and design, defining how to solve the problem, what to program, capturing this design in ways that are easy to communicate, to review, to implement, and to evolve is what lies at the core of this book. This is what you will learn. The Unified Modeling Language (UML) has become the universally-accepted language for software design blueprints. UML is the visual language used to convey design ideas throughout this book, which emphasizes how developers really apply frequently used UML elements, rather than obscure features of the language. The importance of patterns in crafting complex systems has long been recog- nized in other disciplines. Software design patterns are what allow us to describe design fragments, and reuse design ideas, helping developers leverage the expertise of others. Patterns give a name and form to abstract heuristics, rules and best practices of object-oriented techniques. No reasonable engineer wants to start from a blank slate, and this book offers a palette of readily usable design patterns. But software design looks a bit dry and mysterious when not presented in the context of a software engineering process. And on this topic, I am delighted that for his second edition, Craig Larman has chosen to embrace and introduce the Unified Process, showing how it can be applied in a relatively simple and low-ceremony way. By presenting the case study in an iterative, risk-driven, architecture-centric process, Craig's advice has realistic context; he exposes the dynamics of what really happens in software development, and shows the external forces at play. The design activities are connected to other tasks, and they no longer appear as a purely cerebral activity of systematic transformations or creative intuition. And Craig and I are convinced of the benefits of iterative development, which you will see abundantly illustrated throughout. So for me, this book has the right mix of ingredients. You will learn a systematic method to do Object-Oriented Analysis and Design (OOA/D) from a great teacher, a brilliant methodologist, and an "OO guru" who has taught it to thou- sands around the world. Craig describes the method in the context of the Uni- xv Design a framework. PREFACE Finally, it shows you how to design an object-oriented framework and applies this to the creation of a framework for persistent storage in a database. Objectives The overarching objective is this: XVIII Help students and developers create object designs through the application of a set of explainable principles and heuristics. By studying and applying the information and techniques presented here, you will become more adept at understanding a problem in terms of its processes and concepts, and designing a solid solution using objects. Intended Audience This book is an introduction to OOA/D, related requirements analysis, and to iterative development with the Unified Process as a sample process; it is not meant as an advanced text. It is for the following audience: • Developers and students with experience in an object-oriented programming language, but who are new—or relatively new—to object-oriented analysis and design. • Students in computer science or software engineering courses studying object technology. • Those with some familiarity in OOA/D who want to learn the UML notation, apply patterns, or who want to sharpen and deepen their analysis and design skills. Prerequisites Some prerequisite knowledge is assumed—and necessary—to benefit from this book: • Knowledge and experience in an object-oriented programming language such as Java, C#, C++, or Smalltalk. • Knowledge of fundamental object technology concepts, such as class, instance, interface, polymorphism, encapsulation, interfaces, and inherit ance. Fundamental object technology concepts are not defined. Java Examples In general, the book presents code examples in Java or discusses Java imple- mentations, due to its widespread familiarity. However, the ideas presented are applicable to most—if not all—object-oriented programming languages. PREFACE Book Organization The overall strategy in the organization of this book is that analysis and design topics are introduced in an order similar to that of a software development project running across an "inception" phase (a Unified Process term) followed by three iterations (see Figure P.I). 1. The inception phase chapters introduce the basics of requirements analysis. 2. Iteration 1 introduces fundamental OOA/D and how to assign responsibili ties to objects. 3. Iteration 2 focuses on object design, especially on introducing some high-use "design patterns." 4. Iteration 3 introduces a variety of subjects, such as architectural analysis and framework design. Figure P.I. The organization of the book follows that of a development project. Web-Related Resources • Please see www.craiglarman.com for articles related to object technology, patterns, and process. • Some instructor resources can be found at www.phptr.com/larman. Enhancements to the First Edition While retaining the same core as the first edition, the second is refined in many ways, including: • Use cases are updated to follow the very popular approach of [CockburnOl]. • The well-known Unified Process (UP) is used as the example iterative pro cess within which to introduce OOA/D. Thus, all artifacts are named accord ing to UP terms, such as Domain Model. • New requirements in the case study, leading to a third iteration. XIX Overview Inception Iteration1 Iteration 2 Iteration 3 Object-Oriented Analysis Object-Oriented Design Translating Designs to Code The Book Topics such as OO analysis and OO design are incrementally introduced in iteration 1, 2, and 3. Special Topics xx PREFACE Updated treatment of design patterns. Introduction to architectural analysis. Introduction of Protected Variations as a GRASP pattern. A 50/50 balance between sequence and collaboration diagrams. The latest UML notation updates. Discussion of some practical aspects of drawing using whiteboards or UML CASE tools. Acknowledgments First, a very special thanks to my friends and colleagues at Valtech, world-class object developers and iterative development experts, who in some way contrib- uted to, supported, or reviewed the book, including Chris Tarr, Michel Ezran, Tim Snyder, Curtis Hite, Celso Gonzalez, Pascal Roques, Ken DeLong, Brett Schuchert, Ashley Johnson, Chris Jones, Thomas Liou, Darryl Gebert, Frank Rodorigo, Jean-Yves Hardy, and many more than I can name. To Philippe Kruchten for writing the foreword, reviewing, and helping in so many ways. To Martin Fowler and Alistair Cockburn for many insightful discussions on pro- cess and design, quotes, and reviews. To John Vlissides and Cris Kobryn for the kind quotes. To Chelsea Systems and John Gray for help with some requirements inspired by their Java technology ChelseaStore POS system. To Pete Goad and Dave Astels at TogetherSoft for their support. Many thanks to the other reviewers, including Steve Adolph, Bruce Anderson, Len Bass, Gary K. Evans, Al Goerner, Luke Hohmann, Eric Lefebvre, David Nunn, and Robert J. White. Thanks to Paul Becker at Prentice-Hall for believing the first edition would be a worthwhile project, and to Paul Petralia and Patti Guerrieri for shepherding the second. Finally, a special thanks to Graham Glass for opening a door. About the Author Craig Larman serves as Director of Process for Valtech, an international con- sulting company with divisions in Europe, Asia, and North America, specializ- ing in e-business systems development, object technologies, and iterative development with the Unified Process. Since the mid 1980s, Craig has helped thousands of developers to apply object-oriented programming, analysis, and design, and assisted organizations adopt iterative development practices. Chapter 1 OBJECT-ORIENTED ANALYSIS AND DESIGN The shift of focus (to patterns) will have a profound and enduring effect on the way we write programs. —Ward Cunningham and Ralph Johnson Objectives • Compare and contrast analysis and design. • Define object-oriented analysis and design (OOA/D). • Illustrate a brief example. 1.1 Applying UML and Patterns in OOA/D This is an introduction What does it mean to have a good object design? This book is a tool to help devel- opers and students learn core skills in object-oriented analysis and design (OOA/D). These skills are essential for the creation of well-designed, robust, and maintainable software using object technologies and languages such as Java, C++, Smalltalk, and C#. The proverb "owning a hammer doesn't make one an architect" is especially true with respect to object technology. Knowing an object-oriented language (such as Java) is a necessary but insufficient first step to create object systems. Knowing how to "think in objects" is also critical. This is an introduction to OOA/D while applying the Unified Modeling Lan- guage (UML), patterns, and the Unified Process. It is not meant as an advanced text; it emphasizes mastery of the fundamentals, such as how to assign respon- sibilities to objects, frequently used UML notation, and common design pat- 1 - OBJECT-ORIENTED ANALYSIS AND DESIGN Applying UML Applying patterns and assigning responsibilities One case study Use cases and requirements analysis An example iterative process— the Unified Process terns. At the same time, primarily in later chapters, the material progresses to a few intermediate-level topics, such as framework design. The book is not just about the UML. The UML is a standard diagramming nota- tion. As useful as it is to learn notation, there are more critical object-oriented things to learn; specifically, how to think in objects—how to design object-ori- ented systems. The UML is not OOA/D or a method, it is simply notation. It is not so helpful to learn syntactically correct UML diagramming and perhaps a UML CASE tool, but then not be able to create an excellent design, or evaluate and improve an existing one. This is the harder and more valuable skill. Conse- quently, this book is an introduction to object design. Yet, one needs a language for OOA/D and "software blueprints," both as a tool of thought and as a form of communication with others. Therefore, this book explores how to apply the UML in the service of doing OOA/D, and covers fre- quently used UML notation. But the emphasis is on helping people learn the art and science of building object systems, rather than notation. How should responsibilities be allocated to classes of objects? How should objects interact? What classes should do what? These are critical questions in the design of a system. Certain tried-and-true solutions to design problems can be (and have been) expressed as best-practice principles, heuristics, or pat- terns—named problem-solution formulas that codify exemplary design princi- ples. This book, by teaching how to apply patterns, supports quicker learning and skillful use of these fundamental object design idioms. This introduction to OOA/D is illustrated in a single case study that is fol- lowed throughout the book, going deep enough into the analysis and design so that some of the gory details of what must be considered and solved in a realistic problem are considered, and solved. OOA/D (and all software design) is strongly related to the prerequisite activity of requirements analysis, which includes writing use cases. Therefore, the case study begins with an introduction to these topics, even though they are not specifically object-oriented. Given many possible activities from requirements through to implementation, how should a developer or team proceed? Requirements analysis and OOA/D needs to be presented in the context of some development process. In this case, the well-known Unified Process is used as the sample iterative develop- ment process within which these topics are introduced. However, the analysis and design topics that are covered are common to many approaches, and learn- ing them in the context of the Unified Process does not invalidate their applica- bility to other methods. APPLYING UML AND PATTERNS IN OOA/D In conclusion, this book helps a student or developer: • Apply principles and patterns to create better object designs. • Follow a set of common activities in analysis and design, based on the Unified Process as an example. • Create frequently used diagrams in the UML notation. It illustrates this in the context of a single case study. Topics and Skills UML notation Requirements analysis Principles and guidelines Patterns Iterative development with the Unified Process OOA/D Figure 1.1 Topics and skills covered Many Other Skills Are Important Building software involves myriad skills and steps beyond requirements analy- sis, OOA/D, and object-oriented programming. For example, usability engineer- ing and user interface design are critical to success; so is database design. However, this introduction emphasizes OOA/D, and does not attempt to cover all topics in software development. It is one piece of a larger picture. 5 8 1 - OBJECT-ORIENTED ANALYSIS AND DESIGN Define Use Cases Requirements analysis may include a description of related domain processes; these can be written as use cases. Use cases are not an object-oriented artifact—they are simply written stories. However, they are a popular tool in requirements analysis and are an important part of the Unified Process. For example, here is a brief version of the Play a Dice Game use case: Play a Dice Game: A player picks up and rolls the dice. If the dice face value total seven, they win; otherwise, they lose. Define a Domain Model Object-oriented analysis is concerned with creating a description of the domain from the perspective of classification by objects. A decomposition of the domain involves an identification of the concepts, attributes, and associations that are considered noteworthy. The result can be expressed in a domain model, which is illustrated in a set of diagrams that show domain concepts or objects. For example, a partial domain model is shown in Figure 1.3. Figure 1.3 Partial domain model of the dice game. Define domain model Define interaction diagrams Define design class diagramsDefine use cases Define domain model Define interaction diagrams Define design class diagramsDefine use cases Player name DiceGame Die faceValue Rolls Plays Includes 2 2 1 1 1 1 AN EXAMPLE This model illustrates the noteworthy concepts Player, Die, and DiceGame, with their associations and attributes. Note that a domain model is not a description of software objects; it is a visual- ization of concepts in the real-world domain. Define Interaction Diagrams Object-oriented design is concerned with defining software objects and their col- laborations. A common notation to illustrate these collaborations is the interac- tion diagram. It shows the flow of messages between software objects, and thus the invocation of methods. For example, assume that a software implementation of the dice game is desired. The interaction diagram in Figure 1.4 illustrates the essential step of playing, by sending messages to instances of the DiceGame and Die classes. Figure 1.4 Interaction diagram illustrating messages between software objects. Notice that although in the real world a player rolls the dice, in the software design the DiceGame object "rolls" the dice (that is, sends messages to Die objects). Software object designs and programs do take some inspiration from real-world domains, but they are not direct models or simulations of the real world. 9 Define domain model Define interaction diagrams Define design class diagramsDefine use cases :DiceGame play() die1 : Die fv1 := getFaceValue() die2 : Die roll() roll() fv2 := getFaceValue() 1 - OBJECT-ORIENTED ANALYSIS AND DESIGN Define Design Class Diagrams In addition to a dynamic view of collaborating objects shown in interaction dia- grams, it is useful to create a static view of the class definitions with a design class diagram. This illustrates the attributes and methods of the classes. For example, in the dice game, an inspection of the interaction diagram leads to the partial design class diagram shown in Figure 1.5. Since a play message is sent to a DiceGame object, the DiceGame class requires a play method, while class Die requires a roll and getFaceValue method. In contrast to the domain model, this diagram does not illustrate real-world con- cepts; rather, it shows software classes. Figure 1.5 Partial design class diagram. Summary The dice game is a simple problem, presented to focus on a few steps and arti- facts in analysis and design. To keep the introduction simple, not all the illus- trated UML notation was explained. Future chapters explore analysis and design and these artifacts in closer detail. 1.6 The UML To quote: The Unified Modeling Language (UML) is a language for speci- fying, visualizing, constructing, and documenting the artifacts of software systems, as well as for business modeling and other non-software systems [OMG01]. The UML has emerged as the de facto and de jure standard diagramming nota- tion for object-oriented modeling. It started as an effort by Grady Booch and Jim Rumbaugh in 1994 to combine the diagramming notations from their two popu- 10 Define domain model Define interaction diagrams Define design class diagramsDefine use cases 2 Die faceValue : int getFaceValue() : int roll() DiceGame die1 : Die die2 : Die play() 1 Chapter 2 ITERATIVE DEVELOPMENT AND THE UNIFIED PROCESS People are more important than any process. Good people with a good process will outperform good people with no process every time. —Grady Booch Objectives • Provide motivation for the content and order of subsequent chapters. • Define an iterative and adaptive process. • Define fundamental concepts in the Unified Process. Introduction Iterative development is a skillful approach to software development, and lies at the heart of how OOA/D is presented in this book. The Unified Process is an example iterative process for projects using OOA/D, and it shapes the book's presentation. Consequently, it is useful to read this chapter so that these core concepts and their influence on the book's structure are clear. This chapter summarizes a few key ideas; please see Chapter 37 for further dis- cussion of the UP and iterative process practices. Informally, a software development process describes an approach to build- ing, deploying, and possibly maintaining software. The Unified Process [JBR99] has emerged as a popular software development process for building object-oriented systems. In particular, the Rational Unified Process or RUP 13 2 - ITERATIVE DEVELOPMENT AND THE UNIFIED PROCESS [KruchtenOO], a detailed refinement of the Unified Process, has been widely adopted. The Unified Process (UP) combines commonly accepted best practices, such as an iterative lifecycle and risk-driven development, into a cohesive and well-doc- umented description. Consequently, it is used in this book as the example pro- cess within which to introduce OOA/D. This book starts with an introduction to the UP for two reasons: 1. The UP is an iterative process. Iterative development is a valuable practice that influences how this book introduces OOA/D, and how it is best prac ticed. 2. UP practices provide an example structure to talk about how to do—and how to learn—OOA/D. This text presents an introduction to the UP, not complete coverage. It emphasizes common ideas and artifacts related to an introduction to OOA/D and requirements analysis. What If I Don't Care About the UP? The UP is used as an example process within which to explore requirements analysis and OOA/D, since it is necessary to introduce the subject in the context of some process, and the UP (or the RUP refinement) is relatively widely used. Also, the UP presents common activities and best practices. Nevertheless, the central ideas of this book—such as use cases and design patterns—are indepen- dent of any particular process, and apply to many. 2.1 The Most Important UP Idea: Iterative Development The UP promotes several best practices, but one stands above the others: itera- tive development. In this approach, development is organized into a series of short, fixed-length (for example, four week) mini-projects called iterations; the outcome of each is a tested, integrated, and executable system. Each iteration includes its own requirements analysis, design, implementation, and testing activities. The iterative lifecycle is based on the successive enlargement and refinement of a system through multiple iterations, with cyclic feedback and adaptation as core drivers to converge upon a suitable system. The system grows incremen- tally over time, iteration by iteration, and thus this approach is also known as iterative and incremental development (see Figure 2.1). 14 Figure 2.1 Iterative and incremental development. Example As an example (not a recipe), in a two-week iteration half-way through a project, perhaps Monday is spent primarily on distributing and clarifying the tasks and requirements of the iteration, while one person reverse-engineers the last iteration's code into UML diagrams (via a CASE tool), and prints and displays noteworthy diagrams. Tuesday is spent at whiteboards doing pair design work drawing rough UML diagrams captured on digital cameras, and writing some pseudocode and design notes. The remaining eight days are spent on implementation, testing (unit, acceptance, usability, ...), further design, integration, daily builds, system testing, and stabilization of the par- tial system. Other activities include demonstrations and evaluations with stakeholders, and planning for the next iteration. Notice in this example that there is neither a rush to code, nor a long drawn-out design step that attempts to perfect all details of the design before program- ming. A "little" forethought regarding the design with visual modeling using rough and fast UML drawings is done; perhaps a half or full day by developers doing design work in pairs. The result of each iteration is an executable but incomplete system; it is not ready to deliver into production. The system may not be eligible for production deployment until after many iterations; for example, 10 or 15 iterations. 15 THE MOST IMPORTANT UP IDEA: ITERATIVE DEVELOPMENT Early iterative process ideas were known as spiral development and evolution- ary development [Boehm.88, Gilb88]. Requirements Design Implementation & Test & Integration & More Design Final Integration & System Test Requirements Design 4 weeks (for example) The system grows incrementally. Feedback from iteration N leads to refinement and adaptation of the requirements and design in iteration N+1. Iterations are fixed in length, or timeboxed. Time Implementation & Test & Integration & More Design Final Integration & System Test 2 - ITERATIVE DEVELOPMENT AND THE UNIFIED PROCESS Iteration Length and Timeboxing The UP (and experienced iterative developers) recommends an iteration length between two and six weeks. Small steps, rapid feedback, and adaptation are central ideas in iterative development; long iterations subvert the core motiva- tion for iterative development and increase project risk. Much less than two weeks, and it is difficult to complete sufficient work to get meaningful through- put and feedback; much more than six or eight weeks, and the complexity becomes rather overwhelming, and feedback is delayed. A very long iteration misses the point of iterative development. Short is good. A key idea is that iterations are timeboxed, or fixed in length. For example, if the next iteration is chosen to be four weeks long, then the partial system should be integrated, tested, and stabilized by the scheduled date—date slippage is dis- couraged. If it seems that it will be difficult to meet the deadline, the recom- mended response is to remove tasks or requirements from the iteration, and include them in a future iteration, rather than slip the completion date. Chapter 37 summarizes reasons for timeboxing. Massive teams (for example, several hundred developers) may require longer than six-week iterations to compensate for the overhead of coordination and communication; but no more than three to six months is recommended. For example, the successful replacement in the 1990s of the Canadian air traffic control system was developed with an iterative lifecycle and other UP practices. It involved 150 programmers and was organized into six-month iterations.2 But note that even in the case of an overall six-month project iteration, a subsystem team of 10 or 20 developers can break down their work into a series of six one-month iterations. A six-month iteration is the exception for massive teams, not the rule. To reiter- ate, the UP recommends that normally an iteration should be between two and six weeks in duration. 2.2 Additional UP Best Practices and Concepts The central idea to appreciate and practice in the UP is short timeboxed itera- tive, adaptive development. Another implicit, but core, UP idea is the use of object technologies, including OOA/D and object-oriented programming. 2. Philippe Kruchten, who also led the development of the RUP, served as chief architect for the project. 18 THE UP PHASES AND SCHEDULE-ORIENTED TERMS Some additional best practices and key concepts in the UP include: • tackle high-risk and high-value issues in early iterations • continuously engage users for evaluation, feedback, and requirements • build a cohesive, core architecture in early iterations • continuously verify quality; test early, often, and realistically • apply use cases • model software visually (with the UML) • carefully manage requirements • practice change request and configuration management See Chapter 37 for a more detailed description of these practices. 2.3 The UP Phases and Schedule-Oriented Terms A UP project organizes the work and iterations across four major phases: 1. Inception— approximate vision, business case, scope, vague estimates. 2. Elaboration—refined vision, iterative implementation of the core architec ture, resolution of high risks, identification of most requirements and scope, more realistic estimates. 3. Construction—iterative implementation of the remaining lower risk and easier elements, and preparation for deployment. 4. Transition—beta tests, deployment. These phases are more fully defined in subsequent chapters. This is not the old "waterfall" or sequential lifecycle of first defining all the requirements, and then doing all or most of the design. Inception is not a requirements phase; rather, it is a kind of feasibility phase, where just enough investigation is done to support a decision to continue or stop. Similarly, elaboration is not the requirements or design phase; rather, it is a phase where the core architecture is iteratively implemented, and high risk issues are mitigated. Figure 2.3 illustrates common schedule-oriented terms in the UP. Notice that one development cycle (which ends in the release of a system into production) is composed of many iterations. 19 Figure 2.3 Schedule-oriented terms in the UP. 2.4 The UP Disciplines (was Workflows) The UP describes work activities, such as writing a use case, within disciplines (originally called workflows).3 Informally, a discipline is a set of activities (and related artifacts) in one subject area, such as the activities within requirements analysis. In the UP, an artifact is the general term for any work product: code, Web graphics, database schema, text documents, diagrams, models, and so on. There are several disciplines in the UP; this book focuses on some artifacts in the following three: • Business Modeling—When developing a single application, this includes domain object modeling. When engaged in large-scale business analysis or business process reengineering, this includes dynamic modeling of the busi ness processes across the entire enterprise. • Requirements—Requirements analysis for an application, such as writing use cases and identifying non-functional requirements. • Design—All aspects of design, including the overall architecture, objects, databases, networking, and the like. 3. In 2001, the old UP term "workflow" was replaced by the new term "discipline" in order to harmonize with an international standardization effort called the OMG SPEM; because of its prior meaning in the UP, many continue to use the term work- flow to mean discipline, although this is not strictly correct. The term "workflow" took on a new but slightly different meaning within the UP: On a particular project, it is a particular sequence of activities (perhaps across disciplines)—a flow of work. 20 2 - ITERATIVE DEVELOPMENT AND THE UNIFIED PROCESS inc. elaboration construction transition iteration phase development cycle release A stable executable subset of the final product. The end of each iteration is a minor release. increment The difference (delta) between the releases of 2 subsequent iterations. final production release At this point, the system is released for production use. milestone An iteration end- point when some significant decision or evaluation occurs. Figure 2.6 Book organization is related to the UP phases and iterations. 2.5 Process Customization and the Development Case Optional Artifacts Some UP practices and principles are invariant, such as iterative and risk-driven development, and continuous verification of quality. However, a key insight into the UP is that all activities and artifacts (models, diagrams, documents, ...) are optional—well, maybe not the code! The set of pos- sible artifacts described in the UP should be viewed like a set of medicines in a pharmacy. Just as one does not indiscriminately take many medicines, but matches the choice to the ailment, likewise on a UP project, a team should select a small subset of artifacts that address its particular problems and needs. In general, focus on a small set of artifacts that demonstrate high practical value. The Development Case The choice of UP artifacts for a project may be written up in a short document called the Development Case (an artifact in the Environment discipline). For example, Table 2.1 could be the Development Case describing the artifacts for the "NextGen Project" case study explored in this book. Subsequent chapters describe the creation of some of these artifacts, including the Domain Model, Use-Case Model, and Design Model. The example artifacts presented in this case study are by no means sufficient for, or suitable for, all projects. For example, a machine control system may ben- efit from doing many state diagrams. A Web-based e-commerce system may require a focus on user interface prototypes. A "green-field" new development 23 PROCESS CUSTOMIZATION AND THE DEVELOPMENT CASE Overview Inception Elaboratio n Iteration 1 Elaboratio n Iteration 2 Elaboratio n Iteration 3 Object-Oriented Analysis Object-Oriented Design Translating Designs to Code The Book Topics such as OO analysis and OO design are incrementally introduced in iteration 1, 2, and 3. Special Topics 2 - ITERATIVE DEVELOPMENT AND THE UNIFIED PROCESS project has very different design artifact needs than a systems integration project. Discipline Artifact Iteration-* Incep. 11 Elab. El. .En Const. CL.Cn Trans. T1..T2 Business Modeling Domain Model s Use-Case Model s r Vision s r Supplementary Specification s r Requirements Glossary s r Design Model s r SW Architecture Document s Design Data Model s r Implementation Implementation Model s r r Project Management SW Development Plan s r r r Testing Test Model s r Environment Development Case s r Table 2.1 Sample Development Case of UP artifacts, s - start; r - refine 2.6 The Agile UP Methodologists speak of processes as heavy vs. light, and predictive vs. adaptive. A heavy process is a pejorative term meant to suggest one with the following qualities [FowlerOO]: • many artifacts created in a bureaucratic atmosphere • rigidity and control • elaborate, long-term, detailed planning • predictive rather than adaptive A predictive process is one that attempts to plan and predict the activities and resource (people) allocations in detail over a relatively long time span, such as the majority of a project. Predictive processes usually have a "waterfall" or sequential lifecycle—first, defining all the requirements; second, defining a detailed design; and third, implementing. In contrast, an adaptive process is one that accepts change as an inevitable driver and encourages flexible adapta- tion; they usually have an iterative lifecycle. An agile process implies a light and adaptive process, nimble in response to changing needs. The UP was not meant by its authors to be either heavy or predictive, although its large optional set of activities and artifacts have understandably led to that 24 THE SEQUENTIAL "WATERFALL" LIFECYCLE impression in some. Rather, it was meant to be adopted and applied in the spirit of an agile process—agile UP. Some examples of how this applies: • Prefer a small set of UP activities and artifacts. Some projects will benefit from more than others, but, in general, keep it simple. • Since the UP is iterative, requirements and designs are not completed before implementation. They adaptively emerge through a series of itera tions, based on feedback. • There isn't a detailed plan for the entire project. There is a high level plan (called the Phase Plan) that estimates the project end date and other major milestones, but it does not detail the fine-grained steps to those milestones. A detailed plan (called the Iteration Plan) only plans with greater detail one iteration in advance. Detailed planning is done adaptively from itera tion to iteration. Please see Chapter 36 for some comments on planning iter ative projects, and the justification for this approach. The case study emphasizes a relatively small number of artifacts, and iterative development, in the spirit of an agile UP. 2.7 The Sequential "Waterfall" Lifecycle In contrast to the iterative lifecycle of the UP, an old alternative was the sequen- tial, linear, or "waterfall" lifecycle [RoyceTO]. In common usage, it defined steps similar to the following: 1. Clarify, record, and commit to a set of complete and frozen requirements. 2. Design a system based on these requirements. 3. Implement, based on the design. A two year study reported in the MIT Sloan Management Review of successful software projects identified four common factors for success; iterative develop- ment, rather than a waterfall process, was first on the list [MacCormackO!!.•'' A brief description of its problems, and how they are mitigated by iterative development, is presented in Chapter 37. 5. The others were: 2) at least daily incorporation of new code into a complete system build, and rapid feedback on design changes (via testing); 3) a team experienced in shipping multiple products; and 4) an early focus on building and proving a cohesive architecture. Three of these four factors are explicit practices in the UP. 25 Chapter 3 CASE STUDY: THE NEXTGEN POS SYSTEM Few things are harder to put up with than a good example. —Mark Twain Introduction This chapter briefly describes the case study. If you understand the problem domain, it may be skipped. Indeed, this problem was chosen because it is familiar, but rich with interesting design and architectural problems, and thus allows one to concentrate on how to do analysis and design, rather than explain the problem and domain. 3.1 The NextGen POS System The case study is the NextGen point-of-sale (POS) system. In this apparently straightforward problem domain, we shall see that there are very interesting requirement and design problems to solve. In addition, it is a realistic problem; organizations really do write POS systems using object technologies. A POS system is a computerized application used (in part) to record sales and handle payments; it is typically used in a retail store. It includes hardware components such as a computer and bar code scanner, and software to run the system. It interfaces to various service applications, such as a third-party tax calculator and inventory control. These systems must be relatively fault-tolerant; that is, even if remote services are temporarily unavailable (such as the inventory system), they must still be capable 29 3 - CASE STUDY: THE NEXTGEN POS SYSTEM of capturing sales and handling at least cash payments (so that the business is not crippled). A POS system increasingly must support multiple and varied client-side termi- nals and interfaces. These include a thin-client Web browser terminal, a regular personal computer with something like a Java Swing graphical user interface, touch screen input, wireless PDAs, and so forth. Furthermore, we are creating a commercial POS system that we will sell to dif- ferent clients with disparate needs in terms of business rule processing. Each client will desire a unique set of logic to execute at certain predictable points in scenarios of using the system, such as when a new sale is initiated or when a new line item is added. Therefore, we will need a mechanism to provide this flexibility and customization. Using an iterative development strategy, we are going to proceed through requirements, object-oriented analysis, design, and implementation. 3.2 Architectural Layers and Case Study Emphasis A typical object-oriented information system is designed in terms of several architectural layers or subsystems (see Figure 3.1). The following is not a com- plete list, but provides an example: • User Interface—graphical interface; windows. • Application Logic and Domain Objects—software objects representing domain concepts (for example, a software class named Sale) that fulfill application requirements. • Technical Services—general purpose objects and subsystems that provide supporting technical services, such as interfacing with a database or error logging. These services are usually application-independent and reusable across several systems. OOA/D is generally most relevant for modeling the application logic and tech- nical service layers. The NextGen case study primarily emphasizes the problem domain objects, allo- cating responsibilities to them to fulfill the requirements of the application. Object-oriented design is also applied to create a technical service subsystem for interfacing with a database. In this design approach, the UI layer has very little responsibility; it is said to be thin. Windows do not contain code that performs application logic or process- ing. Rather, task requests are forwarded on to other layers. 30 Figure 3.1 Sample layers and objects in an object-oriented system, and the case study focus. 3.3 The Book's Strategy: Iterative Learning and Development This book is organized to follow an iterative development strategy. OOA/D is applied to the NextGen POS system in multiple iterations; the first iteration is for some core functions. Later iterations expand the functionality of the system (see Figure 3.2). In conjunction with iterative development, the presentation of analysis and design topics, UML notation, and patterns are introduced itera-tively and incrementally. In the first iteration, a core set of analysis and design topics and notation is presented. The second iteration expands into new ideas, UML notation, and patterns. And likewise in the third iteration. 31 THE BOOK'S STRATEGY: ITERATIVE LEARNING AND DEVELOPMENT Figure 3.2 Learning path follows iterations. Interface Sale Payment Log PersistenceFacade application logic and domain object layer technical services layer minor focus explore how to connect to other layers primary focus of case study explore how to design objects secondary focus explore how to design objects Iteration 1 Iteration 2 Iteration 3 Introduces just those analysis and design skills related to iteration one. Additional analysis and design skills introduced. Likewise. 4 - INCEPTION Thus, the inception phase should be relatively short for most projects, such as one or a few weeks long. Indeed, on many projects, if it is more than a week long, then the point of inception has been missed: It is to decide if the project is worth a serious investigation (during elaboration), not to do that investigation. Inception in one sentence: Envision the product scope, vision, and business case. The main problem solved in one sentence: Do the stakeholders have basic agreement on the vision of the project, and is it worth investing in serious investigation? 4.1 Inception: An Analogy In the oil business, when a new field is being considered, some of the steps include: 1. Decide if there is enough evidence or a business case to even justify explor atory drilling. 2. If so, do measurements and exploratory drilling. 3. Provide scope and estimate information. 4. Further steps... The inception phase is like step one in this analogy. In step one people do not predict how much oil there is, or the cost or effort to extract it. It is premature— there is insufficient information. Although it would be nice to be able to answer "how much" and "when" questions without the cost and effort of the exploration, in the oil business it is understood to not be realistic. In UP terms, the realistic exploration step is the elaboration phase. The preced- ing inception phase is akin to a feasibility study to decide if it is even worth investing in exploratory drilling. Only after exploration (elaboration) do we have the data and insight to make somewhat believable estimates and plans. There- fore, in iterative development and the UP, plans and estimates are not to be con- sidered reliable in the inception phase. They merely provide an order-of-magnitude sense of the level of effort, to aid the decision to continue or not. 4.2 Inception May Be Very Brief The intent of inception is to establish some initial common vision for the objec- tives of the project, determine if it is feasible, and decide if it is worth some seri- 36 WHAT ARTIFACTS MAY START IN INCEPTION? ous investigation in elaboration. If it has been decided beforehand that the project will definitely be done, and it is clearly feasible (perhaps because the team has done projects like this before), then the inception phase will be espe- cially brief. It may include the first requirements workshop, planning for the first iteration, and then quickly moving forward to elaboration. 4.3 What Artifacts May Start in Inception? Table 4.1 lists common inception (or early elaboration) artifacts and indicates the issues they address. Subsequent chapters will examine some of these in greater detail, especially the Use-Case Model. A key insight regarding iterative development is to appreciate that these are only partially completed in this phase, will be refined in later iterations, and should not even be created unless it is deemed likely they will add real practical value. And since it is inception, the investigation and artifact content should be light. For example, the Use-Case Model (to be described in following chapters) may list the names of most of the expected use cases and actors, but perhaps only describe 10% of the use cases in detail—done in the service of developing a rough high-level vision of the system scope, purpose, and risks. Note that some programming work may occur in inception in order to create "proof of concept" prototypes, to clarify a few requirements via (typically) Ul-ori-ented prototypes, and to do programming experiments for key "show stopper" technical questions. Artifact1 Comment Vision and Business Case Describes the high-level goals and constraints, the business case, and provides an executive summary. Use-Case Model Describes the functional requirements, and related non-func- tional requirements. Supplementary Specification Describes other requirements. Glossary Key domain terminology. Risk List & Risk Management Plan Describes the business, technical, resource, schedule risks, and ideas for their mitigation or response. Prototypes and proof-of-concepts To clarify the vision, and validate technical ideas. Iteration Plan Describes what to do in the first elaboration iteration. 37 4 - INCEPTION Artifact1 Comment Phase Plan & Software Develop- ment Plan Low-precision guess for elaboration phase duration and effort. Tools, people, education, and other resources. Development Case A description of the customized UP steps and artifacts for this project. In the UP, one always customizes it for the project. Table 4.1 Sample inception artifacts. t-These artifacts are only partially completed in this phase. They will be itera-tively refined in subsequent iterations. Name capitalization implies it is an officially named UP artifact. Isn't That a Lot of Documentation? Recall that artifacts should be considered optional. Choose to create only those that really add value for the project, and drop them if their worth is not proved. The point of an artifact is not the document or diagram itself, but the thinking, analysis, and proactive readiness (and then its recording, to avoid re-invention or having to repeat things verbally). As General Eisenhower said, "In preparing for battle I have always found that plans are useless, but planning indispens- able" [Nixon90, BFOO]. Record artifacts digitally and online—available on the project's website—rather than on paper. Note also that UP artifacts from previous projects can be reused on later ones. It is common for there to be many similarities in risk, project management, testing, and environment artifacts across projects. All UP projects will (or should) organize artifacts the same way, with the same names (Risk List, Development Case, and so on). This simplifies finding reusable artifacts from prior projects on new UP engagements. 4.4 You Know You Didn't Understand Inception When... • It is more than "a few" weeks long for most projects. • There is an attempt to define most of the requirements. • Estimates or plans are expected to be reliable. • You define the architecture; rather, this should be done iteratively in elaboration. 38 5 - UNDERSTANDING REQUIREMENTS skillful elicitation via techniques such as use case writing and requirements workshops. As indicated in Figure 5.1, one study of factors on challenged projects revealed that 37% of factors related to problems with requirements, making require- ments issues the largest single contributor to problems [Standish94]. Conse- quently, masterful requirements management is important. The waterfall response to this data would be to try harder to polish, stabilize, and freeze the requirements before any design or implementation, but history shows this to be a losing battle. The iterative response is to use a process that embraces change and feedback as core drivers in discovering requirements. Figure 5.1 Factors on challenged software projects. 5.1 Types of Requirements In the UP, requirements are categorized according to the FURPS+ model [Grady92], a useful mnemonic with the following meaning:1 • Functional—features, capabilities, security. • Usability—human factors, help, documentation. • Reliability—frequency of failure, recoverability, predictability. 1. There are several systems of requirements categorization and quality attributes pub- lished in books and by standards organizations, such as ISO 9126 (which is similar to the FURPS+ list), and several from the Software Engineering Institute (SE1); any can be used on a UP project. 42 FURTHER READINGS • Performance—response times, throughput, accuracy, availability, resource usage. • Supportability—adaptability, maintainability, internationalization, con figurability. The "+" in FURPS+ indicates ancillary and sub-factors, such as: • Implementation—resource limitations, languages and tools, hardware, ... • Interface—constraints imposed by interfacing with external systems. • Operations—system management in its operational setting. • Packaging • Legal—licensing and so forth. It is helpful to use FURPS+ categories (or some categorization scheme) as a checklist for requirements coverage, to reduce the risk of not considering some important facet of the system. Some of these requirements are collectively called the quality attributes, quality requirements, or the "-ilities" of a system. These include usability, reliability, performance, and supportability. In common usage, requirements are categorized as functional (behavioral) or non-functional (everything else); some dislike this broad generalization [BCK98], but it is very widely used. Functional requirements are explored and recorded in the Use-Case Model, the subject of the next chapter, and in the system features list of the Vision artifact. Other requirements can be recorded in the use cases they relate to, or in the Supplementary Specifications artifact. The Vision artifact summarizes high-level requirements that are elaborated in these other documents. The Glossary records and clarifies terms used in the requirements. The Glossary in the UP also encompasses the concept of the data dictionary, which records requirements related to data, such as validation rules, acceptable values, and so forth. Prototypes are a mechanism to clarify what is wanted or possible. As we shall see when exploring architectural analysis, the quality requirements have a strong influence on the architecture of a system. For example, a high-per- formance, high-reliability requirement will influence the choice of software and hardware components, and their configuration. The need for easy adaptability due to frequent changes in the functional requirements would likewise funda- mentally shape the design of the software. 5.2 Further Readings References related to requirements with use cases are covered in a subsequent chapter. Use-case-oriented requirements texts, such as Writing Effective Use Cases [CockburnOl] are the recommended starting point in requirements study, rather than more general (and usually, traditional) requirements texts. 43 44 5 - UNDERSTANDING REQUIREMENTS There is a broad effort to discuss requirements—and a wide variety of software engineering topics—under the umbrella of the Software Engineering Body of Knowledge (SWEBOK), available at www.swebok.org. The SEI (www.sei.cmu.edu) has several proposals related to quality require- ments. The ISO 9126, IEEE Std 830, and IEEE Std 1061 are standards related to requirements and quality attributes, and available on the Web at various sites. Some cautions regarding general requirements books, even those that purport to cover use cases, iterative development, or indeed even requirements in the UP: 1. Most are written with a waterfall bias of significant or "thorough" up-front requirements definition before moving on to design and implementation. This is not meant to invalidate their broader value or often deep and useful method-independent requirements insights, but to clarify that they do not represent an accurate view of iterative development. This is because the authors may have a primary background in waterfall projects, working to refine, carefully and thoroughly define, and finalize the requirements before continuing to design. Those books that also mention iterative development may do so superficially, perhaps with "iterative" material added to appeal to modern trends. Thus, requirements books and articles should be read with alertness; one could be lulled into the idea of trying to carefully define all the requirements in the initial phase, which is not consistent with an itera tive process. 2. Many general requirements books that also purport to include use cases do so superficially, or misunderstand what use-case driven requirements really means. This may be because the authors' primary background is in tradi tional requirements methods, and there has been an attempt to recently append use cases to their prior method, without appreciating that a central idea of use cases as envisioned by Ivar Jacobson and the Ul' is to make use cases the heart-and-center overarching requirements approach—replacing other requirements documents as the central element; use cases suffuse and drive the requirements work, rather than being some minor or medium- level adjunct technique appended to traditional requirements documents or approaches. In summary, general requirements books offer useful advice on techniques and issues of requirements gathering, written by skilled practitioners, but often present the advice in a waterfall process context, and without great insight into the deeper implications of use cases. Any variant of process advice implying "try to define most of the requirements, and then move forward to design and imple- mentation" is not consistent with iterative development and the UP. USE CASES AND ADDING VALUE utility being its chief virtues. Although many have made contributions to the subject, arguably the most influential, comprehensive, and coherent next step in defining what use cases are (or should be) and how to write them came from Alistair Cockburn, summarized in the very popular text Writing Effective Use Cases [CockburnOl], based on his earlier work and writings stemming from 1992 onwards. This introduction is therefore based upon and consistent with the latter work. : 6.3 Use Cases and Adding Value First, some informal definitions: an actor is something with behavior, such as a person (identified by role), computer system, or organization; for example, a cashier. A scenario is a specific sequence of actions and interactions between actors and the system under discussion; it is also called a use case instance. It is one par- ticular story of using a system, or one path through the use case; for example, the scenario of successfully purchasing items with cash, or the scenario of failing to purchase items because of a credit card transaction denial. Informally then, a use case is a collection of related success and failure scenar- ios that describe actors using a system to support a goal. For example, here is a casual format use case that includes some alternate scenarios: Handle Returns Main Success Scenario: A customer arrives at a checkout with items to return. The cashier uses the POS system to record each returned item ... Alternate Scenarios: If the credit authorization is reject, inform the customer and ask for an alternate payment method. If the item identifier is not found in the system, notify the Cash- ier and suggest manual entry of the identifier code (perhaps it is corrupted). If the system detects failure to communicate with the external tax calculator system, ... An alternate, but similar definition of a use case is provided by the RUP: A set of use-case instances, where each instance is a sequence of actions a system performs that yields an observable result of value to a particular actor [RUP]. 47 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT The phrasing "an observable result of value" is subtle but important, because it stresses the attitude that the system behavior should emphasize providing value to the user. A key attitude in use case work is to focus on the question "How can using the system provide observable value to the user, or fulfill their goals?", rather than merely thinking of system requirements in terms of a "laundry list" of features or functions. Perhaps it seems obvious to stress providing observable user value, but the soft- ware industry is littered with failed projects that did not deliver what people really needed. The feature and function list approach to capturing requirements can contribute to that negative outcome because it does not encourage the stake- holders to consider the requirements in a larger context of using the system in a scenario to achieve some observable result of value, or some goal. In contrast, use cases place features and functions in a goal-oriented context. Hence the chapter title.2 This is a key idea that Jacobson was trying to convey in the use case concept: Do requirements work with a focus on how a system can add value and fulfill goals. 6.4 Use Cases and Functional Requirements Use cases are requirements; primarily they are functional requirements that indicate what the system will do. In terms of the FURPS+ requirements types, they emphasize the "F" (functional or behavioral), but can also be used for other types, especially when those other types strongly relate to a use case. In the UP—and most modern methods—use cases are the central mechanism that is recommended for their discovery and definition. Use cases define a promise or contract of how a system will behave. To be clear: Use cases are requirements (although not all requirements). Some think of requirements only as "the system shall do..." function or feature lists. Not so, and a key idea of use cases is to (usually) reduce the importance or use of detailed older-style feature lists and rather, write use cases for the functional requirements. More on this point in a later section. Use cases are text documents, not diagrams, and use-case modeling is primarily an act of writing text, not drawing. However, the UML defines a use case dia- gram to illustrate the names of use cases and actors, and their relationships. 2. Originally from the aptly titled Uses Cases: Requirements in Context |GKOO| (chapter title adapted with permission of the authors). 48 USE CASE TYPES AND FORMATS 6.5 Use Case Types and Formats Black-Box Use Cases and System Responsibilities Black-box use cases are the most common and recommended kind; they do not describe the internal workings of the system, its components, or design. Rather, the system is described as having responsibilities, which is a common unifying metaphorical theme in object-oriented thinking—software elements have responsibilities and collaborate with other elements that have responsibilities. By defining system responsibilities with black-box use cases, it is possible to specify what the system must do (the functional requirements) without deciding how it will do it (the design). Indeed, the definition of "analysis" versus "design" is sometimes summarized as "what" versus "how." This is an important theme in good software development: During requirements analysis avoid making "how" decisions, and specify the external behavior for the system, as a black box. Later, during design, create a solution that meets the specification. Black-box style Not The system records the sale. The system writes the sale to a data- base. ...or (even worse): The system generates a SQL INSERT statement for the sale... Formality Types Use cases are written in different formats, depending on need. In addition to the black-box versus white-box visibility type, use cases are written in varying degrees of formality: • brief—terse one-paragraph summary, usually of the main success scenario. The prior Process Sale example was brief. • casual—informal paragraph format. Multiple paragraphs that cover vari ous scenarios. The prior Handle Returns example was casual. • fully dressed—the most elaborate. All steps and variations are written in detail, and there are supporting sections, such as preconditions and success guarantees. The following example is a fully dressed case for our NextGen case study. 49 52 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT 7a. Paying by cash: 1. Cashier enters the cash amount tendered. 2. System presents the balance due, and releases the cash drawer. 3. Cashier deposits cash tendered and returns balance in cash to Customer. 4. System records the cash payment. 7b. Paying by credit: 1. Customer enters their credit account information. 2. System sends payment authorization request to an external Payment Authoriza tion Service System, and requests payment approval. 2a. System detects failure to collaborate with external system: 1. System signals error to Cashier. 2. Cashier asks Customer for alternate payment. 3. System receives payment approval and signals approval to Cashier. 3a. System receives payment denial: 1. System signals denial to Cashier. 2. Cashier asks Customer for alternate payment. 4. System records the credit payment, which includes the payment approval. 5. System presents credit payment signature input mechanism. 6. Cashier asks Customer for a credit payment signature. Customer enters signa ture. 7c. Paying by check... 7d. Paying by debit... 7e. Customer presents coupons: 1. Before handling payment, Cashier records each coupon and System reduces price as appropriate. System records the used coupons for accounting reasons. 1a. Coupon entered is not for any purchased item: 1. System signals error to Cashier. 9a. There are product rebates: 1. System presents the rebate forms and rebate receipts for each item with a rebate. 9b. Customer requests gift receipt (no prices visible): 1. Cashier requests gift receipt and System presents it. Special Requirements: - Touch screen Ul on a large flat panel monitor. Text must be visible from 1 meter. - Credit authorization response within 30 seconds 90% of the time. - Somehow, we want robust recovery when access to remote services such the inven tory system is failing. - Language internationalization on the text displayed. - Pluggable business rules to be insertable at steps 3 and 7. Technology and Data Variations List: 3a. Item identifier entered by bar code laser scanner (if bar code is present) or key- board. 3b. Item identifier may be any UPC, EAN, JAN, or SKU coding scheme. 7a. Credit account information entered by card reader or keyboard. 7b. Credit payment signature captured on paper receipt. But within two years, we pre- dict many customers will want digital signature capture. FULLY DRESSED EXAMPLE: PROCESS SALE Frequency of Occurrence: Could be nearly continuous. Open Issues: - What are the tax law variations? - Explore the remote service recovery issue. - What customization is needed for different businesses? - Must a cashier take their cash drawer when they log out? - Can the customer directly use the card reader, or does the cashier have to do it? This use case is illustrative rather than exhaustive (although it is based on a real POS system's requirements). Nevertheless, there is enough detail and com- plexity here to offer a realistic sense that a fully-dressed use case can record many requirement details. This example will serve well as a model for many use case problems. The Two-Column Variation Some prefer the two-column or conversational format, which emphasizes the fact that there is an interaction going on between the actors and the system. It was first proposed by Rebecca Wirfs-Brock in [Wirfs-Brock93], and is also pro- moted by Constantine and Lockwood to aid usability analysis and engineering [CL99]. Here is the same content using the two-column format: Use Case UC1: Process Sale Primary Actor: ... ... as before ... Main Success Scenario: Actor Action (or Intention) 1. Customer arrives at a POS checkout with goods and/or services to purchase. 2. Cashier starts a new sale. 3. Cashier enters item identifier. Cashier repeats steps 3-4 until indi- cates done. 6. Cashier tells Customer the total, and asks for payment. 7. Customer pays. System Responsibility 4. Records each sale line item and pre sents item description and running total. 5. System presents total with taxes calculated. 8. Handles payment. 53 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT 9. Logs the completed sale and sends information to the external account- ing (for all accounting and commis- sions) and inventory systems (to update inventory). System presents receipt. The Best Format? There isn't one best format; some prefer the one-column style, some the two-col- umn. Sections may be added and removed; heading names may change. None of this is particularly important; the key thing is to write the details of the main success scenario and its extensions, in some form. [Cockburnl] summarizes many usable formats. Personal Practice This is my practice, not a recommendation. For some years, I used the two-column format because of its clear visual separation in the conversation. However, I have reverted to a one-column style as it is more compact and easier to format, and the slight value of the visually separated conversation does not for me outweigh these benefits. I find it still simple to visually iden- tify the different parties in the conversation (Customer, System, ...) if each party and the System responses are usually allocated to their own steps. 6.7 Explaining the Sections Preface Elements Many optional preface elements are possible. Only place elements at the start which are important to read before the main success scenario. Move extraneous "header" material to the end of the use case. Primary Actor: The principal actor that calls upon system services to fulfill a goal. Important: Stakeholders and Interests List This list is more important and practical than may appear at first glance. It sug- gests and bounds what the system must do. To quote: 54 EXPLAINING THE SECTIONS requirements expressed in the Supplementary Specification rather than the use cases. Extension scenarios are branches from the main success scenario, and so can be notated with respect to it. For example, at Step 3 of the main success scenario there may be an invalid item identifier, either because it was incorrectly entered or unknown to the system. An extension is labeled "3a"; it first identifies the condition and then the response. Alternate extensions at Step 3 are labeled "3b" and so forth. Extensions: 3a. Invalid identifier: 1. System signals error and rejects entry. 3b. There are multiple of same item category and tracking unique item identity not important (e.g., 5 packages of veggie-burgers): 1. Cashier can enter item category identifier and the quantity. An extension has two parts: the condition and the handling. Guideline: Write the condition as something that can be detected by the system or an actor. To contrast: 5a. System detects failure to communicate with external tax calculation system service: 5a. External tax calculation system not working: The former style is preferred because this is something the system can detect; the latter is an inference. Extension handling can be summarized in one step, or include a sequence, as in this example, which also illustrates notation to indicate that a condition can arise within a range of steps: 3-6a: Customer asks Cashier to remove an item from the purchase: 1. Cashier enters the item identifier for removal from the sale. 2. System displays updated running total. At the end of extension handling, by default the scenario merges back with the main success scenario, unless the extension indicates otherwise (such as by halting the system). Sometimes, a particular extension point is quite complex, as in the "paying by credit" extension. This can be a motivation to express the extension as a sepa- rate use case. This extension example also demonstrates the notation to express failures within extensions. 57 58 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT 7b. Paying by credit: 1. Customer enters their credit account information. 2. System requests payment validation from external Payment Authorization Ser vice System. 2a. System detects failure to collaborate with external system: 1. System signals error to Cashier. 2. Cashier asks Customer for alternate payment. 3. ... If it is desirable to describe an extension condition as possible during any (or at least most) steps, the labels *a, *b, ..., can be used. *a. At any time, System crashes: In order to support recovery and correct accounting, ensure all transaction sensitive state and events can be recovered at any step in the scenario. 1. Cashier restarts the System, logs in, and requests recovery of prior state. 2. System reconstructs prior state. Special Requirements If a non-functional requirement, quality attribute, or constraint relates specifi- cally to a use case, record it with the use case. These include qualities such as performance, reliability, and usability, and design constraints (often in I/O devices) that have been mandated or considered likely. Special Requirements: - Touch screen Ul on a large flat panel monitor. Text must be visible from 1 meter. - Credit authorization response within 30 seconds 90% of the time. - Language internationalization on the text displayed. - Pluggable business rules to be insertable at steps 2 and 6. Recording these with the use case is classic UP advice, and a reasonable location when first writing the use case. However, many practitioners find it useful to ultimately consolidate all non-functional requirements in the Supplementary Specification, for content management, comprehension, and readability, because these requirements usually have to be considered as a whole during architec- tural analysis. Technology and Data Variations List Often there are technical variations in how something must be done, but not what, and it is noteworthy to record this in the use case. A common example is a GOALS AND SCOPE OF A USE CASE technical constraint imposed by a stakeholder regarding input or output tech- nologies. For example, a stakeholder might say, "The POS system must support credit account input using a card reader and the keyboard." Note that these are examples of early design decisions or constraints; in general, it is skillful to avoid premature design decisions, but sometimes they are obvious or unavoid- able, especially concerning input/output technologies. It is also necessary to understand variations in data schemes, such as using UPCs or EANs for item identifiers, encoded in bar code symbology. This list is the place to record such variations. It is also useful to record varia- tions in the data that may be captured at a particular step. Technology and Data Variations List: 3a. Item identifier entered by laser scanner or keyboard. 3b. Item identifier may be any UPC, EAN, JAN, or SKU coding scheme. 7a. Credit account information entered by card reader or keyboard. 7b. Credit payment signature captured on paper receipt. But within two years, we predict many customers will want digital signature capture. Suggestion This section should not contain multiple steps to express varying behavior for different cases. If that is necessary, say it in the Extensions section. 6.8 Goals and Scope of a Use Case How should use cases be discovered? It is common to be unsure if something is a valid (or more practically, a useful) use case. Tasks can be grouped at many lev- els of granularity, from one or a few small steps, up to enterprise-level activities. At what level and scope should use cases be expressed? The following sections examine the simple ideas of elementary business pro- cesses and goals as a framework for identifying the use cases for an application. Use Cases for Elementary Business Processes Which of these is a valid use case? • Negotiate a Supplier Contract • Handle Returns • Log In 59 62 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT Example: Applying the EBP Guideline As the system analyst responsible for the NextGen system requirements discov- ery, you are investigating user goals. The conversation goes like this: During a requirements workshop: System analyst: "What are some of your goals in the context of using a POS system?" Cashier: "One, to quickly log in. Also, to capture sales." System analyst: "What do you think is the higher level goal motivating log- ging in?" Cashier: "I'm trying to identify myself to the system, so it can validate that I'm allowed to use the system for sales capture and other tasks." System analyst: "Higher than that?" Cashier: "To prevent theft, data corruption, and display of private company information." Note the analyst's strategy of searching up the goal hierarchy to find higher level user goals that still satisfy the EBP guideline, to get at the real intent behind the action, and also to understand the context of the goals. "Prevent theft, ..." is higher than a user goal; it may be called an enterprise goal, and is not an EBP. Therefore, although it can inspire new ways of thinking about the problem and solutions (such as eliminating POS systems and cashiers completely), we will set it aside for now. Lowering the goal level to "identify myself and be validated" appears closer to the user goal level. But is it at the EBP level? It does not add observable or mea- surable business value. If the CEO asked, "What did you do today?" and you said "I logged in 20 times!", she would not be impressed. Consequently, this is a secondary goal, always in the service of doing something useful, and is not an EBP or user goal. By contrast, "capture a sale" does fit the criteria of being an EBP or user goal. As another example, in some stores there is a process called "cashing in", in which a cashier inserts their own cash drawer tray into the terminal, logs in, and tells the system how much cash is in drawer. Cashing In is an EBP-level (or user goal level) use case; the log in step, rather than being a EBP-level use case, is a subfunction goal in support of the goal of cashing in. Subfunction Goals and Use Cases Although "identify myself and be validated" (or "log in") has been eliminated as a user goal, it is a goal at a lower level, called a subfunction goal—subgoals that support a user goal. Use cases should only occasionally be written for these subfunction goals, although it is a common problem that use case experts observe when asked to evaluate and improve (usually simplify) a set of use cases. FINDING PRIMARY ACTORS, GOALS, AND USE CASES It is not illegal to write use cases for subfunction goals, but it is not always help- ful, as it adds complexity to a use-case model; there can be hundreds of subfunc-tion goals—or subfunction use cases—for a system. Important point: The number and granularity of use cases influences the time and difficulty to understand, maintain, and manage the requirements. The most common, valid motivation to express a subfunction goal as a use case is when the subfunction is repeated in or is a precondition for multiple user goal-level use cases. This in fact is probably true of "identify myself and be vali- dated," which is a precondition of most, if not all, other user goal-level use cases. Consequently, it may be written as the use case Authenticate User. Goals and Use Cases Can Be Composite Goals are usually composite, from the level of an enterprise ("be profitable"), to many supporting intermediate goals while using applications ("sales are cap- tured"), to supporting subfunction goals within applications ("input is valid"). Similarly, use cases can be written at different levels to satisfy these goals, and can be composed of lower level use cases. These varying goal and use case levels are a common source of confusion in identifying the appropriate level of use cases for an application. The EBP guideline provides guidance to filter out excessive low-level use cases. 6.9 Finding Primary Actors, Goals, and Use Cases Use cases are defined to satisfy the user goals of the primary actors. Hence, the basic procedure is: 1. Choose the system boundary. Is it just a software application, the hardware and application as a unit, that plus a person using it, or an entire organiza tion? 2. Identify the primary actors—those that have user goals fulfilled through using services of the system. 3. For each, identify their user goals. Raise them to the highest user goal level that satisfies the EBP guideline. 4. Define use cases that satisfy user goals; name them according to their goal. Usually, user goal-level use cases will be one-to-one with user goals, but there is at least one exception, as will be examined. 63 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT Step 1: Choosing the System Boundary For this case study, the POS system itself is the system under design; every- thing outside of it is outside the system boundary, including the cashier, pay- ment authorization service, and so on. If it is not clear, defining the boundary of the system under design can be clari- fied by defining what is outside—the external primary and supporting actors. Once the external actors are identified, the boundary becomes clearer. For example, is the complete responsibility for payment authorization within the system boundary? No, there is an external payment authorization service actor. Steps 2 and 3: Finding Primary Actors and Goals It is artificial to strictly linearize the identification of primary actors before user goals; in a requirements workshop, people brainstorm and generate a mixture of both. Sometimes, goals reveal the actors, or vice versa. Guideline: Emphasize brainstorming the primary actors first, as this sets up the framework for further investigation. Reminder Questions to Find Actors and Goals In addition to obvious primary actors and user goals, the following questions help identify others that may be missed: Who starts and stops the system? Who does user and security management? Is there a monitoring process that restarts the system if it fails? How are software updates handled? Push or pull update? Who does system administration? Is "time" an actor because the sys- tem does something in response to a time event? Who evaluates system activity or performance? Who evaluates logs? Are they remotely retrieved? 64 Primary and Supporting Actors Recall that primary actors have user goals fulfilled through using services of the system. They call upon the system to help them. This is in contrast to support- ing actors, which provide services to the system under design. For now, the focus is on finding the primary actors, not the supporting ones. CONGRATULATIONS: USE CASES HAVE BEEN WRITTEN, AND ABE IMPERFECT External Event From Actor Goal enter sale line item Cashier process a sale enter payment Cashier or Customer process a sale … Step 4: Define Use Cases In general, define one EBP-level use case for each user goal. Name the use case similar to the user goal—for example, Goal: process a sale; Use Case: Process Sale. Also, name use cases starting with a verb. A common exception to one use case per goal is to collapse CRUD (create, retrieve, update, delete) separate goals into one CRUD use case, idiomatically called Manage <X>. For example, the goals "edit user," "delete user," and so forth are all satisfied by the Manage Users use case. "Define use cases" has several levels of effort, ranging from a few minutes to simply record names, up to weeks to write fully dressed versions. The later UP process section of this chapter puts this work—when and how much—in the context of iterative development and the UP. 6.10 Congratulations: Use Cases Have Been Written, and Are Imperfect The Need for Communication and Participation The NextGen POS team is writing use cases in multiple requirements work- shops over a series of short development iterations, incrementally adding to the set, and refining and adapting based on feedback. Subject matter experts, cash- iers, and programmers actively participate in the writing process. There are no intermediaries between the cashiers, other users, and the developers; rather, there is direct communication. Good, but not good enough. Written requirement specifications give the illusion of correctness; they are not. The use cases and other requirements still will not be correct—guaranteed. They will lack critical information and contain wrong 67 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT statements. The solution is not the "waterfall" process attitude of trying harder to record requirements perfect and complete at the start, although of course we do the best we can in the time available. But it will never be enough. A different approach is required. A large part of this is iterative development, but something else is needed: ongoing personal communication. Continual— daily—close participation and communication between the developers and someone who understands the domain and can make requirement decisions. Someone the programmers can walk up to in a matter of seconds and get clarifi- cation, whenever a question arises. For example, the XP practices [Beck00] con-tain an excellent recommendation: User full-time on the project, in the project room. 6.11 Write Use Cases in an Essential Ill-Free Style New and Improved! The Case for Fingerprinting Investigating and asking about goals rather than tasks and procedures encour- ages a focus on the essence of the requirements—the intent behind them. For example, during a requirements workshop, the cashier may say one of his goals is to "log in." The cashier was probably thinking of a GUI, dialog box, user ID, and password. This is a mechanism to achieve a goal, rather than the goal itself. By investigating up the goal hierarchy ("What is the goal of that goal?"), the sys- tem analyst arrives at a mechanism-independent goal: "identify myself and get authenticated," or an even higher goal: "prevent theft ...". This discovery process can open up the vision to new and improved solutions. For example, keyboards and mice with biometric readers, usually for a finger- print, are now common and inexpensive. If the goal is "identification and authentication" why not make it easy and fast, using a biometric reader on the keyboard? But properly answering that question involves some usability analy- sis work as well, such as knowing the typical users' profiles. Are their fingers covered in grease? Do they have fingers? Essential Style Writing This idea has been summarized in various use case guidelines as "keep the user interface out; focus on intent" [Cockburn0l]. Its motivation and notation has been most fully explored by Larry Constantine in the context of creating better user interfaces (UIs) and doing usability engineering [Constantine94, CL99]. Constantine calls the writing style essential when it avoids UI details and focuses on the real user intent.5 5. The term comes from "essential models" in Essential Systems Analysis |MP84|. 68 WRITE USE CASES IN AN ESSENTIAL UI-FREE STYLE In an essential writing style, the narrative is expressed at the level of the user's intentions and system's responsibilities rather than their concrete actions. They remain free of technology and mechanism details, especially those related to the UI. Write use cases in an essential style; keep the user interface out and focus on actor intent. All the previous example use cases in this chapter, such as Process Sale, were written aiming towards an essential style. Note that the dictionary defines goal as a synonym for intention [MW89], illus- trating the connection between the essential style idea of Constantine and the goal-oriented viewpoint previously stressed in this chapter. Indeed, many actor intention steps in an essential use case can also be characterized as subfunction goals. Contrasting Examples Essential Style Assume that the Manage Users use case requires identification and authentica- tion. The Constantine-inspired essential style uses the two-column format. However, it can be written in one column. Actor Intention 1. Administrator identifies self. 3. . . . System Responsibility 2. Authenticates identity. In the one-column format this is shown as: 1. Administrator identifies self. 2. System authenticates identity. 3. . . . The design solution to these intentions and responsibilities is wide open: bio-metric readers, graphical user interfaces (GUIs), and so forth. Concrete Style—Avoid During Early Requirements Work In contrast, there is a concrete use case style. In this style, user interface deci- sions are embedded in the use case text. The text may even show window screen 69 72 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT visual context diagram for the system, illustrating the external actors and how they use the system. Suggestion Draw a simple use case diagram in conjunction with an actor-goal list. A use case diagram is an excellent picture of the system context; it makes a good context diagram, that is, showing the boundary of a system, what lies outside of it, and how it gets used. It serves as a communication tool that summarizes the behavior of a system and its actors. A sample partial use case context dia- gram for the NextGen system is shown in Figure 6.2. Diagramming Suggestions Figure 6.3 offers some diagram advice. Notice the actor box with the symbol «actor». This symbol is called a UML stereotype; it is a mechanism to catego- rize an element in some way. A stereotype name is surrounded by guillemets symbols—special single-character brackets (not "«" and "»" ) most widely known by their use in French typography to indicate a quote. Figure 6.3 Notation suggestions. NextGen Process Sale . . . Cashier Show computer system actors with an alternate notation to human actors. primary actors on the left supporting actors on the right For a use case context diagram, limit the use cases to user-goal level use cases. «actor» Payment Authorization Service Figure 6.4 Alternate actor notation. A Caution on Over-Diagramming To reiterate, the important use case work is to write text, not diagram or focus on use case relationships. If an organization is spending many hours (or worse, days) working on a use case diagram and discussing use case relationships, rather than focussing on writing text, relative effort has been misplaced. 6.14 Requirements in Context and Low-Level Feature Lists As implied by the title of the book Uses Cases: Requirements in Context [GK00], a key motivation of the use case idea is the consideration and organization of requirements in the context of the goals and scenarios of using a system. That's a good thing—it improves cohesion and comprehension. However, use cases are not the only necessary requirements artifact. Some non-functional require- ments, domain rules and context, and other hard-to-place elements are better captured in the Supplementary Specification, which is described in the next chapter. One idea behind use cases is to replace detailed, low-level feature lists (which were common in traditional requirements methods) with use cases (with some exceptions). These lists tended to look as follows, usually grouped into func- tional areas: ID Feature FEAT1 .9 The system shall accept entry of item identifiers. 73 REQUIREMENTS IN CONTEXT AND LOW-LEVEL FEATURE LISTS To clarify, some prefer to highlight external computer system actors with an alternate notation, as illustrated in Figure 6.4. NextGen Process Sale «system» Payment Authorization Service ... «actor» Payment Authorization Service Some UML alternatives to illustrate external actors that are other computer systems. The class box style can be used for any actor, computer or human. Using it for computer actors provides visual distinction. Payment Authorization Service 74 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT ID Feature … … FEAT2.4 The system shall log credit payments to the accounts receivable system. Such detailed lists of low-level features are somewhat usable. However, the com- plete list is not a half-page; more likely it is dozens or a hundred pages. This leads to some drawbacks, which use cases help address. These include: • Long, detailed function lists do not relate the requirements in a cohesive context; the different functions and features increasingly appear like a dis jointed "laundry list" of items. In contrast, use cases place the requirements in the context of the stories and goals of using the system. • If both use case and detailed feature lists are used, there is duplication. More work, more volume to write and read, more consistency and synchroni zation problems. Suggestion Strive to replace detailed, low-level feature lists with use cases. High-Level System Feature Lists Are Acceptable It is common and useful to summarize system functionality with a terse, high-level feature list called system features in a Vision document. In contrast to 100 pages of low-level, detailed features, a system features list tends to include only a few dozen items. The list provides a very succinct summary of system functionality, independent of the use case view. For example: Summary of System Features • sales capture • payment authorization (credit, debit, check) • system administration for users, security, code and constants tables, and so on • automatic offline sales processing when external components fail • real-time transactions, based on industry standards, with third-party systems, including inventory, accounting, human resources, tax calculators, and payment authorization services • definition and execution of customized "pluggable" business rules at fixed, common points in the processing scenarios • … This is explored in the next chapter. USE CASES WITHIN THE UP Observe that near the end of the first iteration of elaboration, there is a second requirements workshop, during which perhaps 30% of the use cases are written in detail. This staggered requirements analysis benefits from the feedback of having built a little of the core software. The feedback includes user evaluation, testing, and improved "knowing what we don't know." That is, the act of building software rapidly surfaces assumptions and questions that need clarification. Timing of UP Artifact Creation Table 6.2 illustrates some UP artifacts, and an example of their start and refine- ment schedule. The Use-Case Model is started in inception, with perhaps only 10% of the use cases written in any detail. The majority are incrementally writ- ten over the iterations of the elaboration phase, so that by the end of elabora- tion, a large body of detailed use cases and other requirements (in the Supplementary Specification) are written, providing a realistic basis for estima- tion through to the end of the project. Discipline Artifact Iteration-> Incep. I1 Elab. El. .En Const. CL..Cn Trans. T1..T2 Business Modeling Domain Model s Use-Case Model s r Vision s r Supplementary Specification s r Requirements Glossary s r Design Model s r SW Architecture Document s Design Data Model s r Implementation Implementation Model s r r Project Management SW Development Plan s r r r Testing Test Model s r Environment Development Case s r Table 6.2 Sample UP artifacts and timing. s - start; r - refine Use Cases Within Inception The following discussion expands on the information in Table 6.1. Not all use cases are written in their fully dressed format during the inception phase. Rather, suppose there is a two-day requirements workshop during the early NextGen investigation. The earlier part of the day is spent identifying goals and stakeholders, and speculating what is in and out of scope of the project. An actor-goal-use case table is written and displayed with the computer projector. A use case context diagram is started. After a few hours, perhaps 20 user goals (and thus, user goal level use cases) are identified, including Process 77 78 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT Sale, Handle Returns, and so on. Most of the interesting, complex, or risky use cases are written in brief format; each averaging around two minutes to write. The team starts to form a high-level picture of the system's functionality. After this, 10% to 20% of the use cases that represent core complex functions, or which are especially risky in some dimension, are rewritten in a fully dressed format; the team investigates a little deeper to better comprehend the magni- tude, complexities, and hidden demons of the project, through a small sample of interesting use cases. Perhaps this means two use cases: Process Sale and Han- dle Returns. A requirements management tool that integrates with a word processor is used for the writing, and the work is displayed via a projector while the team collabo- rates on the analysis and writing. The Stakeholders and Interests lists are writ- ten for these use cases, to discover more subtle (and perhaps costly) functional and key non-function requirements—or system qualities—such as for reliability or throughput. The analysis goal is not to exhaustively complete the use cases, but spend a few hours to obtain some insight. The project sponsor needs to decide if the project is worth significant investiga- tion (that is, the elaboration phase). The inception work is not meant to do that investigation, but to obtain low-fidelity (and admittedly error-prone) insights regarding scope, risk, effort, technical feasibility, and business case, in order to decide to move forward, where to start if they do, or if to stop. Perhaps the NextGen project inception step lasts five days. The combination of the two day requirements workshop and its brief use case analysis, and other investigation during the week, lead to the decision to continue on to an elabora- tion step for the system. Use Cases Within Elaboration The following discussion expands on the information in Table 6.1. This is a phase of multiple timeboxed iterations (for example, four iterations) in which risky, high-value, or architecturally significant parts of the system are incrementally built, and the "majority" of requirements identified and clarified. The feedback from the concrete steps of programming influences and informs the team's understanding of the requirements, which are iteratively and adap-tively refined. Perhaps there is a two-day requirements workshop in each iteration—four workshops. However, not all use cases are investigated in each workshop. They are prioritized; early workshops focus on a subset of the most important use cases. Each subsequent short workshop is a time to adapt and refine the vision of the core requirements, which will be unstable in early iterations, and stabilizing in later ones. Thus, there is an iterative interplay between requirements discovery, and building parts of the software. CASE STUDY: USE CASES IN THE NEXTGEN INCEPTION PHASE During each requirements workshop, the user goals and use case list are refined. More of the use cases are written, and rewritten, in their fully dressed format. By the end of elaboration, "80-90%" of the use cases are written in detail. For the POS system with 20 user goal level use cases, 15 or more of the most complex and risky should be investigated, written, and rewritten in a fully dressed format. Note that elaboration involves programming parts of the system. At the end of this step, the NextGen team should not only have a better definition of the use cases, but some quality executable software. Use Cases Within Construction The construction step is composed of timeboxed iterations (for example, 20 itera- tions of two weeks each) that focus on completing the system, once the risky and core unstable issues have settled down in elaboration. There will still be some minor use case writing and perhaps requirements workshops, but much less so than in elaboration. By this step, the majority of core functional and non-func- tional requirements should have iteratively and adaptively stabilized. That does not mean to imply requirements are frozen or investigation finished, but the degree of change is much lower. 6.17 Case Study: Use Cases in the NextGen Inception Phase As described in the previous section, not all use cases are written in their fully dressed form during inception. The Use-Case Model at this phase of the case study could be detailed as follows: Fully Dressed Casual Brief Process Sale Handle Returns Process Rental Analyze Sales Activity Manage Security … Cash In Cash Out Manage Users Start Up Shut Down Manage System Tables … 6.18 Further Readings The most popular use-case guide, translated into several languages, is Writing Effective Use Cases [Cockburn0l].7 This has emerged with good reason as the 79 82 6 - USE-CASE MODEL: WRITING REQUIREMENTS IN CONTEXT In the UP, use case work is a requirements discipline activity which could be initiated during a requirements workshop. Figure 6.6 offers suggestions on the time and space for doing this work. Figure 6.6 Process and setting context. January February Use Case: Capture a Sale . . . Main Success Scenario: 1. ... 2. ... 3. ... Extensions: Use Case: Handle Returns . . . Main Success Scenario: 1. ... 2. ... 3. ... Extensions: When Once during inception. Short; do not try to define or polish all requirements. Several times during elaboration iterations. Where At a requirements workshop. Who Many, including, end users and developers, will play the role of requirements specifier, helping to write use cases. Led by system analyst, who is responsible for requirements definition. How: Tools Software: For use case text, use a web-enabled requirements tool that integrates with a popular word processor. For use case diagrams, a UML CASE tool. Hyperlink the use cases; present them on the project website. Hardware: Use two projectors attached to dual video cards and set the display width double, to improve the spaciousness of the drawing area or display 2 adjacenct word processor windows . Developer Customer System Analyst End User Two adjacent projections. Software Architect Chapter 7 IDENTIFYING OTHER REQUIREMENTS When ideas fail, words come in very handy. —Johann Wolfgang von Goethe Objectives Write a Supplementary Specification, Glossary, and Vision. Compare and contrast system features with use cases. Relate the Vision to other artifacts, and to iterative development. Define quality attributes. Introduction It is not sufficient to write use cases. There are other kinds of requirements that need to be identified, such as documentation, packaging, supportability, licens- ing, and so forth. These are captured in the Supplementary Specification. The Glossary captures terms and definitions; it can also play the role of a data dictionary. The Vision summarizes the "vision" of the project. It serves to tersely communi- cate the big ideas regarding why the project was proposed, what the problems are, who the stakeholders are, what they need, and what the proposed solution looks like. To quote: The Vision defines the stakeholders' view of the product to be developed, specified in terms of the stakeholders' key needs and 83 7 - IDENTIFYING OTHER REQUIREMENTS features. Containing an outline of the envisioned core require- ments, it provides the contractual basis for the more detailed technical requirements [RUP]. 7.1 NextGen POS Examples The purpose of the following examples is not to present an exhaustive Vision, Glossary, or Supplementary Specification, as some of the sections—although useful for a project—are not relevant to the learning objectives.1 The book's goal is core skills in object design, use case requirements analysis, and object-ori- ented analysis, not POS problems or Vision statements. Therefore, only some sections are briefly touched upon in order to make connections between prior and future work, highlight noteworthy issues, provide a feel for the contents, and move forward quickly. 7.2 NextGen Example: (Partial) Supplementary Specification Supplementary Specification Revision History Version Date Description Author Inception draft Jan 10, 2031 First draft. To be refined primarily during elabora- tion. Craig Larman Introduction This document is the repository of all NextGen POS requirements not captured in the use cases. Functionality (Functionality common across many use cases) Logging and Error Handling Log all errors to persistent storage. Pluggable Business Rules At various scenario points of several use cases (to be defined) support the ability to customize the func- tionality of the system with a set of arbitrary rules that execute at that point or event. Security All usage requires user authentication. 1. Scope creep is not only a problem in requirements, but in writing about requirements. 84
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved