325 23 2MB
English Pages 118 Year 1999
1/ 118
FOREWORD TO THE THIRD EDITION ................................................................................................................................... 4 FOREWORD TO THE FIRST EDITION.................................................................................................................................... 5 PREFACE ........................................................................................................................................................................... 5 Why Bother with the UML?........................................................................................................................................ 6 Structure of the Book.................................................................................................................................................. 7 Changes for the Third Edition.................................................................................................................................... 7 Acknowledgments ...................................................................................................................................................... 7 DIAGRAMS ....................................................................................................................................................................... 10 CHAPTER 1. INTRODUCTION ............................................................................................................................................ 14 What Is the UML?..................................................................................................................................................... 14 Where to Find Out More .......................................................................................................................................... 14 Ways of Using the UML ........................................................................................................................................... 15 How We Got to the UML .......................................................................................................................................... 18 Notations and Meta-Models..................................................................................................................................... 20 UML Diagrams.......................................................................................................................................................... 21 What Is Legal UML?................................................................................................................................................. 23 The Meaning of UML................................................................................................................................................ 24 UML Is Not Enough.................................................................................................................................................. 24 Where to Start with the UML.................................................................................................................................... 25 CHAPTER 2. DEVELOPMENT PROCESS ............................................................................................................................ 26 Iterative and Waterfall Processes............................................................................................................................ 26 Predictive and Adaptive Planning............................................................................................................................ 28 Agile Processes........................................................................................................................................................ 29 Rational Unified Process.......................................................................................................................................... 30 Fitting a Process to a Project................................................................................................................................... 30 Fitting the UML into a Process ................................................................................................................................ 32 Choosing a Development Process.......................................................................................................................... 35 Where to Find Out More .......................................................................................................................................... 35 CHAPTER 3. CLASS DIAGRAMS: THE ESSENTIALS ........................................................................................................... 35 Properties.................................................................................................................................................................. 36 When to Use Class Diagrams ................................................................................................................................. 38 Where to Find Out More .......................................................................................................................................... 38 Multiplicity.................................................................................................................................................................. 38 Programming Interpretation of Properties .............................................................................................................. 39 Bidirectional Associations........................................................................................................................................ 41 Operations................................................................................................................................................................. 42 Generalization........................................................................................................................................................... 43 Notes and Comments .............................................................................................................................................. 44 Dependency.............................................................................................................................................................. 44 Constraint Rules....................................................................................................................................................... 46 CHAPTER 4. SEQUENCE DIAGRAMS ................................................................................................................................. 47 Creating and Deleting Participants.......................................................................................................................... 50 Loops, Conditionals, and the Like........................................................................................................................... 51 Synchronous and Asynchronous Calls................................................................................................................... 54 When to Use Sequence Diagrams.......................................................................................................................... 54 CHAPTER 5. CLASS DIAGRAMS: ADVANCED CONCEPTS .................................................................................................. 56 Keywords .................................................................................................................................................................. 56 Classification and Generalization............................................................................................................................ 57 Multiple and Dynamic Classification........................................................................................................................ 57 Association Class ..................................................................................................................................................... 58 Template (Parameterized) Class............................................................................................................................. 61 Enumerations............................................................................................................................................................ 62 Active Class .............................................................................................................................................................. 63 Visibility ..................................................................................................................................................................... 63 Messages.................................................................................................................................................................. 64 Responsibilities......................................................................................................................................................... 64 Static Operations and Attributes.............................................................................................................................. 65 Aggregation and Composition................................................................................................................................. 65 Derived Properties.................................................................................................................................................... 66 Interfaces and Abstract Classes.............................................................................................................................. 67 Read-Only and Frozen............................................................................................................................................. 70 Reference Objects and Value Objects.................................................................................................................... 70 Qualified Associations.............................................................................................................................................. 71 CHAPTER 6. OBJECT DIAGRAMS ...................................................................................................................................... 72 2/ 118
When to Use Object Diagrams................................................................................................................................ 72 CHAPTER 7. PACKAGE DIAGRAMS ................................................................................................................................... 73 Packages and Dependencies.................................................................................................................................. 74 Package Aspects...................................................................................................................................................... 76 Implementing Packages........................................................................................................................................... 76 When to Use Package Diagrams............................................................................................................................ 77 Where to Find Out More .......................................................................................................................................... 78 CHAPTER 8. DEPLOYMENT DIAGRAMS ............................................................................................................................. 78 When to Use Deployment Diagrams....................................................................................................................... 79 CHAPTER 9. USE CASES ................................................................................................................................................. 79 Content of a Use Case............................................................................................................................................. 80 Use Case Diagrams ................................................................................................................................................. 81 Levels of Use Cases ................................................................................................................................................ 82 Use Cases and Features (or Stories) ..................................................................................................................... 82 When to Use Use Cases.......................................................................................................................................... 83 Where to Find Out More .......................................................................................................................................... 83 CHAPTER 10. STATE MACHINE DIAGRAMS ...................................................................................................................... 83 Internal Activities ...................................................................................................................................................... 85 Activity States ........................................................................................................................................................... 85 Superstates............................................................................................................................................................... 86 Concurrent States..................................................................................................................................................... 86 Implementing State Diagrams................................................................................................................................. 87 When to Use State Diagrams.................................................................................................................................. 89 Where to Find Out More .......................................................................................................................................... 89 CHAPTER 11. ACTIVITY DIAGRAMS .................................................................................................................................. 89 Decomposing an Action........................................................................................................................................... 91 And There's More..................................................................................................................................................... 93 When to Use Activity Diagrams............................................................................................................................... 93 Where to Find Out More .......................................................................................................................................... 93 Partitions ................................................................................................................................................................... 93 Signals....................................................................................................................................................................... 94 Tokens....................................................................................................................................................................... 95 Flows and Edges...................................................................................................................................................... 96 Pins and Transformations........................................................................................................................................ 96 Expansion Regions .................................................................................................................................................. 97 Flow Final.................................................................................................................................................................. 98 Join Specifications.................................................................................................................................................... 99 CHAPTER 12. COMMUNICATION DIAGRAMS ................................................................................................................... 100 When to Use Communication Diagrams............................................................................................................... 101 CHAPTER 13. COMPOSITE STRUCTURES ....................................................................................................................... 101 When to Use Composite Structures...................................................................................................................... 103 CHAPTER 14. COMPONENT DIAGRAMS .......................................................................................................................... 103 When to Use Component Diagrams ..................................................................................................................... 105 CHAPTER 15. COLLABORATIONS ................................................................................................................................... 105 When to Use Collaborations.................................................................................................................................. 107 CHAPTER 16. INTERACTION OVERVIEW DIAGRAMS ........................................................................................................ 107 When to Use Interaction Overview Diagrams ...................................................................................................... 108 CHAPTER 17. TIMING DIAGRAMS ................................................................................................................................... 109 When to Use Timing Diagrams.............................................................................................................................. 110 APPENDIX CHANGES BETWEEN UML VERSIONS ............................................................................................................ 110 Revisions to the UML............................................................................................................................................. 110 Changes in UML Distilled....................................................................................................................................... 111 Changes from UML 1.0 to 1.1 ............................................................................................................................... 112 Changes from UML 1.2 (and 1.1) to 1.3 (and 1.5)............................................................................................... 113 Changes from UML 1.3 to 1.4 ............................................................................................................................... 114 Changes from UML 1.4. to 1.5 .............................................................................................................................. 114 From UML 1.x to UML 2.0...................................................................................................................................... 114 BIBLIOGRAPHY............................................................................................................................................................... 116
3/ 118
Foreword to the Third Edition Since ancient t im es, t he m ost t alent ed archit ects and t he m ost gift ed designers have known t he law of parsim ony. Whet her it is st at ed as a paradox ( " less is m ore" ) , or a koan ( "Zen m ind is beginner's m ind" ) , it s wisdom is t im eless: Reduce everyt hing t o it s essence so t hat form harm onizes wit h funct ion. From the pyram ids t o t he Sydney Opera House, from von Neum ann archit ect ures t o UNI X and Sm allt alk, t he best archit ect s and designers have st rived t o follow this universal and et ernal principle. Recognizing t he value of shaving wit h Occam 's Razor, when I archit ect and read I seek proj ect s and books t hat adhere t o t he law of parsim ony. Consequent ly, I applaud t he book you are reading now. You m ay find m y last rem ark surprising at first . I am frequent ly associat ed wit h t he volum inous and dense specificat ions that define t he Unified Modeling Language (UML) . These specificat ions allow t ool vendors t o im plem ent t he UML and m et hodologist s t o apply it . For seven years, I have chaired large int ernat ional st andardizat ion t eam s t o specify UML 1.1 and UML 2.0, as well as several m inor revisions in bet ween. During t his tim e, the UML has m at ured in expressiveness and precision, but it has also added grat uit ous com plexit y as a result of t he st andardizat ion process. Regret t ably, st andardizat ion processes are bet t er known for design- by-com m it t ee com prom ises than parsim onious elegance. What can a UML expert fam iliar wit h t he arcane m inut iae of the specificat ion learn from Mart in's dist illat ion of UML 2.0? Quit e a bit , as can you. To st art wit h, Mart in adroit ly reduces a large and com plex language int o a pragm at ic subset t hat he has proven effect ive in his pract ice. He has resist ed t he easy rout e of t acking on addit ional pages t o t he last edit ion of his book. As t he language has grown, Mart in has kept t rue t o his goal of seeking t he " fract ion of UML that is m ost useful" and t elling you j ust t hat . The fraction he refers t o is t he m yt hical 20 percent of UML that helps you do 80 percent of your work. Capt uring and t am ing t his elusive beast is no m ean accom plishm ent ! I t is even m ore im pressive t hat Mart in achieves t his goal while writ ing in a wonderfully engaging conversat ional st yle. By sharing his opinions and anecdot es wit h us, he m akes t his book fun t o read and rem inds us t hat archit ect ing and designing syst em s should be bot h creat ive and product ive. I f we pursue t he parsim ony koan t o it s full int ent , we should find UML m odeling proj ect s t o be as enj oyable as we found finger- paint ing and drawing classes in gram m ar school. UML should be a light ning rod for our creat ivit y as well as a laser for precisely specifying syst em blueprint s so t hat t hird part ies can bid and build t hose syst em s. The lat t er is t he acid t est for any bona fide blueprint language. So, while t his m ay be a sm all book, it is not a t rivial one. You can learn as m uch from Mart in's approach t o m odeling as you can learn from his explanat ions of UML 2.0. I have enj oyed working wit h Martin t o im prove the select ion and correct ness of t he UML 2.0 language feat ures explained in t his revision. We need t o keep in m ind t hat all living languages, bot h nat ural and synt het ic, m ust evolve or perish. Mart in's choices of new feat ures, along wit h your preferences and t hose of ot her pract it ioners, are a crucial part of t he UML revision process. They keep t he language vit al and help it evolve via nat ural select ion in the m arket place. Much challenging work rem ains before m odel- driven developm ent becom es m ainst ream , but I am encouraged by books like t his t hat explain UML m odeling basics clearly and apply them pragm at ically. I hope you will learn from it as I have and will use your new insight s t o im prove your own soft ware m odeling pract ices. Cris Kobryn Chair, U2 Part ners' UML 2.0 Subm ission Team Chief Technologist , Telelogic
4/ 118
Foreword to the First Edition When we began t o craft t he Unified Modeling Language, we hoped t hat we could produce a st andard m eans of expressing design t hat would not only reflect t he best practices of indust ry, but would also help dem yst ify the process of soft ware syst em m odeling. We believed t hat the availabilit y of a st andard m odeling language would encourage m ore developers t o m odel t heir soft ware syst em s before building t hem . The rapid and widespread adopt ion of t he UML dem onst rat es t hat t he benefit s of m odeling are indeed well known t o t he developer com m unit y. The creat ion of the UML was it self an it erat ive and increm ent al process very sim ilar t o t he m odeling of a large soft ware syst em . The end result is a st andard built on, and reflect ive of, t he m any ideas and cont ribut ions m ade by num erous individuals and com panies from t he obj ect com m unit y. We began t he UML effort , but m any ot hers helped bring it t o a successful conclusion; we are grat eful for t heir cont ribut ion. Creat ing and agreeing on a st andard m odeling language is a significant challenge by it self. Educat ing t he developm ent com m unit y, and present ing t he UML in a m anner that is bot h accessible and in t he cont ext of t he soft ware developm ent process, is also a significant challenge. I n t his decept ively short book, updat ed t o reflect the m ost recent changes t o t he UML, Mart in Fowler has m ore t han m et t his challenge. I n a clear and friendly st yle, Mart in not only int roduces t he key aspect s of UML, but also clearly dem onst rat es t he role UML plays in t he developm ent process. Along the way, we are t reat ed t o abundant nugget s of m odeling insight and wisdom drawn from Mart in's 12- plus years of design and m odeling experience. The result is a book t hat has int roduced m any t housands of developers t o UML, whet t ing t heir appet it e t o further explore t he m any benefit s of m odeling wit h t his now st andard m odeling language. We recom m end t he book t o any m odeler or developer int erest ed in get t ing a first look at UML and in gaining a perspective on t he key role it plays in t he developm ent process. Grady Booch I var Jacobson Jam es Rum baugh
Preface I 've been lucky in a lot of ways in m y life; one of m y great st rokes of fort une was being in t he right place wit h the right knowledge t o writ e t he first edit ion of t his book in 1997. Back t hen, t he chaot ic world of obj ect - orient ed (OO) m odeling was just beginning t o unify under t he Unified Modeling Language ( UML) . Since t hen, t he UML has becom e t he st andard for t he graphical m odeling of soft ware, not j ust for obj ect s. My fort une is that t his book has been t he m ost popular book on the UML, selling m ore t han a quart er of a m illion copies. Well, that 's very nice for m e, but should you buy t his book? I like t o st ress t hat t his is a brief book. I t 's not int ended t o give you t he det ails on every facet of t he UML, which has grown and grown over t he years. My int ent ion is t o find that fraction of t he UML t hat is m ost useful and t ell you j ust t hat . Alt hough a bigger book gives you m ore det ail, it also t akes longer t o read. And your t im e is t he biggest invest m ent you'll m ake in a book. By keeping t his book sm all, I 've spent the t im e select ing t he best bit s t o save you from having t o do t hat select ion yourself. ( Sadly, being sm aller doesn't m ean proport ionat ely cheaper; t here is a cert ain fixed cost t o producing a qualit y t echnical book.) 5/ 118
One reason t o have t his book is t o begin t o learn about the UML. Because t his is a short book, it will quickly get you up t o speed on t he essent ials of t he UML. Wit h t hat under your belt , you can go int o m ore det ail on t he UML wit h the bigger books, such as t he User Guide [ Booch, UML user] or t he Reference Manual [ Rum baugh, UML Reference] . This book can also act as a handy reference t o t he m ost com m on part s of t he UML. Alt hough t he book doesn't cover everyt hing, it 's a lot light er to carry around t han m ost ot her UML books. I t 's also an opinionat ed book. I 've been working wit h obj ect s for a long t im e now, and I have definit e ideas about what works and what doesn't . Any book reflect s t he opinions of the aut hor, and I don't t ry t o hide m ine. So if you're looking for som et hing that has a flavor of obj ect ivit y, you m ight want t o t ry som et hing else. Alt hough m any people have t old m e that this book is a good int roduct ion t o obj ect s, I didn't writ e it wit h t hat in m ind. I f you are aft er an int roduct ion t o OO design, I suggest Craig Larm an's book [ Larm an] . Many people who are int erest ed in t he UML are using t ools. This book concent rat es on t he st andard and on convent ional usage of t he UML and doesn't get int o t he det ails of what various t ools support . Alt hough t he UML did resolve t he t ower of Babel of pre-UML not at ions, m any annoying differences rem ain bet ween what t ools show and allow when drawing UML diagram s. I don't say m uch in t his book about Model Driven Archit ecture ( MDA) . Alt hough m any people consider the t wo t o be t he sam e t hing, m any developers use the UML wit hout being int erest ed in MDA. I f you want t o learn m ore about MDA, I would st art wit h this book t o get an overview of the UML first and t hen m ove on t o a book that 's m ore specific about MDA. Alt hough t he m ain point of t his book is t he UML, I 've also added bit s of ot her m at erial about t echniques, such as CRC cards, that are valuable for OO design. The UML is j ust a part of what you need t o succeed wit h obj ect s, and I t hink that it 's im port ant t o int roduce you t o som e ot her t echniques. I n a brief book like t his, it 's im possible t o go int o det ail about how t he UML relat es t o source code, part icularly as t here is no st andard way of m aking t hat correspondence. However, I do point out com m on coding t echniques for im plem ent ing pieces of t he UML. My code exam ples are in Java and C# , as I 've found t hat t hese languages are usually t he m ost widely underst ood. Don't assum e that I prefer t hose languages; I 've done t oo m uch Sm allt alk for t hat !
Why Bother with the UML? Graphical design not at ions have been wit h us for a while. For m e, t heir prim ary value is in com m unicat ion and underst anding. A good diagram can oft en help com m unicat e ideas about a design, part icularly when you want t o avoid a lot of det ails. Diagram s can also help you underst and eit her a soft ware syst em or a business process. As part of a t eam t rying t o figure out som et hing, diagram s bot h help underst anding and com m unicat e that underst anding throughout a t eam . Alt hough t hey aren't , at least yet , a replacem ent for t ext ual program m ing languages, t hey are a helpful assist ant . Many people believe t hat in the fut ure, graphical t echniques will play a dom inant role in soft ware developm ent . I 'm m ore skept ical of t hat , but it 's cert ainly useful t o have an appreciat ion of what t hese not at ions can and can't do. Of t hese graphical not at ions, t he UML's im port ance com es from it s wide use and st andardizat ion wit hin t he OO developm ent com m unit y. The UML has becom e not only t he dom inant graphical not at ion wit hin t he OO world but also a popular t echnique in non- OO circles.
6/ 118
Structure of the Book Chapt er 1 gives an int roduct ion t o t he UML: what it is, t he different m eanings it has t o different people, and where it cam e from . Chapt er 2 t alks about soft ware process. Alt hough t his is st rict ly independent of t he UML, I t hink t hat it 's essent ial t o underst and process in order t o see t he cont ext of som et hing like t he UML. I n part icular, it 's im port ant t o underst and the role of it erat ive developm ent , which has been t he underlying approach t o process for m ost of t he OO com m unit y. I 've organized t he rest of t he book around the diagram t ypes wit hin t he UML. Chapt ers 3 and 4 discuss t he t wo m ost useful part s of the UML: class diagram s ( core) and sequence diagram s. Even t hough t his book is slim , I believe t hat you can get t he m ost value out of t he UML by using t he t echniques that I t alk about in t hese chapt ers. The UML is a large and growing beast , but you don't need all of it . Chapt er 5 goes int o det ail on t he less essent ial but st ill useful part s of class diagram s. Chapt ers 6 t hrough 8 describe t hree useful diagram s t hat shed further light on t he st ruct ure of a syst em : obj ect diagram s, package diagram s, and deploym ent diagram s. Chapt ers 9 t hrough 11 show t hree furt her useful behavioral t echniques: use cases, st at e diagram s ( alt hough officially known as st at e m achine diagram s, t hey are generally called st at e diagram s) , and act ivit y diagram s. Chapt ers 12 t hrough 17 are very brief and cover diagram s t hat are generally less im port ant , so for t hese, I 've only provided a quick exam ple and explanat ion. The inside covers sum m arize t he m ost useful part s of t he not at ion. I 've oft en heard people say t hat t hese covers are the m ost valuable part of t he book. You'll probably find it handy t o refer t o t hem as you're reading som e of t he ot her part s of t he book.
Changes for the Third Edition I f you have earlier edit ions of this book, you're probably wondering what is different and, m ore im port ant , whet her you should buy the new edit ion. The prim ary t rigger for t he third edit ion was t he appearance of UML 2. UML 2 has added a lot of new st uff, including several new diagram t ypes. Even fam iliar diagram s have a lot of new not at ion, such as int eract ion fram es in sequence diagram s. I f you want t o be aware of what 's happened but don't want t o wade t hrough the specificat ion ( I cert ainly don't recom m end t hat ! ) , this book should give you a good overview. I 've also t aken t his opport unit y t o com plet ely rewrit e m ost of t he book, bringing t he t ext and exam ples up t o dat e. I 've incorporat ed m uch t hat I 've learned in t eaching and using t he UML over t he past five years. So alt hough t he spirit of t his ult rat hin UML book is int act , m ost of t he words are new. Over the years, I 've worked hard t o keep t his book as current as is possible. As t he UML has gone t hrough it s changes, I 've done m y best t o keep pace. This book is based on t he UML 2 draft s t hat were accept ed by t he relevant com m it t ee in June 2003. I t 's unlikely t hat furt her changes will occur bet ween t hat vot e and m ore form al vot es, so I feel that UML 2 is now st able enough for m y revision t o go int o print . I 'll post inform at ion any furt her updat es on m y Web sit e ( h t t p:/ / m a rt in fow le r .com ) .
Acknowledgments 7/ 118
Over m any years, m any people have been part of t he success of t his book. My first t hanks go Cart er Shanklin and Kendall Scot t . Cart er was t he edit or at Addison-Wesley who suggest ed this book t o m e. Kendall Scot t helped m e put t oget her t he first t wo edit ions, working over t he t ext and graphics. Bet ween them , t hey pulled off t he im possible in get t ing t he first edit ion out in an im possibly short t im e, while keeping up t he high qualit y t hat people expect from Addison-Wesley. They also kept pushing out changes during the early days of the UML when not hing seem ed st able. Jim Odell has been m y m ent or and guide for m uch of t he early part of m y career. He's also been deeply involved wit h t he t echnical and personal issues of m aking opinionat ed m et hodologist s set t le t heir differences and agree t o a com m on st andard. His cont ribut ion t o t his book is bot h profound and difficult t o m easure, and I bet it 's t he sam e for t he UML t oo. The UML is a creat ure of st andards, but I 'm allergic t o st andards bodies. So t o know what 's going on, I need a net work of spies who can keep m e up t o dat e on all t he m achinat ions of t he com m it t ees. Wit hout these spies, including Conrad Bock, St eve Cook, Cris Kobryn, Jim Odell, Guus Ram ackers, and Jim Rum baugh, I would be sunk. They've all given m e useful tips and answered st upid quest ions. Grady Booch, I var Jacobson, and Jim Rum baugh are known as the Three Am igos. Despit e t he playful j ibes I 've given them over the years, they have given m e m uch support and encouragem ent wit h t his book. Never forget t hat m y j abs usually sprout from fond appreciat ion. Reviewers are t he key t o a book's qualit y, and I learned from Cart er t hat you can never have t oo m any reviewers. The reviewers of the previous edit ions of this book were Sim m i Kochhar Bhargava, Grady Booch, Eric Evans, Tom Hadfield, I var Jacobson, Ronald E. Jeffries, Joshua Kerievsky, Helen Klein, Jim Odell, Jim Rum baugh, and Vivek Salgar. The t hird edit ion also had a fine group of reviewers: Conrad Bock
Craig Larm an
Andy Carm ichael
St eve Mellor
Alist air Cockburn
Jim Odell
St eve Cook
Alan O'Callaghan
Luke Hohm ann
Guus Ram ackers
Pavel Hruby
Jim Rum baugh
Jon Kern
Tim Selt zer
Cris Kobryn All t hese reviewers spent t im e reading t he m anuscript , and every one of t hem found at least one em barrassing howler. My sincere t hanks t o all of t hem . Any howlers t hat rem ain are ent irely m y responsibilit y. I will post an errat a sheet t o t he books sect ion of m a r t in fow le r .com when I find t hem . The core t eam t hat designed and wrot e the UML specificat ion are Don Baisley, Morgan Bj örkander, Conrad Bock, St eve Cook, Philippe Desfray, Nat han Dykm an, Anders Ek, David Frankel, Eran Gery, Øyst ein Haugen, Sridhar I yengar, Cris Kobryn, Birger Møller- Pedersen, Jam es Odell, Gunnar Övergaard, Karin Palm kvist , Guus Ram ackers, Jim Rum baugh, Bran Selic, Thom as Weigert , and Larry William s. Wit hout t hem , I would have not hing t o writ e about . Pavel Hruby developed som e excellent Visio t em plat es t hat I use a lot for UML diagram s; you can get t hem at h t t p:/ / ph r u by.com . Many people have cont act ed m e on t he Net and in person wit h suggest ions and quest ions and t o point out errors. I haven't been able t o keep t rack of you all, but m y t hanks are no less sincere. 8/ 118
The people at m y favorit e t echnical bookst ore, Soft Pro in Burlingt on, Massachuset t s, let m e spend m any hours t here looking at t heir st ock t o find how people use t he UML in pract ice and fed m e good coffee while I was t here. For t he t hird edit ion, t he acquisit ion edit or was Mike Hendrickson. Kim Arney Mulcahy m anaged t he proj ect , as well as did t he layout and clean-up of t he diagram s. John Fuller, at Addison-Wesley, was t he product ion edit or, while Evelyn Pyle and Rebecca Rider helped wit h t he copyedit ing and proofreading of t he book. I t hank t hem all. Cindy has st ayed wit h m e while I persist in writ ing books. She t hen plant s t he proceeds in t he garden. My parent s st art ed m e off wit h a good educat ion, from which all else springs. Mart in Fowler Melrose, Massachuset t s h t t p:/ / m a r t in fow le r .com
9/ 118
Diagrams
10/ 118
11/ 118
12/ 118
13/ 118
Chapter 1. Introduction What I s the UML? Ways of Using t he UML How We Got t o t he UML Not at ions and Met a- Models UML Diagram s What I s Legal UML? The Meaning of UML UML I s Not Enough Where t o St art wit h the UML Where t o Find Out More
What Is the UML? The Unified Modeling Language (UML) is a fam ily of graphical not at ions, backed by single m et am odel, t hat help in describing and designing soft ware syst em s, part icularly soft ware syst em s built using t he obj ect - orient ed (OO) st yle. That 's a som ewhat sim plified definit ion. I n fact , t he UML is a few different t hings t o different people. This com es bot h from it s own hist ory and from t he different views t hat people have about what m akes an effect ive soft ware engineering process. As a result , m y t ask in m uch of t his chapt er is t o set t he scene for t his book by explaining t he different ways in which people see and use t he UML. Graphical m odeling languages have been around in t he soft ware indust ry for a long t im e. The fundam ent al driver behind t hem all is t hat program m ing languages are not at a high enough level of abst raction t o facilit at e discussions about design. Despit e t he fact that graphical m odeling languages have been around for a long t im e, t here is an enorm ous am ount of disput e in the soft ware indust ry about t heir role. These disput es play direct ly int o how people perceive t he role of t he UML it self. The UML is a relat ively open st andard, cont rolled by t he Obj ect Managem ent Group ( OMG) , an open consort ium of com panies. The OMG was form ed t o build st andards that support ed int eroperabilit y, specifically the int eroperabilit y of obj ect - orient ed syst em s. The OMG is perhaps best known for the CORBA ( Com m on Obj ect Request Broker Archit ect ure) st andards. The UML was born out of the unificat ion of the m any obj ect - orient ed graphical m odeling languages t hat t hrived in t he lat e 1980s and early 1990s. Since it s appearance in 1997, it has relegat ed t hat part icular t ower of Babel t o hist ory. That 's a service I , and m any ot her developers, am deeply t hankful for.
Where to Find Out More 14/ 118
This book is not a com plet e and definit ive reference t o t he UML, let alone OO analysis and design. A lot of words are out t here and a lot of wort hwhile t hings t o read. As I discuss t he individual t opics, I also m ent ion ot her books you should go t o for m ore in- dept h inform at ion t here. Here are som e general books on the UML and obj ect - orient ed design. As wit h all book recom m endat ions, you m ay need t o check which version of the UML t hey are writ t en for. As of June 2003, no published book uses UML 2.0, which is hardly surprising, as t he ink is barely dry on t he st andard. The books I suggest are good books, but I can't t ell whet her or when t hey will be updat ed t o t he UML 2 st andard. I f you are new t o obj ect s, I recom m end m y current favorit e int roduct ory book: [ Larm an] . The aut hor's st rong responsibilit y- driven approach t o design is wort h following. For t he conclusive word on t he UML, you should look t o t he official st andards docum ent s; but rem em ber, t hey are writ t en for consent ing m et hodologist s in the privacy of t heir own cubicles. For a m uch m ore digestible version of t he st andard, take a look at [ Rum baugh, UML Reference] . For m ore det ailed advice on obj ect - orient ed design, you'll learn m any good t hings from [ Mart in] . I also suggest t hat you read books on pat t erns for m at erial t hat will t ake you beyond t he basics. Now t hat t he m et hods war is over, pat t erns ( page 27) are where m ost of t he int erest ing m at erial about analysis and design appears.
Ways of Using the UML At the heart of t he role of t he UML in soft ware developm ent are t he different ways in which people want t o use it , differences t hat carry over from ot her graphical m odeling languages. These differences lead t o long and difficult argum ent s about how t he UML should be used. To unt angle t his, St eve Mellor and I independent ly cam e up wit h a charact erizat ion of t he t hree m odes in which people use t he UML: sket ch, blueprint , and program m ing language. By far t he m ost com m on of t he t hree, at least t o m y biased eye, is UML a s sk e tch. I n t his usage, developers use t he UML t o help com m unicat e som e aspect s of a syst em . As wit h blueprint s, you can use sket ches in a forward- engineering or reverse- engineering direct ion. For w ar d e n gin ee r in g draws a UML diagram before you writ e code, while r e ve rse en gin e e r in g builds a UML diagram from exist ing code in order t o help underst and it . The essence of sket ching is select ivit y. Wit h forward sket ching, you rough out som e issues in code you are about t o writ e, usually discussing t hem wit h a group of people on your t eam . Your aim is t o use the sket ches t o help com m unicat e ideas and alt ernat ives about what you're about t o do. You don't t alk about all t he code you are going t o work on, only im port ant issues t hat you want t o run past your colleagues first or sect ions of the design t hat you want t o visualize before you begin program m ing. Sessions like t his can be very short : a 10- m inut e session t o discuss a few hours of program m ing or a day t o discuss a 2- week it erat ion. Wit h reverse engineering, you use sket ches t o explain how som e part of a syst em works. You don't show every class, sim ply t hose t hat are int erest ing and wort h t alking about before you dig int o t he code. Because sket ching is pret t y inform al and dynam ic, you need t o do it quickly and collaborat ively, so a com m on m edium is a whit eboard. Sket ches are also useful in docum ent s, in which case t he focus is com m unicat ion rat her t han com plet eness. The tools used for sket ching are light weight drawing t ools, and oft en people aren't t oo particular about keeping t o every st rict rule of t he UML. Most UML diagram s shown in books, such as m y ot her books, are sket ches. Their em phasis is on select ive com m unicat ion rat her t han com plet e specificat ion.
15/ 118
I n cont rast , UM L a s blu e pr in t is about com plet eness. I n forward engineering, t he idea is t hat blueprint s are developed by a designer whose j ob is t o build a det ailed design for a program m er t o code up. That design should be sufficient ly com plet e in that all design decisions are laid out , and t he program m er should be able t o follow it as a pret t y st raight forward act ivit y t hat requires lit t le t hought . The designer m ay be t he sam e person as t he program m er, but usually t he designer is a m ore senior developer who designs for a t eam of program m ers. The inspirat ion for t his approach is ot her form s of engineering in which professional engineers creat e engineering drawings t hat are handed over t o const ruct ion com panies t o build. Blueprint ing m ay be used for all det ails, or a designer m ay draw blueprint s t o a part icular area. A com m on approach is for a designer t o develop blueprint - level m odels as far as int erfaces of subsyst em s but then let developers work out the det ails of im plem ent ing t hose det ails. I n reverse engineering, blueprint s aim t o convey det ailed inform at ion about the code eit her in paper docum ent s or as an int eract ive graphical browser. The blueprint s can show every det ail about a class in a graphical form that 's easier for developers t o underst and. Blueprint s require m uch m ore sophist icat ed t ools t han sket ches do in order t o handle the det ails required for t he t ask. Specialized CASE ( com put er- aided soft ware engineering) t ools fall int o t his cat egory, alt hough t he t erm CASE has becom e a dirt y word, and vendors t ry t o avoid it now. Forward- engineering t ools support diagram drawing and back it up wit h a reposit ory t o hold t he inform at ion. Reverse- engineering t ools read source code and int erpret from it int o t he reposit ory and generat e diagram s. Tools t hat can do bot h forward and reverse engineering like t his are referred t o as r oun d- t r ip t ools. Som e t ools use t he source code it self as t he reposit ory and use diagram s as a graphic viewport on t he code. These t ools tie m uch m ore closely int o program m ing and oft en int egrat e direct ly wit h program m ing edit ors. I like t o t hink of t hese as t r iple ss t ools. The line bet ween blueprint s and sket ches is som ewhat blurry, but the dist inct ion, I t hink, rest s on t he fact that sket ches are deliberat ely incom plet e, highlight ing im port ant inform at ion, while blueprint s int end t o be com prehensive, oft en wit h t he aim of reducing program m ing t o a sim ple and fairly m echanical act ivit y. I n a sound bit e, I 'd say t hat sket ches are explorat ive, while blueprint s are definit ive. As you do m ore and m ore in t he UML and t he program m ing get s increasingly m echanical, it becom es obvious t hat the program m ing should be aut om at ed. I ndeed, m any CASE t ools do som e form of code generat ion, which aut om at es building a significant part of a syst em . Event ually, however, you reach t he point at which all t he syst em can be specified in t he UML, and you reach UM L a s progr a m m in g la n gu a ge. I n t his environm ent , developers draw UML diagram s t hat are com piled direct ly t o execut able code, and t he UML becom es t he source code. Obviously, this usage of UML dem ands part icularly sophist icat ed t ooling. ( Also, t he not ions of forward and reverse engineering don't m ake any sense for t his m ode, as t he UML and source code are t he sam e t hing.)
Model Driven Arquitecture and Executable UML When people t alk about t he UML, t hey also oft en t alk about M ode l D r ive n Ar ch it ect ur e ( M DA) [ Kleppe et al.] . Essent ially, MDA is a st andard approach t o using t he UML as a program m ing language; the st andard is cont rolled by the OMG, as is t he UML. By producing a m odeling environm ent t hat conform s t o t he MDA, vendors can creat e m odels t hat can also work wit h ot her MDA- com pliant environm ent s. MDA is oft en t alked about in t he sam e breat h as t he UML because MDA uses t he UML as it s basic m odeling language. But , of course, you don't have t o be using MDA t o use t he UML. MDA divides developm ent work int o t wo m ain areas. Modelers represent a part icular applicat ion by creat ing a Pla t for m I n de pen den t M ode l ( PI M ) . The PI M is a UML m odel t hat is independent of any particular t echnology. Tools can t hen t urn a PI M int o a Pla t for m Spe cific M ode l ( PSM ) . The PSM is a m odel of a syst em t arget ed t o a specific 16/ 118
execut ion environm ent . Furt her t ools t hen t ake t he PSM and generat e code for t hat plat form . The PSM could be UML but doesn't have t o be. So if you want t o build a warehousing syst em using MDA, you would st art by creat ing a single PI M of your warehousing syst em . I f you t hen want ed this warehousing syst em t o run on J2EE and .NET, you would use som e vendor t ools t o creat e t wo PSMs: one for each plat form . Then further t ools would generat e code for t he t wo plat form s. I f t he process of going from PI M t o PSM t o final code is com plet ely aut om at ed, we have t he UML as program m ing language. I f any of t he st eps is m anual, we have blueprint s. St eve Mellor has long been act ive in t his kind of work and has recent ly used t he t erm Ex e cu t a ble UML [ Mellor and Balcer] . Execut able UML is sim ilar t o MDA but uses slight ly different t erm s. Sim ilarly, you begin wit h a plat form - independent m odel t hat is equivalent t o MDA's PI M. However, the next st ep is t o use a Model Com piler t o t urn t hat UML m odel int o a deployable syst em in a single st ep; hence, t here's no need for t he PSM. As t he t erm com piler suggest s, t his st ep is com plet ely aut om at ic. The m odel com pilers are based on reusable archet ypes. An a r ch e t ype describes how t o t ake an execut able UML m odel and t urn it int o a part icular program m ing plat form . So for t he warehousing exam ple, you would buy a m odel com piler and t wo archet ypes ( J2EE and .NET) . Run each archet ype on your execut able UML m odel, and you have your t wo versions of t he warehousing syst em . Execut able UML does not use t he full UML st andard; m any const ruct s of UML are considered t o be unnecessary and are t herefore not used. As a result , Execut able UML is sim pler t han full UML. All t his sounds good, but how realist ic is it ? I n m y view, t here are t wo issues here. First is t he quest ion of t he t ools: whet her t hey are m at ure enough t o do t he j ob. This is som et hing that changes over t im e; cert ainly, as I writ e t his, t hey aren't widely used, and I haven't seen m uch of t hem in act ion. A m ore fundam ent al issue is t he whole not ion of t he UML as a program m ing language. I n m y view, it 's wort h using t he UML as a program m ing language only if it result s in som et hing that 's significant ly m ore productive than using anot her program m ing language. I 'm not convinced that it is, based on various graphical developm ent environm ent s I 've worked wit h in the past . Even if it is m ore product ive, it st ill needs t o get a cri t ical m ass of users for it t o m ake t he m ainst ream . That 's a big hurdle in it self. Like m any old Sm allt alkers, I consider Sm allt alk t o be m uch m ore productive than current m ainst ream languages. But as Sm allt alk is now only a niche language, I don't see m any proj ect s using it . To avoid Sm allt alk's fat e, t he UML has t o be luckier, even if it is superior.
One of t he int erest ing quest ions around the UML as program m ing language is how t o m odel behavioral logic. UML 2 offers t hree ways of behavioral m odeling: int eract ion diagram s, st at e diagram s, and act ivit y diagram s. All have t heir proponent s for program m ing in. I f the UML does gain popularit y as a program m ing language, it will be int erest ing t o see which of t hese t echniques becom e successful. Anot her way in which people look at t he UML is t he range bet ween using it for concept ual and for soft ware m odeling. Most people are fam iliar wit h t he UML used for soft ware m odeling. I n t his soft w ar e pe rspe ct ive, t he elem ent s of t he UML m ap pret t y direct ly t o elem ent s in a soft ware syst em . As we shall see, t he m apping is by no m eans prescript ive, but when we use t he UML, we are t alking about soft ware elem ent s. Wit h t he con ce pt u a l pe r spe ct ive, the UML represent s a descript ion of t he concept s of a dom ain of st udy. Here, we aren't t alking about soft ware elem ent s so m uch as we are building a vocabulary t o t alk about a part icular dom ain. 17/ 118
There are no hard- and- fast rules about perspective; as it t urns out , t here's really quit e a large range of usage. Som e t ools aut om at ically t urn source code int o t he UML diagram s, t reat ing t he UML as an alt ernat ive view of t he source. That 's very m uch a soft ware perspect ive. I f you use UML diagram s t o t ry and underst and t he various m eanings of t he t erm s asset pool wit h a bunch of account ant s, you are in a m uch m ore concept ual fram e of m ind. I n previous edit ions of t his book, I split t he soft ware perspect ive int o specificat ion (int erface) and im plem ent at ion. I n practice, I found t hat it was t oo hard t o draw a precise line bet ween t he t wo, so I feel that t he dist inct ion is no longer wort h m aking a fuss about . However, I 'm always inclined t o em phasize int erface rat her than im plem ent at ion in m y diagram s. These different ways of using the UML lead t o a host of argum ent s about what UML diagram s m ean and what their relat ionship is t o t he rest of t he world. I n particular, it affect s the relat ionship bet ween t he UML and source code. Som e people hold t he view t hat t he UML should be used t o creat e a design t hat is independent of t he program m ing language t hat 's used for im plem ent at ion. Ot hers believe t hat language-independent design is an oxym oron, wit h a st rong em phasis on the m oron. Anot her difference in viewpoint s is what t he essence of t he UML is. I n m y view, m ost users of t he UML, part icularly sket chers, see t he essence of t he UML t o be t he diagram s. However, t he creat ors of t he UML see t he diagram s as secondary; t he essence of t he UML is the m et a-m odel. Diagram s are sim ply a present at ion of the m et a-m odel. This view also m akes sense t o blueprint ers and UML program m ing language users. So whenever you read anyt hing involving t he UML, it 's im port ant t o underst and t he point of view of t he aut hor. Only t hen can you m ake sense of t he oft en fierce argum ent s t hat t he UML encourages. Having said all that , I need t o m ake m y biases clear. Alm ost all t he t im e, m y use of t he UML is as sket ches. I find t he UML sket ches useful wit h forward and reverse engineering and in bot h concept ual and soft ware perspect ives. I 'm not a fan of det ailed forward- engineered blueprint s; I believe t hat it 's t oo difficult t o do well and slows down a developm ent effort . Blueprint ing t o a level of subsyst em int erfaces is reasonable, but even t hen you should expect t o change t hose int erfaces as developers im plem ent the int eract ions across t he int erface. The value of reverse- engineered blueprint s is dependent on how t he t ool works. I f it 's used as a dynam ic browser, it can be very helpful; if it generat es a large docum ent , all it does is kill t rees. I see t he UML as program m ing language as a nice idea but doubt t hat it will ever see significant usage. I 'm not convinced t hat graphical form s are m ore product ive t han t ext ual form s for m ost program m ing t asks and t hat even if t hey are, it 's very difficult for a language t o be widely accept ed. As a result of m y biases, t his book focuses m uch m ore on using t he UML for sket ching. Fort unat ely, t his m akes sense for a brief guide. I can't do j ust ice t o t he UML in it s ot her m odes in a book t his size, but a book this size m akes a good int roduct ion t o ot her books t hat can. So if you're int erest ed in t he UML in it s ot her m odes, I 'd suggest t hat you t reat t his book as an int roduct ion and m ove on t o ot her books as you need t hem . I f you're int erest ed only in sket ches, t his book m ay well be all you need.
How We Got to the UML I 'll adm it , I 'm a hist ory buff. My favorit e idea of light reading is a good hist ory book. But I also know t hat it 's not everybody's idea of fun. I t alk about hist ory here because I think t hat in m any ways, it 's hard t o underst and where t he UML is wit hout underst anding t he hist ory of how it got here.
18/ 118
I n the 1980s, obj ect s began t o m ove away from t he research labs and t ook their first st eps t oward t he " real" world. Sm allt alk st abilized int o a plat form t hat people could use, and C+ + was born. At t hat t im e, various people st art ed t hinking about obj ect - orient ed graphical design languages. The key books about obj ect - orient ed graphical m odeling languages appeared bet ween 1988 and 1992. Leading figures included Grady Booch [ Booch, OOAD] ; Pet er Coad [ Coad, OOA] , [ Coad, OOD] ; I var Jacobson (Obj ect ory) [ Jacobson, OOSE] ; Jim Odell [ Odell] ; Jim Rum baugh ( OMT) [ Rum baugh, insight s] , [ Rum baugh, OMT] ; Sally Shlaer and St eve Mellor [ Shlaer and Mellor, dat a] , [ Shlaer and Mellor, st at es] ; and Rebecca Wirfs-Brock ( Responsibilit y Driven Design) [ Wirfs- Brock] . Each of those aut hors was now inform ally leading a group of pract it ioners who liked t hose ideas. All t hese m et hods were very sim ilar, yet t hey cont ained a num ber of oft en annoying m inor differences am ong t hem . The sam e basic concept s would appear in very different not at ions, which caused confusion t o m y client s. During that heady t im e, st andardizat ion was as t alked about as it was ignored. A t eam from t he OMG t ried t o look at st andardizat ion but got only an open let t er of prot est from all t he key m et hodologist s. ( This rem inds m e of an old j oke. Quest ion: What is t he difference bet ween a m et hodologist and a t errorist ? Answer: You can negot iat e wit h a t errorist .) The cat aclysm ic event t hat first init iat ed the UML was when Jim Rum baugh left GE t o j oin Grady Booch at Rat ional ( now a part of I BM) . The Booch/ Rum baugh alliance was seen from t he beginning as one t hat could get a crit ical m ass of m arket share. Grady and Jim proclaim ed t hat " t he m et hods war is over we won," basically declaring t hat they were going t o achieve st andardizat ion "t he Microsoft way." A num ber of ot her m et hodologist s suggest ed form ing an Ant i- Booch Coalit ion. By OOPSLA '95, Grady and Jim had prepared t heir first public descript ion of t heir m erged m et hod: version 0.8 of t he Unified Met hod docum ent at ion. Even m ore significant , t hey announced t hat Rat ional Soft ware had bought Obj ect ory and t hat t herefore, I var Jacobson would be j oining t he Unified t eam . Rat ional held a well- at t ended party t o celebrat e t he release of t he 0.8 draft . ( The highlight of t he part y was t he first public display of Jim Rum baugh's singing; we all hope it 's also t he last .) The next year saw a m ore open process em erge. The OMG, which had m ost ly st ood on t he sidelines, now t ook an act ive role. Rat ional had t o incorporat e I var's ideas and also spent t im e wit h ot her part ners. More im port ant , t he OMG decided t o t ake a m aj or role. At this point , it 's im port ant t o realize why the OMG got involved. Met hodologist s, like book aut hors, like t o t hink t hat t hey are im port ant . But I don't t hink that t he scream s of book aut hors would even be heard by t he OMG. What got t he OMG involved were the scream s of t ools vendors, all of which were fright ened t hat a st andard cont rolled by Rat ional would give Rat ional t ools an unfair com pet it ive advant age. As a result , t he vendors energized t he OMG t o do som et hing about it , under t he banner of CASE t ool int eroperabilit y. This banner was im port ant , as t he OMG was all about int eroperabilit y. The idea was t o creat e a UML t hat would allow CASE t ools t o freely exchange m odels. Mary Loom is and Jim Odell chaired the init ial t ask force. Odell m ade it clear t hat he was prepared t o give up his m et hod t o a st andard, but he did not want a Rat ional-im posed st andard. I n January 1997, various organizat ions subm it t ed proposals for a m et hods st andard t o facilit at e the int erchange of m odels. Rat ional collaborat ed wit h a num ber of ot her organizat ions and released version 1.0 of t he UML docum ent at ion as their proposal, t he first anim al t o answer t o t he nam e Unified Modeling Language. Then followed a short period of arm t wist ing while t he various proposals were m erged. The OMG adopt ed t he result ing 1.1 as an official OMG st andard. Som e revisions were m ade lat er on. Revision 1.2 was ent irely cosm et ic. Revision 1.3 was m ore significant . Revision 1.4 added a num ber of det ailed concept s around com ponent s and profiles. Revision 1.5 added act ion sem ant ics. When people t alk about t he UML, t hey credit m ainly Grady Booch, I var Jacobson, and Jim Rum baugh as it s creat ors. They are generally referred t o as t he Three Am igos, alt hough wags like t o 19/ 118
drop t he first syllable of t he second word. Alt hough t hey are m ost credit ed wit h the UML, I think it som ewhat unfair t o give t hem t he dom inant credit . The UML not at ion was first form ed in t he Booch/ Rum baugh Unified Met hod. Since t hen, m uch of the work has been led by OMG com m it t ees. During these lat er st ages, Jim Rum baugh is t he only one of t he t hree t o have m ade a heavy com m it m ent . My view is that it 's t hese m em bers of t he UML com m it t ee process t hat deserve t he principal credit for t he UML.
Notations and Meta-Models The UML, in it s current st at e, defines a not at ion and a m et a- m odel. The n ot a t ion is the graphical st uff you see in m odels; it is t he graphical synt ax of t he m odeling language. For inst ance, class diagram not at ion defines how it em s and concept s, such as class, associat ion, and m ult iplicit y, are represent ed. Of course, this leads t o t he quest ion of what exact ly is m eant by an associat ion or m ult iplicit y or even a class. Com m on usage suggest s som e inform al definit ions, but m any people want m ore rigor t han t hat . The idea of rigorous specificat ion and design languages is m ost prevalent in t he field of form al m et hods. I n such t echniques, designs and specificat ions are represent ed using som e derivat ive of predicat e calculus. Such definit ions are m at hem at ically rigorous and allow no am biguit y. However, t he value of t hese definit ions is by no m eans universal. Even if you can prove that a program sat isfies a m at hem at ical specificat ion, t here is no way t o prove t hat the m at hem at ical specificat ion m eet s t he real requirem ent s of t he syst em . Most graphical m odeling languages have very lit t le rigor; t heir not at ion appeals t o int uit ion rat her t han t o form al definit ion. On t he whole, t his does not seem t o have done m uch harm . These m et hods m ay be inform al, but m any people st ill find t hem useful—and it is usefulness that count s. However, m et hodologist s are looking for ways to im prove t he rigor of m et hods wit hout sacrificing t heir usefulness. One way t o do t his is t o define a m e t a - m ode l: a diagram , usually a class diagram , t hat defines t he concept s of the language. Figure 1.1, a sm all piece of t he UML m et a-m odel, shows t he relat ionship am ong feat ures. ( The ext ract is t here t o give you a flavor of what m et a- m odels are like. I 'm not even going t o t ry t o explain it .)
Figu r e 1 .1 . A sm a ll pie ce of t h e UM L m e t a - m ode l
20/ 118
How m uch does t he m et a- m odel affect a user of t he m odeling not at ion? The answer depends m ost ly on t he m ode of usage. A sket cher usually doesn't care t oo m uch; a blueprint er should care rat her m ore. I t 's vit ally im port ant t o t hose who use the UML as a program m ing language, as it defines t he abst ract synt ax of that language. Many of t he people who are involved in t he ongoing developm ent of t he UML are int erest ed prim arily in t he m et a- m odel, part icularly as t his is im port ant t o t he usage of t he UML and a program m ing language. Not at ional issues oft en run second place, which is im port ant t o bear in m ind if you ever t ry t o get fam iliar wit h the st andards docum ent s t hem selves. As you get deeper int o t he m ore det ailed usage of t he UML, you realize t hat you need m uch m ore t han t he graphical not at ion. This is why UML t ools are so com plex. I am not rigorous in t his book. I prefer t he t radit ional m et hods pat h and appeal m ainly t o your int uit ion. That 's nat ural for a sm all book like t his writ t en by an aut hor who's inclined m ost ly t o a sket ch usage. I f you want m ore rigor, you should t urn t o m ore det ailed t om es.
UML Diagrams UML 2 describes 13 official diagram t ypes list ed in Table 1.1 and classified as indicat ed on Figure 1.2. Alt hough t hese diagram t ypes are t he way m any people approach t he UML and how I 've organized t his book, the UML's aut hors do not see diagram s as the cent ral part of the UML. As a result , t he diagram t ypes are not part icularly rigid. Oft en, you can legally use elem ent s from one diagram t ype on anot her diagram . The UML st andard indicat es t hat cert ain elem ent s are t ypically drawn on cert ain diagram t ypes, but t his is not a prescript ion.
Figu r e 1 .2 . Cla ssifica t ion of UM L dia gr a m t y pe s
21/ 118
Ta ble 1 .1 . Officia l D ia gr a m Ty pe s of t h e UM L Book Ch a pt e r s
D ia gr a m
Pu r pose
Lin e a ge
Act ivit y
11
Procedural and parallel behavior
I n UML 1
Class
3, 5
Class, feat ures, and relat ionships
I n UML 1
Com m unicat ion
12
I nt eraction bet ween obj ect s; em phasis on links
UML 1 collaborat ion diagram
Com ponent
14
St ruct ure and connect ions of com ponent s
I n UML 1
Com posit e st ruct ure
13
Runt im e decom posit ion of a class
New t o UML 2
Deploym ent
8
Deploym ent of art ifact s t o nodes
I n UML 1
22/ 118
Ta ble 1 .1 . Officia l D ia gr a m Ty pe s of t h e UM L Book Ch a pt e r s
D ia gr a m
Pu r pose
Lin e a ge
I nt eraction overview
16
Mix of sequence and act ivit y diagram
New t o UML 2
Obj ect
6
Exam ple configurat ions of inst ances
Unofficially in UML 1
Package
7
Com pile- t im e hierarchic st ruct ure
Unofficially in UML 1
Sequence
4
I nt eraction bet ween obj ect s; em phasis on sequence
I n UML 1
St at e m achine
10
How event s change an obj ect over it s life
I n UML 1
Tim ing
17
I nt eraction bet ween obj ect s; em phasis on t im ing
New t o UML 2
Use case
9
How users int eract wit h a syst em
I n UML 1
What Is Legal UML? At first blush, t his should be a sim ple question to answer: Legal UML is what is defined as well form ed in t he specificat ion. I n pract ice, however, t he answer is a bit m ore com plicat ed. An im port ant part of this quest ion is whet her t he UML has descript ive or prescript ive rules. A language wit h pr e scr ipt ive r u le s is cont rolled by an official body t hat st at es what is or isn't legal in t he language and what m eaning you give t o ut t erances in t hat language. A language wit h de scr ipt ive r u les is one in which you underst and it s rules by looking at how people use t he language in pract ice. Program m ing languages t end t o have prescript ive rules set by a st andards com m it t ee or dom inant vendor, while nat ural languages, such as English, t end t o have descript ive rules whose m eaning is set by convent ion. UML is quit e a precise language, so you m ight expect it t o have prescript ive rules. But UML is oft en considered t o be t he soft ware equivalent of t he blueprint s in ot her engineering disciplines, and these blueprint s are not prescript ive not at ions. No com m it t ee says what t he legal sym bols are on a st ruct ural engineering drawing; the not at ion has been accept ed by convent ion, sim ilarly t o a nat ural language. Sim ply having a st andards body doesn't do t he t rick eit her, because people in t he field m ay not follow everyt hing t he st andards body says; j ust ask t he French about t he Académ ie Française. I n addit ion, t he UML is so com plex t hat t he st andard is oft en open t o m ult iple int erpret at ions. Even the UML leaders who reviewed t his book would disagree on int erpret at ion of t he UML st andard. This issue is im port ant bot h for m e writ ing t his book and for you using the UML. I f you want t o underst and a UML diagram , it 's im port ant t o realize t hat underst anding t he UML st andard is not t he whole pict ure. People do adopt convent ions, bot h in t he indust ry widely and wit hin a part icular proj ect . As a result , alt hough t he UML st andard can be t he prim ary source of inform at ion on the UML, it can't be t he only one. My at t it ude is that , for m ost people, the UML has descript ive rules. The UML st andard is t he biggest single influence on what UML m eans, but it isn't t he only one. I t hink t hat t his will becom e part icularly t rue wit h UML 2, which int roduces som e not at ional convent ions t hat conflict wit h eit her UML 1's definit ion or t he convent ional usage of UML, as well as adds yet m ore com plexit y t o t he UML. I n t his book, therefore, I 'm t rying t o sum m arize t he UML as I find it : bot h t he st andards and t he convent ional usage. When I have t o m ake a dist inct ion in this book, I 'll use t he t erm con ven t ion a l use t o indicat e som et hing t hat isn't in t he st andard but that I think is widely used. For som et hing t hat conform s t o t he st andard, I 'll use the t erm s st a n da r d or nor m a t ive. ( Norm at ive is t he t erm st andards people use t o m ean a st at em ent t hat you m ust conform t o be
23/ 118
valid in the st andard. So non- norm at ive UML is a fancy way of saying t hat som et hing is st rict ly illegal according t o t he UML st andard.) When you are looking at a UML diagram , you should bear in m ind t hat a general principle in the UML is t hat any inform at ion m ay be su ppr e sse d for a part icular diagram . This suppression can occur eit her generally—hide all at t ribut es—or specifically—don't show t hese t hree classes. I n a diagram , t herefore, you can never infer anyt hing by it s absence. I f a m ult iplicit y is m issing, you cannot infer what value it m ight be. Even if t he UML m et a-m odel has a default , such as [ 1] for at t ribut es, if you don't see t he inform at ion on the diagram , it m ay be because it 's t he default or because it 's suppressed. Having said t hat , t here are som e general convent ions, such as m ult ivalued propert ies being set s. I n t he t ext , I 'll point out t hese default convent ions. I t 's im port ant t o not put t oo m uch em phasis on having legal UML if you're a sket cher or blueprint er. I t 's m ore im port ant t o have a good design for your syst em , and I would rat her have a good design in illegal UML t han a legal but poor design. Obviously, good and legal is best , but you're bet t er off put t ing your energy int o having a good design than worrying about t he arcana of UML. ( Of course, you have t o be legal in UML as program m ing language, or your program won't run properly! )
The Meaning of UML One of t he awkward issues about t he UML is t hat , alt hough t he specificat ion describes in great det ail what well- form ed UML is, it doesn't have m uch t o say about what t he UML m eans out side of t he rarefied world of the UML m et a- m odel. No form al definit ion exist s of how t he UML m aps t o any part icular program m ing language. You cannot look at a UML diagram and say exact ly what t he equivalent code would look like. However, you can get a rough idea of what t he code would look like. I n pract ice, t hat 's enough t o be useful. Developm ent t eam s oft en form t heir local convent ions for t hese, and you'll need t o be fam iliar wit h the ones in use.
UML Is Not Enough Alt hough t he UML provides quit e a considerable body of various diagram s t hat help t o define an applicat ion, it 's by no m eans a com plet e list of all the useful diagram s t hat you m ight want t o use. I n m any places, different diagram s can be useful, and you shouldn't hesit at e t o use a non-UML diagram if no UML diagram suit s your purpose. Figure 1.3, a screen flow diagram , shows t he various screens on a user int erface and how you m ove bet ween t hem . I 've seen and used these screen flow diagram s for m any years. I 've never seen m ore t han a very rough definit ion of what t hey m ean; t here isn't anyt hing like it in t he UML, yet I 've found it a very useful diagram .
Figu r e 1 .3 . An in for m a l scr e e n flow dia gr a m for pa r t of t h e w ik i ( h t t p:/ / c2 .com / cgi/ w ik i)
24/ 118
Table 1.2 shows anot her favorit e: t he decision table. Decision t ables are a good way t o show com plicat ed logical condit ions. You can do t his wit h an act ivit y diagram , but once you get beyond sim ple cases, t he t able is bot h m ore com pact and m ore clear. Again, m any form s of decision t ables are out t here. Table 1.2 divides t he t able int o t wo sect ions: condit ions above t he double line and consequences below it . Each colum n shows how a part icular com binat ion of condit ions leads t o a part icular set of consequences.
Ta ble 1 .2 . A D e cision Ta ble Prem ium cust om er
X
X
Y
Y
N
N
Priorit y order
Y
N
Y
N
Y
N
I nt ernat ional order
Y
Y
N
N
N
N
Fee
$150
$100
$70
$50
$80
$60
Alert rep
•
•
•
You'll run int o various kinds of t hese t hings in various books. Don't hesit at e t o t ry out t echniques t hat seem appropriat e for your proj ect . I f t hey work well, use them . I f not , discard t hem . ( This is, of course, t he sam e advice as for UML diagram s.)
Where to Start with the UML Nobody, not even t he creat ors of t he UML, underst and or use all of it . Most people use a sm all subset of t he UML and work wit h t hat . You have t o find t he subset of t he UML t hat works for you and your colleagues. I f you are st art ing out , I suggest t hat you concent rat e first on t he basic form s of class diagram s and sequence diagram s. These are the m ost com m on and, in m y view, t he m ost useful diagram t ypes.
25/ 118
Once you've got t he hang of t hose, you can st art using som e of t he m ore advanced class diagram not at ion and t ake a look at t he ot her diagram s t ypes. Experim ent wit h the diagram s and see how helpful they are t o you. Don't be afraid t o drop any that don't seem be useful t o your work.
Chapter 2. Development Process As I 've already m ent ioned, t he UML grew out of a bunch of OO analysis and design m et hods. To som e ext ent , all of t hem m ixed a graphical m odeling language wit h a process t hat described how t o go about developing soft ware. I nt erest ingly, as t he UML was form ed, t he various players discovered t hat alt hough t hey could agree on a m odeling language, t hey m ost cert ainly could not agree on a process. As a result , they agreed t o leave any agreem ent on process unt il lat er and t o confine t he UML t o being a m odeling language. The t it le of t his book is UML Dist illed, so I could have safely ignored process. However, I don't believe that m odeling t echniques m ake any sense wit hout knowing how they fit int o a process. The way you use t he UML depends a lot on the st yle of process you use. As a result , I t hink t hat it 's im port ant t o t alk about process first so t hat you can see t he cont ext for using t he UML. I 'm not going t o go int o great det ail on any part icular process; I sim ply want t o give you enough inform at ion t o see t his cont ext and point ers t o where you can find out m ore. When you hear people discuss t he UML, you oft en hear t hem t alk about t he Rat ional Unified Process ( RUP) . RUP is one process—or, m ore st rict ly, a process fram ework—t hat you can use wit h t he UML. But ot her t han t he com m on involvem ent of various people from Rat ional and t he nam e "unified," it doesn't have any special relat ionship t o t he UML. The UML can be used wit h any process. RUP is a popular approach and is discussed on page 25.
Iterative and Waterfall Processes One of t he biggest debat es about process is t hat bet ween wat erfall and it erat ive st yles. The t erm s oft en get m isused, part icularly as it erat ive is seen as fashionable, while t he wat erfall process seem s t o wear plaid t rousers. As a result , m any proj ects claim t o do it erat ive developm ent but are really doing wat erfall. The essent ial difference bet ween t he t wo is how you break up a proj ect int o sm aller chunks. I f you have a proj ect t hat you t hink will t ake a year, few people are com fort able t elling t he t eam t o go away for a year and t o com e back when done. Som e breakdown is needed so t hat people can approach t he problem and t rack progress. The w a t er fa ll st yle breaks down a proj ect based on activit y. To build soft ware, you have t o do cert ain act ivit ies: requirem ent s analysis, design, coding, and t est ing. Our 1- year proj ect m ight t hus have a 2-m ont h analysis phase, followed by a 4- m ont h design phase, followed by a 3-m ont h coding phase, followed by a 3-m ont h t est ing phase. The it e r a t ive st yle breaks down a proj ect by subset s of funct ionalit y. You m ight t ake a year and break it int o 3-m ont h it erat ions. I n the first it erat ion, you'd t ake a quart er of t he requirem ent s and do t he com plet e soft ware life cycle for t hat quart er: analysis, design, code, and t est . At t he end of t he first it erat ion, you'd have a syst em t hat does a quart er of t he needed funct ionalit y. Then you'd do a second it erat ion so t hat at t he end of 6 m ont hs, you'd have a syst em t hat does half t he funct ionalit y.
26/ 118
Of course, the above is a sim plified descript ion, but it is the essence of t he difference. I n pract ice, of course, som e im purit ies leak int o t he process. Wit h wat erfall developm ent , t here is usually som e form of form al handoff bet ween each phase, but t here are oft en backflows. During coding, som et hing m ay com e up that causes you t o revisit the analysis and design. You cert ainly should not assum e t hat all design is finished when coding begins. I t 's inevit able t hat analysis and design decisions will have t o be revisit ed in lat er phases. However, t hese backflows are except ions and should be m inim ized as m uch as possible. Wit h it erat ion, you usually see som e form of explorat ion act ivit y before t he t rue it erat ions begin. At t he very least , t his will get a high- level view of t he requirem ent s: at least enough t o break t he requirem ent s down int o t he it erat ions t hat will follow. Som e high- level design decisions m ay occur during explorat ion t oo. At t he ot her end, alt hough each it erat ion should produce product ion- ready int egrat ed soft ware, it oft en doesn't quit e get t o t hat point and needs a st abilizat ion period t o iron out the last bugs. Also, som e act ivit ies, such as user t raining, are left t o t he end. You m ay well not put t he syst em int o product ion at t he end of each it erat ion, but be of product ion qualit y. Oft en, however, you can put t he syst em int o product ion int ervals; t his is good because you get value from t he syst em earlier and you get feedback. I n t his sit uat ion, you oft en hear of a proj ect having m ult iple r e le ase s, broken down int o several it er a t ions.
t he syst em should at regular bet t er- qualit y each of which is
I t erat ive developm ent has com e under m any nam es: increm ent al, spiral, evolut ionary, and j acuzzi spring t o m ind. Various people m ake distinctions am ong t hem , but t he dist inct ions are neit her widely agreed on nor t hat im port ant com pared to t he it erat ive/ wat erfall dichot om y. You can have hybrid approaches. [ McConnell] describes the st a ge d de live r y life cycle whereby analysis and high-level design are done first , in a wat erfall st yle, and t hen t he coding and t est ing are divided up int o it erat ions. Such a proj ect m ight have 4 m ont hs of analysis and design followed by four 2- m ont h it erat ive builds of t he syst em . Most writ ers on soft ware process in the past few years, especially in t he obj ect - orient ed com m unit y, dislike t he wat erfall approach. Of the m any reasons for t his, t he m ost fundam ent al is t hat it 's very difficult t o t ell whet her t he proj ect is t ruly on t rack wit h a wat erfall process. I t 's t oo easy t o declare vict ory wit h early phases and hide a schedule slip. Usually, the only way you can really t ell whet her you are on t rack is t o produce t est ed, int egrat ed soft ware. By doing this repeat edly, an it erat ive st yle gives you bet t er warning if som et hing is going awry. For t hat reason alone, I st rongly recom m end that proj ect s do not use a pure wat erfall approach. You should at least use st aged delivery, if not a m ore pure it erat ive t echnique. The OO com m unit y has long been in favor of it erat ive developm ent , and it 's safe t o say t hat pret t y m uch everyone involved in building the UML is in favor of at least som e form of it erat ive developm ent . My sense of indust rial pract ice is that wat erfall developm ent is st ill t he m ore com m on approach, however. One reason for t his is what I refer t o as pseudoit erat ive developm ent : People claim t o be doing it erat ive developm ent but are in fact doing wat erfall. Com m on sym pt om s of this are: • •
" We are doing one analysis it erat ion followed by t wo design it erat ions. . . ." " This it erat ion's code is very buggy, but we'll clean it up at the end."
I t is part icularly im port ant t hat each it erat ion produces t est ed, int egrat ed code t hat is as close to product ion qualit y as possible. Test ing and int egrat ion are t he hardest act ivit ies t o est im at e, so it 's im port ant not t o have an open- ended act ivit y like t hat at t he end of t he proj ect . The t est should be t hat any it erat ion t hat 's not scheduled t o be released could be released wit hout subst ant ial ext ra developm ent work. A com m on t echnique wit h it erat ions is t o use t im e box in g. This forces an it erat ion t o be a fixed lengt h of tim e. I f it appears t hat you can't build all you int ended t o build during an it erat ion, you m ust decide t o slip som e functionalit y from the it erat ion; you m ust not slip the dat e of t he it erat ion. 27/ 118
Most proj ect s t hat use it erat ive developm ent use t he sam e it erat ion lengt h t hroughout t he proj ect ; t hat way, you get a regular rhyt hm of builds. I like t im e boxing because people usually have difficult y slipping funct ionalit y. By pract icing slipping funct ion regularly, t hey are in a bet t er posit ion to m ake an int elligent choice at a big release bet ween slipping a dat e and slipping funct ion. Slipping funct ion during it erat ions is also effect ive at helping people learn what t he real requirem ent s priorit ies are. One of t he m ost com m on concerns about it erat ive developm ent is the issue of rework. I t erat ive developm ent explicit ly assum es t hat you will be reworking and delet ing exist ing code during t he lat er it erat ions of a proj ect . I n m any dom ains, such as m anufact uring, rework is seen as a wast e. But soft ware isn't like m anufact uring; as a result , it oft en is m ore efficient t o rework existing code t han t o pat ch around code t hat was poorly designed. A num ber of t echnical pract ices can great ly help m ake rework be m ore efficient . •
•
•
Au t om at e d r e gre ssion t e st s help by allowing you t o quickly det ect any defect s t hat m ay have been int roduced when you are changing t hings. The xUnit fam ily of t esting fram eworks is a part icularly valuable t ool for building aut om at ed unit t est s. St arting wit h t he original JUnit h t t p:/ / j un it .or g, t here are now port s t o alm ost every language im aginable ( see h t t p:/ / w w w .x pr ogra m m in g.com / soft w a re .h t m ) . A good rule of t hum b is t hat t he size of your unit t est code should be about t he sam e size as your product ion code. Re fact or in g is a disciplined t echnique for changing exist ing soft ware [ Fowler, refact oring] . Refact oring works by using a series of sm all behavior- preserving t ransform at ions t o t he code base. Many of these t ransform at ions can be aut om at ed (see h t t p:/ / w w w .r efa ctor in g.com ) . Con t in u ou s in t e gra t ion keeps a t eam in sync t o avoid painful int egrat ion cycles [ Fowler and Foem m el] . At the heart of t his lies a fully aut om at ed build process t hat can be kicked off aut om at ically whenever any m em ber of t he t eam checks code int o t he code base. Developers are expect ed t o check in daily, so aut om at ed builds are done m any t im es a day. The build process includes running a large block of aut om at ed regression t est s so t hat any inconsist encies are caught quickly so t hey can be fixed easily.
All t hese t echnical pract ices have been popularized recent ly by Ext rem e Program m ing [ Beck] , alt hough t hey were used before and can, and should, be used whet her or not you use XP or any ot her agile process.
Predictive and Adaptive Planning One reason t hat t he wat erfall endures is t he desire for predict abilit y in soft ware developm ent . Not hing is m ore frust rat ing t han not having a clear idea how m uch it will cost t o build som e soft ware and how long it will t ake t o build it . A predict ive approach looks t o do work early in the proj ect in order t o yield a great er underst anding of what has t o be done lat er. This way, you can reach a point where the lat t er part of t he proj ect can be est im at ed wit h a reasonable degree of accuracy. Wit h pr e dict ive pla n n in g, a proj ect has t wo st ages. The first st age com es up wit h plans and is difficult t o predict , but t he second st age is m uch m ore predict able because the plans are in place. This isn't necessarily a black- and- whit e affair. As t he proj ect goes on, you gradually get m ore predict abilit y. And even once you have a predictive plan, t hings will go wrong. You sim ply expect t hat t he deviat ions becom e less significant once a solid plan is in place. However, there is a considerable debat e about whet her m any soft ware proj ect s can ever be predict able. At the heart of t his quest ion is requirem ent s analysis. One of t he unique sources of com plexit y in soft ware proj ect s is t he difficult y in underst anding t he requirem ent s for a soft ware syst em . The m aj orit y of soft ware proj ect s experience significant r e qu ire m e n ts chu r n : changes in requirem ent s in t he lat er st ages of t he proj ect . These changes shat t er t he foundat ions of a 28/ 118
predictive plan. You can com bat t hese changes by freezing the requirem ent s early on and not perm it t ing changes, but t his runs t he risk of delivering a syst em t hat no longer m eet s t he needs of it s users. This problem leads t o t wo very different react ions. One rout e is t o put m ore effort int o t he requirem ent s process it self. This way, you m ay get a m ore accurat e set of requirem ent s, which will reduce t he churn. Anot her school cont ends t hat requirem ent s churn is unavoidable, t hat it 's t oo difficult for m any proj ect s t o st abilize requirem ent s sufficient ly t o use a predict ive plan. This m ay be eit her owing t o t he sheer difficult y of envisioning what soft ware can do or because m arket condit ions force unpredict able changes. This school of t hought advocat es a da pt ive pla n n in g, whereby predict ivit y is seen as an illusion. I nst ead of fooling ourselves wit h illusory predict abilit y, we should face t he realit y of const ant change and use a planning approach t hat t reat s change as a const ant in a soft ware proj ect . This change is cont rolled so t hat t he proj ect delivers the best soft ware it can; but alt hough t he proj ect is cont rollable, it is not predict able. The difference bet ween a predict ive proj ect and an adapt ive proj ect surfaces in m any ways t hat people t alk about how t he proj ect goes. When people t alk about a proj ect t hat 's doing well because it 's going according t o plan, t hat 's a predict ive form of t hinking. You can't say " according t o plan" in an adapt ive environm ent , because the plan is always changing. This doesn't m ean that adapt ive proj ect s don't plan; t hey usually plan a lot , but the plan is t reat ed as a baseline t o assess t he consequences of change rat her than as a prediction of t he fut ure. Wit h a predict ive plan, you can develop a fixed-price/ fixed- scope cont ract . Such a cont ract says exact ly what should be built , how m uch it will cost , and when it will be delivered. Such fixing isn't possible wit h an adapt ive plan. You can fix a budget and a t im e for delivery, but you can't fix what funct ionalit y will be delivered. An adapt ive cont ract assum es t hat t he users will collaborat e wit h t he developm ent t eam t o regularly reassess what funct ionalit y needs t o be built and will cancel t he proj ect if progress ends up being t oo slow. As such, an adapt ive planning process can be fixed price/ variable scope. Nat urally, t he adapt ive approach is less desirable, as anyone would prefer great er predict abilit y in a soft ware proj ect . However, predict abilit y depends on a precise, accurat e, and st able set of requirem ent s. I f you cannot st abilize your requirem ent s, t he predict ive plan is based on sand and t he chances are high that t he proj ect goes off course. This leads t o t wo im port ant pieces of advice. 1. Don't m ake a predict ive plan unt il you have precise and accurat e requirem ent s and are confident that t hey won't significant ly change. 2. I f you can't get precise, accurat e, and st able requirem ent s, use an adapt ive planning st yle. Predict ivit y and adapt ivit y feed int o t he choice of life cycle. An adapt ive plan absolut ely requires an it erat ive process. Predict ive planning can be done eit her way, alt hough it 's easier t o see how it works wit h wat erfall or a st aged delivery approach.
Agile Processes I n the past few years, there's been a lot of int erest in agile soft ware processes. Agile is an um brella t erm t hat covers m any processes t hat share a com m on set of values and principles as defined by t he Manifest o of Agile Soft ware Developm ent ( ht t p:/ / a gile M an ife sto.or g) . Exam ples of t hese processes are Ext rem e Program m ing (XP) , Scrum , Feat ure Driven Developm ent ( FDD) , Cryst al, and DSDM ( Dynam ic Syst em s Developm ent Met hod). I n t erm s of our discussion, agile processes are st rongly adapt ive in t heir nat ure. They are also very m uch people- orient ed processes. Agile approaches assum e t hat t he m ost im port ant fact or in a proj ect 's success is t he qualit y of the people on t he proj ect and how well t hey work t oget her in hum an t erm s. Which process they use and which t ools t hey use are st rictly second- order effect s. 29/ 118
Agile m et hods t end t o use short , t im e- boxed it erat ions, m ost oft en of a m ont h or less. Because t hey don't at t ach m uch weight t o docum ent s, agile approaches disdain using t he UML in blueprint m ode. Most use the UML in sket ch m ode, wit h a few advocat ing using it as a program m ing language. Agile processes t end t o be low in ce re m on y . A high- cerem ony, or heavyweight , process has a lot of docum ent s and cont rol point s during t he proj ect . Agile processes consider t hat cerem ony m akes it harder t o m ake changes and works against the grain of t alent ed people. As a result , agile processes are oft en charact erized as ligh t w e igh t. I t 's im port ant t o realize t hat t he lack of cerem ony is a consequence of adapt ivit y and people orient at ion rat her t han a fundam ent al propert y.
Rational Unified Process Alt hough t he Rat ional Unified Process ( RUP) is independent of the UML, t he t wo are oft en t alked about t oget her. So I t hink it 's wort h saying a few t hings about it here. Alt hough RUP is called a process, it act ually is a process fram ework, providing a vocabulary and loose st ruct ure t o t alk about processes. When you use RUP, t he first t hing you need t o do is choose a de ve lopm e n t ca se: t he process you are going t o use in t he proj ect . Developm ent cases can vary widely, so don't assum e t hat your developm ent case will look t hat m uch like any ot her developm ent case. Choosing a developm ent case needs som eone early on who is very fam iliar wit h RUP: som eone who can t ailor RUP for a part icular proj ect 's needs. Alt ernat ively, t here is a growing body of packaged developm ent cases t o st art from . What ever the developm ent case, RUP is essent ially an it erat ive process. A wat erfall st yle isn't com pat ible wit h t he philosophy of RUP, alt hough sadly it 's not uncom m on t o run int o proj ect s t hat use a wat erfall-st yle process and dress it up in RUP's clot hes. All RUP proj ect s should follow four phases. 1. I n ce pt ion m akes an init ial evaluat ion of a proj ect . Typically in incept ion, you decide whet her t o com m it enough funds t o do an elaborat ion phase. 2. Ela bor a t ion ident ifies the prim ary use cases of t he proj ect and builds soft ware in it erat ions in order t o shake out t he archit ect ure of t he syst em . At t he end of elaborat ion, you should have a good sense of t he requirem ent s and a skelet al working syst em t hat act s as t he seed of developm ent . I n part icular, you should have found and resolved the m aj or risks t o t he proj ect . 3. Con st r uct ion cont inues t he building process, developing enough funct ionalit y t o release. 4. Tr a nsit ion includes various lat e-st age act ivit ies t hat you don't do it erat ively. These m ay include deploym ent int o t he dat a cent er, user t raining, and t he like. There's a fair am ount of fuzziness bet ween t he phases, especially bet ween elaborat ion and const ruct ion. For som e, t he shift t o const ruction is t he point at which you can m ove int o a predict ive planning m ode. For ot hers, it m erely indicat es t he point at which you have a broad vision of requirem ent s and an archit ecture that you t hink is going t o last the rest of t he proj ect . Som et im es, RUP is referred t o as the Unified Process ( UP) . This is usually done by organizat ions t hat wish t o use t he t erm inology and overall st yle of RUP wit hout using the licensed product s of Rat ional Soft ware. You can t hink of RUP as Rat ional's product offering based on t he UP, or you can t hink of RUP and UP as t he sam e t hing. Eit her way, you'll find people who agree wit h you.
Fitting a Process to a Project Soft ware proj ect s differ great ly from one anot her. The way you go about soft ware developm ent depends on m any fact ors: t he kind of syst em you're building, t he t echnology you're using, t he size and dist ribut ion of t he t eam , the nat ure of t he risks, t he consequences of failure, t he working st yles
30/ 118
of t he t eam , and t he cult ure of t he organizat ion. As a result , you should never expect t here t o be a one- size- fit s- all process t hat will work for all proj ect s. Consequent ly, you always have t o adapt a process t o fit your part icular environm ent . One of the first things you need t o do is look at your proj ect and consider which processes seem close t o a fit . This should give you a short list of processes t o consider. You should then consider what adapt at ions you need t o m ake t o fit t hem t o your proj ect . You have t o be som ewhat careful wit h t his. Many processes are difficult t o fully appreciat e unt il you've worked wit h t hem . I n t hese cases, it 's oft en wort h using t he process out of t he box for a couple of it erat ions unt il you learn how it works. Then you can st art m odifying t he process. I f from the beginning you are m ore fam iliar wit h how a process works, you can m odify it from t he beginning. Rem em ber t hat it 's usually easier t o st art wit h t oo lit t le and add t hings t han it is t o st art wit h t oo m uch and t ake t hings away.
Patterns The UML t ells you how t o express an obj ect - orient ed design. Pat t erns look, inst ead, at the result s of t he process: exam ple designs. Many people have com m ent ed t hat proj ect s have problem s because the people involved were not aware of designs t hat are well known t o t hose wit h m ore experience. Pat t erns describe com m on ways of doing t hings and are collect ed by people who spot repeat ing t hem es in designs. These people t ake each t hem e and describe it so t hat ot her people can read t he pat t ern and see how t o apply it . Let 's look at an exam ple. Say t hat you have som e obj ect s running in a process on your deskt op and t hat t hey need t o com m unicat e wit h ot her obj ect s running in anot her process. Perhaps t his process is also on your deskt op; perhaps it resides elsewhere. You don't want t he obj ect s in your syst em t o have t o worry about finding ot her obj ect s on t he net work or execut ing rem ot e procedure calls. What you can do is creat e a proxy obj ect wit hin your local process for t he rem ot e obj ect . The proxy has t he sam e int erface as t he rem ot e obj ect . Your local obj ect s t alk t o t he proxy, using the usual in- process m essage sends. The proxy t hen is responsible for passing any m essages on t o t he real obj ect , wherever it m ight reside. Proxies are a com m on t echnique used in net works and elsewhere. People have a lot of experience using proxies, knowing how t hey can be used, what advant ages t hey can bring, t heir lim it at ions, and how t o im plem ent them . Met hods books like t his one don't discuss t his knowledge; all t hey discuss is how you can diagram a proxy, alt hough useful, is not as useful as discussing t he experience involving proxies. I n the early 1990s, som e people began t o capt ure t his experience. They form ed a com m unit y int erest ed in writ ing pat t erns. These people sponsor conferences and have produced several books. The m ost fam ous pat t erns book t o em erge from t his group is [ Gang of Four] , which discusses 23 design pat t erns in det ail. I f you want t o know about proxies, t his book spends t en pages on t he subj ect , giving det ails about how t he obj ect s work t oget her, t he benefit s and lim it at ions of t he pat t ern, com m on variat ions, and im plem ent at ion t ips. A pat t ern is m uch m ore t han a m odel. A pat t ern m ust also include t he reason why it is t he way it is. I t is oft en said t hat a pat t ern is a solut ion t o a problem . The pat t ern m ust ident ify t he problem clearly, explain why it solves t he problem , and also explain the circum st ances under which t he pat t ern works and doesn't work. Pat t erns are im port ant because t hey are the next st age beyond underst anding t he basics of a language or a m odeling t echnique. Pat t erns give you a series of solut ions and also 31/ 118
show you what m akes a good m odel and how you go about const ruct ing a m odel. Pat t erns t each by exam ple. When I st art ed out , I wondered why I had t o invent t hings from scrat ch. Why didn't I have handbooks t o show m e how t o do com m on things? The pat t erns com m unit y is t rying t o build t hese handbooks. There are now m any pat t erns books out t here, and t hey vary great ly in qualit y. My favorit es are [ Gang of Four] , [ POSA1] , [ POSA2] , [ Core J2EE Pat t erns] , [ Pont ] , and wit h suit able im m odest y [ Fowler, AP] and [ Fowler, P of EAA] . You can also t ake a look at t he pat t erns hom e page: h t t p:/ / w w w .h illside .n et / pa t t e r ns.
However confident you are wit h your process when you begin, it 's essent ial t o learn as you go along. I ndeed, one of t he great benefit s of it erat ive developm ent is that it support s frequent process im provem ent . At the end of each it erat ion, conduct an it e ra t ion r e t r ospe ct ive, whereby t he t eam assem bles t o consider how t hings went and how they can be im proved. A couple of hours is plent y if your it erat ions are short . A good way t o do t his is t o m ake a list wit h t hree cat egories: 1. Keep: t hings t hat worked well t hat you want t o ensure you cont inue t o do 2. Problem s: areas t hat aren't working well 3. Try: changes t o your process t o im prove it You can st art each it erat ion ret rospect ive aft er t he first by reviewing the it em s from t he previous session and seeing how t hings have changed. Don't forget t he list of t hings t o keep; it 's im port ant t o keep t rack of things that are working. I f you don't do t hat , you can lose a sense of perspect ive on t he proj ect and pot ent ially st op paying at t ent ion t o winning pract ices. At the end of a proj ect or at a m aj or release, you m ay want t o consider a m ore form al pr oj e ct r e t r ospe ct ive t hat will last a couple of days; see h t t p:/ / w w w .re t r ospe ct ives.com / and [ Kert h] for m ore det ails. One of m y biggest irrit at ions is how organizat ions consist ent ly fail t o learn from t heir own experience and end up m aking expensive m ist akes t im e and t im e again.
Fitting the UML into a Process When t hey look at graphical m odeling languages, people usually t hink of t hem in t he cont ext of a wat erfall process. A wat erfall process usually has docum ent s t hat act as t he handoffs bet ween analysis, design, and coding phases. Graphical m odels can oft en form a m aj or part of t hese docum ent s. I ndeed, m any of t he st ruct ured m et hods from t he 1970s and 1980s t alk a lot about analysis and design m odels like t his. Whet her or not you use a wat erfall approach, you st ill do t he act ivit ies of analysis, design, coding, and t est ing. You can run an it erat ive proj ect wit h 1- week it erat ions, wit h each week a m iniwat erfall. Using the UML doesn't necessarily im ply developing docum ent s or feeding a com plex CASE t ool. Many people draw UML diagram s on whit eboards only during a m eet ing t o help com m unicat e t heir ideas.
Requirements Analysis The act ivit y of requirem ent s analysis involves t rying t o figure out what t he users and cust om ers of a soft ware effort want t he syst em t o do. A num ber of UML t echniques can com e in handy here: • •
Use cases, which describe how people int eract wit h t he syst em . A class diagram drawn from t he concept ual perspect ive, which can be a good way of building up a rigorous vocabulary of t he dom ain. 32/ 118
• •
An act ivit y diagram , which can show t he work flow of t he organizat ion, showing how soft ware and hum an act ivit ies int eract . An act ivit y diagram can show t he cont ext for use cases and also t he det ails of how a com plicat ed use case works. A st at e diagram , which can be useful if a concept has an int erest ing life cycle, wit h various st at es and event s t hat change t hat st at e.
When working in requirem ent s analysis, rem em ber t hat t he m ost im port ant thing is com m unicat ion wit h your users and cust om ers. Usually, they are not soft ware people and will be unfam iliar wit h t he UML or any ot her t echnique. Even so, I 've had success using t hese t echniques wit h nont echnical people. To do t his, rem em ber t hat it 's im port ant t o keep t he not at ion t o a m inim um . Don't int roduce anyt hing t hat specific t o t he soft ware im plem ent at ion. Be prepared t o break t he rules of the UML at any t im e if it helps you com m unicat e bet t er. The biggest risk wit h using the UML in analysis is t hat you draw diagram s that t he dom ain expert s don't fully underst and. A diagram t hat isn't underst ood by t he people who know t he dom ain is worse than useless; all it does is breed a false sense of confidence for t he developm ent t eam .
Design When you are doing design, you can get m ore technical wit h your diagram s. You can use m ore not at ion and be m ore precise about your not at ion. Som e useful t echniques are • • • • •
Class diagram s from a soft ware perspect ive. These show t he classes in t he soft ware and how t hey int errelat e. Sequence diagram s for com m on scenarios. A valuable approach is t o pick t he m ost im port ant and int erest ing scenarios from t he use cases and use CRC cards or sequence diagram s t o figure out what happens in t he soft ware. Package diagram s t o show t he large-scale organizat ion of t he soft ware. St at e diagram s for classes wit h com plex life hist ories. Deploym ent diagram s t o show t he physical layout of t he soft ware.
Many of t hese sam e t echniques can be used t o docum ent soft ware once it 's been writ t en. This m ay help people find t heir way around t he soft ware if t hey have t o work on it and are not fam iliar wit h t he code. Wit h a wat erfall life cycle, you would do t hese diagram s and act ivit ies as part of t he phases. The end- of- phase docum ent s usually include the appropriat e UML diagram s for t hat activit y. A wat erfall st yle usually im plies t hat t he UML is used as a blueprint . I n an it erat ive st yle, t he UML diagram s can be used in eit her a blueprint or a sket ch st yle. Wit h a blueprint , t he analysis diagram s will usually be built in the it erat ion prior t o t he one t hat builds t he funct ionalit y. Each it erat ion doesn't st art from scrat ch; rat her, it m odifies t he exist ing body of docum ent s, highlight ing t he changes in t he new it erat ion. Blueprint designs are usually done early in t he it erat ion and m ay be done in pieces for different bit s of funct ionalit y t hat are t arget ed for t he it erat ion. Again, it erat ion im plies m aking changes t o an existing m odel rat her t han building a new m odel each t im e. Using the UML in sket ch m ode im plies a m ore fluid process. One approach is t o spend a couple of days at t he beginning of an it erat ion, sket ching out the design for t hat it erat ion. You can also do short design sessions at any point during t he it erat ion, set t ing up a quick m eet ing for half an hour whenever a developer st art s t o t ackle a nont rivial funct ion. Wit h a blueprint , you expect t he code im plem ent at ion t o follow t he diagram s. A change from t he blueprint is a deviat ion that needs review from the designers who did t he blueprint . A sket ch is usually t reat ed m ore as a first cut at t he design; if, during coding, people find t hat t he sket ch isn't exact ly right , t hey should feel free t o change t he design. The im plem ent ors have t o use t heir j udgm ent as t o whet her t he change needs a wider discussion t o underst and t he full ram ificat ions.
33/ 118
One of m y concerns wit h blueprint s is m y own observat ion t hat it 's very hard t o get t hem right , even for a good designer. I oft en find t hat m y own designs do not survive cont act wit h coding int act . I st ill find UML sket ches useful, but I don't find t hat t hey can be t reat ed as absolut es. I n bot h m odes, it m akes sense t o explore a num ber of design alt ernat ives. I t 's usually best t o explore alt ernat ives in sket ch m ode so t hat you can quickly generat e and change t he alt ernat ives. Once you pick a design t o run wit h, you can eit her use t hat sket ch or det ail it int o a blueprint .
Documentation Once you have built t he soft ware, you can use the UML t o help docum ent what you have done. For t his, I find UML diagram s useful for get t ing an overall underst anding of a syst em . I n doing t his, however, I should st ress t hat I do not believe in producing det ailed diagram s of t he whole syst em . To quot e Ward Cunningham [ Cunningham ] : Carefully select ed and well- writ t en m em os can easily substit ut e for t radit ional com prehensive design docum ent at ion. The lat t er rarely shines except in isolat ed spot s. Elevat e t hose spot s . . . and forget about t he rest . ( p. 384) I believe t hat det ailed docum ent at ion should be generat ed from t he code—like, for inst ance, JavaDoc. You should writ e addit ional docum ent at ion t o highlight im port ant concept s. Think of t hese as com prising a first st ep for t he reader before he or she goes int o t he code-based det ails. I like t o st ruct ure t hese as prose docum ent s, short enough t o read over a cup of coffee, using UML diagram s t o help illust rat e t he discussion. I prefer t he diagram s as sket ches t hat highlight t he m ost im port ant part s of t he syst em . Obviously, t he writ er of t he docum ent needs t o decide what is im port ant and what isn't , but t he writ er is m uch bet t er equipped t han t he reader t o do t hat . A package diagram m akes a good logical road m ap of t he syst em . This diagram helps m e underst and t he logical pieces of t he syst em and see t he dependencies and keep t hem under cont rol. A deploym ent diagram ( see Chapt er 8) , which shows t he high- level physical pict ure, m ay also prove useful at t his st age. Wit hin each package, I like t o see a class diagram . I don't show every operat ion on every class. I show only t he im port ant feat ures t hat help m e underst and what is in t here. This class diagram act s as a graphical t able of cont ent s. The class diagram should be support ed by a handful of int eract ion diagram s t hat show t he m ost im port ant int eract ions in the syst em . Again, select ivit y is im port ant here; rem em ber t hat , in t his kind of docum ent , com prehensiveness is t he enem y of com prehensibilit y. I f a class has com plex life-cycle behavior, I draw a st at e m achine diagram (see Chapt er 10) t o describe it . I do t his only if t he behavior is sufficient ly com plex, which I find doesn't happen oft en. I 'll oft en include som e im port ant code, writ t en in a lit erat e program st yle. I f a part icularly com plex algorit hm is involved, I 'll consider using an act ivit y diagram ( see Chapt er 11) but only if it gives m e m ore underst anding t han t he code alone. I f I find concept s that are com ing up repeat edly, I use pat t erns ( page 27) t o capt ure t he basic ideas. One of t he m ost im port ant t hings t o docum ent is t he design alt ernat ives you didn't t ake and why you didn't do t hem . That 's oft en t he m ost forgot t en but m ost useful piece of ext ernal docum ent at ion you can provide.
Understanding Legacy Code The UML can help you figure out a gnarly bunch of unfam iliar code in a couple of ways. Building a sket ch of key fact s can act as a graphical not e- t aking m echanism t hat helps you capt ure im portant inform at ion as you learn about it . Sket ches of key classes in a package and t heir key int eract ions can help clarify what 's going on. 34/ 118
Wit h m odern t ools, you can generat e det ailed diagram s for key part s of a syst em . Don't use these t ools t o generat e big paper report s; inst ead, use t hem t o drill int o key areas as you are exploring t he code it self. A part icularly nice capabilit y is t hat of generat ing a sequence diagram t o see how m ult iple obj ect s collaborat e in handling a com plex m et hod.
Choosing a Development Process I 'm st rongly in favor of it erat ive developm ent processes. As I 've said in t his book before: You should use it erat ive developm ent only on proj ect s t hat you want t o succeed. Perhaps t hat 's a bit glib, but as I get older, I get m ore aggressive about using it erat ive developm ent . Done well, it is an essent ial t echnique, one you can use t o expose risk early and to obt ain bet t er cont rol over developm ent . I t is not t he sam e as having no m anagem ent , alt hough t o be fair, I should point out t hat som e have used it t hat way. I t does need t o be well planned. But it is a solid approach, and every OO developm ent book encourages using it —for good reason. You should not be surprised t o hear t hat as one t he aut hors of t he Manifest o for Agile Soft ware Developm ent , I 'm very m uch a fan of agile approaches. I 've also had a lot of posit ive experiences wit h Ext rem e Program m ing, and cert ainly you should consider it s pract ices very seriously.
Where to Find Out More Books on soft ware process have always been com m on, and t he rise of agile soft ware developm ent has led t o m any new books. Overall, m y favorit e book on process in general is [ McConnell] . He gives a broad and pract ical coverage of m any of t he issues involved in soft ware developm ent and a long list of useful practices. From t he agile com m unit y, [ Cockburn, agile] and [ Highsm it h] provide a good overview. For a lot of good advice about applying t he UML in an agile way, see [ Am bler] . One of t he m ost popular agile m et hods is Ext rem e Program m ing ( XP) , which you can delve int o via such Web sit es as h t t p:/ / x pr ogra m m in g.com and h t t p:/ / w w w .e x tr e m e progr a m m in g.or g. XP has spawned m any books, which is why I now refer t o it as t he form erly light weight m et hodology. The usual st art ing point is [ Beck] . Alt hough it 's writ t en for XP, [ Beck and Fowler] gives m ore det ails on planning an it erat ive proj ect . Much of t his is also covered by t he ot her XP books, but if you're int erest ed only in t he planning aspect , t his would be a good choice. For m ore inform at ion on t he Rat ional Unified Process, m y favorit e int roduction is [ Krucht en] .
Chapter 3. Class Diagrams: The Essentials I f som eone were t o com e up t o you in a dark alley and say, " Psst , wanna see a UML diagram ?" that diagram would probably be a class diagram . The m aj orit y of UML diagram s I see are class diagram s. The class diagram is not only widely used but also subj ect t o t he great est range of m odeling concept s. Alt hough t he basic elem ent s are needed by everyone, the advanced concept s are used less oft en. Therefore, I 've broken m y discussion of class diagram s int o t wo part s: t he essent ials ( t his chapt er) and the advanced ( Chapt er 5) .
35/ 118
A class dia gr a m describes t he t ypes of obj ect s in t he syst em and t he various kinds of st at ic relat ionships t hat exist am ong them . Class diagram s also show t he propert ies and operat ions of a class and t he const raint s t hat apply t o t he way obj ect s are connect ed. The UML uses the t erm fe a t ur e as a general t erm t hat covers propert ies and operat ions of a class. Figure 3.1 shows a sim ple class m odel that would not surprise anyone who has worked wit h order processing. The boxes in the diagram are classes, which are divided int o t hree com part m ent s: t he nam e of t he class ( in bold) , it s at t ribut es, and it s operat ions. Figure 3.1 also shows t wo kinds of relat ionships bet ween classes: associat ions and generalizat ions.
Figu r e 3 .1 . A sim ple cla ss dia gr a m
Properties Pr oper t ie s represent st ructural feat ures of a class. As a first approxim at ion, you can t hink of propert ies as corresponding t o fields in a class. The realit y is rat her involved, as we shall see, but t hat 's a reasonable place t o st art . Propert ies are a single concept , but t hey appear in t wo quit e dist inct not at ions: at t ribut es and associat ions. Alt hough t hey look quit e different on a diagram , t hey are really t he sam e t hing.
Attributes The a t t r ibu t e not at ion describes a propert y as a line of t ext wit hin the class box it self. The full form of an at t ribut e is:
36/ 118
visibility name: type multiplicity = default {property-string} An exam ple of t his is:
- name: String [1] = "Untitled" {readOnly} Only t he name is necessary. • • • • • •
This visibility m arker indicat es whet her t he at t ribut e is public ( + ) or privat e ( - ) ; I 'll discuss ot her visibilit ies on page 83. The name of t he at t ribut e—how the class refers t o t he at t ribut e—roughly corresponds t o t he nam e of a field in a program m ing language. The type of t he at t ribut e indicat es a rest rict ion on what kind of obj ect m ay be placed in t he at t ribut e. You can t hink of this as t he t ype of a field in a program m ing language. I 'll explain multiplicity on page 38. The default value is t he value for a newly creat ed obj ect if t he at t ribut e isn't specified during creat ion. The {property-string} allows you t o indicat e addit ional properties for t he at t ribut e. I n t he exam ple, I used {readOnly} t o indicat e t hat client s m ay not m odify t he propert y. I f t his is m issing, you can usually assum e t hat t he at t ribut e is m odifiable. I 'll describe ot her propert y st rings as we go.
Associations The ot her way t o not at e a propert y is as an associat ion. Much of t he sam e inform at ion t hat you can show on an at t ribut e appears on an associat ion. Figures 3.2 and 3.3 show t he sam e propert ies represent ed in t he t wo different not at ions.
Figu r e 3 .2 . Sh ow in g pr ope r t ie s of a n or de r a s a t t r ibu t e s
Figu r e 3 .3 . Sh ow in g pr ope r t ie s of a n or de r a s a ssocia t ion s
An a ssocia t ion is a solid line bet ween t wo classes, direct ed from t he source class t o t he t arget class. The nam e of t he propert y goes at t he t arget end of t he associat ion, t oget her wit h it s m ult iplicit y. The t arget end of t he associat ion links t o t he class t hat is t he t ype of t he propert y.
37/ 118
Alt hough m ost of t he sam e inform at ion appears in bot h not at ions, som e it em s are different . I n part icular, associat ions can show m ult iplicit ies at bot h ends of t he line. Wit h t wo not at ions for t he sam e t hing, t he obvious question is, Why should you use one or the ot her? I n general, I t end t o use at t ribut es for sm all t hings, such as dat es or Booleans—in general, value t ypes ( page 73) —and associat ions for m ore significant classes, such as cust om ers and orders. I also t end t o prefer t o use class boxes for classes t hat are significant for t he diagram , which leads t o using associat ions, and at t ribut es for t hings less im port ant for t hat diagram . The choice is m uch m ore about em phasis t han about any underlying m eaning.
When to Use Class Diagrams Class diagram s are t he backbone of t he UML, so you will find yourself using t hem all t he t im e. This chapt er covers t he basic concept s; Chapt er 5 discusses m any of t he advanced concept s. The t rouble wit h class diagram s is t hat t hey are so rich, they can be overwhelm ing t o use. Here are a few t ips. • • •
Don't t ry t o use all t he not at ions available t o you. St art wit h t he sim ple st uff in t his chapt er: classes, associat ions, at t ribut es, generalizat ion, and const raint s. I nt roduce ot her not at ions from Chapt er 5 only when you need t hem . I 've found concept ual class diagram s very useful in exploring t he language of a business. For t his t o work, you have t o work hard on keeping soft ware out of the discussion and keeping t he not at ion very sim ple. Don't draw m odels for everyt hing; inst ead, concent rat e on the key areas. I t is bet t er t o have a few diagram s t hat you use and keep up t o dat e t han t o have m any forgot t en, obsolet e m odels.
The biggest danger wit h class diagram s is t hat you can focus exclusively on st ruct ure and ignore behavior. Therefore, when drawing class diagram s t o underst and soft ware, always do t hem in conj unct ion wit h som e form of behavioral t echnique. I f you're going well, you'll find yourself swapping bet ween t he t echniques frequent ly.
Where to Find Out More All t he general UML books I m ent ioned in Chapt er 1 t alk about class diagram s in m ore det ail. Dependency m anagem ent is a crit ical feat ure of larger proj ect s. The best book on t his t opic is [ Mart in] .
Multiplicity The m u lt iplicit y of a propert y is an indicat ion of how m any obj ect s m ay fill t he propert y. The m ost com m on m ult iplicit ies you will see are • • •
1 ( An order m ust have exact ly one cust om er.) 0 ..1 (A corporat e cust om er m ay or m ay not have a single sales rep.) * ( A cust om er need not place an Order and t here is no upper lim it t o t he num ber of Orders a Cust om er m ay place—zero or m ore orders.)
More generally, m ult iplicit ies are defined wit h a lower bound and an upper bound, such as 2..4 for players of a gam e of canast a. The lower bound m ay be any posit ive num ber or zero; t he upper is 38/ 118
any posit ive num ber or * ( for unlim it ed) . I f t he lower and upper bounds are the sam e, you can use one num ber; hence, 1 is equivalent t o 1..1. Because it 's a com m on case, * is short for 0..* . I n at t ribut es, you com e across various t erm s t hat refer t o t he m ult iplicit y. • • • •
Opt ion a l im plies a lower bound of 0. M a n da t or y im plies a lower bound of 1 or possibly m ore. Sin gle - va lu e d im plies an upper bound of 1. M u lt iva lu e d im plies an upper bound of m ore than 1: usually * .
I f I have a m ult ivalued propert y, I prefer t o use a plural form for it s nam e. By default , t he elem ent s in a m ult ivalued m ult iplicit y form a set , so if you ask a cust om er for it s orders, t hey do not com e back in any order. I f the ordering of t he orders in associat ion has m eaning, you need t o add {ordered} t o t he associat ion end. I f you want t o allow duplicat es, add {nonunique}. ( I f you want t o explicit ly show t he default , you can use {unordered} and {unique}.) You m ay also see collect ion- orient ed nam es, such as {bag} for unordered, nonunique. UML 1 allowed discont inuous m ult iplicit ies, such as 2, 4 (m eaning 2 or 4, as in cars in t he days before m inivans) . Discont inuous m ult iplicit ies weren't very com m on and UML 2 rem oved t hem . The default m ult iplicit y of an at t ribut e is [ 1] . Alt hough t his is t rue in t he m et a-m odel, you can't assum e t hat an at t ribut e in a diagram t hat 's m issing a m ult iplicit y has a value of [ 1] , as t he diagram m ay be suppressing the m ult iplicit y inform at ion. As a result , I prefer t o explicit ly st at e a [ 1] m ult iplicit y if it 's im port ant .
Programming Interpretation of Properties As wit h anyt hing else in t he UML, there's no one way t o int erpret propert ies in code. The m ost com m on soft ware represent at ion is t hat of a field or propert y of your program m ing language. So t he Order Line class from Figure 3.1 would correspond t o som et hing like t he following in Java:
public class OrderLine... private int quantity; private Money price; private Order order; private Product product I n a language like C# , which has propert ies, it would correspond t o:
public class OrderLine ... public int Quantity; public Money Price; public Order Order; public Product Product; Not e t hat an at t ribut e t ypically corresponds t o public propert ies in a language t hat support s propert ies but t o privat e fields in a language t hat does not . I n a language wit hout propert ies, you m ay see t he fields exposed through accessor ( get t ing and set t ing) m et hods. A read- only at t ribut e will have no set t ing m et hod ( wit h fields) or set act ion (for propert ies) . Not e t hat if you don't give a nam e for a propert y, it 's com m on t o use t he nam e of the t arget class. Using privat e fields is a very im plem ent at ion-focused int erpret at ion of t he diagram . A m ore int erface- orient ed int erpret at ion m ight inst ead concent rat e on t he get t ing m et hods rat her than the
39/ 118
underlying dat a. I n this case, we m ight see t he Order Line's at t ribut es corresponding t o t he following m et hods:
public class OrderLine... private int quantity; private Product product; public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public Money getPrice() { return product.getPrice().multiply(quantity); } I n this case, t here is no dat a field for price; inst ead, it 's a com put ed value. But as far as client s of t he Order Line class are concerned, it looks t he sam e as a field. Client s can't t ell what is a field and what is com put ed. This inform at ion hiding is t he essence of encapsulat ion. I f an at t ribut e is m ult ivalued, t his im plies that t he dat a concerned is a collect ion. So an Order class would refer t o a collection of Order Lines. Because t his m ult iplicit y is ordered, that collect ion m ust be ordered, (such as a List in Java or an I List in .NET) . I f t he collect ion is unordered, it should, st rict ly, have no m eaningful order and t hus be im plem ent ed wit h a set , but m ost people im plem ent unordered at t ribut es as list s as well. Som e people use arrays, but the UML im plies an unlim it ed upper bound, so I alm ost always use a collect ion for dat a st ruct ure. Mult ivalued propert ies yield a different kind of int erface t o single-valued propert ies ( in Java) :
class Order { private Set lineItems = new HashSet(); public Set getLineItems() { return Collections.unmodifiableSet(lineItems); } public void addLineItem (OrderItem arg) { lineItems.add (arg); } public void removeLineItem (OrderItem arg) { lineItems.remove(arg); } I n m ost cases, you don't assign t o a m ult ivalued propert y; inst ead, you updat e wit h add and rem ove m et hods. I n order t o cont rol it s Line I t em s propert y, t he order m ust cont rol m em bership of that collect ion; as a result , it shouldn't pass out t he naked collect ion. I n this case, I used a prot ection proxy t o provide a read- only wrapper t o t he collect ion. You can also provide a nonupdat able it erat or or m ake a copy. I t 's okay for client s t o m odify the m em ber obj ect s, but t he client s shouldn't direct ly change t he collect ion it self. Because m ult ivalued at t ribut es im ply collect ions, you alm ost never see collect ion classes on a class diagram . You would show t hem only in very low level im plem ent at ion diagram s of collect ions t hem selves. You should be very afraid of classes t hat are not hing but a collect ion of fields and their accessors. Obj ect - orient ed design is about providing obj ect s t hat are able t o do rich behavior, so t hey shouldn't be sim ply providing dat a t o ot her obj ect s. I f you are m aking repeat ed calls for dat a by using accessors, t hat 's a sign t hat som e behavior should be m oved t o t he obj ect t hat has t he dat a. These exam ples also reinforce t he fact that t here is no hard- and-fast correspondence bet ween t he UML and code, yet there is a sim ilarit y. Wit hin a proj ect t eam , t eam convent ions will lead t o a closer correspondence. 40/ 118
Whet her a propert y is im plem ent ed as a field or as a calculat ed value, it represent s som et hing an obj ect can always provide. You shouldn't use a propert y t o m odel a t ransient relat ionship, such as an obj ect t hat is passed as a param et er during a m et hod call and used only wit hin t he confines of t hat int eract ion.
Bidirectional Associations The associat ions we've looked at so far are called unidirect ional associat ions. Anot her com m on kind of associat ion is a bidirect ional associat ion, such as Figure 3.4.
Figu r e 3 .4 . A bidir e ct ion a l a ssocia t ion
A bidirect ional associat ion is a pair of propert ies t hat are linked t oget her as inverses. The Car class has propert y owner:Person[1], and t he Person class has a propert y cars:Car[*]. ( Not e how I nam ed t he cars propert y in t he plural form of t he propert y's t ype, a com m on but non-norm at ive convent ion.) The inverse link bet ween t hem im plies t hat if you follow bot h propert ies, you should get back t o a set that cont ains your st art ing point . For exam ple, if I begin wit h a part icular MG Midget , find it s owner, and t hen look at it s owner's cars, t hat set should cont ain t he Midget that I st art ed from . As an alt ernat ive t o labeling an associat ion by a propert y, m any people, part icularly if t hey have a dat a- m odeling background, like t o label an associat ion by using a verb phrase ( Figure 3.5) so t hat t he relat ionship can be used in a sent ence. This is legal and you can add an arrow t o t he associat ion t o avoid am biguit y. Most obj ect m odelers prefer t o use a propert y nam e, as t hat corresponds bet t er t o responsibilit ies and operat ions.
Figu r e 3 .5 . Usin g a v e r b ph r a se t o na m e a n a ssocia t ion
Som e people nam e every associat ion in som e way. I choose t o nam e an associat ion only when doing so im proves underst anding. I 've seen t oo m any associat ions wit h such nam es as "has" or "is relat ed t o." I n Figure 3.4, t he bidirect ional nat ure of t he associat ion is m ade obvious by t he n a viga bilit y a r r ow s at bot h ends of t he associat ion. Figure 3.5 has no arrows; t he UML allows you t o use t his form eit her t o indicat e a bidirect ional associat ion or when you aren't showing navigabilit y. My preference is t o use t he double-headed arrow of Figure 3.4 when you want t o m ake it clear t hat you have a bidirect ional associat ion. I m plem ent ing a bidirectional associat ion in a program m ing language is oft en a lit t le t ricky because you have t o be sure that bot h properties are kept synchronized. Using C# , I use code along these lines t o im plem ent a bidirect ional associat ion:
class Car... 41/ 118
public Person Owner { get {return _owner;} set { if (_owner != null) _owner.friendCars().Remove(this); _owner = value; if (_owner != null) _owner.friendCars().Add(this); } } private Person _owner; ... class Person ... public IList Cars { get {return ArrayList.ReadOnly(_cars);} } public void AddCar(Car arg) { arg.Owner = this; } private IList _cars = new ArrayList(); internal IList friendCars() { //should only be used by Car.Owner return _cars; } .... The prim ary t hing is t o let one side of t he associat ion—a single- valued side, if possible—cont rol the relat ionship. For t his t o work, t he slave end ( Person) needs t o leak t he encapsulat ion of it s dat a t o t he m ast er end. This adds t o t he slave class an awkward m et hod, which shouldn't really be t here, unless t he language has fine- grained access cont rol. I 've used t he nam ing convent ion of " friend" here as a nod t o C+ + , where the m ast er's set t er would indeed be a friend. Like m uch propert y code, t his is pret t y boilerplat e st uff, which is why m any people prefer t o use som e form of code generat ion t o produce it . I n concept ual m odels, navigabilit y isn't an im port ant issue, so I don't show any navigabilit y arrows on concept ual m odels.
Operations Ope r a t ion s are t he act ions that a class knows t o carry out . Operat ions m ost obviously correspond t o t he m et hods on a class. Norm ally, you don't show t hose operat ions t hat sim ply m anipulat e propert ies, because t hey can usually be inferred. The full UML synt ax for operat ions is:
visibility name (parameter-list) : return-type {property-string} • • • • •
This visibility m arker is public ( + ) or privat e ( - ) ; ot hers on page 83. The name is a st ring. The parameter-list is t he list of param et ers for t he operat ion. The return-type is t he t ype of t he ret urned value, if there is one. The property-string indicat es propert y values t hat apply t o t he given operat ion.
The param et ers in t he param et er list are not at ed in a sim ilar way t o at t ribut es. The form is:
direction name: type = default value • •
The name, type, and default value are t he sam e as for at t ribut es. The direction indicat es whet her t he param et er is input ( in) , out put ( out) or bot h ( inout) . I f no direct ion is shown, it 's assum ed t o be in. 42/ 118
An exam ple operat ion on account m ight be:
+ balanceOn (date: Date) : Money Wit h concept ual m odels, you shouldn't use operat ions t o specify t he int erface of a class. I nst ead, use them t o indicat e t he principal responsibilit ies of t hat class, perhaps using a couple of words sum m arizing a CRC responsibilit y ( page 65) . I oft en find it useful t o dist inguish bet ween operat ions t hat change the st at e of t he syst em and t hose t hat don't . UML defines a qu e r y as an operat ion t hat get s a value from a class wit hout changing t he syst em st at e—in ot her words, wit hout side effect s.You can m ark such an operat ion wit h t he propert y st ring {query}. I refer t o operat ions t hat do change st at e as m odifier s, also called com m ands. St rict ly, t he difference bet ween query and m odifiers is whet her t hey change t he observable st at e [ Meyer] . The observable st at e is what can be perceived from the out side. An operat ion t hat updat es a cache would alt er t he int ernal st at e but would have no effect t hat 's observable from t he out side. I find it helpful t o highlight queries, as you can change t he order of execut ion of queries and not change t he syst em behavior. A com m on convent ion is t o t ry t o writ e operat ions so t hat m odifiers do not ret urn a value; t hat way, you can rely on t he fact t hat operat ions t hat ret urn a value are queries. [ Meyer] refers t o t his as t he Com m and-Query separat ion principle. I t 's som et im es awkward t o do t his all t he tim e, but you should do it as m uch as you can. Ot her t erm s you som et im es see are get t ing m et hods and set t ing m et hods. A ge t t in g m e t h od ret urns a value from a field ( and does not hing else) . A se t t in g m e th od put s a value int o a field ( and does not hing else) . From t he out side, a client should not be able t o t ell whet her a query is a get t ing m et hod or a m odifier is a set t ing m et hod. Knowledge of get t ing and set t ing m et hods is ent irely int ernal t o t he class. Anot her dist inct ion is bet ween operat ion and m et hod. An oper a t ion is som et hing that is invoked on an obj ect —t he procedure declarat ion—whereas a m e t h od is t he body of a procedure. The t wo are different when you have polym orphism . I f you have a supert ype wit h t hree subt ypes, each of which overrides t he supert ype's getPrice operat ion, you have one operat ion and four m et hods t hat im plem ent it . People usually use t he t erm s operat ion and m et hod int erchangeably, but there are tim es when it is useful t o be precise about t he difference.
Generalization A t ypical exam ple of gen e r a liza t ion involves t he personal and corporat e cust om ers of a business. They have differences but also m any sim ilarit ies. The sim ilarit ies can be placed in a general Cust om er class (t he supert ype) , wit h Personal Cust om er and Corporat e Cust om er as subt ypes. This phenom enon is also subj ect t o various int erpret at ions at t he various perspect ives of m odeling. Concept ually, we can say that Corporat e Cust om er is a subt ype of Cust om er if all inst ances of Corporat e Cust om er are also, by definit ion, instances of Cust om er. A Corporat e Cust om er is t hen a special kind of Cust om er. The key idea is t hat everyt hing we say about a Cust om er—associat ions, at t ribut es, operat ions—is t rue also for a Corporat e Cust om er. Wit h a soft ware perspect ive, t he obvious int erpret at ion is inherit ance: The Corporat e Cust om er is a subclass of Cust om er. I n m ainst ream OO languages, t he subclass inherit s all t he feat ures of t he superclass and m ay override any superclass m et hods. An im port ant principle of using inherit ance effect ively is su bst it u t a bilit y. I should be able t o subst it ut e a Corporat e Cust om er wit hin any code t hat requires a Cust om er, and everyt hing should work fine. Essent ially, this m eans t hat if I writ e code assum ing I have a Cust om er, I can freely use any subt ype of Cust om er. The Corporat e Cust om er m ay respond t o cert ain com m ands different ly 43/ 118
from anot her Cust om er, using polym orphism , but t he caller should not need t o worry about t he difference. ( For m ore on this, see t he Liskov Subst it ut ion Principle ( LSP) in [ Mart in] .) Alt hough inherit ance is a powerful m echanism , it brings in a lot of baggage that isn't always needed t o achieve substit ut abilit y. A good exam ple of t his was in the early days of Java, when m any people didn't like t he im plem ent at ion of t he built -in Vect or class and want ed t o replace it wit h som et hing light er. However, the only way they could produce a class t hat was subst it ut able for Vect or was t o subclass it , and t hat m eant inherit ing a lot of unwant ed dat a and behavior. Many ot her m echanism s can be used t o provide subst it ut able classes. As a result , m any people like t o different iat e bet ween subt yping, or int erface inherit ance, and subclassing, or im plem ent at ion inherit ance. A class is a su bt ype if it is subst it ut able for it s supert ype, whet her or not it uses inherit ance. Su bcla ssin g is used as a synonym for regular inherit ance. Many ot her m echanism s are available that allow you t o have subt yping wit hout subclassing. Exam ples are im plem ent ing an int erface ( page 69) and m any of t he st andard design pat t erns [ Gang of Four] .
Notes and Comments Not es are com m ent s in the diagram s. Not es can st and on t heir own, or t hey can be linked wit h a dashed line t o t he elem ent s t hey are com m ent ing ( Figure 3.6) . They can appear in any kind of diagram .
Figu r e 3 .6 . A n ot e is u se d a s a com m e n t on on e or m or e dia gr a m e le m e n t s
The dashed line can som et im es be awkward because you can't posit ion exactly where t his line ends. So a com m on convent ion is t o put a very sm all open circle at the end of t he line. Som et im es, it 's useful t o have an in-line com m ent on a diagram elem ent . You can do t his by prefixing the t ext wit h t wo dashes: - - .
Dependency A de pen de ncy exist s bet ween t wo elem ent s if changes t o t he definit ion of one elem ent ( t he su pplie r) m ay cause changes t o t he ot her (t he clie n t ) . Wit h classes, dependencies exist for various reasons: One class sends a m essage t o anot her; one class has anot her as part of it s dat a; one class m ent ions anot her as a param et er t o an operat ion. I f a class changes it s int erface, any m essage sent t o t hat class m ay no longer be valid. As com put er syst em s grow, you have t o worry m ore and m ore about cont rolling dependencies. I f dependencies get out of cont rol, each change t o a syst em has a wide ripple effect as m ore and m ore t hings have t o change. The bigger t he ripple, t he harder it is t o change anyt hing. The UML allows you t o depict dependencies bet ween all sort s of elem ent s. You use dependencies whenever you want t o show how changes in one elem ent m ight alt er ot her elem ent s. Figure 3.7 shows som e dependencies t hat you m ight find in a m ult ilayered applicat ion. The Benefit s Window class—a user int erface, or pre sen t a t ion class—is dependent on t he Em ployee class: a 44/ 118
dom a in obj ect t hat capt ures t he essent ial behavior of t he syst em —in this case, business rules. This m eans t hat if the em ployee class changes it s int erface, the Benefit s Window m ay have t o change.
Figu r e 3 .7 . Ex a m ple de pe n de n cie s
The im port ant t hing here is that the dependency is in only one direct ion and goes from t he present at ion class t o t he dom ain class. This way, we know t hat we can freely alt er t he Benefit s Window wit hout t hose changes having any effect on t he Em ployee or ot her dom ain obj ect s. I 've found t hat a st rict separat ion of present at ion and dom ain logic, wit h t he present at ion depending on t he dom ain but not vice versa, has been a valuable rule for m e t o follow. A second not able thing from this diagram is t hat t here is no direct dependency from t he Benefit s Window t o t he t wo Dat a Gat eway classes. I f t hese classes change, t he Em ployee class m ay have t o change. But if t he change is only t o t he im plem ent at ion of the Em ployee class, not it s int erface, t he change st ops there. The UML has m any variet ies of dependency, each wit h part icular sem ant ics and keywords. The basic dependency t hat I 've out lined here is the one I find t he m ost useful, and I usually use it wit hout keywords. To add m ore det ail, you can add an appropriat e keyword ( Table 3.1) . The basic dependency is not a t ransit ive relat ionship. An exam ple of a t ra n sit ive relat ionship is t he " larger beard" relat ionship. I f Jim has a larger beard t han Grady, and Grady has a larger beard than I var, we can deduce t hat Jim has a larger beard t han I var. Som e kind of dependencies, such as subst it ut e, are t ransit ive, but in m ost cases t here is a significant difference bet ween direct and indirect dependencies, as t here is in Figure 3.7. Many UML relat ionships im ply a dependency. The navigable associat ion from Order t o Cust om er in Figure 3.1 m eans t hat Order is dependent on Cust om er. A subclass is dependent on it s superclass but not vice versa.
Ta ble 3 .1 . Se le ct e d D e pe n de n cy Ke yw or ds Ke yw or d
M e a n in g
«call»
The source calls an operat ion in t he t arget .
«create»
The source creat es inst ances of t he t arget .
«derive»
The source is derived from the t arget .
«instantiate» The source is an inst ance of the t arget . ( Not e t hat if t he source is a class, t he class it self is an inst ance of t he class class; that is, t he t arget class is a m et aclass) . «permit»
The t arget allows t he source t o access t he t arget 's privat e feat ures.
«realize»
The source is an im plem ent at ion of a specificat ion or int erface defined by the t arget ( page 69) .
«refine»
Refinem ent indicat es a relat ionship bet ween different sem ant ic levels; for exam ple, t he source m ight be a design class and t he t arget t he corresponding analysis class.
«substitute»
The source is subst it ut able for the t arget ( page 45) .
«trace»
Used t o t rack such t hings as requirem ent s t o classes or how changes in one m odel 45/ 118
Ta ble 3 .1 . Se le ct e d D e pe n de n cy Ke yw or ds Ke yw or d
M e a n in g link t o changes elsewhere.
«use»
The source requires t he t arget for it s im plem ent at ion.
Your general rule should be t o m inim ize dependencies, part icularly when they cross large areas of a syst em . I n part icular, you should be wary of cycles, as t hey can lead t o a cycle of changes. I 'm not super st rict on this. I don't m ind m ut ual dependencies bet ween closely relat ed classes, but I do t ry t o elim inat e cycles at a broader level, particularly bet ween packages. Trying t o show all t he dependencies in a class diagram is an exercise in fut ilit y; t here are t oo m any and t hey change t oo m uch. Be selective and show dependencies only when t hey are directly relevant t o t he part icular t opic that you want t o com m unicat e. To underst and and cont rol dependencies, you are best off using t hem wit h package diagram s ( pages 89) . The m ost com m on case I use for dependencies wit h classes is when illust rat ing a t ransient relat ionship, such as when one obj ect is passed t o anot her as a param et er. You m ay see t hese used wit h keywords «parameter», «local», and «global». You m ay also see these keywords on associat ions in UML 1 m odels, in which case t hey indicat e t ransient links, not propert ies. These keywords are not part of UML 2. Dependencies can be det erm ined by looking at code, so t ools are ideal for doing dependency analysis. Get t ing a t ool t o reverse engineer pictures of dependencies is t he m ost useful way t o use t his bit of the UML.
Constraint Rules Much of what you are doing in drawing a class diagram is indicat ing const raint s. Figure 3.1 indicat es t hat an Order can be placed only by a single Cust om er. The diagram also im plies t hat each Line I t em is thought of separat ely: You say " 40 brown widget s, 40 blue widget s, and 40 red widget s," not " 120 t hings" on the Order. Furt her, t he diagram says t hat Corporat e Cust om ers have credit lim it s but Personal Cust om ers do not . The basic const ruct s of associat ion, at t ribut e, and generalizat ion do m uch t o specify im port ant const raint s, but t hey cannot indicat e every const raint . These const raint s st ill need t o be capt ured; t he class diagram is a good place t o do t hat . The UML allows you t o use anyt hing t o describe const raint s. The only rule is that you put t hem inside braces ({ } ) . You can use nat ural language, a program m ing language, or t he UML's form al Obj ect Const raint Language ( OCL) [ Warm er and Kleppe] , which is based on predicat e calculus. Using a form al not at ion avoids the risk of m isint erpret at ion due t o an am biguous nat ural language. However, it int roduces the risk of m isint erpret at ion due t o writ ers and readers not really underst anding OCL. So unless you have readers who are com fort able wit h predicat e calculus, I 'd suggest using nat ural language. Opt ionally, you can nam e a const raint by put t ing t he nam e first , followed by a colon; for exam ple, { disallow incest : husband and wife m ust not be siblings} .
Design by Contract Design by Cont ract is a design t echnique developed by Bert rand Meyer [ Meyer] . The t echnique is a cent ral feat ure of the Eiffel language he developed. Design by Cont ract is not specific t o Eiffel, however; it is a valuable t echnique that can be used wit h any program m ing language. At the heart of Design by Cont ract is t he assert ion. An asse r t ion is a Boolean st at em ent 46/ 118
t hat should never be false and, therefore, will be false only because of a bug. Typically, assert ions are checked only during debug and are not checked during product ion execut ion. I ndeed, a program should never assum e t hat assert ions are being checked. Design by Cont ract uses t hree part icular kinds of assert ions: post - condit ions, precondit ions, and invariant s. Pre- condit ions and post - condit ions apply t o operat ions. A post con dit ion is a st at em ent of what t he world should look like aft er execut ion of an operat ion. For inst ance, if we define t he operat ion " square root " on a num ber, t he post condit ion would t ake t he form input = result * result , where result is t he out put and input is t he input value. The post - condit ion is a useful way of saying what we do wit hout saying how we do it —in ot her words, of separat ing int erface from im plem ent at ion. A pr e - con dit ion is a st at em ent of how we expect t he world t o be before we execut e an operat ion. We m ight define a pre- condit ion for t he " square root " operat ion of input > = 0 . Such a pre-condit ion says t hat it is an error t o invoke " square root " on a negat ive num ber and t hat t he consequences of doing so are undefined. On first glance, this seem s a bad idea, because we should put som e check som ewhere t o ensure t hat " square root " is invoked properly. The im port ant question is who is responsible for doing so. The pre- condit ion m akes it explicit t hat t he caller is responsible for checking. Wit hout t his explicit st at em ent of responsibilit ies, we can get eit her t oo lit t le checking—because bot h part ies assum e that t he ot her is responsible—or t oo m uch—bot h part ies check. Too m uch checking is a bad thing because it leads t o a lot of duplicat e checking code, which can significant ly increase t he com plexit y of a program . Being explicit about who is responsible helps t o reduce t his com plexit y. The danger that t he caller forget s t o check is reduced by t he fact that assertions are usually checked during debugging and t est ing. From t hese definit ions of pre- condit ion and post - condit ion, we can see a st rong definit ion of t he t erm e xce pt ion. An except ion occurs when an operat ion is invoked wit h it s precondit ion sat isfied yet cannot ret urn wit h it s post - condit ion sat isfied. An in va r ia n t is an assert ion about a class. For inst ance, an Account class m ay have an invariant t hat says that balance = = sum ( ent ries.am ount ( ) ) . The invariant is " always" t rue for all inst ances of the class. Here, " always" m eans " whenever t he obj ect is available t o have an operat ion invoked on it ." I n essence, t his m eans t hat t he invariant is added t o pre- condit ions and post - condit ions associat ed wit h all public operat ions of t he given class. The invariant m ay becom e false during execut ion of a m et hod, but it should be rest ored t o t rue by t he t im e any ot her obj ect can do anyt hing t o t he receiver. Assert ions can play a unique role in subclassing. One of t he dangers of inherit ance is t hat you could redefine a subclass's operat ions t o be inconsist ent wit h the superclass's operat ions. Assert ions reduce t he chances of t his. The invariant s and post - condit ions of a class m ust apply t o all subclasses. The subclasses can choose t o st rengt hen these assert ions but cannot weaken t hem . The pre- condit ion, on t he ot her hand, cannot be st rengt hened but m ay be weakened. This looks odd at first , but it is im port ant t o allow dynam ic binding. You should always be able t o t reat a subclass obj ect as if it were an inst ance of t he superclass, per the principle of subst it ut abilit y. I f a subclass st rengt hened it s pre- condit ion, a superclass operat ion could fail when applied t o t he subclass.
Chapter 4. Sequence Diagrams 47/ 118
I n t e r act ion dia gr a m s describe how groups of obj ect s collaborat e in som e behavior. The UML defines several form s of int eract ion diagram , of which the m ost com m on is the sequence diagram . Typically, a sequence diagram capt ures t he behavior of a single scenario. The diagram shows a num ber of exam ple obj ect s and t he m essages that are passed bet ween t hese obj ect s wit hin t he use case. To begin t he discussion, I 'll consider a sim ple scenario. We have an order and are going t o invoke a com m and on it t o calculat e it s price. To do t hat , t he order needs t o look at all the line it em s on t he order and det erm ine t heir prices, which are based on the pricing rules of the order line's product s. Having done t hat for all t he line it em s, t he order t hen needs t o com put e an overall discount , which is based on rules t ied t o t he cust om er. Figure 4.1 is a sequence diagram that shows one im plem ent at ion of t hat scenario. Sequence diagram s show t he int eract ion by showing each part icipant wit h a lifeline t hat runs vert ically down t he page and the ordering of m essages by reading down t he page.
Figu r e 4 .1 . A se qu e n ce dia gr a m for ce n t r a lize d con t r ol
One of t he nice t hings about a sequence diagram is t hat I alm ost don't have t o explain t he not at ion. You can see that an inst ance of order sends getQuantity and getProduct m essages t o t he order line. You can also see how we show the order invoking a m et hod on it self and how t hat m et hod sends getDiscountInfo t o an inst ance of cust om er. The diagram , however, doesn't show everyt hing very well. The sequence of m essages getQuantity, getProduct, getPricingDetails, and calculateBasePrice needs t o be done for each order line on t he order, while calculateDiscounts is invoked j ust once. You can't t ell t hat from t his diagram , alt hough I 'll int roduce som e m ore not at ion t o handle t hat lat er. Most of t he t im e, you can think of t he part icipant s in an int eract ion diagram as obj ect s, as indeed t hey were in UML 1. But in UML 2, t heir roles are m uch m ore com plicat ed, and t o explain it all fully is beyond t his book. So I use t he t erm par t icipa n t s, a word t hat isn't used form ally in t he UML
48/ 118
spec. I n UML 1, part icipant s were obj ect s and so t heir nam es were underlined, but in UML 2, t hey should be shown wit hout the underline, as I 've done here. I n these diagram s, I 've nam ed the part icipant s using t he st yle anOrder. This works well m ost of t he t im e. A fuller synt ax is name : Class, where bot h t he nam e and t he class are opt ional, but you m ust keep the colon if you use the class. ( Figure 4.4, shown on page 58, uses this st yle.) Each lifeline has an activat ion bar that shows when t he part icipant is act ive in t he int eract ion. This corresponds t o one of t he part icipant 's m et hods being on t he st ack. Act ivat ion bars are opt ional in UML, but I find t hem ext rem ely valuable in clarifying t he behavior. My one except ion is when exploring a design during a design session, because they are awkward t o draw on whit eboards. Nam ing oft en is useful t o correlat e part icipant s on t he diagram . The call getProduct is shown ret urning aProduct, which is t he sam e nam e, and t herefore t he sam e part icipant , as t he aProduct t hat t he getPricingDetails call is sent t o. Not e t hat I 've used a ret urn arrow for only t his call; I did t hat t o show t he correspondance. Som e people use ret urns for all calls, but I prefer t o use t hem only where t hey add inform at ion; ot herwise, t hey sim ply clut t er t hings. Even in this case, you could probably leave t he ret urn out wit hout confusing your reader. The first m essage doesn't have a participant t hat sent it , as it com es from an undet erm ined source. I t 's called a fou n d m e ssa ge. For anot her approach t o t his scenario, t ake a look at Figure 4.2. The basic problem is st ill t he sam e, but t he way in which t he part icipant s collaborat e t o im plem ent it is very different . The Order asks each Order Line t o calculat e it s own Price. The Order Line it self furt her hands off the calculat ion to t he Product ; not e how we show t he passing of a param et er. Sim ilarly, t o calculat e t he discount , t he Order invokes a m et hod on t he Cust om er. Because it needs inform at ion from t he Order t o do t his, t he Cust om er m akes a reent rant call ( getBaseValue) t o t he Order t o get t he dat a.
Figu r e 4 .2 . A se qu e n ce dia gr a m for dist r ibu t e d con t r ol
The first t hing t o not e about t hese t wo diagram s is how clearly t he sequence diagram indicat es the differences in how t he part icipant s int eract . This is t he great st rengt h of int eract ion diagram s. They aren't good at showing det ails of algorit hm s, such as loops and condit ional behavior, but they m ake t he calls bet ween part icipant s cryst al clear and give a really good pict ure about which part icipant s are doing which processing. The second t hing t o not e is t he clear difference in st yles bet ween t he t wo int eractions. Figure 4.1 is ce n t ra lize d con tr ol, wit h one part icipant pret t y m uch doing all t he processing and ot her part icipant s t here t o supply dat a. Figure 4.2 uses dist r ibu t e d con t rol, in which t he processing is split am ong m any part icipant s, each one doing a lit t le bit of t he algorit hm . 49/ 118
Bot h st yles have t heir st rengt hs and weaknesses. Most people, part icularly t hose new t o obj ect s, are m ore used t o cent ralized cont rol. I n m any ways, it 's sim pler, as all t he processing is in one place; wit h dist ribut ed cont rol, in cont rast , you have t he sensat ion of chasing around t he obj ect s, t rying t o find t he program . Despit e t his, obj ect bigot s like m e st rongly prefer dist ribut ed cont rol. One of the m ain goals of good design is t o localize the effect s of change. Dat a and behavior t hat accesses that dat a oft en change t oget her. So put t ing the dat a and t he behavior t hat uses it t oget her in one place is the first rule of obj ect - orient ed design. Furt herm ore, by dist ribut ing cont rol, you creat e m ore opport unit ies for using polym orphism rat her t han using condit ional logic. I f t he algorit hm s for product pricing are different for different t ypes of product , t he dist ribut ed cont rol m echanism allows us t o use subclasses of product t o handle t hese variat ions. I n general t he OO st yle is t o use a lot of lit t le obj ect s wit h a lot of lit t le m et hods t hat give us a lot of plug point s for overriding and variat ion. This st yle is very confusing t o people used t o long procedures; indeed, t his change is t he heart of the par a digm sh ift of obj ect orient at ion. I t 's som et hing that 's very difficult t o t each. I t seem s t hat the only way t o really underst and it is t o work in an OO environm ent wit h st rongly dist ribut ed cont rol for a while. Many people then say t hat they get a sudden " aha" when t he st yle m akes sense. At t his point , t heir brains have been rewired, and t hey st art t hinking that decent ralized cont rol is act ually easier.
Creating and Deleting Participants Sequence diagram s show som e ext ra not at ion for creat ing and delet ing part icipant s ( Figure 4.3) . To creat e a participant , you draw the m essage arrow direct ly int o t he part icipant box. A m essage nam e is opt ional here if you are using a const ruct or, but I usually m ark it wit h " new" in any case. I f t he part icipant im m ediat ely does som et hing once it 's creat ed, such as t he query com m and, you st art an act ivat ion right aft er t he part icipant box.
Figu r e 4 .3 . Cr e a t ion a n d de le t ion of pa r t icipa n t s
50/ 118
Delet ion of a part icipant is indicat ed by big X. A m essage arrow going int o t he X indicat es one part icipant explicit ly delet ing anot her; an X at t he end of a lifeline shows a part icipant delet ing it self. I n a garbage-collect ed environm ent , you don't delet e obj ect s directly, but it 's st ill wort h using the X t o indicat e when an obj ect is no longer needed and is ready t o be collect ed. I t 's also appropriat e for close operat ions, indicat ing t hat t he obj ect isn't usable any m ore.
Loops, Conditionals, and the Like A com m on issue wit h sequence diagram s is how t o show looping and condit ional behavior. The first t hing t o point out is t hat t his isn't what sequence diagram s are good at . I f you want t o show cont rol st ruct ures like this, you are bet t er off wit h an act ivit y diagram or indeed wit h code it self. Treat sequence diagram s as a visualizat ion of how obj ect s int eract rat her than as a way of m odeling cont rol logic. That said, here's t he not at ion t o use. Bot h loops and condit ionals use in t er a ct ion fr a m e s, which are ways of m arking off a piece of a sequence diagram . Figure 4.4 shows a sim ple algorit hm based on t he following pseudocode:
Figu r e 4 .4 . I n t e r a ct ion fr a m e s
51/ 118
procedure dispatch foreach (lineitem) if (product.value > $10K) careful.dispatch else regular.dispatch end if end for if (needsConfirmation) messenger.confirm end procedure I n general, fram es consist of som e region of a sequence diagram t hat is divided int o one or m ore fragm ent s. Each fram e has an operat or and each fragm ent m ay have a guard. ( Table 4.1 list s com m on operat ors for int eract ion fram es.) To show a loop, you use t he loop operand wit h a single fragm ent and put the basis of t he it erat ion in t he guard. For condit ional logic, you can use an alt operat or and put a condit ion on each fragm ent . Only t he fragm ent whose guard is t rue will execut e. I f you have only one region, t here is an opt operat or. I nt eraction fram es are new in UML 2. As a result , you m ay see diagram s prepared before UML 2 and t hat use a different approach; also, som e people don't like t he fram es and prefer som e of t he older convent ions. Figure 4.5 shows som e of t hese unofficial t weaks.
Figu r e 4 .5 . Olde r con v e n t ions for con t r ol logic
52/ 118
UML 1 used it erat ion m arkers and guards. An ite r a t ion m a r ke r is a * added t o t he m essage nam e. You can add som e t ext in square bracket s t o indicat e t he basis of t he it erat ion. Gu ar ds are a condit ional expression placed in square bracket s and indicat e t hat t he m essage is sent only if the guard is t rue. While these not at ions have been dropped from sequence diagram s in UML 2, they are st ill legal on com m unicat ion diagram s.
Ta ble 4 .1 . Com m on Ope r a t or s for I n t e r a ct ion Fr a m e s M e a n in g
Ope r a tor alt
Alt ernat ive m ult iple fragm ent s; only t he one whose condit ion is t rue will execut e ( Figure
4.4 ) . opt
Opt ional; t he fragm ent execut es only if the supplied condit ion is t rue. Equivalent t o an alt wit h only one t race ( Figure 4.4 ) .
par
Parallel; each fragm ent is run in parallel.
loop
Loop; t he fragm ent m ay execut e m ult iple t im es, and the guard indicat es t he basis of it erat ion ( Figure 4.4 ) .
region
Crit ical region; t he fragm ent can have only one t hread execut ing it at once.
neg
Negat ive; t he fragm ent shows an invalid int eract ion.
ref
Reference; refers t o an int eract ion defined on anot her diagram . The fram e is drawn t o cover t he lifelines involved in the int eract ion. You can define param et ers and a ret urn value.
sd
Sequence diagram ; used t o surround an ent ire sequence diagram , if you wish.
Alt hough it erat ion m arkers and guards can help, t hey do have weaknesses. The guards can't indicat e t hat a set of guards are m ut ually exclusive, such as t he t wo on Figure 4.5. Bot h not at ions work only wit h a single m essage send and don't work well when several m essages com ing out of a single act ivat ion are wit hin t he sam e loop or condit ional block. To get around t his last problem , an unofficial convent ion t hat 's becom e popular is t o use a pse u dom essa ge, wit h t he loop condit ion or t he guard on a variat ion of t he self-call not at ion. I n Figure 4.5, I 've shown t his wit hout a m essage arrow; som e people include a m essage arrow, but 53/ 118
leaving it out helps reinforce that this isn't a real call. Som e also like t o gray shade t he pseudom essage's act ivat ion bar. I f you have alt erat ive behavior, you can show t hat wit h an alt ernat ive m arker bet ween t he act ivat ions. Alt hough I find act ivat ions very helpful, t hey don't add m uch in t he case of t he dispatch m et hod, whereby you send a m essage and not hing else happens wit hin the receiver's act ivat ion. A com m on convent ion t hat I 've shown on Figure 4.5 is t o drop t he activat ion for those sim ple calls. The UML st andard has no graphic device t o show passing dat a; inst ead, it 's shown by param et ers in t he m essage nam e and ret urn arrows. D a t a t a dpole s have been around in m any m et hods t o indicat e t he m ovem ent of dat a, and m any people st ill like t o use t hem wit h t he UML. All in all, alt hough various schem es can add not at ion for condit ional logic t o sequence diagram s, I don't find t hat t hey work any bet t er than code or at least pseudocode. I n part icular, I find the int eraction fram es very heavy, obscuring t he m ain point of t he diagram , so I prefer pseudom essages.
Synchronous and Asynchronous Calls I f you're except ionally alert , you'll have not iced t hat t he arrowheads in t he last couple of diagram s are different from the arrowheads earlier on. That m inor difference is quit e im port ant in UML 2. I n UML 2, filled arrowheads show a synchronous m essage, while st ick arrowheads show an asynchronous m essage. I f a caller sends a synch ronou s m e ssa ge , it m ust wait unt il t he m essage is done, such as invoking a subrout ine. I f a caller sends an a synch ron ous m e ssa ge , it can cont inue processing and doesn't have t o wait for a response. You see asynchronous calls in m ult it hreaded applicat ions and in m essage- orient ed m iddleware. Asynchrony gives bet t er responsiveness and reduces t he t em poral coupling but is harder t o debug. The arrowhead difference is very subt le; indeed, rat her t oo subt le. I t 's also a backward-incom pat ible change int roduced in UML 1.4, before t hen an asynchronous m essage was shown wit h t he half-st ick arrowhead, as in Figure 4.5. I t hink t hat t his arrowhead dist inct ion is t oo subt le. I f you want t o highlight asynchronous m essages, I would recom m end using t he obsolet e half- stick arrowhead, which draws t he eye m uch bet t er to an im port ant dist inct ion. I f you're reading a sequence diagram , beware of m aking assum pt ions about synchrony from t he arrowheads unless you're sure t hat t he aut hor is int ent ionally m aking the dist inct ion.
When to Use Sequence Diagrams You should use sequence diagram s when you want t o look at t he behavior of several obj ect s wit hin a single use case. Sequence diagram s are good at showing collaborat ions am ong t he obj ect s; they are not so good at precise definit ion of t he behavior. I f you want t o look at t he behavior of a single obj ect across m any use cases, use a st at e diagram ( see Chapt er 10) . I f you want t o look at behavior across m any use cases or m any threads, consider an act ivit y diagram (see Chapt er 11) . I f you want t o explore m ult iple alt ernat ive int eract ions quickly, you m ay be bet t er off wit h CRC cards, as t hat avoids a lot of drawing and erasing. I t 's oft en handy t o have a CRC card session t o explore design alt ernat ives and t hen use sequence diagram s t o capt ure any int eract ions t hat you want t o refer t o lat er. Ot her useful form s of int eract ion diagram s are com m unicat ion diagram s, for showing connect ions; and t im ing diagram s, for showing t im ing const raint s.
54/ 118
CRC Cards One of t he m ost valuable t echniques in com ing up wit h a good OO design is t o explore obj ect int eract ions, because it focuses on behavior rat her than dat a. CRC ( ClassResponsibilit y- Collaborat ion) diagram s, invent ed by Ward Cunningham in t he lat e 1980s, have st ood t he t est of tim e as a highly effect ive way t o do t his ( Figure 4.6 ) . Alt hough t hey aren't part of the UML, t hey are a very popular t echnique am ong skilled obj ect designers.
Figu r e 4 .6 . A sa m ple CRC ca r d
To use CRC cards, you and your colleagues gat her around a t able. Take various scenarios and act t hem out wit h t he cards, picking them up in t he air when t hey are act ive and m oving t hem t o suggest how t hey send m essages t o each ot her and pass t hem around. This t echnique is alm ost im possible t o describe in a book yet is easily dem onst rat ed; t he best way t o learn it is t o have som eone who has done it show it t o you. An im port ant part of CRC thinking is ident ifying responsibilit ies. A r e spon sibilit y is a short sent ence t hat sum m arizes som et hing that an obj ect should do: an action the obj ect perform s, som e knowledge t he obj ect m aint ains, or som e im port ant decisions t he obj ect m akes. The idea is that you should be able t o t ake any class and sum m arize it wit h a handful of responsibilit ies. Doing that can help you t hink m ore clearly about t he design of your classes. The second C refers t o colla bor a t or s: t he ot her classes t hat t his class needs t o work wit h. This gives you som e idea of the links bet ween classes—st ill at a high level. One of t he chief benefit s of CRC cards is t hat they encourage anim at ed discussion am ong t he developers. When you are working t hrough a use case t o see how classes will im plem ent it , the int eract ion diagram s in t his chapt er can be slow t o draw. Usually, you need t o consider alt ernat ives; wit h diagram s, t he alt ernat ives can t ake t oo long t o draw and rub out . Wit h CRC cards, you m odel t he int eract ion by picking up t he cards and m oving t hem around. This allows you t o quickly consider alt ernat ives. As you do t his, you form ideas about responsibilit ies and writ e them on the cards. Thinking about responsibilit ies is im port ant , because it get s you away from t he not ion of classes as dum b dat a holders and eases t he t eam m em bers t oward underst anding t he higher-level behavior of each class. A responsibilit y m ay correspond t o an operat ion, t o an at t ribut e, or, m ore likely, t o an undet erm ined clum p of at t ribut es and operat ions. A com m on m ist ake I see people m ake is generat ing long list s of low- level responsibilit ies. But doing so m isses t he point . The responsibilit ies should easily fit on one card. Ask yourself whet her the class should be split or whet her t he responsibilit ies would be bet t er 55/ 118
st at ed by rolling them up int o higher-level st at em ent s. Many people st ress t he im port ance of role playing, whereby each person on t he t eam plays t he role of one or m ore classes. I 've never seen Ward Cunningham do t hat , and I find t hat role playing get s in t he way. Books have been writ t en on CRC, but I 've found t hat they never really get t o t he heart of t he t echnique. The original paper on CRC, writ t en wit h Kent Beck, is [ Beck and Cunningham ] . To learn m ore about bot h CRC cards and responsibilit ies in design, t ake a look at [ Wirfs- Brock] .
Chapter 5. Class Diagrams: Advanced Concepts The concept s described in Chapt er 3 correspond t o t he key not at ions in class diagram s. Those concept s are t he first ones t o underst and and becom e fam iliar wit h, as t hey will com prise 90 percent of your effort in building class diagram s. The class diagram t echnique, however, has bred dozens of not at ions for addit ional concept s. I find t hat I don't use t hese all t he t im e, but t hey are handy when t hey are appropriat e. I 'll discuss t hem one at a t im e and point out som e of t he issues in using t hem . You'll probably find this chapt er som ewhat heavy going. The good news is t hat during your first pass t hrough t he book, you can safely skip t his chapt er and com e back t o it lat er.
Keywords One of t he challenges of a graphical language is t hat you have t o rem em ber what t he sym bols m ean. Wit h t oo m any, users find it very difficult t o rem em ber what all t he sym bols m ean. So t he UML oft en t ries t o reduce t he num ber of sym bols and use keywords inst ead. I f you find t hat you need a m odeling const ruct t hat isn't in t he UML but is sim ilar t o som et hing t hat is, use t he sym bol of t he exist ing UML const ruct but m ark it wit h a keyword t o show t hat you have som et hing different An exam ple of t his is t he int erface. A UML in te rfa ce ( page 69) is a class t hat has only public operat ions, wit h no m et hod bodies. This corresponds t o int erfaces in Java, COM ( Com ponent Obj ect Module) , and CORBA. Because it 's a special kind of class, it is shown using t he class icon wit h the keyword «interface». Keywords are usually shown as t ext bet ween guillem et s. As an alt ernat ive t o keywords, you can use special icons, but t hen you run int o t he issue of everyone having t o rem em ber what t hey m ean. Som e keywords, such as {abstract}, show up in curly bracket s. I t 's never really clear what should t echnically be in guillem et s and what should be in curlies. Fort unat ely, if you get it wrong, only serious UML weenies will not ice—or care. Som e keywords are so com m on that t hey oft en get abbreviat ed: «interface» oft en get s abbreviat ed t o «I» and {abstract} t o {A}. Such abbreviat ions are very useful, part icularly on whit eboards, but nonst andard, so if you use t hem , m ake sure you find a spot t o spell out what they m ean. I n UML 1, t he guillem et s were used m ainly for st e r e ot ypes. I n UML 2, st ereot ypes are defined very t ight ly, and describing what is and isn't a st ereot ype is beyond t he scope of t his book. However,
56/ 118
because of UML 1, m any people use t he t erm st ereot ype t o m ean t he sam e as keyword, alt hough t hat is no longer correct . St ereot ypes are used as part of profiles. A pr ofile t akes a part of t he UML and ext ends it wit h a coherent group of st ereot ypes for a particular purpose, such as business m odeling. The full sem ant ics of profiles are beyond this book. Unless you are int o serious m et a-m odel design, you're unlikely t o need t o creat e one yourself. You're m ore likely t o use one creat ed for a specific m odeling purpose, but fort unat ely, use of a profile doesn't require you t o know the gory det ails of how they are t ied int o t he m et a-m odel.
Classification and Generalization I oft en hear people t alk about subt yping as the is a relat ionship. I urge you t o beware of that way of t hinking. The problem is t hat t he phrase is a can m ean different things. Consider t he following phrases. 1. 2. 3. 4. 5.
Shep is a Border Collie. A Border Collie is a Dog. Dogs are Anim als. A Border Collie is a Breed. Dog is a Species.
Now t ry com bining t he phrases. I f I com bine phrases 1 and 2, I get " Shep is a Dog" ; 2 and 3 t aken t oget her yield " Border Collies are Anim als." And 1 plus 2 plus 3 gives m e "Shep is an Anim al." So far, so good. Now t ry 1 and 4: " Shep is a Breed." The com binat ion of 2 and 5 is " A Border Collie is a Species." These are not so good. Why can I com bine som e of t hese phrases and not ot hers? The reason is t hat som e are cla ssifica t ion—t he obj ect Shep is an inst ance of t he t ype Border Collie—and som e are ge n e r a liza t ion—t he t ype Border Collie is a subt ype of t he t ype Dog. Generalizat ion is t ransit ive; classificat ion is not . I can com bine a classificat ion followed by a generalizat ion but not vice versa. I m ake t his point t o get you t o be wary of is a. Using it can lead t o inappropriat e use of subclassing and confused responsibilit ies. Bet t er t est s for subt yping in t his case would be t he phrases " Dogs are kinds of Anim als" and " Every inst ance of a Border Collie is an inst ance of a Dog." The UML uses t he generalizat ion sym bol t o show generalizat ion. I f you need t o show classificat ion, use a dependency wit h t he «instantiate» keyword.
Multiple and Dynamic Classification Cla ssifica t ion refers t o t he relat ionship bet ween an obj ect and it s t ype. Mainst ream program m ing languages assum e t hat an obj ect belongs t o a single class. But there are m ore opt ions t o classificat ion t han t hat . I n sin gle cla ssifica t ion, an obj ect belongs t o a single t ype, which m ay inherit from supert ypes. I n m u lt iple cla ssifica t ion, an obj ect m ay be described by several t ypes t hat are not necessarily connect ed by inherit ance. Mult iple classificat ion is different from m ult iple inherit ance. Mult iple inherit ance says t hat a t ype m ay have m any supert ypes but t hat a single t ype m ust be defined for each obj ect . Mult iple classificat ion allows m ult iple t ypes for an obj ect wit hout defining a specific t ype for the purpose. 57/ 118
For exam ple, consider a person subt yped as eit her m an or wom an, doct or or nurse, pat ient or not ( see Figure 5.11) . Mult iple classificat ion allows an obj ect t o have any of t hese t ypes assigned t o it in any allowable com binat ion, wit hout t he need for t ypes t o be defined for all t he legal com binat ions.
Figu r e 5 .1 1 . M u lt iple cla ssifica t ion
I f you use m ult iple classificat ion, you need t o be sure t hat you m ake it clear which com binat ions are legal. UML 2 does t his by placing each generalizat ion relat ionship int o a ge n er a liza t ion se t. On t he class diagram , you label t he generalizat ion arrowhead wit h t he nam e of t he generalizat ion set , which in UML 1 was called t he discrim inat or. Single classificat ion corresponds t o a single generalizat ion set wit h no nam e. Generalizat ion set s are by default disj oint : Any inst ance of the supert ype m ay be an inst ance of only one of the subt ypes wit hin t hat set . I f you roll up generalizat ions int o a single arrow, t hey m ust all be part of t he sam e generalizat ion set , as shown in Figure 5.11. Alt ernat ively, you can have several arrows wit h t he sam e t ext label. To illust rat e, not e t he following legal com binat ions of subt ypes in t he diagram : ( Fem ale, Pat ient , Nurse) ; ( Male, Physiot herapist ) ; ( Fem ale, Pat ient ) ; and ( Fem ale, Doct or, Surgeon) . The com binat ion ( Pat ient , Doct or, Nurse) is illegal because it cont ains t wo t ypes from the role generalizat ion set . Anot her quest ion is whet her an obj ect m ay change it s class. For exam ple, when a bank account is overdrawn, it subst ant ially changes it s behavior. Specifically, several operat ions, including " wit hdraw" and " close," get overridden. D yn a m ic cla ssifica t ion allows obj ect s t o change class wit hin t he subt yping st ruct ure; sta t ic cla ssifica t ion does not . Wit h st at ic classificat ion, a separat ion is m ade bet ween t ypes and st at es; dynam ic classificat ion com bines these not ions. Should you use m ult iple, dynam ic classificat ion? I believe t hat it is useful for concept ual m odeling. For soft ware perspect ives, however, t he dist ance bet ween it and t he im plem ent at ions is t oo m uch of a leap. I n t he vast m aj orit y of UML diagram s, you'll see only single st at ic classificat ion, so t hat should be your default .
Association Class Associa t ion cla sse s allow you t o add at t ribut es, operat ions, and ot her feat ures t o associat ions, as shown in Figure 5.12. We can see from t he diagram t hat a person m ay at t end m any m eet ings. We 58/ 118
need t o keep inform at ion about how awake t hat person was; we can do t his by adding t he at t ribut e at t ent iveness t o t he associat ion.
Figu r e 5 .1 2 . Associa t ion cla ss
Figure 5.13 shows anot her way t o represent this inform at ion: Make At t endance a full class in it s own right . Not e how t he m ult iplicit ies have m oved.
Figu r e 5 .1 3 . Pr om ot in g a n a ssocia t ion cla ss t o a fu ll cla ss
What benefit do you gain wit h t he associat ion class t o offset the ext ra not at ion you have t o rem em ber? The associat ion class adds an ext ra const raint , in t hat there can be only one inst ance of t he associat ion class bet ween any t wo part icipat ing obj ect s. I feel t he need for anot her exam ple. Take a look at t he t wo diagram s in Figure 5.14. These diagram s have m uch t he sam e form . However, we can im agine one Com pany playing different roles in the sam e Cont ract , but it 's harder t o im agine a Person having m ult iple com pet encies in the sam e skill; indeed, you would probably consider that an error.
Figu r e 5 .1 4 . Associa t ion cla ss su bt le t ie s ( Role sh ou ld pr oba bly n ot be a n a ssocia t ion cla ss)
59/ 118
I n the UML, only t he lat t er case is legal. You can have only one com pet ency for each com binat ion of Person and Skill. The t op diagram in Figure 5.14 would not allow a Com pany t o have m ore t han one Role on a single cont ract . I f you need t o allow this, you need t o m ake Role a full class, in the st yle of Figure 5.13. I m plem ent ing associat ion classes isn't t erribly obvious. My advice is t o im plem ent an associat ion class as if it where a full class but t o provide m et hods t hat get inform at ion t o t he classes linked by t he associat ion class. So for Figure 5.12 , I would see the following m et hods on Person:
class Person List getAttendances() List getMeetings() This way, a client of Person can get hold of t he people at t he m eet ing; if t hey want det ails, t hey can get t he Att endances t hem selves. I f you do t his, rem em ber t o enforce t he const raint t hat t here can be only one At t endance obj ect for any pair of Person and Meet ing. You should place a check in whichever m et hod creat es the At t endance. You oft en find t his kind of const ruct wit h hist orical inform at ion, such as in Figure 5.15. However, I find t hat creat ing ext ra classes or associat ion classes can m ake t he m odel t ricky t o underst and, as well as t ilt t he im plem ent at ion in a part icular direct ion that 's oft en unsuit able.
Figu r e 5 .1 5 . Usin g a cla ss for a t e m por a l r e la t ion sh ip
I f I have this kind of t em poral inform at ion, I use a «temporal» keyword on t he associat ion ( see Figure 5.16) . The m odel indicat es t hat a Person m ay work for only a single Com pany at one t im e.
60/ 118
Over t im e, however, a Person m ay work for several Com panies. This suggest s an int erface along t he lines of:
Figu r e 5 .1 6 . «Temporal» k e yw or d for a ssocia t ion s
class Person ... Company getEmployer();//get current employer Company getEmployer(Date);//get employer at a given date void changeEmployer(Company newEmployer,Date changeDate); void leaveEmployer (Date changeDate); The «temporal» keyword is not part of t he UML, but I m ent ion it here for t wo reasons. First , it is a not ion I have found useful on several occasions in m y m odeling career. Second, it shows how you can use keywords t o ext end t he UML. You can read a lot m ore about this at h t t p:/ / m a r t in fow le r .com / a p2 / t im e N a r r a t ive .h t m l.
Template (Parameterized) Class Several languages, m ost not iceably C+ + , have the not ion of a pa ra m e t er ize d cla ss, or t e m pla t e. ( Tem plat es are on t he list t o be included in Java and C# in t he near fut ure.) This concept is m ost obviously useful for working wit h collect ions in a st rongly t yped language. This way, you can define behavior for set s in general by defining a t em plat e class Set.
class Set { void insert (T newElement); void remove (T anElement); When you have done t his, you can use t he general definit ion t o m ake Set classes for m ore specific elem ent s:
Set employeeSet; You declare a t em plat e class in t he UML by using t he not at ion shown in Figure 5.17. The T in the diagram is a placeholder for t he t ype param et er. ( You m ay have m ore t han one.)
Figu r e 5 .1 7 . Te m pla t e cla ss
A use of a param et erized class, such as Set, is called a de r iva t ion. You can show a derivat ion in t wo ways. The first way m irrors t he C+ + synt ax ( see Figure 5.18) . You describe t he derivat ion expression wit hin angle bracket s in t he form . I f 61/ 118
t here's only one param et er, convent ional use oft en om it s t he param et er nam e. The alt ernat ive not at ion ( see Figure 5.19 ) reinforces t he link t o t he t em plat e and allows you t o renam e t he bound elem ent .
Figu r e 5 .1 8 . Bou n d e le m e n t ( v e rsion 1 )
Figu r e 5 .1 9 . Bou n d e le m e n t ( v e rsion 2 )
The «bind» keyword is a st ereot ype on t he refinem ent relat ionship. This relat ionship indicat es t hat EmployeeSet will conform t o t he int erface of Set. You can t hink of t he EmployeeSet as a subt ype of Set. This fit s t he ot her way of im plem ent ing t ype- specific collect ions, which is t o declare all appropriat e subt ypes. Using a derivat ion is not t he sam e as subt yping, however. You are not allowed t o add feat ures to t he bound elem ent , which is com plet ely specified by it s t em plat e; you are adding only rest rict ing t ype inform at ion. I f you want t o add feat ures, you m ust creat e a subt ype.
Enumerations Enum erat ions ( Figure 5.20) are used t o show a fixed set of values t hat don't have any propert ies ot her t han t heir sym bolic value. They are shown as t he class wit h t he «enumeration» keyword.
Figu r e 5 .2 0 . En um e r a t ion
62/ 118
Active Class An a ct ive class has inst ances, each of which execut es and cont rols it s own thread of cont rol. Met hod invocat ions m ay execut e in a client 's t hread or in the active obj ect 's thread. A good exam ple of t his is a com m and processor t hat accept s com m and obj ect s from t he out side and then execut es t he com m ands wit hin it s own t hread of cont rol. The not at ion for act ive classes has changed from UML 1 t o UML 2, as shown in Figure 5.21. I n UML 2, an act ive class has ext ra vertical lines on t he side; in UML 1, it had a t hick border and was called an act ive obj ect .
Figu r e 5 .2 1 . Act iv e cla ss
Visibility Visibilit y is a subj ect t hat is sim ple in principle but has com plex subt let ies. The sim ple idea is that any class has public and privat e elem ent s. Public elem ent s can be used by any ot her class; privat e elem ent s can be used only by t he owning class. However, each language m akes it s own rules. Alt hough m any languages use such t erm s as public, privat e, and prot ect ed, t hey m ean different t hings in different languages. These differences are sm all, but they lead t o confusion, especially for t hose of us who use m ore t han one language. The UML t ries t o address this wit hout get t ing int o a horrible t angle. Essent ially, wit hin t he UML, you can t ag any at t ribut e or operat ion wit h a visibilit y indicat or. You can use any m arker you like, and it s m eaning is language dependent . However, t he UML provides four abbreviat ions for visibilit y: + ( public) , – ( privat e) , ~ ( package) , and # ( prot ect ed) . These four levels are used wit hin t he UML m et a-m odel and are defined wit hin it , but t heir definit ions vary subt ly from t hose in ot her languages. When you are using visibilit y, use t he rules of t he language in which you are working. When you are looking at a UML m odel from elsewhere, be wary of t he m eanings of the visibilit y m arkers, and be aware of how t hose m eanings can change from language t o language.
63/ 118
Most of t he t im e, I don't draw visibilit y m arkers in diagram s; I use t hem only if I need t o highlight t he differences in visibilit y of cert ain feat ures. Even t hen, I can m ost ly get away wit h + and –, which at least are easy t o rem em ber.
Messages St andard UML does not show any inform at ion about m essage calls on class diagram s. However, I 've som et im es seen convent ional diagram s like Figure 5.22 .
Figu r e 5 .2 2 . Cla sse s w it h m e ssa ge s
These add arrows t o t he sides of associat ions. The arrows are labeled wit h t he m essages that one obj ect sends t o anot her. Because you don't need an associat ion t o a class t o send a m essage t o it , you m ay also need t o add a dependency arrow to show m essages bet ween classes that aren't associat ed. This m essage inform at ion spans m ult iple use cases, so t hey aren't num bered t o show sequences, unlike com m unicat ion diagram s.
Responsibilities Oft en, it 's handy t o show responsibilit ies ( page 63) on a class in a class diagram . The best way t o show t hem is as com m ent st rings in t heir own com part m ent in t he class ( Figure 5.1) . You can nam e t he com partm ent , if you wish, but I usually don't , as there's rarely any pot ent ial for confusion.
Figu r e 5 .1 . Sh ow in g r espon sibilit ie s in a cla ss dia gr a m
64/ 118
Static Operations and Attributes The UML refers t o an operat ion or an at t ribut e that applies t o a class rat her t han t o an inst ance as st a t ic. This is equivalent t o st at ic m em bers in C- based languages. St at ic feat ures are underlined on a class diagram ( see Figure 5.2 ) .
Figu r e 5 .2 . St a t ic n ot a t ion
Aggregation and Composition One of t he m ost frequent sources of confusion in t he UML is aggregat ion and com posit ion. I t 's easy t o explain glibly: Aggr e ga t ion is t he part - of relat ionship. I t 's like saying t hat a car has an engine and wheels as it s part s. This sounds good, but the difficult thing is considering what t he difference is bet ween aggregat ion and associat ion. I n the pre- UML days, people were usually rat her vague on what was aggregat ion and what was associat ion. Whet her vague or not , they were always inconsist ent wit h everyone else. As a result , m any m odelers t hink t hat aggregat ion is im port ant , alt hough for different reasons. So t he UML included aggregat ion ( Figure 5.3 ) but wit h hardly any sem ant ics. As Jim Rum baugh says, " Think of it as a m odeling placebo" [ Rum baugh, UML Reference] .
Figu r e 5 .3 . Aggr e ga t ion
65/ 118
As well as aggregat ion, t he UML has t he m ore defined propert y of com posit ion . I n Figure 5.4 , an inst ance of Point m ay be part of a polygon or m ay be t he cent er of a circle, but it cannot be bot h. The general rule is t hat , alt hough a class m ay be a com ponent of m any ot her classes, any inst ance m ust be a com ponent of only one owner. The class diagram m ay show m ult iple classes of pot ent ial owners, but any inst ance has only a single obj ect as it s owner.
Figu r e 5 .4 . Com posit ion
You'll not e that I don't show t he reverse m ult iplicit ies in Figure 5.4. I n m ost cases, as here, it 's 0..1. I t s only ot her possible value is 1, for cases in which the com ponent class is designed so t hat it can have only one ot her class as it s owner. The " no sharing" rule is t he key t o com posit ion. Anot her assum pt ion is t hat if you delet e t he polygon, it should aut om at ically ensure t hat any owned Point s also are delet ed. Com posit ion is a good way of showing propert ies t hat own by value, properties t o value obj ect s ( page 73) , or propert ies t hat have a st rong and som ewhat exclusive ownership of part icular ot her com ponent s. Aggregat ion is st rict ly m eaningless; as a result , I recom m end that you ignore it in your own diagram s. I f you see it in ot her people's diagram s, you'll need t o dig deeper t o find out what t hey m ean by it . Different aut hors and t eam s use it for very different purposes.
Derived Properties D e r ive d pr oper t ie s can be calculat ed based on ot her values. When we think about a dat e range ( Figure 5.5) , we can t hink of t hree propert ies: the st art dat e, t he end dat e, and t he num ber of days in t he period. These values are linked, so we can t hink of t he lengt h as being derived from t he ot her t wo values.
Figu r e 5 .5 . D e r iv e d a t t r ibu t e in a t im e pe r iod
Derivat ion in soft ware perspectives can be int erpret ed in a couple of different ways. You can use derivat ion t o indicat e t he difference bet ween a calculat ed value and a st ored value. I n this case, we would int erpret Figure 5.5 as indicat ing t hat t he st art and end are st ored but t hat t he lengt h is com put ed. Alt hough t his is a com m on use, I 'm not so keen, because it reveals t oo m uch of the int ernals of DateRange. My preferred t hinking is t hat it indicat es a const raint bet ween values. I n t his case, we are saying t hat t he const raint am ong t he t hree values holds, but it isn't im port ant which of t he t hree values is com put ed. I n t his case, t he choice of which at t ribut e t o m ark as derived is arbit rary and st rict ly unnecessary, but it 's useful t o help rem ind people of t he const raint . This usage also m akes sense wit h concept ual diagram s.
66/ 118
Derivat ion can also be applied t o propert ies using associat ion not at ion. I n this case, you sim ply m ark the nam e wit h a / .
Interfaces and Abstract Classes An a bst r act cla ss is a class t hat cannot be direct ly inst ant iat ed. I nst ead, you inst ant iat e an inst ance of a subclass. Typically, an abst ract class has one or m ore operat ions t hat are abst ract . An a bst r a ct ope r a t ion has no im plem ent at ion; it is pure declarat ion so t hat client s can bind t o t he abst ract class. The m ost com m on way t o indicat e an abst ract class or operat ion in t he UML is t o it alicize t he nam e. You can also m ake propert ies abst ract , indicat ing an abst ract propert y or accessor m et hods. I t alics are t ricky t o do on a whit eboards, so you can use t he label: {abstract}. An int erface is a class t hat has no im plem ent at ion; t hat is, all it s feat ures are abst ract . I nt erfaces correspond direct ly t o int erfaces in C# and Java and are a com m on idiom in ot her t yped languages. You m ark an int erface wit h t he keyword «interface». Classes have t wo kinds of relat ionships wit h int erfaces: providing and requiring. A class provides a n in t e r fa ce if it is subst it ut able for t he int erface. I n Java and .NET, a class can do t hat by im plem ent ing the int erface or im plem ent ing a subt ype of t he int erface. I n C+ + , you subclass t he class t hat is t he int erface. A class r e qu ir e s a n in te r face if it needs an inst ance of that int erface in order t o work. Essent ially, t his is having a dependency on t he int erface. Figure 5.6 shows these relat ionships in act ion, based on a few collect ion classes from Java. I m ight writ e an Order class t hat has a list of line it em s. Because I 'm using a list , t he Order class is dependent on t he List int erface. Let 's assum e that it uses t he m et hods equals, add, and get. When t he obj ect s connect , t he Order will actually use an inst ance of ArrayList but need not know t hat in order t o use t hose three m et hods, as t hey are all part of t he List int erface.
Figu r e 5 .6 . A Ja v a e x a m ple of in t e r f a ce s a n d a n a bst r a ct cla ss
67/ 118
The ArrayList it self is a subclass of the AbstractList class. AbstractList provides som e, but not all, the im plem ent at ion of t he List behavior. I n part icular, the get m et hod is abst ract . As a result , ArrayList im plem ent s get but also overrides som e of t he ot her operat ions on AbstractList. I n t his case, it overrides add but is happy t o inherit t he im plem ent at ion of equals. Why don't I sim ply avoid t his and have Order use ArrayList direct ly? By using t he int erface, I allow m yself t he advant age of m aking it easier t o change im plem ent at ions lat er on if I need t o. Anot her im plem ent at ion m ay provide perform ance im provem ent s, som e dat abase int eract ion feat ures, or ot her benefit s. By program m ing t o t he int erface rat her t han t o t he im plem ent at ion, I avoid having t o change all t he code should I need a different im plem ent at ion of List. You should always t ry t o program t o an int erface like t his; always use the m ost general t ype you can. I should also point out a pragm at ic wrinkle in this. When program m ers use a collect ion like t his, t hey usually init ialize t he collect ion wit h a declarat ion, like t his:
private List lineItems = new ArrayList(); Not e t hat t his st rict ly int roduces a dependency from Order t o t he concret e ArrayList. I n t heory, t his is a problem , but people don't worry about it in pract ice. Because t he t ype of lineItems is declared as List, no ot her part of t he Order class is dependent on ArrayList. Should we change t he im plem ent at ion, t here's only t his one line of init ializat ion code t hat we need t o worry about . I t 's quit e com m on t o refer t o a concret e class once during creat ion but t o use only the int erface aft erward. The full not at ion of Figure 5.6 is one way t o not at e int erfaces. Figure 5.7 shows a m ore com pact not at ion. The fact t hat ArrayList im plem ent s List and Collection is shown by having ball icons, oft en referred t o as lollipops, out of it . The fact that Order requires a List int erface is shown by t he socket icon. The connection is nicely obvious.
Figu r e 5 .7 . Ba ll- a n d- sock e t n ot a t ion 68/ 118
The UML has used t he lollipop not at ion for a while, but t he socket not at ion is new t o UML 2. (I think it 's m y favorit e not at ional addit ion.) You'll probably see older diagram s use t he st yle of Figure 5.8 , where a dependency st ands in for t he socket not at ion.
Figu r e 5 .8 . Olde r de pe n de n cie s w it h lollipops
Any class is a m ix of an int erface and an im plem ent at ion. Therefore, we m ay oft en see an obj ect used t hrough the int erface of one of it s superclasses. St rictly, it wouldn't be legal t o use the lollipop not at ion for a superclass, as the superclass is a class, not a pure int erface. But I bend t hese rules for clarit y. As well as on class diagram s, people have found lollipops useful elsewhere. One of t he perennial problem s wit h int eraction diagram s is that t hey don't provide a very good visualizat ion for polym orphic behavior. Alt hough it 's not norm at ive usage, you can indicat e t his along the lines of Figure 5.9. Here, we can see that , alt hough we have an inst ance of Salesm an, which is used as such by t he Bonus Calculat or, t he Pay Period obj ect uses t he Salesm an only t hrough it s Em ployee int erface. (You can do t he sam e t rick wit h com m unicat ion diagram s.)
Figu r e 5 .9 . Usin g a lollipop t o sh ow poly m or ph ism in a se qu e n ce dia gr a m
69/ 118
Read-Only and Frozen On page 37, I described t he {readOnly} keyword. You use t his keyword t o m ark a propert y that can only be read by client s and t hat cannot be updat ed. Sim ilar yet different is t he {frozen} keyword from UML 1. A propert y is fr oze n if it cannot change during t he lifet im e of an obj ect ; such propert ies are oft en called im m ut able. Alt hough it was dropped from UML 2, {frozen} is a very useful concept , so I would cont inue t o use it . As well as m arking individual propert ies as frozen, you can apply t he keyword t o a class t o indicat e t hat all propert ies of all inst ances are frozen. (I have heard that frozen m ay well be reinst at ed short ly.)
Reference Objects and Value Objects One of t he com m on t hings said about obj ect s is t hat t hey have ident it y. This is t rue, but it is not quit e as sim ple as t hat . I n pract ice, you find t hat ident it y is im port ant for reference obj ect s but not so im port ant for value obj ect s. Re fer e nce obj e cts are such t hings as Cust om er. Here, ident it y is very im port ant because you usually want only one soft ware obj ect t o designat e a cust om er in t he real world. Any obj ect t hat references a Cust om er obj ect will do so t hrough a reference, or point er; all obj ect s t hat reference t his Cust om er will reference t he sam e soft ware obj ect . That way, changes t o a Cust om er are available t o all users of t he Cust om er. I f you have t wo references t o a Cust om er and wish t o see whet her t hey are t he sam e, you usually com pare t heir ident it ies. Copies m ay be disallowed; if t hey are allowed, t hey t end t o be m ade rarely, perhaps for archive purposes or for replicat ion across a net work. I f copies are m ade, you need to sort out how t o synchronize changes. Va lu e obj ect s are such things as Dat e. You oft en have m ult iple value obj ect s represent ing t he sam e obj ect in t he real world. For exam ple, it is norm al t o have hundreds of obj ect s t hat designat e 1- Jan-04. These are all int erchangeable copies. New dat es are creat ed and dest royed frequent ly.
70/ 118
I f you have t wo dat es and wish t o see whet her t hey are t he sam e, you don't look at t heir ident it ies but rat her at t he values t hey represent . This usually m eans that you have t o writ e an equalit y t est operat or, which for dat es would m ake a t est on year, m ont h, and day—or what ever t he int ernal represent at ion is. Each obj ect t hat references 1-Jan- 04 usually has it s own dedicat ed obj ect , but you can also share dat es. Value obj ect s should be im m ut able; in ot her words, you should not be able t o t ake a dat e obj ect of 1- Jan-04 and change t he sam e dat e obj ect t o be 2- Jan- 04. I nst ead, you should creat e a new 2-Jan04 obj ect and use t hat inst ead. The reason is that if t he dat e were shared, you would updat e anot her obj ect 's dat e in an unpredict able way, a problem referred t o as a lia sin g. I n days gone by, t he difference bet ween reference obj ect s and value obj ect s was clearer. Value obj ect s were t he built -in values of t he t ype syst em . Now you can ext end the t ype syst em wit h your own classes, so t his issue requires m ore t hought . The UML uses t he concept of da t a t ype, which is shown as a keyword on t he class sym bol. St rict ly, dat a t ype isn't t he sam e as value obj ect , as dat a t ypes can't have ident it y. Value obj ect s m ay have an ident it y, but don't use it for equalit y. Prim it ives in Java would be dat a t ypes, but dat es would not , alt hough t hey would be value obj ect s. I f it 's im port ant t o highlight t hem , I use com posit ion when associat ing wit h a value obj ect . You can also use a keyword on a value t ype; com m on convent ional ones I see are «value» or «struct».
Qualified Associations A qu a lifie d a ssocia t ion is t he UML equivalent of a program m ing concept variously known as associat ive arrays, m aps, hashes, and dict ionaries. Figure 5.10 shows a way t hat uses a qualifier t o represent t he associat ion bet ween t he Order and Order Line classes. The qualifier says t hat in connect ion wit h an Order, t here m ay be one Order Line for each inst ance of Product .
Figu r e 5 .1 0 . Qu a lifie d a ssocia t ion
From a soft ware perspect ive, t his qualified associat ion would im ply an int erface along t he lines of
class Order ... public OrderLine getLineItem(Product aProduct); public void addLineItem(Number amount, Product forProduct); Thus, all access t o a given Order Line requires a Product as an argum ent , suggest ing an im plem ent at ion using a key and value dat a st ruct ure. I t 's com m on for people t o get confused about t he m ult iplicit ies of a qualified associat ion. I n Figure 5.10, an Order m ay have m any Line I t em s, but t he m ult iplicit y of the qualified associat ion is t he m ult iplicit y in t he cont ext of t he qualifier. So t he diagram says that an Order has 0..1 Line I t em s per Product . A m ult iplicit y of 1 would indicat e that Order would have t o have a Line I t em for every inst ance of Product . A * would indicat e t hat you would have m ult iple Line I t em s per Product but t hat access t o t he Line I t em s is indexed by Product . I n concept ual m odeling, I use the qualifier const ruct only t o show const raint s along t he lines of " single Order Line per Product on Order."
71/ 118
Chapter 6. Object Diagrams An obj ect dia gr a m is a snapshot of t he obj ect s in a syst em at a point in tim e. Because it shows inst ances rat her t han classes, an obj ect diagram is oft en called an inst ance diagram . You can use an obj ect diagram t o show an exam ple configurat ion of obj ect s. ( See Figure 6.1, which shows a set of classes, and Figure 6.2, which shows an associat ed set of obj ect s.) This lat t er use is very useful when t he possible connect ions bet ween obj ect s are com plicat ed.
Figu r e 6 .1 . Cla ss dia gr a m of Pa r t y com posit ion st r u ct u r e
Figu r e 6 .2 . Obj e ct dia gr a m sh ow in g e x a m ple in st a n ce s of Pa r t y
You can t ell t hat t he elem ent s in Figure 6.2 are inst ances because t he nam es are underlined. Each nam e t akes the form instance name : class name. Bot h part s of t he nam e are opt ional, so John, :Person, and aPerson are legal nam es. I f you use only the class nam e, you m ust include t he colon. You can show values for at t ribut es and links, as in Figure 6.2. St rict ly, t he elem ent s of an obj ect diagram are inst ance specificat ions rat her t han t rue inst ances. The reason is t hat it 's legal t o leave m andat ory at t ribut es em pt y or t o show inst ance specificat ions of abst ract classes. You can t hink of an in st an ce spe cifica t ion as a part ly defined inst ance. Anot her way of looking at an obj ect diagram is as a com m unicat ion diagram ( page 131) wit hout m essages.
When to Use Object Diagrams 72/ 118
Obj ect diagram s are useful for showing exam ples of obj ect s connect ed t oget her. I n m any sit uat ions, you can define a st ruct ure precisely wit h a class diagram , but t he st ruct ure is still difficult t o underst and. I n t hese sit uat ions, a couple of obj ect diagram exam ples can m ake all the difference.
Chapter 7. Package Diagrams Classes represent t he basic form of st ruct uring an obj ect - orient ed syst em . Alt hough t hey are wonderfully useful, you need som et hing m ore t o st ructure large syst em s, which m ay have hundreds of classes. A pa cka ge is a grouping const ruct t hat allows you t o t ake any const ruct in the UML and group it s elem ent s t oget her int o higher-level unit s. I t s m ost com m on use is t o group classes, and t hat 's the way I 'm describing it here, but rem em ber t hat you can use packages for every ot her bit of t he UML as well. I n a UML m odel, each class is a m em ber of a single package. Packages can also be m em bers of ot her packages, so you are left wit h a hierarchic st ructure in which t op- level packages get broken down int o subpackages wit h t heir own subpackages and so on unt il the hierarchy bot t om s out in classes. A package can cont ain bot h subpackages and classes. I n program m ing t erm s, packages correspond t o such grouping const ruct s as packages ( in Java) and nam espaces ( in C+ + and .NET) . Each package represent s a n a m espa ce , which m eans t hat every class m ust have a unique nam e wit hin it s owning package. I f I want t o creat e a class called Dat e, and a Dat e class is already in t he Syst em package, I can have m y Dat e class as long as I put it in a separat e package. To m ake it clear which is which, I can use a fu lly qu a lifie d n a m e, t hat is, a nam e t hat shows t he owning package st ruct ure. You use double colons t o show package nam es in UML, so t he dat es m ight be System::Date and MartinFowler::Util::Date. I n diagram s, packages are shown wit h a t abbed folder, as in Figure 7.1. You can sim ply show t he package nam e or show t he cont ent s t oo. At any point , you can use fully qualified nam es or sim ply regular nam es. Showing the cont ent s wit h class icons allows you t o show all the det ails of a class, even t o t he point of showing a class diagram wit hin t he package. Sim ply list ing t he nam es m akes sense when all you want t o do is indicat e which classes are in which packages.
Figu r e 7 .1 . W a y s of sh ow in g pa ck a ge s on dia gr a m s
73/ 118
I t 's quit e com m on t o see a class labeled som et hing like Date (from java.util) rat her t han the fully qualified form . This st yle is a convent ion t hat was done a lot by Rat ional Rose; it isn't part of t he st andard. The UML allows classes in a package t o be public or privat e. A public class is part of t he int erface of t he package and can be used by classes in ot her packages; a privat e class is hidden. Different program m ing environm ent s have different rules about visibilit y bet ween t heir packaging const ruct s; you should follow t he convent ion of your program m ing environm ent , even if it m eans bending t he UML's rules. A useful t echnique here is t o reduce the int erface of t he package by export ing only a sm all subset of t he operat ions associat ed wit h the package's public classes. You can do t his by giving all classes privat e visibilit y, so t hat they can be seen only by ot her classes in t he sam e package, and by adding ext ra public classes for t he public behavior. These ext ra classes, called Facades [ Gang of Four] , t hen delegat e public operat ions t o t heir shyer com panions in t he package. How do you choose which classes t o put in which packages? This is actually quit e an involved quest ion t hat needs a good bit of design skill t o answer. Two useful principles are t he Com m on Closure Principle and Com m on Reuse Principle [ Mart in] . The Com m on Closure Principle says that t he classes in a package should need changing for sim ilar reasons. The Com m on Reuse Principle says t hat classes in a package should all be reused t oget her. Many of t he reasons for grouping classes in packages have t o do wit h t he dependencies bet ween t he packages, which I 'll com e t o next .
Packages and Dependencies A pa cka ge dia gr a m shows packages and t heir dependencies. I int roduced t he concept of dependency on page 47. I f you have packages for present at ion and dom ain, you have a dependency from t he present at ion package t o t he dom ain package if any class in t he present at ion package has a dependency t o any class in t he dom ain package. I n t his way, int erpackage dependencies sum m arize t he dependencies bet ween their cont ent s. The UML has m any variet ies of dependency, each wit h part icular sem ant ics and st ereot ype. I find it easier t o begin wit h the unst ereot yped dependency and use t he m ore part icular dependencies only if I need t o, which I hardly ever do.
74/ 118
I n a m edium t o large syst em , plot t ing a package diagram can be one of the m ost valuable t hings you can do t o cont rol t he large- scale st ruct ure of t he syst em . I deally, t his diagram should be generat ed from t he code base it self, so t hat you can see what is really t here in t he syst em . A good package st ruct ure has a clear flow t o t he dependencies, a concept that 's difficult t o define but oft en easier t o recognize. Figure 7.2 shows a sam ple package diagram for an ent erprise applicat ion, one t hat is well- st ruct ured and has a clear flow.
Figu r e 7 .2 . Pa ck a ge dia gr a m for a n e n t e r pr ise a pplica t ion
Oft en, you can ident ify a clear flow because all the dependencies run in a single direct ion. Alt hough t hat is a good indicat or of a well- st ruct ured syst em , t he dat a m apper packages of Figure 7.2 show an except ion t o t hat rule of t hum b. The dat a m apper packages act as an insulat ing layer bet ween t he dom ain and dat abase packages, an exam ple of t he Mapper pat t ern [ Fowler, P of EAA] . Many aut hors say t hat t here should be no cycles in t he dependencies (t he Acyclic Dependency Principle [ Martin] ) . I don't t reat t hat as an absolut e rule, but I do t hink t hat cycles should be localized and that , in part icular, you shouldn't have cycles t hat cross layers. The m ore dependencies com ing int o a package, t he m ore st able t he package's int erface needs t o be, as any change in it s int erface will ripple int o all the packages t hat are dependent on it ( t he St able Dependencies Principle [ Mart in] ) . So in Figure 7.2 , t he asset dom ain package needs a m ore st able int erface than t he leasing dat a m apper package. Oft en, you'll find that t he m ore st able packages t end t o have a higher proport ion of int erfaces and abst ract classes ( t he St able Abst ract ions Principle [ Mart in] . The dependency relat ionships are not t ransit ive ( page 48) . To see why t his is im port ant for dependencies, look at Figure 7.2 again. I f a class in t he asset dom ain package changes, we m ay have a change t o classes wit hin t he leasing dom ain package. But t his change does not necessarily ripple t hrough t o t he leasing present at ion. ( I t ripples only if the leasing dom ain changes it s int erface.) 75/ 118
Som e packages are used in so m any places that it would be a m ess t o draw all t he dependency lines t o t hem . I n t his case, a convent ion is t o use a keyword, such as «global», on the package. UML packages also define const ruct s t o allow packages t o im port and m erge classes from one package int o anot her, using dependencies wit h keywords t o not at e t his. However, rules for t his kind of t hing vary great ly wit h program m ing languages. On t he whole, I find t he general not ion of dependencies t o be far m ore useful in pract ice.
Package Aspects I f you t hink about Figure 7.2 , you'll realize t hat t he diagram has t wo kinds of st ruct ures. One is a st ruct ure of layers in t he applicat ion: present at ion, dom ain, dat a m apper, and dat abase. The ot her is a st ruct ure of subj ect areas: leasing and asset s. You can m ake t his m ore apparent by separat ing t he t wo aspect s, as in Figure 7.3 . Wit h t his diagram , you can clearly see each aspect . However, t hese t wo aspect s aren't t rue packages, because you can't assign classes t o a single package. ( You would have t o pick one from each aspect .) This problem m irrors t he problem in the hierarchic nam espaces in program m ing languages. Alt hough diagram s like Figure 7.3 are nonst andard UML, t hey are oft en very helpful in explaining t he st ruct ure of a com plex applicat ion.
Figu r e 7 .3 . Se pa r a t in g Figur e 7 .2 int o t w o a spe ct s
Implementing Packages Oft en, you'll see a case in which one package defines an int erface t hat can be im plem ent ed by a num ber of ot her packages, such as t hat of Figure 7.4. I n t his case, the realizat ion relat ionship indicat es t hat t he dat abase gat eway defines an int erface and t hat t he ot her gat eway classes provide an im plem ent at ion. I n practice, t his would m ean t hat the dat abase gat eway package cont ains int erfaces and abst ract classes t hat are fully im plem ent ed by t he ot her packages. 76/ 118
Figu r e 7 .4 . A pa ck a ge im ple m e n t e d by ot h e r pa ck a ge s
I t 's quit e com m on for an int erface and it s im plem ent at ion t o be in separat e packages. I ndeed, a client package oft en cont ains an int erface for anot her package t o im plem ent : t he sam e not ion of required int erface t hat I discussed on page 70. I m agine t hat we want t o provide som e user int erface (UI ) cont rols t o t urn things on and off. We want this t o work wit h a lot of different t hings, such as heat ers and light s. The UI cont rols need t o invoke m et hods on t he heat er, but we don't want t he cont rols t o have a dependency t o t he heat er. We can avoid t his dependency by defining in t he cont rols package an int erface that is t hen im plem ent ed by any class t hat want s t o work wit h t hese cont rols, as in Figure 7.5. This is an exam ple of t he pat t ern Separat ed I nt erface [ Fowler, P of EAA] .
Figu r e 7 .5 . D e fin in g a r e qu ir e d in t e rfa ce in a clie n t pa ck a ge
When to Use Package Diagrams 77/ 118
I find package diagram s ext rem ely useful on larger- scale syst em s t o get a pict ure of the dependencies bet ween m aj or elem ent s of a system . These diagram s correspond well t o com m on program m ing st ruct ures. Plot t ing diagram s of packages and dependencies helps you keep an applicat ion's dependencies under cont rol. Package diagram s represent a com pile-t im e grouping m echanism . For showing how obj ect s are com posed at runt im e, use a com posit e st ruct ure diagram ( page 135) .
Where to Find Out More The best discussion I know of packages and how t o use them is [ Mart in] . Robert Martin has long had an alm ost pat hological obsession wit h dependencies and writ es well about how t o pay at t ent ion t o dependencies so t hat you can cont rol and m inim ize t hem .
Chapter 8. Deployment Diagrams Deploym ent diagram s show a syst em 's physical layout , revealing which pieces of soft ware run on what pieces of hardware. Deploym ent diagram s are really very sim ple; hence t he short chapt er. Figure 8.1 is a sim ple exam ple of a deploym ent diagram . The m ain it em s on t he diagram are nodes connect ed by com m unicat ion pat hs. A n ode is som et hing t hat can host som e soft ware. Nodes com e in t wo form s. A de vice is hardware, it m ay be a com put er or a sim pler piece of hardware connect ed t o a syst em . An e xe cut ion e n viron m en t is soft ware t hat it self host s or cont ains ot her soft ware, exam ples are an operat ing syst em or a cont ainer process.
Figu r e 8 .1 . Ex a m ple de ploy m e n t dia gr a m
78/ 118
The nodes cont ain a r t ifact s, which are the physical m anifest at ions of soft ware: usually, files. These files m ight be execut ables (such as .exe files, binaries, DLLs, JAR files, assem blies, or script s) , or dat a files, configurat ion files, HTML docum ent s, and so on. List ing an art ifact wit hin a node shows t hat t he art ifact is deployed t o t hat node in t he running syst em . You can show artifact s eit her as class boxes or by list ing the nam e wit hin a node. I f you show t hem as class boxes, you can add a docum ent icon or t he «artifact» keyword. You can t ag nodes or art ifact s wit h t agged values t o indicat e various int erest ing inform at ion about the node, such as vendor, operat ing syst em , locat ion, or anyt hing else t hat t akes your fancy. Oft en, you'll have m ult iple physical nodes carrying out the sam e logical t ask. You can eit her show t his wit h m ult iple node boxes or st at e t he num ber as a t agged value. I n Figure 8.1, I used t he t ag number deployed t o indicat e t hree physical Web servers, but t here's no st andard t ag for t his. Art ifact s are oft en the im plem ent at ion of a com ponent . To show this, you can use a t agged value in t he art ifact box. Com m unicat ion pat hs bet ween nodes indicat e how t hings com m unicat e. You can label t hese pat hs wit h inform at ion about t he com m unicat ion prot ocols t hat are used.
When to Use Deployment Diagrams Don't let t he brevit y of t his chapt er m ake you t hink t hat deploym ent diagram s shouldn't be used. They are very handy in showing what is deployed where, so any nont rivial deploym ent can m ake good use of t hem .
Chapter 9. Use Cases Use cases are a t echnique for capt uring t he funct ional requirem ent s of a syst em . Use cases work by describing t he t ypical int eract ions bet ween the users of a syst em and t he syst em it self, providing a narrat ive of how a syst em is used. Rat her t han describe use cases head- on, I find it easier t o sneak up on t hem from behind and start by describing scenarios. A scen a r io is a sequence of st eps describing an int eract ion bet ween a user and a syst em . So if we have a Web- based on-line st ore, we m ight have a Buy a Product scenario t hat would say this: The cust om er browses t he cat alog and adds desired it em s t o t he shopping basket . When t he cust om er wishes t o pay, t he cust om er describes t he shipping and credit card inform at ion and confirm s t he sale. The system checks t he aut horizat ion on the credit card and confirm s t he sale bot h im m ediat ely and wit h a follow- up e-m ail . This scenario is one t hing that can happen. However, t he credit card aut horizat ion m ight fail, and t his would be a separat e scenario. I n anot her case, you m ay have a regular cust om er for whom you don't need t o capt ure the shipping and credit card inform at ion, and this is a t hird scenario. All t hese scenarios are different yet sim ilar. The essence of t heir sim ilarit y is t hat in all these t hree scenarios, the user has t he sam e goal: t o buy a product . The user doesn't always succeed, but t he goal rem ains. This user goal is t he key t o use cases: A use case is a set of scenarios tied t oget her by a com m on user goal. I n use case–speak, t he users are referred t o as act ors. An a ctor is a role t hat a user plays wit h respect t o t he syst em . Act ors m ight include custom er, cust om er service rep, sales m anager, and 79/ 118
product analyst . Act ors carry out use cases. A single act or m ay perform m any use cases; conversely, a use case m ay have several act ors perform ing it . Usually, you have m any cust om ers, so m any people can be t he cust om er act or. Also, one person m ay act as m ore than one act or, such as a sales m anager who does cust om er service rep t asks. An act or doesn't have t o be hum an. I f t he syst em perform s a service for anot her com put er syst em , t hat ot her syst em is an act or. Act or isn't really t he right t erm ; role would be m uch bet t er. Apparent ly, t here was a m ist ranslat ion from Swedish, and act or is t he t erm the use case com m unit y uses. Use cases are well known as an im port ant part of t he UML. However, t he surprise is t hat in m any ways, t he definit ion of use cases in t he UML is rat her sparse. Not hing in t he UML describes how you should capt ure t he cont ent of a use case. What t he UML describes is a use case diagram , which shows how use cases relat e t o each ot her. But alm ost all the value of use cases lies in t he cont ent , and t he diagram is of rat her lim it ed value.
Content of a Use Case There is no st andard way t o writ e t he cont ent of a use case, and different form at s work well in different cases. Figure 9.1 shows a com m on st yle t o use. You begin by picking one of the scenarios as t he m a in su ccess sce n a r io. You st art t he body of t he use case by writ ing t he m ain success scenario as a sequence of num bered st eps. You t hen t ake t he ot her scenarios and writ e t hem as e x t e n sion s, describing t hem in t erm s of variat ions on t he m ain success scenario. Ext ensions can be successes—user achieves t he goal, as in 3a—or failures, as in 6a.
Figu r e 9 .1 . Ex a m ple u se ca se t e x t
Each use case has a prim ary act or, which calls on t he syst em t o deliver a service. The prim ary act or is t he act or wit h t he goal t he use case is t rying t o sat isfy and is usually, but not always, the init iat or of t he use case. There m ay be ot her act ors as well wit h which t he syst em com m unicat es while carrying out t he use case. These are known as secondary act ors. Each st ep in a use case is an elem ent of t he int eract ion bet ween an act or and t he syst em . Each st ep should be a sim ple st at em ent and should clearly show who is carrying out t he st ep. The st ep should show t he int ent of t he act or, not t he m echanics of what t he act or does. Consequent ly, you don't describe t he user int erface in t he use case. I ndeed, writ ing the use case usually precedes designing t he user int erface. 80/ 118
An ext ension wit hin t he use case nam es a condit ion t hat result s in different int eract ions from t hose described in t he m ain success scenario ( MSS) and st at es what t hose differences are. St art t he ext ension by nam ing t he st ep at which the condit ion is det ect ed and provide a short descript ion of t he condit ion. Follow t he condit ion wit h num bered st eps in t he sam e st yle as t he m ain success scenario. Finish t hese st eps by describing where you ret urn t o t he m ain success scenario, if you do. The use case st ruct ure is a great way t o brainstorm alt ernat ives t o t he m ain success scenario. For each st ep, ask, How could t his go different ly? and in part icular, What could go wrong? I t 's usually best t o brainst orm all t he ext ension condit ions first , before you get bogged down working out t he consequences. You'll probably t hink of m ore condit ions t his way, which t ranslat es t o fewer goofs t hat you have t o pick up lat er. A com plicat ed st ep in a use case can be anot her use case. I n UML t erm s, we say t hat the first use case inclu de s t he second. There's no st andard way t o show an included use case in t he t ext , but I find t hat underlining, which suggest s a hyperlink, works very nicely and in m any t ools really will be a hyperlink. Thus in Figure 9.1 , t he first st ep includes t he use case " browse cat alog and select it em s t o buy." I ncluded use cases can be useful for a com plex st ep that would clut t er t he m ain scenario or for st eps t hat are repeat ed in several use cases. However, don't t ry t o break down use cases int o sub–use cases and subsub–use cases using funct ional decom posit ion. Such a decom posit ion is a good way t o wast e a lot of t im e. As well as the st eps in the scenarios, you can add som e ot her com m on inform at ion t o a use case. • • •
A pr e - con dit ion describes what t he syst em should ensure is t rue before the syst em allows t he use case t o begin. This is useful for t elling the program m ers what condit ions they don't have t o check for in their code. A gu ar a n t ee describes what t he syst em will ensure at t he end of t he use case. Success guarant ees hold aft er a successful scenario; m inim al guarant ees hold aft er any scenario. A t r igge r specifies t he event t hat get s the use case st art ed.
When you're considering adding elem ent s, be skept ical. I t 's bet t er t o do t oo lit t le t han t oo m uch. Also, work hard t o keep t he use case brief and easy t o read. I 've found t hat long, det ailed use cases don't get read, which rat her defeat s the purpose. The am ount of det ail you need in a use case depends on t he am ount of risk in t hat use case. Often, you need det ails on only a few key use cases early on; ot hers can be fleshed out j ust before you im plem ent t hem . You don't have t o writ e all t he det ail down; verbal com m unicat ion is oft en very effective, particularly wit hin an it erat ive cycle in which needs are quickly m et by running code.
Use Case Diagrams As I said earlier, the UML is silent on t he cont ent of a use case but does provide a diagram form at for showing t hem , as in Figure 9.2. Alt hough t he diagram is som et im es useful, it isn't m andat ory. I n your use case work, don't put t oo m uch effort int o t he diagram . I nst ead, concent rat e on t he t ext ual cont ent of the use cases.
Figu r e 9 .2 . Use ca se dia gr a m
81/ 118
The best way t o t hink of a use case diagram is t hat it 's a graphical t able of cont ent s for t he use case set . I t 's also sim ilar t o t he cont ext diagram used in st ruct ured m et hods, as it shows the syst em boundary and t he int eract ions wit h the out side world. The use case diagram shows t he act ors, t he use cases, and t he relat ionships bet ween t hem : • •
Which act ors carry out which use cases Which use cases include ot her use cases
The UML includes ot her relat ionships bet ween use cases beyond t he sim ple includes, such as «extend». I st rongly suggest t hat you ignore t hem . I 've seen t oo m any sit uat ions in which t eam s can get t erribly hung up on when t o use different use case relat ionships, and such energy is wast ed. I nst ead, concent rat e on t he t ext ual descript ion of a use case; that 's where t he real value of t he t echnique lies.
Levels of Use Cases A com m on problem wit h use cases is that by focusing on t he int eraction bet ween a user and the syst em , you can neglect sit uat ions in which a change t o a business process m ay be t he best way t o deal wit h t he problem . Oft en, you hear people talk about syst em use cases and business use cases. The t erm s are not precise, but in general, a syst e m u se case is an int eract ion wit h t he soft ware, whereas a busin e ss u se ca se discusses how a business responds t o a cust om er or an event . [ Cockburn, use cases] suggest s a schem e of levels of use cases. The core use cases are at "sea level." Se a - le ve l use cases t ypically represent a discret e int eract ion bet ween a prim ary act or and t he syst em . Such use cases will deliver som et hing of value t o t he prim ary act or and usually t ake from a couple of m inut es t o half an hour for t he prim ary act or t o com plet e. Use cases t hat are t here only because t hey are included by sea-level use cases are fish le ve l. Higher, k it e - le ve l use cases show how t he sea- level use cases fit int o wider business int eract ions. Kit e-level use cases are usually business use cases, whereas sea and fish levels are syst em use cases. You should have m ost of your use cases at the sea level. I prefer t o indicat e t he level at t he t op of t he use case, as in Figure 9.1.
Use Cases and Features (or Stories) Many approaches use feat ures of a syst em —Extrem e Program m ing calls t hem user st ories—t o help describe requirem ent s. A com m on quest ion is how feat ures and use cases int errelat e. 82/ 118
Feat ures are a good way of chunking up a syst em for planning an it erat ive proj ect , whereby each it erat ion delivers a num ber of feat ures. Use cases provide a narrat ive of how t he act ors use the syst em . Hence, alt hough bot h t echniques describe requirem ent s, t heir purposes are different . Alt hough you can go directly t o describing feat ures, m any people find it helpful t o develop use cases first and then generat e a list of feat ures. A feat ure m ay be a whole use case, a scenario in a use case, a st ep in a use case, or som e variant behavior, such as adding yet anot her depreciat ion m et hod for your asset valuat ions, t hat doesn't show up in a use case narrat ive. Usually, feat ures end up being m ore fine grained t han use cases.
When to Use Use Cases Use cases are a valuable t ool t o help underst and t he funct ional requirem ent s of a syst em . A first pass at use cases should be m ade early on. More det ailed versions of use cases should be worked j ust prior t o developing t hat use case. I t is im port ant t o rem em ber t hat use cases represent an ext ernal view of t he syst em . As such, don't expect any correlat ions bet ween use cases and t he classes inside t he syst em . The m ore I see of use cases, the less valuable t he use case diagram seem s t o be. Wit h use cases, concent rat e your energy on t heir t ext rat her than on t he diagram . Despit e t he fact that t he UML has not hing t o say about t he use case t ext , it is t he t ext t hat cont ains all t he value in t he t echnique. A big danger of use cases is t hat people m ake them t oo com plicat ed and get st uck. Usually, you'll get less hurt by doing t oo lit t le t han by doing t oo m uch. A couple of pages per use case is j ust fine for m ost cases. I f you have t oo lit t le, at least you'll have a short , readable docum ent t hat 's a st art ing point for quest ions. I f you have t oo m uch, hardly anyone will read and underst and it .
Where to Find Out More Use cases were originally popularized by I var Jacobson in [ Jacobson, OOSE] . Alt hough use cases have been around for a while, t here's been lit t le st andardizat ion on their use. The UML is silent on t he im port ant cont ent s of a use case and has st andardized only t he m uch less im port ant diagram s. As a result , you can find a divergent range of opinions on use cases. I n the last few years, however, [ Cockburn, use cases] has becom e t he st andard book on t he subj ect . I n this chapt er, I 've followed t he t erm inology and advice of t hat book for t he excellent reason that when we've disagreed in the past , I 've usually ended up agreeing wit h Alist air Cockburn in t he end. He also m aint ains a Web sit e at h t t p:/ / u se case s.or g. [ Const ant ine and Lockwood] provides a convincing process for deriving user int erfaces from use cases; also see h t t p:/ / for use .com .
Chapter 10. State Machine Diagrams St a t e m a ch in e dia gr a m s are a fam iliar t echnique t o describe t he behavior of a syst em . Various form s of st at e diagram s have been around since t he 1960s and t he earliest obj ect - orient ed t echniques adopt ed them t o show behavior. I n obj ect - orient ed approaches, you draw a st at e m achine diagram for a single class t o show t he lifet im e behavior of a single obj ect . Whenever people writ e about st at e m achines, t he exam ples are inevit ably cruise cont rols or vending m achines. As I 'm a lit t le bored wit h t hem , I decided t o use a cont roller for a secret panel in a Got hic 83/ 118
cast le. I n t his cast le, I want t o keep m y valuables in a safe t hat 's hard t o find. So t o reveal t he lock t o t he safe, I have t o rem ove a st rat egic candle from it s holder, but t his will reveal the lock only while t he door is closed. Once I can see the lock, I can insert m y key t o open t he safe. For ext ra safet y, I m ake sure t hat I can open t he safe only if I replace t he candle first . I f a t hief neglect s this precaut ion, I 'll unleash a nast y m onst er t o devour him . Figure 10.1 shows a st at e m achine diagram of t he cont roller class t hat direct s m y unusual securit y syst em .The st at e diagram st art s wit h t he st at e of t he cont roller obj ect when it 's creat ed: in Figure 10.1, t he Wait st at e. The diagram indicat es t his wit h in it ia l pse u dost a t e, which is not a st at e but has an arrow t hat point s t o t he init ial st at e.
Figu r e 1 0 .1 . A sim ple st a t e m a ch in e dia gr a m
The diagram shows that t he cont roller can be in t hree st at es: Wait , Lock, and Open. The diagram also gives t he rules by which t he cont roller changes from st at e t o st at e. These rules are in t he form of t ransit ions: t he lines that connect t he st at es. The t r a nsit ion indicat es a m ovem ent from one st at e t o anot her. Each t ransit ion has a label t hat com es in t hree part s: trigger-signature [guard]/activity. All t he part s are opt ional. The trigger-signature is usually a single event t hat t riggers a pot ent ial change of st at e. The guard, if present , is a Boolean condit ion t hat m ust be t rue for t he t ransit ion t o be t aken. The activity is som e behavior t hat 's execut ed during t he t ransit ion. I t m ay be any behavioral expression. The full form of a trigger-signature m ay include m ult iple event s and param et ers. So in Figure 10.1 , you read t he out ward t ransit ion from t he Wait st at e as " I n t he Wait st at e if t he candle is rem oved providing t he door is open, you reveal t he lock and m ove t o t he Lock st at e." All t hree part s t o a t ransit ion are opt ional. A m issing act ivit y indicat es t hat you don't do anything during t he t ransit ion. A m issing guard indicat es t hat you always t ake t he t ransit ion if t he event occurs. A m issing t rigger- signat ure is rare but does occur. I t indicat es t hat you t ake the t ransit ion im m ediat ely, which you see m ost ly wit h act ivit y st at es, which I 'll com e t o in a m om ent . When an event occurs in a st at e, you can t ake only one t ransit ion out of it . So if you use m ult iple t ransit ions wit h the sam e event , as in t he Lock st at e of Figure 10.1, t he guards m ust be m ut ually exclusive. I f an event occurs and no t ransit ion is valid—for exam ple, a safe- closed event in the Wait st at e or a candle-rem oved event wit h t he door closed—t he event is ignored. The final st at e indicat es that t he st at e m achine is com plet ed, im plying t he delet ion of t he cont roller obj ect . Thus, if som eone should be so careless as t o fall for m y t rap, t he cont roller obj ect t erm inat es, so I would need t o put t he rabbit in it s cage, m op t he floor, and reboot the syst em . 84/ 118
Rem em ber t hat st at e m achines can show only what t he obj ect directly observes or act ivat es. So alt hough you m ight expect m e t o add or rem ove t hings from t he safe when it 's open, I don't put t hat on t he st at e diagram , because t he cont roller cannot t ell. When developers t alk about obj ect s, t hey oft en refer t o t he st at e of the obj ect s t o m ean t he com binat ion of all the dat a in t he fields of t he obj ect s. However, t he st at e in a st at e m achine diagram is a m ore abst ract not ion of st at e; essent ially, different st at es im ply a different way of react ing t o event s.
Internal Activities St at es can react t o event s wit hout t ransit ion, using in t e rn a l a ct ivit ie s: put t ing t he event , guard, and act ivit y inside the st at e box it self. Figure 10.2 shows a st at e wit h int ernal activit ies of t he charact er and help event s, as you m ight find on a UI t ext field. An int ernal act ivit y is sim ilar to a se lf- tr a n sit ion : a t ransit ion t hat loops back t o t he sam e st at e. The synt ax for int ernal act ivit ies follows t he sam e logic for event , guard, and procedure.
Figu r e 1 0 .2 . I n t e rn a l e v e n t s sh ow n w it h t h e t ypin g st a t e of a t e x t fie ld
Figure 10.2 also shows t wo special act ivit ies: t he ent ry and exit act ivit ies. The e n tr y a ct ivit y is execut ed whenever you ent er a st at e; t he e x it a ct ivit y, whenever you leave. However, int ernal act ivit ies do not t rigger t he ent ry and exit activit ies; that is t he difference bet ween int ernal act ivit ies and self-t ransit ions.
Activity States I n the st at es I 've described so far, t he obj ect is quiet and wait ing for t he next event before it does som et hing. However, you can have st at es in which the obj ect is doing som e ongoing work. The Searching st at e in Figure 10.3 is such an a ct ivit y st a t e : The ongoing act ivit y is m arked wit h t he do/; hence the t erm do- a ct ivit y. Once t he search is com plet ed, any t ransit ions wit hout an act ivit y, such as the one t o display new hardware, are t aken. I f t he cancel event occurs during t he act ivit y, the do- act ivit y is uncerem oniously halt ed, and we go back t o t he Updat e Hardware Window st at e.
Figu r e 1 0 .3 . A st a t e w it h a n a ct iv it y
85/ 118
Bot h do- act ivit ies and regular activit ies represent carrying out som e behavior. The crit ical difference bet ween t he t wo is t hat regular act ivit ies occur "inst ant aneously" and cannot be int errupt ed by regular event s, while do- act ivit ies can t ake finit e t im e and can be int errupt ed, as in Figure 10.3. I nst ant aneous will m ean different t hings for different syst em ; for hard real- t im e syst em s, it m ight be a few m achine inst ruct ions, but for deskt op soft ware m ight be several seconds. UML 1 used t he t erm a ct ion for regular act ivit ies and used activit y only for do- act ivit ies.
Superstates Oft en, you'll find t hat several st at es share com m on t ransit ions and int ernal act ivit ies. I n t hese cases, you can m ake t hem subst at es and m ove t he shared behavior int o a superst at e, as in Figure 10.4. Wit hout t he superst at e, you would have t o draw a cancel t ransit ion for all t hree st at es wit hin t he Ent er Connect ion Det ails st at e.
Figu r e 1 0 .4 . Su pe r st a t e w it h n e st e d su bst a t e s
Concurrent States St at es can be broken int o several ort hogonal st at e diagram s t hat run concurrent ly. Figure 10.5 shows a pat het ically sim ple alarm clock t hat can play eit her CDs or t he radio and show eit her the current t im e or t he alarm t im e.
86/ 118
Figu r e 1 0 .5 . Con cu r r e n t or t h ogon a l st a t e s
The choices CD/ radio and current / alarm t im e are ort hogonal choices. I f you want ed t o represent t his wit h a nonorthogonal st at e diagram , you would need a m essy diagram that would get very m uch out of hand should you want m ore st at es. Separat ing out t he t wo areas of behavior int o separat e stat e diagram s m akes it m uch clearer. Figure 10.5 also includes a h ist or y pse u dost a te. This indicat es t hat when t he clock is swit ched on, t he radio/ CD choice goes back t o t he st at e t he clock was in when it was t urned off. The arrow from t he hist ory pseudost at e indicat es what st at e t o be in on t he first t im e when t here is no hist ory.
Implementing State Diagrams A st at e diagram can be im plem ent ed in t hree m ain ways: nest ed swit ch, t he St at e pat t ern, and st at e t ables. The m ost direct approach t o handling a st at e diagram is a nest ed swit ch st at em ent , such as Figure 10.6. Alt hough it 's direct , it 's long- winded, even for t his sim ple case. I t 's also very easy for t his approach t o get out of cont rol, so I don't like using it even for sim ple cases.
Figu r e 1 0 .6 A C# n e st e d sw it ch t o ha n dle t h e st a t e t r a n sit ion fr om Figur e 1 0 .1 public void HandleEvent (PanelEvent anEvent) { switch (CurrentState) { case PanelState.Open : switch (anEvent) { case PanelEvent.SafeClosed : CurrentState = PanelState.Wait; break; } break; case PanelState.Wait : 87/ 118
switch (anEvent) { case PanelEvent.CandleRemoved : if (isDoorOpen) { RevealLock(); CurrentState = PanelState.Lock; } break; } break; case PanelState.Lock : switch (anEvent) { case PanelEvent.KeyTurned : if (isCandleIn) { OpenSafe(); CurrentState = PanelState.Open; } else { ReleaseKillerRabbit(); CurrentState = PanelState.Final; } break; } break; } } } The St a t e pa t te r n [ Gang of Four] creat es a hierarchy of st at e classes t o handle behavior of t he st at es. Each st at e in t he diagram has one st at e subclass. The cont roller has m et hods for each event , which sim ply forwards t o t he st at e class. The stat e diagram of Figure 10.1 would yield an im plem ent at ion indicat ed by t he classes of Figure 10.7.
Figu r e 1 0 .7 . A St a t e pa t t e r n im ple m e n t a t ion for Figu r e 1 0 .1
The t op of t he hierarchy is an abst ract class t hat im plem ent s all t he event -handling m et hods t o do not hing. For each concret e st at e, you sim ply override t he specific event m et hods for which t hat st at e has t ransit ions. The st a t e t a ble approach capt ures the st at e diagram inform at ion as dat a. So Figure 10.1 m ight end up represent ed in a t able like Table 10.1. We t hen build eit her an int erpret er t hat uses t he st at e t able at runt im e or a code generat or t hat generat es classes based on t he st at e t able. Obviously, t he st at e t able is m ore work t o do once, but then you can use it every t im e you have a st at e problem t o hold. A runt im e st at e t able can also be m odified wit hout recom pilat ion, which in 88/ 118
som e cont ext s is quit e handy. The st at e pat t ern is easier t o put t oget her when you need it , and alt hough it needs a new class for each st at e, it 's a sm all am ount of code t o writ e in each case. These im plem ent at ions are pret t y m inim al, but they should give you an idea of how t o go about im plem ent ing st at e diagram s. I n each case, im plem ent ing st at e m odels leads t o very boilerplat e code, so it 's usually best t o use som e form of code generat ion t o do it .
Ta ble 1 0 .1 . A St a t e Ta ble for Figu r e 1 0 .1 Sou rce Sta t e
Ta r ge t Sta t e
Eve n t
Gu a r d
Pr oce du re
Wait
Lock
Candle rem oved
Door open
Reveal lock
Lock
Open
Key t urned
Candle in
Open safe
Lock
Final
Key t urned
Candle out
Release killer rabbit
Open
Wait
Safe closed
When to Use State Diagrams St at e diagram s are good at describing t he behavior of an obj ect across several use cases. St at e diagram s are not very good at describing behavior t hat involves a num ber of obj ect s collaborat ing. As such, it is useful t o com bine st at e diagram s wit h ot her t echniques. For inst ance, int eract ion diagram s ( see Chapt er 4) are good at describing t he behavior of several obj ect s in a single use case, and act ivit y diagram s ( see Chapt er 11) are good at showing the general sequence of act ivit ies for several obj ect s and use cases. Not everyone finds st at e diagram s nat ural. Keep an eye on how people are working wit h them . I t m ay be t hat your t eam does not find st at e diagram s useful t o it s way of working. That is not a big problem ; as always, you should rem em ber t o use t he m ix of t echniques t hat works for you. I f you do use st at e diagram s, don't t ry t o draw them for every class in t he syst em . Alt hough t his approach is oft en used by high- cerem ony com plet ist s, it is alm ost always a wast e of effort . Use st at e diagram s only for t hose classes t hat exhibit int erest ing behavior, where building t he st at e diagram helps you underst and what is going on. Many people find t hat UI and cont rol obj ect s have t he kind of behavior that is useful t o depict wit h a st at e diagram .
Where to Find Out More Bot h t he User Guide [ Booch, UML user] and t he Reference Manual [ Rum baugh, UML Reference] have m ore inform at ion on st at e diagram s. Real-t im e designers t end t o use st at e m odels a lot , so it 's no surprise t hat [ Douglass] ) has a lot t o say about st at e diagram s, including inform at ion on how t o im plem ent t hem . [ Mart in] cont ains a very good chapt er on t he various ways of im plem ent ing st at e diagram s.
Chapter 11. Activity Diagrams Act ivit y diagram s are a t echnique t o describe procedural logic, business process, and work flow. I n m any ways, t hey play a role sim ilar t o flowchart s, but t he principal difference bet ween t hem and flowchart not at ion is t hat t hey support parallel behavior. Act ivit y diagram s have seen som e of t he biggest changes over t he versions of the UML, so t hey have, not surprisingly, been significant ly ext ended and alt ered again for UML 2. I n UML 1, act ivit y 89/ 118
diagram s were seen as special cases of st at e diagram s. This caused a lot of problem s for people m odeling work flows, which act ivit y diagram s are well suit ed for. I n UML 2, t hat t ie was rem oved. Figure 11.1 shows a sim ple exam ple of an act ivit y diagram . We begin at t he in it ia l n ode act ion and t hen do t he act ion Receive Order. Once that is done, we encount er a fork. A for k has one incom ing flow and several out going concurrent flows.
Figu r e 1 1 .1 . A sim ple a ct iv it y dia gr am
Figure 11.1 says t hat Fill Order, Send I nvoice, and t he subsequent act ions occur in parallel. Essent ially, t his m eans t hat the sequence bet ween t hem is irrelevant . I could fill t he order, send t he invoice, deliver, and t hen receive paym ent ; or, I could send the invoice, receive t he paym ent , fill t he order, and t hen deliver: You get t he picture. I can also do t hese act ions by int erleaving. I grab t he first line it em from st ores, t ype up t he invoice, grab t he second line it em , put t he invoice in an envelope, and so fort h. Or, I could do som e of t his 90/ 118
sim ult aneously: t ype up the invoice wit h one hand while I reach int o m y st ores wit h anot her. Any of t hese sequences is correct , according t o t he diagram . The act ivit y diagram allows whoever is doing the process t o choose t he order in which t o do t hings. I n ot her words, t he diagram m erely st at es t he essent ial sequencing rules I have t o follow. This is im port ant for business m odeling because processes oft en occur in parallel. I t 's also useful for concurrent algorit hm s, in which independent t hreads can do t hings in parallel. When you have parallelism , you'll need t o synchronize. We don't close t he order unt il it is delivered and paid for. We show t his wit h t he j oin before t he Close Order act ion. Wit h a j oin, t he out going flow is t aken only when all t he incom ing flows reach t he j oin. So you can close t he order only when you have bot h received t he paym ent and delivered. UML 1 had part icular rules for balancing t he forks and j oins, as act ivit y diagram s were special cases of st at e diagram s. Wit h UML 2, such balancing is no longer needed. You'll not ice that the nodes on an activit y diagram are called act ions, not activit ies. St rictly, an act ivit y refers t o a sequence of act ions, so t he diagram shows an act ivit y t hat 's m ade up of act ions. Condit ional behavior is delineat ed by decisions and m erges. A de cision, called branch in UML 1, has a single incom ing flow and several guarded out -bound flows. Each out bound flow has a guard: a Boolean condit ion placed inside square bracket s. Each t im e you reach a decision, you can t ake only one of the out bound flows, so t he guards should be m ut ually exclusive. Using [else] as a guard indicat es t hat t he [else] flow should be used if all the ot her guards on t he decision are false. I n Figure 11.1, aft er an order is filled, t here is a decision. I f you have a rush order, you do an Overnight Delivery; ot herwise, you do a Regular Delivery. A m e r ge has m ult iple input flows and a single out put . A m erge m arks t he end of condit ional behavior st art ed by a decision. I n m y diagram s, each act ion has a single flow com ing in and a single flow going out . I n UML 1, m ult iple incom ing flows had an im plicit m erge. That is, your act ion would execut e if any flow t riggered. I n UML 2, t his has changed so t here's an im plicit j oin inst ead; t hus, the action execut es only if all flows t rigger. As a result of this change, I recom m end t hat you use only a single incom ing and out going flow t o an act ion and show all j oins and m erges explicit ly; t hat will avoid confusion.
Decomposing an Action Act ions can be decom posed int o subact ivit ies. I can t ake t he delivery logic of Figure 11.1 and define it as it s own act ivit y ( Figure 11.2 ) . Then I can call it as an act ion ( Figure 11.3 on page 121) .
Figu r e 1 1 .2 . A su bsidia r y a ct iv it y dia gr a m
91/ 118
Figu r e 1 1 .3 . Th e a ct iv it y of Figu r e 1 1 .1 m odifie d t o in v ok e t h e a ct iv it y in Figu r e 1 1 .2
92/ 118
Act ions can be im plem ent ed eit her as subact ivit ies or as m et hods on classes. You can show a subact ivit y by using t he rake sym bol. You can show a call on a m et hod wit h synt ax classname::method-name. You can also writ e a code fragm ent int o t he action sym bol if the invoked behavior isn't a single m et hod call.
And There's More I should st ress that this chapt er only scrat ches the surface on activit y diagram s. As wit h so m uch of t he UML, you could writ e a whole book on t his one t echnique alone. I ndeed, I t hink t hat act ivit y diagram s would m ake a very suit able t opic for a book t hat really dug int o t he not at ion and how t o use it . The vit al quest ion is how widely t hey get used. Act ivit y diagram s aren't t he m ost widely used UML t echnique at t he m om ent , and t heir flow- m odeling progenit ors weren't very popular eit her. Diagram m at ic t echniques haven't yet caught on m uch for describing behavior in t his kind of way. On t he ot her hand, t here are signs in a num ber of com m unit ies of a pent - up dem and t hat a st andard t echnique will help t o sat isfy.
When to Use Activity Diagrams The great st rengt h of act ivit y diagram s lies in t he fact t hat t hey support and encourage parallel behavior. This m akes t hem a great t ool for work flow and process m odeling, and indeed m uch of t he push in UML 2 has com e from people involved in work flow. You can also use an act ivit y diagram as a UML-com pliant flowchart . Alt hough t his allows you t o do flowchart s in a way that st icks wit h the UML, it 's hardly very excit ing. I n principle, you can t ake advant ages of t he forks and j oins t o describe parallel algorit hm s for concurrent program s. Alt hough I don't t ravel in concurrent circles that m uch, I haven't seen m uch evidence of people using them t here. I t hink t he reason is that m ost of the com plexit y of concurrent program m ing is in avoiding cont ent ion on dat a, and act ivit y diagram s don't help m uch wit h t hat . The m ain st rengt h of doing t his m ay com e wit h people using UML as a program m ing language. I n t his case, act ivit y diagram s represent an im port ant t echnique t o represent behavioral logic. I 've oft en seen act ivit y diagram s used t o describe a use case. The danger of t his approach is t hat oft en, dom ain expert s don't follow t hem easily. I f so, you'd be bet t er off wit h the usual t ext ual form .
Where to Find Out More Alt hough act ivit y diagram s have always been rat her com plicat ed and are even m ore so wit h UML 2, t here hasn't been a good book t hat describes t hem in dept h. I hope t his gap will get filled som eday. Various flow- orient ed t echniques are sim ilar in st yle t o act ivit y diagram s. One of t he bet t er known— but hardly well known—is Pet ri Net s, for which ht t p:/ / w w w .da im i.a u .dk / Pe t r iN e ts/ is a good Web sit e.
Partitions Act ivit y diagram s t ell you what happens, but t hey do not t ell you who does what . I n program m ing, t his m eans that t he diagram does not convey which class is responsible for each act ion. I n business 93/ 118
process m odeling, t his does not convey which part of an organizat ion carries out which act ion. This isn't necessarily a problem ; oft en, it m akes sense t o concent rat e on what get s done rat her t han on who does what part s of t he behavior. I f you want t o show who does what , you can divide an activit y diagram int o par t it ion s, which show which act ions one class or organizat ion unit carries out . Figure 11.4 ( on page 122) shows a sim ple exam ple of t his, showing how t he act ions involved in order processing can be separat ed am ong various depart m ent s.
Figu r e 1 1 .4 . Pa r t it ions on a n a ct iv it y dia gr a m
The part it ioning of Figure 11.4 is a sim ple one- dim ensional part it ioning. This st yle is oft en referred t o as sw im la n e s, for obvious reasons and was t he only form used in UML 1.x. I n UML 2, you can use a t wo- dim ensional grid, so t he swim m ing m et aphor no longer holds wat er. You can also t ake each dim ension and divide t he rows or colum ns hierarchically.
Signals I n the sim ple exam ple of Figure 11.1 , act ivit y diagram s have a clearly defined st art point , which corresponds t o an invocat ion of a program or rout ine. Act ions can also respond t o signals.
94/ 118
A t im e sign a l occurs because of the passage of t im e. Such signals m ight indicat e the end of a m ont h in a financial period or each m icrosecond in a real-t im e cont roller. Figure 11.5 shows an act ivit y t hat list ens for t wo signals. A sign a l indicat es t hat t he act ivit y receives an event from an out side process. This indicat es t hat t he act ivit y const ant ly list ens for t hose signals, and the diagram defines how t he act ivit y react s.
Figu r e 1 1 .5 . Sign a ls on a n a ct iv it y dia gr a m
I n the case of Figure 11.5, 2 hours before m y flight leaves, I need t o st art packing m y bags. I f I 'm quick t o pack t hem , I st ill cannot leave unt il t he t axi arrives. I f t he t axi arrives before m y bags are packed, it has t o wait for m e t o finish before we go. As well as accept ing signals, we can send t hem . This is useful when we have t o send a m essage and t hen wait for a reply before we can cont inue. Figure 11.6 shows a good exam ple of t his wit h a com m on idiom of t im ing out . Not e t hat t he t wo flows are in a race: The first t o reach t he final stat e will win and t erm inat e t he ot her flow.
Figu r e 1 1 .6 . Sen din g a n d r e ce iv in g sign a ls
Alt hough accept s are usually j ust wait ing for an ext ernal event , we can also show a flow going int o t hem . That indicat es that we don't st art list ening unt il t he flow t riggers t he accept .
Tokens I f you're sufficient ly brave t o vent ure int o t he dem onic dept hs of t he UML specificat ion, you'll find t hat t he act ivit y sect ion of t he specificat ion t alks a lot about t okens and their product ion and consum pt ion. The init ial node creat es a t oken, which then passes t o t he next act ion, which execut es and t hen passes t he t oken t o t he next . At a fork, one t oken com es in, and t he fork produces a t oken 95/ 118
on each of it s out ward flows. Conversely, on a j oin, as each inbound t oken arrives, not hing happens unt il all t he t okens appear at the j oin; t hen a t oken is produced on t he out ward flow. You can visualize t he t okens wit h coins or count ers m oving across the diagram . As you get t o m ore com plicat ed exam ples of act ivit y diagram s, t okens oft en m ake it easier t o visualize t hings.
Flows and Edges UML 2 uses t he t erm s flow and e dge synonym ously t o describe t he connect ions bet ween t wo act ions. The sim plest kind of edge is t he sim ple arrow bet ween t wo act ions. You can give an edge a nam e if you like, but m ost of the t im e, a sim ple arrow will suffice. I f you're having difficult y rout ing lines, you can use connect ors, which sim ply save you having to draw a line t he whole dist ance. When you use connect ors, you m ust use them in pairs: one wit h incom ing flow, one wit h an out going flow, and bot h wit h the sam e label. I t end t o avoid using connect ors if at all possible, as t hey break up the visualizat ion of t he flow of cont rol. The can you you
sim plest edges pass a t oken t hat has no m eaning ot her t han t o cont rol t he flow. However, you also pass obj ect s along edges; t he obj ect s t hen play t he role of t okens, as well as carry dat a. I f are passing an obj ect along t he edge, you can show t hat by put t ing a class box on the edge, or can use pins on the actions, alt hough pins im ply som e m ore subt let ies t hat I 'll describe short ly.
All t he st yles shown in Figure 11.7 are equivalent ; you should use whichever conveys best what you are t rying t o com m unicat e. Most of the t im e, t he sim ple arrow is quit e enough.
Figu r e 1 1 .7 . Four w a y s of sh ow in g an e dge
Pins and Transformations Act ions can have param et ers, j ust as m et hods do. You don't need t o show inform at ion about param et ers on t he act ivit y diagram , but if you wish, you can show t hem wit h pin s. I f you're decom posing an act ion, pins correspond t o t he param et er boxes on t he decom posed diagram . When you're drawing an act ivit y diagram st rict ly, you have t o ensure t hat t he out put param et ers of an out bound act ion m at ch t he input param et ers of anot her. I f t hey don't m at ch, you can indicat e a 96/ 118
t r a n sfor m a t ion ( Figure 11.8 ) t o get from one to anot her. The t ransform at ion m ust be an expression t hat 's free of side effect s: essent ially, a query on t he out put pin quary t hat supplies an obj ect of t he right t ype for t he input pin.
Figu r e 1 1 .8 . Tr a n sfor m a t ion on a flow
You don't have t o show pins on an act ivit y diagram . Pins are best when you want t o look at t he dat a needed and produced by t he various act ions. I n business process m odeling, you can use pins t o show t he resources produced and consum ed by act ions. I f you use pins, it 's safe t o show m ult iple flows com ing int o t he sam e act ion. The pin not at ion reinforces t he im plicit j oin, and UML 1 didn't have pins, so t here's no confusion wit h t he earlier assum pt ions.
Expansion Regions Wit h act ivit y diagram s, you oft en run int o sit uat ions in which one act ion's out put t riggers m ult iple invocat ions of anot her act ion. There are several ways t o show this, but the best way is t o use an expansion region. An e x pan sion re gion m arks an act ivit y diagram area where act ions occur once for each it em in a collect ion. I n Figure 11.9, t he Choose Topics act ion generat es a list of t opics as it s out put . Each elem ent of t his list then becom es a t oken for input t o t he Writ e Art icle act ion. Sim ilarly, each Review Art icle act ion generat es a single art icle that 's added t o t he out put list of the expansion region. When all t he t okens in t he expansion region end up in t he out put collect ion, t he region generat es a single t oken for t he list that 's passed t o Publish Newslet t er.
Figu r e 1 1 .9 . Ex pa n sion r e gion
97/ 118
I n this case, you have the sam e num ber of it em s in t he out put collect ion as you do in the input collect ion. However, you m ay have fewer, in which case the expansion region act s as a filt er. I n Figure 11.9, all t he art icles are writ t en and reviewed in parallel, which is m arked by the «concurrent» keyword. You can also have an it erat ive expansion region. I t erat ive regions m ust fully process each input elem ent one at a t im e. I f you have only a single act ion that needs m ult iple invocat ion, you use t he short hand of Figure 11.10. The short hand assum es concurrent expansion, as t hat 's t he m ost com m on. This not at ion corresponds t o t he UML 1 concept of dynam ic concurrency.
Figu r e 1 1 .1 0 . Sh or t h a n d for a sin gle a ct ion in a n e x p a n sion r e gion
Flow Final Once you get m ult iple t okens, as in an expansion region, you oft en get flows t hat st op even when t he act ivit y as a whole doesn't end. A flow fin a l indicat es t he end of one particular flow, wit hout t erm inat ing t he whole act ivit y. Figure 11.11 shows t his by m odifying t he exam ple of Figure 11.9 t o allow art icles t o be rej ect ed. I f an art icle is rej ect ed, the t oken is dest royed by the flow final. Unlike an act ivit y final, the rest of t he act ivit y can cont inue. This approach allows expansion regions t o act as filt ers, whereby t he out put collect ion is sm aller than t he input collect ion.
Figu r e 1 1 .1 1 . Flow fin a ls in a n a ct iv it y
98/ 118
Join Specifications By default , a j oin let s execut ion pass on it s out ward flow when all it s input flows have arrived at t he j oin. ( Or in m ore form al speak, it em it s a t oken on it s out put flow when a t oken has arrived on each input flow.) I n som e cases, part icularly when you have a flow wit h m ult iple t okens, it 's useful t o have a m ore involved rule. A j oin spe cifica t ion is a Boolean expression at t ached t o a j oin. Each t im e a t oken arrives at t he j oin, t he j oin specificat ion is evaluat ed and if t rue, an out put t oken is em it t ed. So in Figure 11.12, whenever I select a drink or insert a coin, the m achine evaluat es t he j oin specificat ion. The m achine slakes m y t hirst only if I 've put in enough m oney. I f, as in t his case, you want t o indicat e t hat you have received a t oken on each input flow, you label t he flows and include them in t he j oin specificat ion.
Figu r e 1 1 .1 2 . Join spe cifica t ion
99/ 118
Chapter 12. Communication Diagrams Com m u n ica t ion dia gr a m s, a kind of int eract ion diagram , em phasize the dat a links bet ween t he various participant s in t he int eract ion. I nst ead of drawing each part icipant as a lifeline and showing t he sequence of m essages by vert ical direct ion as t he sequence diagram s does, t he com m unicat ion diagram allows free placem ent of part icipant s, allows you t o draw links t o show how t he part icipant s connect , and use num bering t o show the sequence of m essages. I n UML 1.x, t hese diagram s were called colla bor a t ion dia gr a m s. This nam e stuck well, and I suspect t hat it will be a while before people get used t o t he new nam e. ( These are different from Collaborat ions [ page 143] ; hence t he nam e change.) Figure 12.1 shows a com m unicat ion diagram for t he sam e cent ralized cont rol int eract ion as in Figure 4.2. Wit h a com m unicat ion diagram , we can show how t he part icipant s are linked t oget her.
Figu r e 1 2 .1 . Com m u n ica t ion dia gr a m for ce n t r a lize d con t r ol
As well as showing links that are inst ances of associat ions, we can also show t ransient links, which arise only t he cont ext of t he int eract ion. I n this case, t he «local» link from Order t o Product is a local variable; ot her t ransient links are «parameter» and «global». These keywords were used in UML 1 but are m issing from UML 2. Because t hey are useful, I expect t hem t o st ay around in convent ional use. The num bering st yle of Figure 12.1 is st raight forward and com m only used, but actually isn't legal UML. To be kosher UML, you have t o use a nest ed decim al num bering schem e, as in Figure 12.2 .
Figu r e 1 2 .2 . Com m u n ica t ion dia gr a m w it h n e st e d de cim a l n u m be r in g
100/ 118
The reason for t he nest ed decim al num bers is t o resolve am biguit y wit h self-calls. I n Figure 4.2 , you can clearly see t hat getDiscountInfo is called wit hin t he m et hod calculateDiscount. Wit h t he flat num bering of Figure 12.1 , however, you can't t ell whet her getDiscountInfo is called wit hin calculateDiscount or wit hin t he overall calculatePrice m et hod. The nest ed num bering schem e resolves t his problem . Despit e it s illegalit y, m any people prefer a flat num bering schem e. The nest ed num bers can get very t angled, particularly as calls get rat her nest ed, leading t o such sequence num bers as 1.1.1.2.1.1. I n t hese cases, the cure for am biguit y can be worse t han t he disease. As well as num bers, you m ay also see let t ers on m essages; t hese let t ers indicat e different threads of cont rol. So m essages A5 and B2 would be in different threads; m essages 1a1 and 1b1 would be different threads concurrent ly nest ed wit hin m essage 1. You also see t hread let t ers on sequence diagram s, alt hough t his doesn't convey t he concurrency visually. Com m unicat ion diagram s don't have any precise not at ion for cont rol logic. They do allow you t o use it erat ion m arkers and guards ( page 59) , but t hey don't allow you t o fully specify cont rol logic. There is no special not at ion for creat ing or delet ing obj ect s, but t he «create» and «delete» keywords are com m on convent ions.
When to Use Communication Diagrams The m ain quest ion wit h com m unicat ion diagram s is when t o use t hem rat her t han the m ore com m on sequence diagram s. A st rong part of t he decision is personal preference: Som e people like one over t he ot her. Oft en, that drives t he choice m ore than anyt hing else. On the whole, m ost people seem t o prefer sequence diagram s, and for once, I 'm wit h t he m aj orit y. A m ore rat ional approach says t hat sequence diagram s are bet t er when you want t o em phasize t he sequence of calls and that com m unicat ion diagram s are bet t er when you want t o em phasize t he links. Many people find t hat com m unicat ion diagram s are easier t o alt er on a whit eboard, so t hey are a good approach for exploring alt ernat ives, alt hough in t hose cases, I oft en prefer CRC cards.
Chapter 13. Composite Structures One of t he m ost significant new feat ures in UML 2 is t he abilit y t o hierarchically decom pose a class int o an int ernal st ruct ure. This allows you t o t ake a com plex obj ect and break it down int o part s. Figure 13.1 shows a TV Viewer class wit h it s provided and required int erfaces ( page 69) . I 've shown t his in t wo ways: using t he ball- and- socket not at ion and list ing them int ernally. 101/ 118
Figu r e 1 3 .1 . Tw o w a y s of sh ow in g a TV v ie w e r a n d it s in t e r fa ce s
Figure 13.2 shows how t his class is decom posed int ernally int o t wo part s and which part s support and require the different int erfaces. Each part is nam ed in t he form name : class, wit h bot h elem ent s individually opt ional. Part s are not inst ance specificat ions, so t hey are bolded rat her than underlined.
Figu r e 1 3 .2 . I n t e rn a l v ie w of a com pon e n t ( e x a m ple su gge st e d by Jim Ru m ba u gh )
102/ 118
You can show how m any inst ances of a part are present . Figure 13.2 says that each TV Viewer cont ains one generat or part and one cont rols part . To show a part im plem ent ing an int erface, you draw a delegat ing connect or from t hat int erface. Sim ilarly, t o show t hat a part needs an int erface, you show a delegat ing connect or t o t hat int erface. You can also show connect ors bet ween part s wit h eit her a sim ple line, as I 've done here, or wit h ball- and- socket not at ion ( page 71) . You can add port s ( Figure 13.3) t o t he ext ernal st ruct ure. Port s allow you t o group t he required and provided int erfaces int o logical int eract ions t hat a com ponent has wit h the out side world.
Figu r e 1 3 .3 . A com pon e n t w it h m u lt iple por t s
When to Use Composite Structures Com posit e st ruct ures are new t o UML 2, alt hough som e older m et hods had som e sim ilar ideas. A good way of t hinking about t he difference bet ween packages and com posit e st ruct ures is that packages are a com pile- t im e grouping, while com posit e st ruct ures show runt im e groupings. As such, t hey are a nat ural fit for showing com ponent s and how t hey are broken int o part s; hence, m uch of t his not at ion is used in com ponent diagram s. Because com posit e st ruct ures are new t o t he UML, it 's t oo early t o t ell how effective they will t urn out in practice; m any m em bers of t he UML com m it t ee t hink t hat t hese diagram s will becom e a very valuable addit ion.
Chapter 14. Component Diagrams A debat e t hat 's always ranged large in the OO com m unit y is what the difference is bet ween a com ponent and any regular class. This is not a debat e that I want t o set t le here, but I can show you t he not at ion t he UML uses t o dist inguish bet ween t hem . UML 1 had a dist inct ive sym bol for a com ponent ( Figure 14.1) . UML 2 rem oved t hat icon but allows you t o annot at e a class box wit h a sim ilar-looking icon. Alt ernat ively, you can use t he «component» keyword.
Figu r e 1 4 .1 . N ot a t ion for com pon e n t s 103/ 118
Ot her t han the icon, com ponent s don't int roduce any not at ion that we haven't already seen. Com ponent s are connect ed t hrough im plem ent ed and required int erfaces, oft en using t he ball- andsocket not at ion ( page 71) j ust as for class diagram s. You can also decom pose com ponent s by using com posit e st ruct ure diagram s. Figure 14.2 shows an exam ple com ponent diagram . I n t his exam ple, a sales t ill can connect t o a sales server com ponent , using a sales m essage int erface. Because t he net work is unreliable, a m essage queue com ponent is set up so t he t ill can t alk t o t he server when t he net work is up and t alk t o a queue when t he net work is down; t he queue will t hen t alk t o t he server when t he net work becom es available. As a result , t he m essage queue bot h supplies t he sales m essage int erface t o t alk wit h t he t ill and requires t hat int erface t o t alk wit h t he server. The server is broken down int o t wo m aj or com ponent s. The t ransact ion processor realizes t he sales m essage int erface, and t he account ing driver t alks t o t he account ing syst em .
Figu r e 1 4 .2 . An e x a m ple com pon e n t dia gr a m
As I 've already said, t he issue of what is a com ponent is the subj ect of endless debat e. One of the m ore helpful st at em ent s I 've found is t his: Com ponent s are not a t echnology. Technology people seem t o find t his hard t o underst and. Com ponent s are about how cust om ers want t o relat e t o soft ware. They want t o be able t o buy t heir soft ware a piece at a t im e, and t o be able t o upgrade it j ust like t hey can upgrade t heir st ereo. They want new pieces t o work seam lessly wit h t heir old pieces, and t o be able t o upgrade on their own schedule, not t he m anufacturer's schedule. They want t o be able to m ix and m at ch pieces from various m anufacturers. This is a very reasonable requirem ent . I t is j ust hard t o sat isfy . Ralph Johnson, h t t p:/ / w w w .c2 .com / cgi/ w ik i?D oCom pon e n tsEx ist The im port ant point is t hat com ponent s represent pieces that are independent ly purchasable and upgradeable. As a result , dividing a syst em int o com ponent s is as m uch a m arket ing decision as it is a t echnical decision, for which [ Hohm ann] is an excellent guide. I t 's also a rem inder t o beware of 104/ 118
overly fine- grained com ponent s, because t oo m any com ponent s are hard t o m anage, especially when versioning rears it s ugly head, hence " DLL hell." I n earlier versions of t he UML, com ponent s were used t o represent physical st ruct ures, such as DLLs. That 's no longer t rue; for t his t ask, you now use art ifact s ( page 97) .
When to Use Component Diagrams Use com ponent diagram s when you are dividing your syst em int o com ponent s and want t o show t heir int errelat ionships through int erfaces or t he breakdown of com ponent s int o a lower-level st ruct ure.
Chapter 15. Collaborations Unlike t he ot her chapt ers in t his book, t his one does not correspond t o an official diagram in UML 2. The st andard discusses collaborat ions as part of com posit e st ruct ures, but t he diagram is really quit e different and was used in UML 1 wit hout any link t o com posit e st ruct ures. So I felt it best t o discuss collaborat ions as t heir own chapt er. Let 's consider the not ion of an auct ion. I n any auct ion, we m ight have a seller, som e buyers, a lot of goods, and som e offers for t he sale. We can describe t hese elem ent s in t erm s of a class diagram ( Figure 15.1) and perhaps som e int eract ion diagram s ( Figure 15.2) .
Figu r e 1 5 .1 . A colla bor a t ion w it h it s cla ss dia gr a m of r ole s
Figu r e 1 5 .2 . A se qu e n ce dia gr a m for t h e a u ct ion colla b or a t ion
105/ 118
Figure 15.1 is not quit e a regular class diagram . For a st art , it 's surrounded by t he dashed ellipse, which represent s t he auct ion collaborat ion. Second, t he so- called classes in t he collaborat ion are not classes but role s that will be realized as t he collaborat ion is applied—hence t he fact that t heir nam es aren't capit alized. I t 's not unusual t o see act ual int erfaces or classes t hat correspond t o t he collaborat ion roles, but you don't have t o have t hem . I n the int eract ion diagram , t he part icipant s are labeled slight ly different ly from t he usual case. I n a collaborat ion, t he nam ing schem e is participant-name /role-name : class-name. As usual, all t hese elem ent s are opt ional. When you use a collaborat ion, you can show t hat by placing a collaborat ion occurrence on a class diagram , as in Figure 15.3, a class diagram of som e of t he classes in t he applicat ion. The links from t he collaborat ion t o t hose classes indicat e how the classes play t he various roles defined in t he collaborat ion.
Figu r e 1 5 .3 . A colla bor a t ion occu r r e n ce
106/ 118
The UML suggest s t hat you can use t he collaborat ion occurrence not at ion t o show t he use of pat t erns, but hardly any pat t erns aut hor has done t his. Erich Gam m a developed a nice alt ernat ive not at ion ( Figure 15.4) . Elem ent s of t he diagram are labeled wit h eit her t he pat t ern nam e or a com binat ion of pattern:role.
Figu r e 1 5 .4 . A n onst a n da r d w a y of sh ow in g pa t t e r n u se in JUn it ( j u n it .or g)
When to Use Collaborations Collaborat ions have been around since UML 1, but I adm it I 've hardly used t hem , even in m y pat t erns writ ing. Collaborat ions do provide a way t o group chunks of int eraction behavior when roles are played by different classes. I n pract ice, however, I 've not found that they've been a com pelling diagram t ype.
Chapter 16. Interaction Overview Diagrams I nt eraction overview diagram s are a graft ing t oget her of act ivit y diagram s and sequence diagram s. You can think of int eraction overview diagram s eit her as act ivit y diagram s in which t he act ivit ies are 107/ 118
replaced by lit t le sequence diagram s, or as a sequence diagram broken up wit h act ivit y diagram not at ion used t o show cont rol flow. Eit her way, they m ake a bit of an odd m ixt ure. Figure 16.1 shows a sim ple exam ple of one; the not at ion is fam iliar from what you've already seen in t he act ivit y diagram and sequence diagram chapt ers. I n t his diagram , we want t o produce and form at an order sum m ary report . I f t he cust om er is ext ernal, we get the inform at ion from XML; if int ernal, we get it from a dat abase. Sm all sequence diagram s show the t wo alt ernat ives. Once we get t he dat a, we form at t he report ; in t his case, we don't show t he sequence diagram but sim ply reference it wit h a reference int eract ion fram e.
Figu r e 1 6 .1 . I n t e r a ct ion su m m a ry dia gr a m
When to Use Interaction Overview Diagrams These are new for UML 2, and it 's t oo early t o get m uch sense of how well t hey will work out in pract ice. I 'm not keen on t hem , as I t hink t hat they m ix t wo st yles that don't really m ix t hat well. Eit her draw an act ivit y diagram or use a sequence diagram , depending on what bet t er serves your purpose.
108/ 118
Chapter 17. Timing Diagrams Aft er leaving secondary school, I st art ed out in elect ronic engineering before I swit ched int o com put ing. So I feel a cert ain anguished fam iliarit y when I see t he UML define t im ing diagram s as one of it s st andard diagram s. Tim ing diagram s have been around in elect ronic engineering for a long t im e and never seem ed t o need t he UML's help to define their m eaning. But since t hey are in the UML, t hey deserve a brief m ent ion. Tim ing diagram s are anot her form of int eract ion diagram , where the focus is on t im ing const raint s: eit her for a single obj ect or, m ore usefully, for a bunch of obj ect s. Let 's t ake a sim ple scenario based on t he pum p and hot plat e for a coffee pot . Let 's im agine a rule t hat says t hat at least 10 seconds m ust pass bet ween the pum p com ing on and t he hot plat e com ing on. When the wat er reservoir becom es em pt y, the pum p swit ches off, and the hot plat e cannot st ay on for m ore t han 15 m inut es m ore. Figures 17.1 and 17.2 are alt ernat ive ways of showing t hese tim ing const raint s. Bot h diagram s show t he sam e basic inform at ion. The m ain difference is t hat Figure 17.1 shows t he st at e changes by m oving from one horizont al line t o anot her, while Figure 17.2 ret ains t he sam e horizont al posit ion but shows st at e changes wit h a cross. The st yle of Figure 17.1 works bet t er when t here are j ust a few st at es, as in t his case, and Figure 17.2 is bet t er when t here are m any st at es t o deal wit h.
Figu r e 1 7 .1 . Tim in g dia gr a m sh ow ing st a t e s a s lin e s
Figu r e 1 7 .2 . Tim in g dia gr a m sh ow ing st a t e s a s a r e a s
109/ 118
The dashed lines t hat I 've used on t he { > 10s} const raint s are opt ional. Use t hem if you t hink t hey help clarify exact ly what event s t he t im ing constrains.
When to Use Timing Diagrams Tim ing diagram s are useful for showing t im ing const raint s bet ween st at e changes on different obj ect s. The diagram s are particularly fam iliar t o hardware engineers.
Appendix Changes between UML Versions When t he first edit ion of t his book appeared on the shelves, t he UML was in version 1.0. Much of it appeared t o have st abilized and was in t he process of OMG recognit ion. Since t hen, t here have been a num ber of revisions. I n t his appendix, I describe t he significant changes t hat have occurred since 1.0 and how t hose changes affect t he m at erial in t his book. This appendix sum m arizes t he changes so you can keep up t o dat e if you have an earlier print ing of t he book. I have m ade changes t o t he book t o keep up wit h t he UML, so if you have a lat er print ing, it describes t he sit uat ion as it was as of the print dat e.
Revisions to the UML The earliest public release of what cam e t o be the UML was version 0.8 of t he Unified Met hod, which was released for OOPSLA in Oct ober 1995. This was t he work of Booch and Rum baugh, as Jacobson did not j oin Rat ional unt il around t hat t im e. I n 1996, Rat ional released versions 0.9 and 0.91, which included Jacobson's work. Aft er t he lat t er version, t hey changed t he nam e t o t he UML. Rat ional and a group of partners subm it t ed version 1.0 of the UML t o t he OMG Analysis and Design Task Force in January 1997. Subsequent ly, t he Rat ional part nership and t he ot her subm it t ers com bined their work and subm it t ed a single proposal for t he OMG st andard in Sept em ber 1997, for version 1.1 of t he UML. This was adopt ed by t he OMG t oward the end of 1997. However, in a fit of darkest obfuscat ion, t he OMG called t his st andard version 1.0. So, now t he UML was bot h OMG 110/ 118
version 1.0 and Rat ional version 1.1, not t o be confused wit h Rat ional 1.0. I n pract ice, everyone calls t hat st andard version 1.1. From t hen on, t here were a num ber of further developm ent s in t he UML. UML 1.2 appeared in 1998, 1.3 in 1999, 1.4 in 2001, and 1.5 in 2002. Most of t he changes bet ween t he 1.x versions were fairly deep in the UML, except for UML 1.3, which caused som e very visible changes, especially t o use cases and act ivit y diagram s. As t he UML 1 series cont inued, t he developers of t he UML set their sight s on a m aj or revision t o t he UML wit h UML 2. The first RFPs ( Request for Proposals) were issued in 2000, but UML 2 didn't st art t o properly st abilize unt il 2003. Furt her developm ent s in t he UML will alm ost cert ainly occur. The UML Forum ( h t t p:/ / u m lfor u m .com ) is usually a good place t o look for m ore inform at ion. I also keep som e UML inform at ion on m y sit e ( h t t p:/ / m a r t infow le r .com ) .
Changes in UML Distilled As t hese revisions go on, I 've been t rying t o keep up by revising UML Dist illed wit h subsequent print ings. I 've also t aken t he opport unit y t o fix errors and m ake clarificat ions. The m ost dynam ic period for keeping up wit h t hings was during the first edit ion of UML Dist illed, when we oft en had t o m ake updat es bet ween print ings t o keep up wit h t he em erging UML st andard. The first t hrough fift h print ings were based on UML 1.0. Any changes t o t he UML bet ween these print ings were m inor. The sixth print ing t ook UML 1.1 int o account . The sevent h t hrough t ent h print ings were based on UML 1.2; t he elevent h print ing was t he first t o use UML 1.3. Print ings based on versions of t he UML aft er 1.0 have t he UML version num ber on t he front cover. The first t hough sixt h print ings of t he second edit ion were based on version 1.3. The sevent h print ing was t he first t o t ake int o account t he m inor changes of version 1.4. The t hird edit ion was launched t o updat e t he book wit h UML 2 ( see Table A.1) . I n t he rest of t his appendix, I sum m arize t he m aj or changes in the UML from 1.0 t o 1.1, from 1.2 t o 1.3, and from 1.x t o 2.0. I don't discuss all t he changes t hat occur but rat her only t hose t hat change som et hing I said in UML Dist illed or t hat represent im port ant feat ures t hat I would have discussed in UML Distilled. I am cont inuing t o follow t he spirit of UML Distilled: t o discuss t he key elem ent s of UML as t hey affect t he applicat ion of t he UML wit hin real- world proj ect s. As ever, t he select ions and advice are m y own. I f t here is any conflict bet ween what I say and t he official UML docum ent s, t he UML docum ent s are t he ones t o follow. ( But do let m e know, so I can m ake correct ions.)
Ta ble A.1 . UM L D ist ille d a n d cor r e spon din g UM L ve r sion s UM L D ist ille d
UM L Ver sions
1 st e dit ion
UM L 1 .0 – 1 .3
2 n d e dit ion
UM L 1 .3 – 1 .4
3 r d e dit ion
UM L 2 .0 on w ar d
I have also t aken the opport unit y t o indicat e any im port ant errors and om issions in t he earlier print ings. Thanks t o t he readers who have point ed t hese out t o m e.
111/ 118
Changes from UML 1.0 to 1.1 Type and Implementation Class I n the first edit ion of UML Dist illed, I t alked about perspect ives and how t hey alt ered t he way people draw and int erpret m odels—in part icular, class diagram s. UML now t akes t his int o account by saying t hat all classes on a class diagram can be specialized as eit her t ypes or im plem ent at ion classes. An im ple m e n t a t ion cla ss corresponds t o a class in t he soft ware environm ent in which you are developing. A t ype is rat her m ore nebulous; it represent s a less im plem ent at ion- bound abst raction. This could be a CORBA t ype, a specificat ion perspect ive of a class, or a concept ual perspect ive. I f necessary, you can add st ereot ypes t o different iat e further. You can st at e that for a part icular diagram , all classes follow a part icular st ereot ype. This is what you would do when drawing a diagram from a part icular perspect ive. The im plem ent at ion perspect ive would use im plem ent at ion classes, whereas t he specificat ion and concept ual perspect ive would use t ypes. You use t he realizat ion relat ionship t o indicat e that an im plem ent at ion class im plem ent s one or m ore t ypes. There is a distinction bet ween t ype and int erface. An int erface is int ended t o direct ly correspond t o a Java or COM- st yle int erface. I nt erfaces t hus have only operat ions and no at t ribut es. You m ay use only single, st at ic classificat ion wit h im plem ent at ion classes, but you can use m ult iple and dynam ic classificat ion wit h t ypes. ( I assum e t hat this is because t he m aj or OO languages follow single, st at ic classificat ion. I f one fine day you use a language t hat support s m ult iple or dynam ic classificat ion, t hat rest riction really should not apply.)
Complete and Incomplete Discriminator Constraints I n previous print ings of UML Dist illed, I said that t he {complete} const raint on a generalizat ion indicat ed t hat all inst ances of t he supert ype m ust also be an inst ance of a subt ype wit hin t hat part it ion. UML 1.1 defines inst ead t hat {complete} indicat es t hat all subt ypes wit hin t hat part it ion have been specified, which is not quit e t he sam e t hing. I have found som e inconsist ency on t he int erpret at ion of this const raint , so you should be wary of it . I f you do want t o indicat e t hat all inst ances of t he supert ype should be an inst ance of one of t he subt ypes, I suggest using anot her const raint t o avoid confusion. Current ly, I am using {mandatory}.
Composition I n UML 1.0, using com posit ion im plied that t he link was im m ut able, or frozen, at least for singlevalued com ponent s. That const raint is no longer part of t he definit ion.
Immutability and Frozen UML defines t he const raint {frozen} t o define im m ut abilit y on associat ion roles. As it 's current ly defined, it doesn't seem t o apply it t o at t ribut es or classes. I n m y pract ice, I now use the t erm fr oze n inst ead of im m ut abilit y, and I 'm happy to apply the const raint t o associat ion roles, classes, and at t ribut es.
Returns on Sequence Diagrams I n UML 1.0, a ret urn on a sequence diagram was dist inguished by using a st ick arrowhead inst ead of a solid arrowhead ( see previous print ings) . This was som et hing of a pain, as t he dist inct ion was t oo subt le and easy t o m iss. UML 1.1 uses a dashed arrow for a ret urn, which pleases m e, as it m akes ret urns m uch m ore obvious. (As I used dashed ret urns in Analysis Pat t erns [ Fowler, AP] , it also 112/ 118
m akes m e look influent ial.) You can nam e what is ret urned for lat er use by using t he form enoughStock := check().
Use of the Term "Role" I n UML 1.0, t he t erm r ole indicat ed prim arily a direct ion on an associat ion ( see previous print ings) . UML 1.1 refers t o t his usage as an a ssocia t ion r ole . There is also a colla bora t ion role, which is a role t hat an inst ance of a class plays in a collaborat ion. UML 1.1 gives a lot m ore em phasis t o collaborat ions, and it looks as t hough t his use of " role" m ay becom e t he prim ary one.
Changes from UML 1.2 (and 1.1) to 1.3 (and 1.5) Use Cases The changes t o use cases involve new relat ionships bet ween use cases. UML 1.1 has t wo use case relat ionships: «uses» and «extends», bot h of which are st ereot ypes of generalizat ion. UML 1.3 offers three relat ionships. •
•
•
The «include» const ruct is a st ereot ype of dependency. This indicat es t hat t he pat h of one use case is included in anot her. Typically, t his occurs when a few use cases share com m on st eps. The included use case can fact or out t he com m on behavior. An exam ple from an ATM m ight be t hat Wit hdraw Money and Make Transfer bot h use Validat e Cust om er. This replaces t he com m on use of «uses». Use case ge n er a liza t ion indicat es t hat one use case is a variat ion on anot her. Thus, we m ight have one use case for Wit hdraw Money—t he base use case—and a separat e use case t o handle t he case when t he wit hdrawal is refused because of lack of funds. The refusal could be handled as a use case t hat specializes t he wit hdrawal use case. (You could also handle it as sim ply anot her scenario wit hin t he Wit hdraw Money use case.) A specializing use case like t his m ay change any aspect of t he base use case. The «extend» const ruct is a st ereot ype of dependency. This provides a m ore cont rolled form of ext ension t han t he generalizat ion relat ionship. Here, t he base use case declares a num ber of ext ension point s. The ext ending use case can alt er behavior only at t hose ext ension point s. So, if you are buying a product on line, you m ight have a use case for buying a product wit h ext ension point s for capt uring t he shipping inform at ion and capt uring paym ent inform at ion. That use case could t hen be ext ended for a regular cust om er for which t his inform at ion would be obt ained in a different way.
There is som e confusion about t he relat ionship bet ween t he old relat ionships and t he new ones. Most people used «uses» t he way t he 1.3 «includes» is used, so for m ost people, we can say that «includes» replaces «uses». And m ost people used 1.1 «extends» in bot h t he cont rolled m anner of t he 1.3 «extends» and as a general overriding in t he st yle of t he 1.3 generalizat ion. So, you can t hink t hat 1.1 «extends» has been split int o t he 1.3 «extend» and generalizat ion. Now, alt hough t his explanat ion covers m ost UML usage t hat I 've seen, it isn't t he st rict ly correct way of using t hose old relat ionships. However, m ost people didn't follow the st rict usage, and I don't really want t o get int o all t hat here.
Activity Diagrams When t he UML reached version 1.2, t here were quit e a few open quest ions about t he sem ant ics of act ivit y diagram s. So, t he 1.3 effort involved quit e a lot of t ight ening up on t hese sem ant ics. For condit ional behavior, you can now use the diam ond- shaped decision activit y for a m erge of behavior as well as a branch. Alt hough neit her branches nor m erges are necessary t o describe condit ional behavior, it is increasingly com m on st yle t o show t hem so t hat you can bracket condit ional behavior. 113/ 118
The synchronizat ion bar is now referred t o as a for k —when split t ing cont rol—or as a j oin—when synchronizing cont rol t oget her. However, you can no longer add arbit rary condit ions t o j oins. Also, you m ust follow m at ching rules t o ensure t hat forks and j oins m at ch up. Essent ially, t his m eans t hat each fork m ust have a corresponding j oin t hat j oins t he threads st art ed by t hat fork. You can nest fork and j oins, t hough, and you can elim inat e forks and j oins on t he diagram when threads go direct ly from one fork t o anot her fork, or one j oin t o anot her j oin. Joins are fired only when all incom ing t hreads com plet e. However, you can have a condit ion on a t hread com ing out of a fork. I f t hat condit ion is false, t hat thread is considered com plet e for j oining purposes. The m ult iple-t rigger feat ure is no longer present . I n it s place, you can have dynam ic concurrency in an act ivit y, shown wit h a * inside an act ivit y box. Such an act ivit y m ay be invoked several t im es in parallel; all it s invocat ions m ust com plet e before any out going t ransit ion can be t aken. This is loosely equivalent t o, alt hough less flexible than, a m ult iple t rigger and m at ching synchronizat ion condit ion. These rules reduce som e of flexibilit y of activit y diagram s but do ensure t hat act ivit y diagram s are t ruly special cases of st at e m achines. The relat ionship bet ween act ivit y diagram s and st at e m achines was a m at t er of som e debat e in t he RTF. Fut ure versions of t he UML ( aft er 1.4) m ay well m ake act ivit y diagram s a com plet ely different form of diagram .
Changes from UML 1.3 to 1.4 The m ost visible change in UML 1.4 is t he addit ion of profile s, which allows a group of ext ensions t o be collect ed t oget her int o a coherent set . The UML docum ent at ion includes a couple of exam ple profiles. Toget her wit h this, t here's great er form alism involved in defining a st ereot ype, and m odel elem ent s can now have m ult iple st ereot ypes; t hey were lim it ed t o one st ereot ype in UML 1.3. Ar t ifact s were added t o t he UML. An artifact is a physical m anifest at ion of a com ponent , so, for exam ple, Xerces is a com ponent and all t hose copies of t he Xerces j ar on m y disk drive are art ifact s t hat im plem ent t he Xerces com ponent . Prior t o 1.3, t here was not hing in t he UML m et a-m odel t o handle Java's pack a ge visibilit y. Now t here is, and t he sym bol is " ~ " . UML 1.4 also m ade t he st ick arrowhead in int eract ion diagram s m ark asynchronous, a rat her awkward backward- incom pat ible change. That caught out a few people, including m e.
Changes from UML 1.4. to 1.5 The principal change here was adding act ion sem ant ics t o t he UML, a necessary st ep t o m ake UML a program m ing language. This was done t o allow people t o work on t his wit hout wait ing for t he full UML 2.
From UML 1.x to UML 2.0 UML 2 represent s t he biggest change t hat 's happened yet t o t he UML. All sort s of t hings have changed wit h t his revision, and m any changes have affect ed UML Dist illed. Wit hin t he UML, there have been deep changes t o t he UML m et a-m odel. Alt hough t hese changes don't affect t he discussion in UML Dist illed, t hey are very im port ant t o som e groups. 114/ 118
One of t he m ost obvious changes is the int roduct ion of new diagram t ypes. Obj ect diagram s and package diagram s were widely drawn before but weren't official diagram t ypes; now t hey are. UML 2 changed t he nam e of collaborat ion diagram s t o com m unicat ion diagram s. UML 2 has also int roduced new diagram t ypes: int eract ion overview diagram s, t im ing diagram s, and com posit e st ructure diagram s. A lot of changes haven't t ouched UML Distilled. I 've left out discussion of such const ruct s as st at e m achine ext ensions, gat es in int eract ions diagram s, and power t ypes in class diagram s. So for t his section, I 'm discussing only changes t hat m ake it int o UML Distilled. These are eit her changes t o t hings I discussed in previous edit ions or new t hings I 've st art ed t o discuss wit h t his edit ion. Because t he changes are so widespread, I 've organized t hem according t o t he chapt ers in t his book.
Class Diagrams: The Essentials (Chapter 3) At t ribut es and unidirect ional associat ions are now prim arily sim ply different not at ions for the sam e underlying concept of propert y. Discont inuous m ult iplicit ies, such as [ 2, 4] , have been dropped. The frozen propert y has been dropped. I 've added a list of com m on dependency keywords, several of which are new t o UML 2. The «parameter», and «local» keywords have been dropped.
Sequence Diagrams (Chapter 4) The big change here is the int eract ion fram e not at ion for sequence diagram s t o handle it erat ive, condit ional, and various ot her cont rols of behavior. This now allows you t o express algorit hm s pret t y com plet ely in sequence diagram s, alt hough I 'm not convinced that t hese are any clearer t han code. The old it erat ion m arkers and guards on m essages have been dropped from sequence diagram s. The heads of t he lifelines are no longer inst ances; I use the t erm pa r t icipa n t t o refer t o t hem . The collaborat ion diagram s of UML 1 were renam ed t o com m unicat ion diagram s for UML 2.
Class Diagrams: Concepts (Chapter 5) St ereot ypes are now m ore t ight ly defined. As a result , I now refer t o words in guillem et s as keywords, only som e of which are st ereot ypes. I nst ances on obj ect diagram s are now inst ance specificat ions. Classes can now require int erfaces as well as provide t hem . Mult iple classificat ion uses generalizat ion set s t o group generalizat ions int o groups. Com ponent s are no longer drawn wit h t heir special sym bol. Act ive obj ect s have double vert ical lines inst ead of t hick lines.
State Machine Diagrams (Chapter 10) UML 1 separat ed short - lived act ions from long-lived act ivit ies. UML 2 calls bot h act ivit ies and uses t he t erm do- act ivit y for t he long-lived act ivit ies.
Activity Diagrams (Chapter 11) UML 1 t reat ed act ivit y diagram s as a special case of st at e diagram . UML 2 broke t hat link and as a result rem oved the rules of m at ching forks and j oins t hat UML 2 activit y diagram s had t o keep t o. As a result , t hey are best underst ood by t oken flow rat her t han by st at e t ransit ion. A whole bunch of new not at ion t hus appeared, including t im e and accept signals, param et ers, j oin specificat ions, pins, flow t ransform at ions, subdiagram rakes, expansion regions, and flow finals. A sim ple but awkward change is t hat UML 1 t reat ed m ult iple incom ing flows t o an act ivit y as an im plicit m erge, while UML 2 t reat s t hem as an im plicit j oin. For t his reason, I advise using an explicit m erge or j oin when doing act ivit y diagram s. Swim lanes can now be m ult idim ensional and are generally called part it ions.
115/ 118
Bibliography [ Am ble r] Scot t Am bler, Agile Modeling, Wiley, 2002. [ Be ck] Kent Beck, Ext rem e Program m ing Explained: Em brace Change, Addison- Wesley, 2000. [ Be ck an d Fow le r] Kent Beck and Mart in Fowler, Planning Ext rem e Program m ing, Addison-Wesley, 2000. [ Be ck an d Cu n n in gha m ] Kent Beck and Ward Cunningham , "A Laborat ory for Teaching Obj ectOrient ed Thinking," Proceedings of OOPSLA 89 , 24 (10) : 1–6. h t t p:/ / c2 .com / doc/ oopsla 8 9 / pa pe r .h t m l [ Booch , OOAD] Grady Booch, Obj ect - Orient ed Analysis and Design wit h Applicat ions, Second Edit ion. Addison-Wesley, 1994. [ Booch , UM L u se r ] Grady Booch, Jim Rum baugh, and I var Jacobson, UML User Guide, AddisonWesley, 1999. [ Coa d, OOA] Pet er Coad and Edward Yourdon, Obj ect - Orient ed Analysis, Yourdon Press, 1991. [ Coa d, OOD ] Pet er Coad and Edward Yourdon, Obj ect - Orient ed Design, Yourdon Press, 1991. [ Cock bur n , a gile ] Alist air Cockburn, Agile Soft ware Developm ent , Addison-Wesley, 2001. [ Cock bur n , u se ca se s] Alist air Cockburn, Writ ing Effect ive Use Cases, Addison-Wesley, 2001. [ Con st an t in e a n d Lockw ood] Larry Const ant ine and Lucy Lockwood, Soft ware for Use, AddisonWesley, 2000. [ Cook a n d Da n ie ls] St eve Cook and John Daniels, Designing Obj ect Syst em s: Obj ect -Orient ed Modeling wit h Synt ropy , Prent ice-Hall, 1994. [ Cor e J2 EE Pa t t e rn s] Deepak Alur, John Crupi, and Dan Malks, Core J2EE Pat t erns, Prent ice-Hall, 2001. [ Cu n n in gha m ] Ward Cunningham , "EPI SODES: A Pat t ern Language of Com pet it ive Developm ent ." I n Pat t ern Languages of Program Design 2 , Vlissides, Coplien, and Kert h, Addison-Wesley, 1996, pp. 371–388. [ D ou glass] Bruce Powel Douglass, Real- Tim e UML, Addison-Wesley, 1999. [ Fow le r , AP] Mart in Fowler, Analysis Pat t erns: Reusable Obj ect Models, Addison-Wesley, 1997. [ Fow le r , ne w m e t hodology] Mart in Fowler, " The New Met hodology," h t t p:/ / m a r t in fow le r .com / a r t icle s/ n e w M e th odology.h t m l [ Fow le r a n d Foe m m e l] Mart in Fowler and Mat t hew Foem m el, " Cont inuous I nt egrat ion," h t t p:/ / m a r t in fow le r .com / a r t icle s/ con t in u ou sI n te gr a t ion .h t m l [ Fow le r , P of EAA] Martin Fowler, Pat t erns of Ent erprise Applicat ion Archit ect ure, Addison-Wesley, 2003. [ Fow le r , re fact or in g] Mart in Fowler, Refact oring: I m proving t he Design of Existing Program s, Addison-Wesley, 1999.
116/ 118
[ Ga n g of Fou r] Erich Gam m a, Richard Helm , Ralph Johnson, and John Vlissides, Design Pat t erns: Elem ent s of Reusable Obj ect - Orient ed Soft ware, Addison-Wesley, 1995. [ H igh sm it h ] Jim Highsm it h, Agile Soft ware Developm ent Ecosyst em s, Addison-Wesley, 2002. [ H oh m an n ] Luke Hohm ann, Beyond Soft ware Archit ecture, Addison-Wesley, 2003. [ Ja cobson , OOSE] I var Jacobson, Magnus Christ erson, Pat rik Jonsson, and Gunnar Övergaard, Obj ect - Orient ed Soft ware Engineering: A Use Case Driven Approach , Addison-Wesley, 1992. [ Ja cobson , UP] I var Jacobson, Maria Ericsson, and Agnet a Jacobson, The Obj ect Advant age: Business Process Reengineering wit h Obj ect Technology , Addison-Wesley, 1995. [ Ke r t h] Norm Kert h, Proj ect Ret rospect ives, Dorset House, 2001 [ Kle ppe e t a l.] Anneke Kleppe, Jos Warm er, and Wim Bast , MDA Explained, Addison-Wesley, 2003. [ Kr u ch t e n] Philippe Krucht en, The Rat ional Unified Process: An I nt roduct ion , Addison- Wesley, 1999. [ La r m an ] Craig Larm an, Applying UML and Pat t erns, 2d ed., Prent ice-Hall, 2001. [ M a r t in] Robert Cecil Mart in, The Principles, Pat t erns, and Pract ices of Agile Soft ware Developm ent , Prent ice- Hall, 2003. [ M cCon ne ll] St eve McConnell, Rapid Developm ent : Tam ing Wild Soft ware Schedules, Microsoft Press, 1996. [ M e llor an d Ba lcer ] St eve Mellor and Marc Balcer, Execut able UML, Addison-Wesley, 2002. [ M e yer ] Bert rand Meyer, Obj ect - Orient ed Soft ware Const ruct ion. Prent ice-Hall, 2000. [ Ode ll] Jam es Mart in and Jam es J. Odell, Obj ect - Orient ed Met hods: A Foundat ion (UML Edit ion) , Prent ice Hall, 1998. [ Pon t ] Michael Pont , Pat t erns for Tim e- Triggered Em bedded Syst em s, Addison-Wesley, 2001. [ POSA1 ] Frank Buschm ann, Regine Meunier, Hans Rohnert , Pet er Som m erlad, and Michael St al, Pat t ern- Orient ed Soft ware Archit ecture: A Syst em of Pat t erns, Wiley, 1996. [ POSA2 ] Douglas Schm idt , Michael St al, Hans Rohnert , and Frank Buschm ann, Pat t ern- Orient ed Soft ware Archt ect ure Volum e 2: Pat t erns for Concurrent and Net worked Obj ect s , Wiley, 2000. [ Ru m ba u gh , in sigh t s] Jam es Rum baugh, OMT I nsight s, SI GS Books, 1996. [ Ru m ba u gh , OMT] Jam es Rum baugh, Michael Blaha, William Prem erlani, Frederick Eddy, and William Lorenzen, Obj ect - Orient ed Modeling and Design, Prent ice-Hall, 1991. [ Ru m ba u gh , UM L Re fe r en ce] Jam es Rum baugh, I var Jacobson, and Grady Booch, The Unified Modeling Language Reference Manual, Addison-Wesley, 1999. [ Sh la er a n d M e llor , da t a ] Sally Shlaer and St ephen J. Mellor, Obj ect - Orient ed Syst em s Analysis: Modeling t he World in Dat a, Yourdon Press, 1989. [ Sh la er a n d M e llor , st a t e s] Sally Shlaer and St ephen J. Mellor, Obj ect Lifecycles: Modeling t he World in St at es. Yourdon Press, 1991.
117/ 118
[ W a r m e r an d Kle ppe ] Jos Warm er and Anneke Kleppe, The Obj ect Const raint Language: Precise Modeling wit h UML, Addison-Wesley, 1998. [ W ir fs- Br ock ] Rebecca Wirfs- Brock and Alan McKean, Obj ect Design: Roles Responsibilit ies and Collaborat ions. Prent ice-Hall, 2003.
118/ 118