Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

The Elements of UML 2.0 Style

1,993 views

Published on

  • Be the first to comment

The Elements of UML 2.0 Style

  1. 1. The Elements of TMUML 2.0 Style
  2. 2. For Beverley
  3. 3. The Elements of TMUML 2.0 Style Scott W. Ambler
  4. 4.   Cambridge, New York, Melbourne, Madrid, Cape Town, Singapore, São PauloCambridge University PressThe Edinburgh Building, Cambridge  , UKPublished in the United States of America by Cambridge University Press, New Yorkwww.cambridge.orgInformation on this title: www.cambridge.org/9780521616782This publication is in copyright. Subject to statutory exception and to the provision ofrelevant collective licensing agreements, no reproduction of any part may take placewithout the written permission of Cambridge University Press.First published in print format 2005- ---- paperback- --- paperbackCambridge University Press has no responsibility for the persistence or accuracy of sfor external or third-party internet websites referred to in this publication, and does notguarantee that any content on such websites is, or will remain, accurate or appropriate.
  5. 5. ContentsPreface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ixPurpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ixFeatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xAudience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xAssumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xAcknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.1 Organization of This Book . . . . . . . . . . . . . . . . . . . . . . . . . . 22. General Diagramming Guidelines . . . . . . . . . . . 42.1 Readability Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.2 Simplicity Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.3 Naming Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.4 General Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123. Guidelines for Common UML Modeling Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.1 Guidelines for UML Notes . . . . . . . . . . . . . . . . . . . . . . . . . 153.2 Guidelines for UML Stereotypes . . . . . . . . . . . . . . . . . . . . 183.3 Guidelines for UML Frames . . . . . . . . . . . . . . . . . . . . . . . . 213.4 Guidelines for UML Interfaces . . . . . . . . . . . . . . . . . . . . . . 244. UML Use-Case Diagrams . . . . . . . . . . . . . . . . . . . . . 334.1 Use-Case Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334.2 Actor Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 v
  6. 6. vi CONTENTS4.3 Relationship Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384.4 System Boundary Box Guidelines . . . . . . . . . . . . . . . . . . . 455. UML Class Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . 475.1 General Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475.2 Class Style Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515.3 Relationship Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595.4 Association Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645.5 Inheritance Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685.6 Aggregation and Composition Guidelines . . . . . . . . . . . . 706. UML Package Diagrams . . . . . . . . . . . . . . . . . . . . . 736.1 Class Package Diagram Guidelines . . . . . . . . . . . . . . . . . . . 736.2 Use-Case Package Diagram Guidelines . . . . . . . . . . . . . . . 766.3 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787. UML Sequence Diagrams . . . . . . . . . . . . . . . . . . . . 807.1 General Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817.2 Guidelines for Lifelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 867.3 Message Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897.4 Guidelines for Return Values . . . . . . . . . . . . . . . . . . . . . . . 918. UML Communication Diagrams . . . . . . . . . . . . . 948.1 General Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 958.2 Message Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 988.3 Link Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1009. UML State Machine Diagrams . . . . . . . . . . . . . . 1039.1 General Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1039.2 State Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1059.3 Substate Modeling Guidelines . . . . . . . . . . . . . . . . . . . . . 1069.4 Transition and Action Guidelines . . . . . . . . . . . . . . . . . . 1089.5 Guard Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11110. UML Activity Diagrams . . . . . . . . . . . . . . . . . . . . . 11310.1 General Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11310.2 Activity Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
  7. 7. CONTENTS vii10.3 Decision Point and Guard Guidelines . . . . . . . . . . . . . 11610.4 Parallel Flow Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . 12110.5 Activity Partition (Swim Lane) Guidelines . . . . . . . . . . 12210.6 Action-Object Guidelines . . . . . . . . . . . . . . . . . . . . . . . . 12811. UML Component Diagrams . . . . . . . . . . . . . . . . 13211.1 Component Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . 13211.2 Dependency and Inheritance Guidelines . . . . . . . . . . . 13612. UML Deployment Diagrams . . . . . . . . . . . . . . . 13912.1 General Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14012.2 Node and Component Guidelines . . . . . . . . . . . . . . . . . 14412.3 Dependency and Communication-Association Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14613. UML Object Diagrams . . . . . . . . . . . . . . . . . . . . . . 14814. UML Composite Structure Diagrams . . . . . . 15015. UML Interaction Overview Diagrams . . . . . 15316. UML Timing Diagrams . . . . . . . . . . . . . . . . . . . . . . 15716.1 General Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15716.2 Axis Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15916.3 Time Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16017. Agile Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16217.1 Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16217.2 Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16217.3 Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164Bibliography. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
  8. 8. PrefaceM odels are used by professional developers to commu- nicate their work to project stakeholders and to otherdevelopers. The Unified Modeling Language (UML) has beenan important part of the software development landscape sinceits introduction in 1997. We’ve seen the UML evolve over theyears and it is now into its 2.x series of releases. Modelingstyle, however, has remained constant and will continue to doso. By understanding and following these common model-ing style guidelines, you can improve the effectiveness of yourmodels.I’ve updated this book to include the new diagrams in UML 2,to use the terminology of UML 2, and to include hand-drawndiagrams. The vast majority of models are drawn on white-boards and I think that it’s time that modeling books, includ-ing this one, reflect that reality.PurposeThis book describes a collection of standards, conventions,and guidelines for creating effective UML diagrams. They arebased on sound, proven principles that will lead to diagramsthat are easier to understand and work with.These simple, concise guidelines, if applied consistently, willbe an important first step in increasing your productivity as amodeler. ix
  9. 9. x P R E FAC EFeaturesThis guide attempts to emulate Strunk and White’s (1979)seminal text, The Elements of Style, which lists a set of rulesdescribing the proper application of grammatical and com-positional forms in common use within the written Englishlanguage.Using a similar style of presentation, this book defines a setof rules for developing high-quality UML diagrams. In doingso, this guide■ employs existing standards defined by the Object Manage- ment Group (OMG) whenever possible,■ provides a justification for each rule, and■ presents standards based on real-world experience and proven principles.AudienceThis guide targets information technology (IT) professionalswho are interested in■ creating effective UML diagrams,■ increasing their productivity, and■ working as productive members of a software development team.AssumptionsIn this book I make several assumptions:■ You understand the basics of the UML and modeling. If not, then I suggest UML Distilled (Fowler 2004) if you are looking for a brief overview of the UML, or better yet The Object Primer, third edition (Ambler 2004) for a
  10. 10. P R E FAC E x i more comprehensive discussion. UML Distilled is a great book but is limited to the UML; The Object Primer, third edition, on the other hand, goes beyond the UML where needed, for example, to include user interface, Java, and database development issues. It also covers agile software development techniques in detail.■ You are looking for style guidelines, not design guidelines. If not, then I suggest the book Object-Oriented Design Heuris- tics (Riel 1996).■ Your focus is on business application development. Al- though these guidelines also apply to real-time develop- ment, all of the examples are business application–oriented, simplifications of actual systems that I have built in the past.■ You belong to a Western culture. Many of the layout guide- lines are based on the Western approach to reading—left to right and top down. People in other cultures will need to modify these guidelines as appropriate.AcknowledgmentsThe following people have provided valuable input into thedevelopment and improvement of this text: James Bielak,Chris Britton, Larry Brunelle, Lauren Cowles, Beverley Dawe,Caitlin Doggart, Doug English, Jessica Farris, Scott Fleming,Mark Graybill, Alvery Grazebrook, Jesper R. Jensen, JonKern, Kirk W. Knoernschild, Hubert Matthews, Les Munday,Sabine Noack, Paul Oldfield, Marco Peters, Scott W. Preece,Neil Pitman, Edmund Schweppe, Leo Tohill, Tim Tuxworth,Michael Vizdos, and Robert White.
  11. 11. 1. IntroductionOne of Agile Modeling’s (AM) practices (discussed in Chap-ter 17) is Apply Modeling Standards, the modeling version ofExtreme Programming (XP)’s Coding Standards (Beck 2000).Developers should agree to and follow a common set of stan-dards and guidelines on a software project, and some of thoseguidelines should apply to modeling. Models depicted witha common notation and that follow effective style guidelinesare easier to understand and to maintain. These models willimprove communication internally within your team and ex-ternally to your partners and customers, thereby reducing theopportunities for costly misunderstandings. Modeling guide-lines will also save you time by limiting the number of stylisticchoices you face, allowing you to focus on your actual job –to develop software. A lot of the communication value in a UML diagram is still due to the layout skill of the modeler. —Paul Evitts, A UML Pattern Language (Evitts 2000)When you adopt modeling standards and guidelines withinyour organization, your first step is to settle on a commonnotation. The Unified Modeling Language (UML) (ObjectManagement Group 2004) is a good start because it defines thenotation and semantics for common object-oriented models.Some projects will require more types of models than the UMLdescribes, as I show in The Object Primer 3/e (Ambler 2004),but the UML will form the core of any modern modelingeffort. 1
  12. 12. 2 THE ELEMENTS OF UML 2.0 STYLEYour second step is to identify modeling style guidelines to helpyou to create consistent and clean-looking diagrams. What isthe difference between a standard and a style guideline? Forsource code, a standard would, for example, involve namingthe attributes in the format attributeName, whereas a styleguideline would involve indenting your code within a controlstructure by three spaces. For models, a standard would involveusing a squared rectangle to model a class on a class diagram,whereas a style would involve placing subclasses on diagramsbelow their superclass(es). This book describes the style guide-lines that are missing from many of the UML-based method-ologies that organizations have adopted, guidelines that arecritical to your success in the software development game.The third step is to enact your modeling standards and guide-lines. To do this, you will need to train and mentor your staff inthe modeling techniques appropriate to the projects on whichthey are working. You will also need to train and mentor themin your adopted guidelines, and a good start is to provide themwith a copy of this book. I’ve been amazed at the success ofThe Elements of Java Style (Vermeulen et al. 2000) with respectto this—hundreds of organizations have adopted that bookfor their internal Java coding standards because they rec-ognized that it was more cost-effective for them to buy apocketbook for each developer than to develop their ownguidelines.1.1 Organization of This BookThis book is organized in a straightforward manner. Chapter 2describes general diagramming principles that are applicableto all types of UML diagrams (and many non-UML diagramsfor that matter). Chapter 3 describes guidelines for com-mon UML elements such as stereotypes, notes, and frames.
  13. 13. INTRODUCTION 3Chapters 4 through 16 describe techniques pertinent to eachtype of UML diagram. Chapter 17 provides an overview of thevalues, principles, and practices of AM, with a quick referenceto this popular methodology.
  14. 14. 2. General Diagramming GuidelinesThe guidelines presented in this chapter are applicable to alltypes of diagrams, UML or otherwise. The terms “symbols,”“lines,” and “labels” are used throughout:■ Symbols represent diagram elements such as class boxes, object boxes, use cases, and actors.■ Lines represent diagram elements such as associations, de- pendencies, and transitions between states.■ Labels represent diagram elements such as class names, as- sociation roles, and constraints.2.1 Readability Guidelines1. Avoid Crossing LinesWhen two lines cross on a diagram, such as two associations ona UML class diagram, the potential for misreading a diagramexists. 4
  15. 15. G E N E R A L D I AG R A M M I N G G U I D E L I N E S 5 A A C D C D B B Figure 1. Depiction of crossing lines.2. Depict Crossing Lines as a JumpYou can’t always avoid crossing lines; for example, you cannotfully connect five symbols (try it and see). When you need tohave two lines cross, one of them should “hop” over the otheras in Figure 1.3. Avoid Diagonal or Curved LinesStraight lines, drawn either vertically or horizontally, are eas-ier for your eyes to follow than diagonal or curved lines. Agood approach is to place symbols on diagrams as if theyare centered on the grid point of a graph, a built-in feature ofmany computer-aided system-engineering (CASE) tools. Thismakes it easier to connect your symbols by only using hori-zontal and vertical lines. Note how three lines are improved inFigure 2 when this approach is taken. Also note how the linebetween A and C has been depicted in “step fashion” as a linewith vertical and horizontal segments.4. Apply Consistently Sized SymbolsThe larger a symbol appears, the more important it seemsto be. In the first version of the diagram in Figure 2, the Asymbol is larger than the others, drawing attention to it. Ifthat isn’t the effect that you want, then strive to make yoursymbols of uniform size. Because the size of some symbols is
  16. 16. 6 THE ELEMENTS OF UML 2.0 STYLE Figure 2. Improving the attractiveness of a diagram.determined by their contents—for example, a class will varyin size based on its attributes and operations—this rule isnot universally applicable. Ideally you should only deviate ifyou want to accentuate an aspect of your diagram (Koning,Dormann, and Van Vliet 2002).5. Attach Lines to the Middle of BubblesAs you can see in Figure 2, the Label 1 line between A and Dis much more readable in the updated version of the diagram.6. Align Labels HorizontallyIn Figure 2 the two labels are easier to read in the secondversion of the diagram. Notice how Label 2 is horizontal eventhough the line it is associated with is vertical.7. Arrange Symbols SymmetricallyFigure 3 presents a UML activity diagram (Chapter 10) depict-ing a high-level approach to enterprise modeling. Organizingthe symbols and lines in a symmetrical manner makes the dia-gram easier to understand. A clear pattern will make a diagrameasier to read.8. Don’t Indicate “Exploding” BubblesThe rake symbol in the upper right corner of each activity inFigure 3 is the UML way to indicate that they “explode” to
  17. 17. G E N E R A L D I AG R A M M I N G G U I D E L I N E S 7 Requirements Stakeholder Enterprise Architect Analyst Model Prioritize Enterprise Enterprise Business Requirements Architecture Model Enterprise Support Requirements Project Teams Model Describe Enterprise Enterprise Technical Requirements Architecture Figure 3. UML activity diagram for a software process.another diagram showing a greater level of detail. Althoughthis seems like a good idea, the reality is that people using aCASE tool know enough to double click on it, or whateverstrategy the tool implements, to get more detail. The rake isn’tadding any extra value.9. Minimize the Number of Bubble TypesKoning, Dormann, and Van Vliet (2002) recommend thatyou have six or fewer bubbles on a diagram; any more risksoverwhelming the user of the model.10. Include White Space in DiagramsWhite space is the empty areas between modeling elementson your diagrams. In the first version of Figure 2 the symbolsare crowding each other, whereas in the second version, thesymbols are spread out from one another, thus improving the
  18. 18. 8 THE ELEMENTS OF UML 2.0 STYLEreadability of the diagram. Observe that in the second versionthere is adequate space to add labels to the lines.11. Organize Diagrams Left to Right, Top to BottomIn Western cultures, people read left to right and top to bottomand therefore this is how they will read your diagrams. If thereis a starting point for reading the diagram, such as the initialstate of a UML state chart diagram or the beginning of the flowof logic on a UML sequence diagram, then place it toward thetop left corner of your diagram and continue appropriatelyfrom there.12. Avoid Many Close LinesSeveral lines close together are hard to follow.13. Provide a Notation LegendIf you’re not sure that all of the users of a model under-stand the notation that you’re using, provide them with alegend that overviews it. A good legend indicates the nota-tional symbols used, the name of the symbol, and a descriptionof its usage. Figure 4 provides an example for robustness dia-grams (Jacobson, Christerson, Jonsson, and Overgaard 1992;Rosenberg and Scott 1999), a modification of UML commu-nication diagrams (Chapter 8).2.2 Simplicity Guidelines14. Show Only What You Have to ShowDiagrams showing too many details are difficult to read be-cause they are too information-dense. One of the practicesof Agile Modeling (Chapter 17) is to Depict Models Simply:to include only critical information on your diagrams and toexclude anything extraneous. A simple model that shows thekey features that you are trying to depict—perhaps a UML
  19. 19. G E N E R A L D I AG R A M M I N G G U I D E L I N E S 9 Actors represent people, organizations, or other Actor systems which interact with our system. Examples: Student, Financial Institution, and Payment Processor. Actor Name Process/ Process/controller classes implement logic which Controller crosses several business entities. Examples: Print aProcess Name Class student transcript and Drop student from a seminar. Domain Domain classes implement fundamental business Class entities. Examples: Student, Seminar, Course. Entity Name Interface classes enable actors to interact with our Interface system, other via a user interface or a system interface. Class Examples: Student registration screen and PaymentInterface Name Processing System Interface. Whenever an actor interacts with a class, or two Association classes interact, there is an association between them. Figure 4. A legend for robustness diagrams.class diagram depicting the primary responsibilities of classesand the relationships between them—often proves to be suf-ficient. Yes, you could model all of the scaffolding code thatyou will need to implement, but what value would that add?Very little.15. Prefer Well-Known Notation over Esoteric NotationDiagrams that include esoteric notation, instead of just the20 percent “kernel notation” that does 80 percent of the job,can be difficult to read. Of course, what is well known in oneorganization may not be so well known in another, and so, youmay want to consider supplying people with a brief summaryof the notation that you’re using.16. Reorganize Large Diagrams into SeveralSmaller OnesIt is often better to have several diagrams showing vari-ous degrees of detail than one complex diagram that shows
  20. 20. 10 THE ELEMENTS OF UML 2.0 STYLEeverything. A good rule of thumb is that a diagram shouldn’thave more than nine symbols on it, based on the 7 ± 2 rule(Miller 1957), because there is a limit on the amount of in-formation that someone can deal with at once. “Wallpaper”diagrams, particularly enterprise data models or enterprise ob-ject models, may look interesting but they’re too information-dense to be effective. When you are reorganizing a large dia-gram into several smaller ones, you may choose to introducea high-level UML package diagram (Chapter 6).17. Prefer Single-Page DiagramsTo reduce complexity, a diagram should be printable on asingle sheet of paper to help reduce its scope as well as toprevent wasted time cutting and taping several pages together.Be aware that you will reduce the usability of a diagram if youneed to reduce the font too much or crowd the symbols andlines.18. Focus on Content First, Appearance SecondThere is always the danger of adding hours onto your CASEtool modeling efforts by rearranging the layout of your sym-bols and lines to improve the diagram’s readability. The bestapproach is to focus on the content of a diagram at first andonly try to get it looking good in a rough sort of way—itdoesn’t have to be perfect while you’re working on it. Onceyou’re satisfied that your diagram is accurate enough, and thatyou want to keep it, then invest the appropriate time to make itlook good. An advantage of this approach is that you don’t in-vest significant effort improving diagrams that you eventuallydiscard.19. Apply Consistent, Readable FontsConsistent, easy-to-read fonts improve the readability of yourdiagrams. Good ideas include fonts in the Courier, Arial,
  21. 21. G E N E R A L D I AG R A M M I N G G U I D E L I N E S 1 1and Times families. Bad ideas include small fonts (less than10 point), large fonts (greater than 18 point), and italics.2.3 Naming Guidelines20. Set and Follow Effective Naming ConventionsThis is one of the easiest things that you can do to ensure con-sistency within your models, and hence increase their read-ability.21. Apply Common Domain Terminology in NamesApply consistent and recognizable domain terminology, suchas customer and order, whenever possible on your diagrams.This is particularly true for requirements and analysis-orienteddiagrams with which your project stakeholders are likely to beworking.22. Apply Language Naming Conventions onDesign DiagramsDesign diagrams should reflect implementation issues, in-cluding language naming conventions, such as orderNumberfor an attribute and sendMessage() in Java. Requirements andanalysis-oriented diagrams should not reflect language issuessuch as this.23. Name Common Elements ConsistentlyAcross DiagramsA single modeling element, such as an actor or a class, willappear on several of your diagrams. For example, the sameclass will appear on several UML class diagrams, several UMLsequence diagrams, several UML communication diagrams,and several UML activity diagrams. This class should havethe same name on each diagram; otherwise your readers willbecome confused.
  22. 22. 12 THE ELEMENTS OF UML 2.0 STYLE2.4 General Guidelines24. Indicate Unknowns with a Question MarkWhile you are modeling, you may discover that you do nothave complete information. This is particularly true when youare analyzing the domain. You should always try to track downa sufficient answer, but if you cannot do so immediately, thenmake a good guess and indicate your uncertainty. Figure 5depicts a common way to do so with its use of questionmarks.1 First, there is a UML note (see Section 3.1) attachedto the association between Professor and Seminar questioningthe multiplicity. Second, there is a question mark above theconstraint on the wait listed association between Student andSeminar, likely an indication that the modeler isn’t sure thatit really is a first in, first out (FIFO) list.25. Consider Applying Color to Your DiagramsCoad, Lefebvre, and DeLuca (1999) provide excellent advicein their book Java Modeling in Color with UML for improvingthe understandability of diagrams by applying color to them,in addition to UML stereotypes. Perhaps color could indicatethe implementation language of a class (e.g., blue for Javaand red for C++) on a UML class diagram, the developmentpriority of a use case (e.g., red for phase 1, orange for phase 2,and yellow for future phases) on a UML use case diagram, orthe target platform (e.g., blue for an application server, greenfor a client machine, and pink for a database server) for asoftware element on a UML deployment diagram.26. Apply Color or Different Fonts SparinglyEvitts (2000) suggests the use of different fonts, line styles,colors, and shading to emphasize different aspects of your1 Question marks are not official UML notation.
  23. 23. 0..* enrolled in 1..* Student Seminar name name address seminarNumber ? phoneNumber {ordered, FIFO } fees emailAddress 0..* wait listed 0..* waitingList studentNumber addStudent(student) averageMark 0..* dropStudent(student) isEligible (name,13 studentNumber) getSeminarsTaken() Professor instructs name address 0..1 phoneNumber ?Some seminars may emailAddress not have an salary instructor? getInformation() Figure 5. Indicating uncertainty on a diagram.
  24. 24. 14 THE ELEMENTS OF UML 2.0 STYLEdiagrams. The secret is to do this sparingly; otherwise you runthe risk of creating noisy/gaudy diagrams. Sometimes less ismore. Koning, Dormann, and Van Vliet (2002) also suggestrestraint when applying color, suggesting that you not usemore than six colors in a single diagram, that you use vividcolors only for strong signaling, and that you prefer colors thatare light.
  25. 25. 3. Guidelines for Common UML Modeling ElementsAn important benefit of the UML is that it is consistent, andpart of that consistency is the application of common model-ing elements across different diagrams. This chapter describesguidelines for■ Notes■ Stereotypes■ Frames■ Interfaces3.1 Guidelines for UML NotesA UML note is a modeling construct for adding textualinformation—such as a comment, constraint definition, ormethod body—to UML diagrams. As you can see in Figure 6,notes are depicted as rectangles with the top right cornersfolded over.27. Describe Diagrams with NotesEver look at a diagram and not know what it represents? Asimple solution is to include a UML note on each diagram 15
  26. 26. 16 THE ELEMENTS OF UML 2.0 STYLE SWA Online Common Business Components Owner: H. Jordan Figure 6. A summary note for a diagram.that provides a simple and concise description. This is oftenreferred to as a “legend.” In Figure 6 you can see that the nameof the system, the purpose of the diagram, and its owner areindicated. It is common also to indicate when the diagramwas last updated and the contact information for the owner.28. Set a Convention for Placement ofDiagram LegendsPlacing diagram legends in the same place on all your diagramsincreases their usability by making them easy to find. Commonspots are one of the corners or the bottom center of a diagram.29. Left-Justify Text in NotesIt is common practice to left-justify text in UML notes, as youcan see in Figure 6.30. Prefer Notes over OCL or ASL toIndicate ConstraintsSource code, describing a constraint or processing logic, canbe modeled on any UML diagram using a note. In UML,constraints are modeled either by a UML note using free-formtext or with Object Constraint Language (OCL) (Warmer andKleppe 2003). Future versions of UML are expected to sup-port a common Action Semantic Language (ASL) for definingprocess logic—right now it is common to model tool-specificASL, program source code (e.g., Java or C#), or structuredEnglish.
  27. 27. Common UML Modeling Elements 17 { ordered, FIFO } wait listed for 0..* 0..* 0..* prerequisite 0..* takes 1..* 0..* for Student Seminar {subset} 0..* 0..* currently enrolled in context Student::previousCourses derive: Student.takes – Student.currentlyEnrolledin inv: Student.currentlyEnrolledin->forAll ( Student.previousCourses.contains (each.prerequisites)) Figure 7. Indicating OCL on a UML diagram.Figure 7 includes three examples of OCL—two as simple con-straints on relationships and one as a note. The constraint{ordered, FIFO} indicates that the waiting list to get into aseminar is ordered in “first in, first out” sequence. The con-straint {subset} indicates that the currently enrolled in rela-tionship is a subset of the takes relationships. Both of theseare reasonably straightforward to understand, although theywould prove too abstract for some business stakeholders. Thenote contains an even more complex example of OCL, some-thing that likely could be written and understood only byprogrammers. Sophisticated CASE tools will use the infor-mation contained in this note to generate working software,although if your CASE tool doesn’t do this then I questionthe value of writing this OCL.It would have been easier to have just written the text “Studentsmust have taken the prerequisite seminars for each one they arecurrently enrolled in.” When the audience for a diagram in-cludes project stakeholders, you should write a free-form note,perhaps using natural language, for your constraint. ConsiderOCL or ASL for diagrams whose only audience is developers,
  28. 28. 18 THE ELEMENTS OF UML 2.0 STYLEbut recognize that this is only appropriate if everyone involvedunderstands OCL or ASL.31. Follow Common Coding Conventionsfor OCL and ASLThe book The Elements of Java Style (Vermeulen et al. 2000)provides Java coding guidance that you can modify for OCLand ASL.3.2 Guidelines for UML StereotypesA stereotype denotes a variation on an existing modelingelement with the same form but with a modified intent(Rumbaugh, Jacobson, and Booch 2004). Stereotypes are usedto extend the UML in a consistent manner.32. Name Stereotypes in <<user interface>>and <<UI>> FormatIt is common UML convention to use lowercase for stereotypesthat are spelled out fully, such as <<include>> instead of<<Include>>, and to use all uppercase for stereotypes thatare abbreviations, such as <<HTTP>> instead of <<Http>>.33. List Stereotypes LastThe most important information should always come first,followed by the next most important information, and so on.The stereotypes applicable to a model element should be listedto the right of or below the primary information. In Figure 8the second version of the Customer class lists the stereotypesfor its operations after the operation signature, not before it.34. Don’t Indicate Assumed StereotypesIn Figure 8 I dropped the <<business domain>> stereo-type because it is common practice to assume that a class is abusiness domain one unless marked otherwise.
  29. 29. <<business domain>> Customer Customer <<unique id>> # customerNumber: int # customerNumber: int <<unique id>> - homeAddress: Address - homeAddress: Address - name: String - name: String <<constructor>> + Customer(): Customer + Customer(): Customer <<constructor>>19 <<search>> + findAllInstances(): Vector + findAllInstances(): Vector <<search>> + findForID(customerNumber): Vector + findForID(customerNumber): Vector <<search>> + findForOrder(order): Vector + findForOrder(order): Vector <<getter>> + getTotalBusiness(sinceDate): Currency {default = 0} + getTotalBusiness(sinceDate): Currency <<getter>> {default = 0} + scheduleShipment(forDate): Shipment + scheduleShipment(forDate): Shipment Figure 8. Indicating stereotypes.
  30. 30. 20 THE ELEMENTS OF UML 2.0 STYLE35. Prefer Naming Conventions over StereotypesAn effective alternative to applying a stereotype is to applya naming convention. For example, instead of applying thestereotype <<getter>> on an operation, you could simplystart all getters with the text get, as you can see in Figure 5with the getSeminarsTaken() operation. This simplifies yourdiagrams and increases the consistency of your source code.Normally I would have not included <<getter>> in Figure 8but I left it there for the discussion of Guideline #36. Noticehow in Figure 8 the <<search>> stereotypes were removedbecause the operation names all start with find.A drawback of this approach is that using naming conventionscan hide the stereotyping information from your modelingtool. Ideally you should be able to define your naming con-ventions in your tool, enabling it to act intelligently, but thatcan be a lot to ask of the vendors.36. Tagged Values Follow StereotypesIn Figure 8 you see that the tagged value default follows the<<getter>> stereotype, because this level of detail is oftenthe least important information shown on a diagram. Taggedvalues are sometimes referred to as named variables or namedelements.37. Align Classifier Stereotypes with NamesThe stereotype for the Customer class in Figure 8 is centeredbecause the name is centered. Had the name in the class beenleft justified then so should the stereotype have been. Thishelps to visually associate the two pieces of information.38. Introduce New Stereotypes SparinglyA common mistake made by UML novices is to apply stereo-types to everything, forcing them to introduce a plethora ofnew stereotypes. The end result is that their diagrams are
  31. 31. Common UML Modeling Elements 21cluttered with stereotypes. Introduce a new stereotype to clar-ify an aspect of a model, but don’t introduce one simply to“complete” your model.39. Apply Stereotypes ConsistentlyYou will find that you need to document your common stereo-types, above and beyond those defined by the UML standard,to ensure that they are applied consistently. For example,you need to decide whether you are going to use <<userinterface>> or <<UI>> as your preferred stereotype. Bothare good choices; choose one and move forward.40. Apply Visual Stereotypes SparinglyFigure 9 depicts a sequence diagram (Chapter 7), which in-cludes the standard robustness diagram symbols (Jacobson,Christerson, Jonsson, and Overgaard 1992; Rosenberg andScott 1999) that are commonly applied to UML communica-tion diagrams (Chapter 8). The visual stereotypes—a stick fig-ure for an actor, a circle with an arrowhead for a process class,and a circle on top of a line for business domain classes—are applied instead of text stereotypes such as <<actor>>.Apply visual stereotypes only when they are well known to theuser(s) of your diagrams. It should be safe to assume that userscan read a text stereotype, but it’s not as safe to assume theyunderstand the visual representations.3.3 Guidelines for UML FramesA frame in the UML encapsulates a collection of collaboratinginstances or refers to another representation of such. Framesare depicted as rectangles with notched descriptor boxes inthe top left corners. Frames come in two flavors, diagramframes such as Batch Transcript Printing and combinedfragment frames such as the loop frame, both in Figure 9.Diagram frames explicitly define the boundary of a diagram,
  32. 32. sd Batch Transcript Printing : TranscriptBatch : TranscriptBuilder student: : Seminar printer: SharedServices ref PrintRun Student <<system>> new(student) getSeminars() loop [for each seminar] getMark()22 calculateMark() print(studentTranscript) ref SharedServices.print() Figure 9. A frame encompassing a sequence diagram.
  33. 33. Common UML Modeling Elements 23whereas combined fragment frames encompass portions of adiagram or provide references to other diagrams or methoddefinitions.41. Deemphasize Frame BordersIn Figure 9 you see that the frame border is lighter than thelines around it, reflecting the idea that the frame border is notas critical as the other information contained in the diagram.42. Avoid Diagram FramesThe Batch Transcript Printing diagram frame of Figure 9 adds asignificant amount of visual clutter. The only real value that itadds is that it indicates the name of the diagram, informationthat could have been captured in a note if it needed to bedepicted at all. Diagram frames are in effect generic boundaryboxes for diagrams, and that purpose is accomplished justas well by the edge of your computer screen, whiteboard, orpaper.Note that combined fragment frames, such as the loop inFigure 9, are very useful.43. Apply Standard Labels to DescriptorsTable 1 summarizes common labels for diagram frames andTable 2 the common labels for combined fragments. Unfortu-nately many of these labels, which are part of the UML stan-dard (Object Management Group 2004), are abbreviations,which decrease the readability of your diagrams.44. Use Interaction Occurrences overPart DecompositionsThere are two references to logic external to Figure 9: the Tran-scriptBatch object includes a reference to PrintRun and thereis a combined fragment referencing the SharedServices.print()method. The style of the first reference is called a part
  34. 34. 24 THE ELEMENTS OF UML 2.0 STYLE Table 1. Diagram Frame Labels Label Usage Component The frame depicts the internal design of a component. Package The frame depicts the internal organization of a package, often using a UML class diagram or a UML use case diagram sd Indicates that the frame contains an interaction diagram, usually a UML sequence diagram, although UML communication diagrams are also common options. Use Case The frame depicts the logic of a use case, often as a UML activity diagram or an interaction overview diagram.decomposition and the second an interaction occurrence. Asyou can see, interaction occurrences are much more explicitthan part decomposition and thus won’t be overlooked aseasily.45. Fully Specify Operation Names in ReferencesThe reference to the print method in Figure 9 is presented inthe full classifier.operation() format, making it explicit whichoperation (or in this case a service) is being invoked.3.4 Guidelines for UML InterfacesAn interface is a collection of operation signatures and/or at-tribute definitions that ideally defines a cohesive set of behav-iors. Interfaces are implemented, “realized” in UML parlance,by classes and components—to realize an interface, a classor component must implement the operations and attributesdefined by the interface. Any given class or component may
  35. 35. Common UML Modeling Elements 25 Table 2. Combined Fragment Labels Label Usage alt Indicates several alternatives, only one of which will be taken, separated by dashed lines. Used to model if and switch statements. assert Indicates that the fragment models an assertion. criticalRegion Indicates that the fragment must be treated as atomic and cannot be interleaved with other event occurrences. Often used within a par frame (Douglass 2004). loop Models logic that will potentially be repeated several times. opt Models optional logic depending on the run-time evaluation of a guard. par Indicates several fragments of logic, separated by dashed lines, all of which will run in parallel. An example is presented in Figure 10. ref References another diagram or a method definition. This is often called an interaction use frame because this style of frame doesn’t contain visual model elements, only text.implement zero or more interfaces, and one or more classes orcomponents can implement the same interface.46. Depict One Interface per PortPorts are connection points between a classifier and its envi-ronment, which are depicted on the side of frames as smallrectangles. You may attach one or more interfaces to a port. InFigure 11 each port has exactly one interface, which is logicallycohesive and thus does not reveal anything about the internaldesign of the Seminar component.
  36. 36. Financial :FundsTransfer Record Transaction source :Account target :Account <<controller>> Transaction Manager start(UserID): transactionIDpar attemptWithdrawal(amount, transactionID) addWithdrawal(amount, source, transactionID) attemptDeposit(amount, transactionID): Vector addDeposit(amount, target, transactionID) commit(transactionID) par commit(transactionID) commit(transactionID) <<include>> Figure 10. Transferring funds between accounts.
  37. 37. 27 Figure 11. The internals of a (simple) component.
  38. 38. 28 THE ELEMENTS OF UML 2.0 STYLE47. Depict One Port per Realizing ClassAnother approach to organizing the interfaces for Seminar-Component of Figure 11 would be to have a single port of-fering the Enrollment, Transcript, and DataEntity interfaces.This would make for a more compact diagram, although itcan contradict Guideline #46.48. Provided Interfaces on the LeftProvided interfaces, those that a classifier implements, shouldbe placed on the left of the box if possible. In Figure 11 theprovided interfaces are depicted using “lollipop” notation. Ifyou cannot fit a provided interface on the left side your nextbest option is the top of the box.49. Required Interfaces on the RightRequired interfaces are those that a classifier must have pro-vided for it to work. Required interfaces, such as Student,Persistence, and XMLProcessor in Figure 11 are depicted inUML 2 as “sockets.” The next best option is to place them onthe bottom of the classifier. This rule, in combination withGuideline #48, makes it easier to create wiring-diagram stylecomponent diagrams (Chapter 11).50. Apply Realizes Relationships for PortsThere are several ways to indicate that a classifier implementsor requires the interfaces of a port. In Figure 11 SeminarCom-ponent realizes the three ports on the left of the frame and theEnrollment class delegates to the Student port. It would havealso been accurate to model the Transcript port as delegatingto SeminarComponent or the Student port as realizing the re-quired interface for the Enrollment class. We could also haveused dependencies to model these relationships (dashed lineswith arrowheads).
  39. 39. Common UML Modeling Elements 29 Figure 12. Interfaces on UML class diagrams.51. Reflect Implementation Language Constraintsin Interface DefinitionsIn Figure 12, you can see that a standard class box has beenused to define the interface PersistentObject (note the use ofthe <<interface>> stereotype). This interface includes apublic attribute named POID and several public operations.Unfortunately, it could not be implemented in Java becausethis language does not (yet) support instance attributes in thedefinition of interfaces. Therefore, you need to rework thisinterface definition if you wish to implement my model inJava.52. Name Interfaces According toLanguage-Naming ConventionsInterfaces are named in the same manner as classes: they havefully described names in the format InterfaceName. In Java itis common to have interface names such as Serializable thatend in able or ible or just descriptive nouns such as EJBObject.
  40. 40. 30 THE ELEMENTS OF UML 2.0 STYLEIn Microsoft environments, it is common practice to prefixinterface names with a capital I, resulting in names such asIComponent.53. Prefer “Lollipop” Notation to Indicate Realizationof an InterfaceAs you can see in Figure 12, there are two ways to indicatethat a class or component implements an interface: the lollipopnotation used with the Serializable interface and the realizationline (the dashed line with a closed arrowhead) used with thePersistentObject interface. The lollipop notation is preferredbecause it is visually compact; the class box and realizationline approach tend to clutter your diagrams. Note that you’llstill need to model the specifics of the interface somewhereelse.54. Define Interfaces Separately from Your ClassifiersTo reduce clutter, you can define interfaces separately fromclassifiers, either in another diagram specifically for interfacedefinitions or simply on one edge of your class/componentdiagram.55. Do Not Depict the Operations and Attributesof Interfaces in Your ClassesIn Figure 12, you’ll notice that the Shipment class does not in-clude the attributes or operations defined by the two interfacesthat it realizes. That information would be redundant becauseit is already contained within the interface definitions. Notethat a CASE tool should still include these elements in thedefinition of your classes, but that it shouldn’t display it.56. One Label per Interface ConnectionIn Figure 13 you see that the IPersistence interface is indicatedtwice, once for the lollipop and once for the socket. When you
  41. 41. Apache IXML Struts University DB Customer <<framework>> ICustomer <<datastore>> JDBC <<requires>> Online IXML Ordering Order Persistence IOrder <<component>> IPersistence <<infrastructure>>31 <<application>> IPersistence IXML IEncryption Shipping Delivery Security <<application>> IDelivery <<component>> IAccessControl <<infrastructure>> Figure 13. UML component diagram representing the logical architecture of a simple e-commerce system.
  42. 42. 32 THE ELEMENTS OF UML 2.0 STYLEcompare this with how the other interface names are modeledyou see that listing it twice is unnecessary clutter.57. Place Interface Labels Above the InterfaceWhenever possible, interface labels should be placed above theinterface lollipop/socket symbols.
  43. 43. 4. UML Use-Case DiagramsA UML use-case diagram shows the relationships among ac-tors and use cases within a system. They are often used to■ provide an overview of all or part of the usage requirements for a system or organization in the form of an essential model (Constantine and Lockwood 1999, Ambler 2004) or a business model (Rational Corporation 2002);■ communicate the scope of a development project;■ model the analysis of usage requirements in the form of a system use-case model (Cockburn 2001).A use-case model comprises one or more use-case diagramsand any supporting documentation such as use-case specifica-tions and actor definitions. Within most use-case models, theuse-case specifications tend to be the primary artifact, withUML use-case diagrams filling a supporting role as the “glue”that keeps your requirements model together. Use-case modelsshould be developed from the point of view of your projectstakeholders and not from the (often technical) point of viewof developers.4.1 Use-Case GuidelinesA use case describes a sequence of actions that provide ameasurable value to an actor. A use case is drawn as a 33
  44. 44. 34 THE ELEMENTS OF UML 2.0 STYLEhorizontal ellipse on a UML use case diagram, as you can see inFigure 14.58. Begin Use-Case Names with a Strong VerbGood use-case names include Withdraw Funds, Register Stu-dent in Seminar, and Deliver Shipment because it is clear whateach use case does. Use-case names beginning with weak verbssuch as “process,” “perform,” and “do” are often problem-atic. Such names often result in communication difficultieswith your project stakeholders, people who are far more likelyto say that they withdraw funds from accounts instead ofprocess withdrawal transactions. These communication diffi-culties are likely to decrease your ability to understand theirrequirements. Furthermore, names such as Process WithdrawalTransaction or Perform Student Enrollment Request often indi-cate that the use case was written with a technically orientedview, instead of a user-oriented view, and therefore may be atrisk of not reflecting the actual needs of your project stake-holders.59. Name Use Cases Using Domain TerminologyThe name of a use case should immediately convey meaningto your project stakeholders. For example, Convey Package ViaVehicular Transportation is a generic name for a use case butDeliver Shipment reflects common domain terminology andtherefore is far more understandable.60. Imply Timing Considerations by Stacking Use CasesAlthough diagrams should not reflect timing considerations,such as the need to work through use case A before proceedingto use case B, the fact is that you can increase the readabilityof your diagrams by arranging use cases to imply timing. Onesuch way is to stack them, as you can see in Figure 14, so thatthe use cases that typically occur first are shown above thosethat appear later. Note that the order in which these use cases
  45. 45. U M L U S E - CA S E D I AG R A M S 3 5 Figure 14. Implying timing considerations between use cases.are invoked is only implied; throughout most of the life of abank account, you can deposit to it or withdraw from it in anyorder that you like, assuming you conform to the appropriatebusiness rules when doing so.You can define preconditions in your use cases to describetiming considerations, such as the need for an online shopperto define his or her default address information before beingallowed to place an order. You may want to consider drawingan activity diagram representing the overall business processinstead of indicating timing considerations on your diagrams.Note that Figure 14 goes against the general guideline AvoidDiagonal or Curved Lines—but it’s a small diagram, and so thediagonal lines are still easy to follow from one model elementto another.4.2 Actor GuidelinesAn actor is a person, organization, local process (e.g., systemclock), or external system that plays a role in one or more in-teractions with your system (actors are drawn as stick figures).
  46. 46. 36 THE ELEMENTS OF UML 2.0 STYLE Search For Items Place Order Payment Processor <<system>> Release 1Customer Obtain Help Release 2 Customer Support Submit Taxes Release 3 Tax Authority Time Figure 15. Online shopping.61. Place Your Primary Actor(s) in the Top Left Cornerof the DiagramIn Western cultures, we start reading in the top left corner. Allthings being equal, this is the best location for your primary ac-tors, who are often directly involved with your primary/criticaluse cases.For example, you can see in Figure 15 that Customer is placednear the top left corner of the diagram, as opposed to theCustomer Support actor, which is placed on the right-handside. Also notice how the two most critical use cases, the onessupporting the sale of items on the Web site, are also placedat the top left, and the guideline Imply Timing Considerationsby Stacking Use Cases has also been applied to order Search forItems and Place Order.62. Draw Actors on the Outside Edges of aUse-Case DiagramBy definition, actors are outside your scope of control, some-thing that you can communicate by drawing them on theoutside edges of a diagram, as you can see in Figure 15.
  47. 47. U M L U S E - CA S E D I AG R A M S 3 763. Name Actors with Singular, Domain-RelevantNounsAn actor should have a name that accurately reflects itsrole within your model. Actor names are usually singularnouns such as Grade Administrator, Customer, and PaymentProcessor.64. Associate Each Actor with One or More Use CasesEvery actor is involved with at least one use case, and every usecase is involved with at least one actor. Note that there isn’tnecessarily a one-to-one relationship between actors and usecases. For example, in Figure 15 you can see that Customer isinvolved with several use cases and that the use case ObtainHelp has two actors interacting with it.65. Name Actors to Model Roles, Not Job TitlesA common mistake when naming actors is to use the names ofjob titles that people hold instead of the roles that the peoplefulfill. This results in actors with names such as Junior CSR,2Lead CSR, and CSR Manager instead of Customer Support,which you can see in Figure 15. A good indication that youare modeling job titles instead of roles in a diagram depictingseveral actors with similar names that have associations to thesame use case(s). Modeling roles instead of job titles will sim-plify your diagrams and will avoid the problem of couplingyour use-case diagram to the current position hierarchy withinyour organization: you wouldn’t want to have to update yourmodels simply because your human resources department re-placed the term CSR with Support Engineer. However, if youare working in a politically charged environment where it isadvantageous for you to show certain positions on a use-casediagram, feel free to do so at your own discretion.2 CSR = Customer Service Representative.
  48. 48. 38 THE ELEMENTS OF UML 2.0 STYLE66. Use <<system>> to Indicate System ActorsIn Figure 15, you immediately know that Payment Processor is asystem and not a person or organization because of the stereo-type applied to it. The <<system>> stereotype is applicableto system/concrete diagrams that reflect architectural deci-sions made for your system as opposed to essential diagrams(Constantine and Lockwood 1999) or business diagrams (Rat-ional Corporation 2002), which are technology-independent.67. Don’t Allow Actors to Interact with One AnotherThe nature of the interaction between two actors will becaptured in the text of the use case, not pictorially on yourdiagram.68. Introduce an Actor Called “Time” to InitiateScheduled EventsCertain events happen on a regular basis—payroll is fulfilledevery two weeks, bills are paid once a month, and staff eval-uations are held annually. In Figure 15, you can see that theTime actor initiates the Submit Taxes use case because it issomething that occurs on a periodic basis (typically monthly).You can also see that I’ve applied a visual stereotype to the actor,using the hourglass symbol used on UML activity diagrams(Chapter 10) for time events.4.3 Relationship GuidelinesThere are several types of relationships that may appear on ause-case diagram:■ an association between an actor and a use case,■ an association between two use cases,■ a generalization between two actors,■ a generalization between two use cases.
  49. 49. U M L U S E - CA S E D I AG R A M S 3 9 Figure 16. Enrolling students in a university.Associations are depicted as lines connecting two modelingelements with an optional open-headed arrowhead on one endof the line, indicating the direction of the initial invocation ofthe relationship. Generalizations are depicted as closed-headedarrows pointing toward the more general modeling elements.69. Indicate an Association Between an Actor and a UseCase if the Actor Appears Within the Use-Case LogicYour use-case diagram should be consistent with your usecases. If an actor supplies information, initiates the use case,or receives any information as a result of the use case, then thecorresponding diagram should depict an association betweenthe two. As you can see in Figure 16, these types of associationsare depicted with solid lines. Note that if you are taking anAgile Modeling (AM) approach to development, then yourartifacts don’t need to be perfectly in synch with each other—they just need to be good enough.70. Avoid Arrowheads on Actor–Use-Case RelationshipsThe arrowheads on actor–use-case associations indicate whoor what invokes the interaction. Indicate an arrowhead onlywhen doing so provides significant value, such as when it is
  50. 50. 40 THE ELEMENTS OF UML 2.0 STYLEimportant to indicate that an actor is passive regarding itsinteraction with your system, or when your audience for themodel understands the implications of the arrowhead.In Figure 16, Student invokes the Enroll Student use case,whereas in Figure 15, the Place Order use case initiates theinteraction with the Payment Processor actor. Although thisis perfectly fine, the problem is that many people think thatthese arrowheads imply information or data flow, such as youwould see in a data flow diagram (Gane and Sarson 1979;Ambler 2004), instead of initial invocation. Associations donot represent information; they merely indicate that an actoris somehow involved with a use case. Yes, there is informationflowing back and forth between the actor and the use case; forexample, students would need to indicate in which seminarsthey wished to enroll and the system would need to indicateto the students whether or not they have been enrolled.71. Apply <<include>> When You Know ExactlyWhen to Invoke the Use CaseIn Figure 16 the Enroll Student use case includes the use caseEnroll in Seminar. It is modeled like this because, at a specificpoint in Enroll Student, the logic encapsulated by the includeduse case is required. In this example, part of the task of en-rolling a student in the university is also initially to enroll thatstudent in one or more seminars, something that is done at aspecific step in the use case.The best way to think of an <<include>> association is as theinvocation of one use case by another one, just like calling afunction or invoking an operation within source code. It isquite common to introduce a use case that encapsulates com-mon logic required by several use cases and to have that usecase included by the ones that require it. It is also commonfor one use case to include another when the logic of the in-cluded use case is invoked in a synchronous manner. Include
  51. 51. U M L U S E - CA S E D I AG R A M S 4 1associations, as well as extend associations, are modeled asdependencies between use cases and therefore a dashed line isused, as you can see in Figure 16.72. Apply <<extend>> When a Use Case May BeInvoked Across Several Use Case StepsIn Figure 16, you can see that the Perform Security Check usecase extends the Enroll Student use case. It is modeled thisway because the extending use case defines logic that may berequired during a given set of steps in the parent use case. Inthis example, international students are subject to additionalscrutiny during the enrollment task, something that will occursometime after their basic name and address information hasbeen taken but before they are given their student informationpackages—anywhere within a range of use case steps.An extend association is a generalization relationship wherethe extending use case continues the behavior of the base usecase by conceptually inserting additional action sequences intothe base use case, steps that may work in parallel to the ex-isting use-case steps (asynchronously). One way to think ofextension is to consider it the use-case equivalent of a hard-ware interrupt—you’re not sure when or if the interrupt willoccur. It is quite common to introduce an extending use casewhenever the logic for an alternate course of action is at acomplexity level similar to that of your basic course of actionor when you require an alternate course for an alternate course(in this case the extending use case would encapsulate bothalternate courses).73. Apply Extend Associations SparinglyMany use-case modelers avoid the use of extend associa-tions because they have a tendency to make use case diagramsdifficult to understand.
  52. 52. 42 THE ELEMENTS OF UML 2.0 STYLE74. Generalize Use Cases When a Single ConditionResults in Significantly New Business LogicIn Figure 16, you can see that the Enroll Family Member usecase inherits from the Enroll Student use case. It is modeledthis way because the inheriting use case describes businesslogic similar to yet different from the base use case and there-fore either the basic course of action or one or more alternatecourses of action within the use case are completely rewritten.In this example, you enroll family members of university pro-fessors in a manner similar to that for “normal students,” themain differences being that several enrollment requirementsare reduced or removed completely and the university fees arecalculated differently (residence and seminar fees are chargedat a reduced rate and all incidental fees are waived).Inheritance between use cases is not as common as eitherthe use of extend or include associations, but it is stillpossible.75. Do Not Apply <<uses>>, <<includes>>,or <<extends>>All three of these stereotypes were supported by ear-lier versions of the UML but over time they have beenreplaced—<<uses>> and <<includes>> were both re-placed by <<include>>, and <<extends>> was reworkedinto <<extend>> and generalization. You will likely findthese stereotypes applied on older use-case diagrams becauseexperienced use-case modelers may not yet have transitionedto the newer stereotypes for use-case associations.76. Avoid More Than Two Levels of Use-CaseAssociationsWhenever your use-case diagram shows that a use case includesanother use case, which includes another use case, which inturn includes yet another use case, it is a very good indication
  53. 53. U M L U S E - CA S E D I AG R A M S 4 3that you are taking a functional decomposition approach toyour usage requirements. Functional decomposition is a de-sign activity, and you should avoid reflecting design decisionswithin your requirements artifacts.77. Place an Included Use Case to the Right of theInvoking Use CaseIt is common convention to draw include associations hori-zontally, with the included use case to the right of the invokinguse case, as you can see in Figure 16 with Enroll Student andEnroll in Seminar.78. Place an Extending Use Case Below the ParentUse CaseIt is common convention to draw extend associations ver-tically, with the extending use case placed lower on your di-agram than the base use case, as you can see in Figure 16with Perform Security Check and Enroll Student.79. Apply the “Is Like” Rule to Use-Case GeneralizationThe sentence “the [inheriting use-case name] is like the [parentuse-case name]” should make sense. In Figure 16, it makessense to say that enrolling a family member is like enrollinga student; therefore, it’s a good indication that generalizationmakes sense. It doesn’t make sense to say that enrolling astudent is like enrolling in a seminar. The logic for each activityis different—although the two use cases may be related it isn’tby generalization.80. Place an Inheriting Use Case Below the BaseUse CaseIt is a common convention to draw generalization relation-ships vertically, with the inheriting use case placed lower onyour diagram than the parent use case, as you can see inFigure 16 with Enroll Family Member and Enroll Student.
  54. 54. 44 THE ELEMENTS OF UML 2.0 STYLE Enroll in University Extension points Condition: {student born outside of country} Verify Citizenship Extension point: Verify Citizenship Validate Payment<<extend>>Perform Security Check Figure 17. Enrolling students in a university.81. Apply the “Is Like” Rule to Actor InheritanceThe sentence “the [inheriting actor name] is like the [parentactor name]” should make sense. In Figure 16, it makes senseto say that an international student is like a student; thereforeit’s a good indication that generalization makes sense. It doesn’tmake sense in Figure 15 to say that customer support is like apayment processor because the two roles are clearly different.82. Place an Inheriting Actor Below the Parent ActorIt is a common convention to draw generalization relation-ships vertically, with the inheriting actor placed lower on yourdiagram than the parent actor, as you can see in Figure 16 withInternational Student and Student.83. Avoid Modeling Extension PointsFigure 17 shows the notation for indicating extension pointswithin a use-case bubble. In my experience this informationis extraneous in diagrams. If you want it you can simply readthe use-case text.
  55. 55. U M L U S E - CA S E D I AG R A M S 4 584. Model Extension Conditions Only When TheyAren’t ClearFigure 17 depicts how to define the condition(s) under whichthe extending use case will be invoked. Once again this in-formation clutters the diagram and can be documented betterwithin the use case itself.4.4 System Boundary Box GuidelinesThe rectangle around the use cases is called the system bound-ary box and, as the name suggests, it indicates the scope ofyour system—the use cases inside the rectangle represent thefunctionality that you intend to implement.85. Indicate Release Scope with a System Boundary BoxIn Figure 15, you can see that three system boundary boxesare included, each of which has a label indicating the release towhich the various use cases have been assigned. This projectteam is taking an incremental approach to software devel-opment and therefore needs to communicate to the projectstakeholders what will be delivered in each release, and it hasdone so using system boundary boxes.Notice how the nature of each release is indicated by the place-ment of each system boundary box. You can see that release 2includes release 1, whereas release 3 is separate. The team maybe trying to indicate that, during release 2, they expect to en-hance the functionality initially provided by release 1, whereasthey don’t expect to do so during release 3. Or perhaps theyintend to develop release 3 in parallel to release 1 and/or 2.The exact details aren’t readily apparent from the diagram.You could add a note, if appropriate, but the diagram wouldsupport information contained in another project artifact suchas your project plan.
  56. 56. 46 THE ELEMENTS OF UML 2.0 STYLEFigure 15 should have included another system boundary box,one encompassing all three releases to specify the exact bound-ary of the overall system, but it doesn’t. I did this in accordancewith AM’s (Chapter 17) Depict Models Simply practice, mak-ing the assumption that the readers of the diagram would readbetween the lines.86. Avoid Meaningless System Boundary BoxesSystem boundary boxes are optional—neither Figure 14 norFigure 16 includes one because it wouldn’t add to the com-munication value of the diagram.
  57. 57. 5. UML Class DiagramsUML class diagrams show the classes of a system, their inter-relationships, and the operations and attributes of the classes.They are used to■ explore domain concepts in the form of a domain model,■ analyze requirements in the form of a conceptual/analysis model,■ depict the detailed design of object-oriented or object- based software.A class model comprises one or more class diagrams and thesupporting specifications that describe model elements, in-cluding classes, relationships between classes, and interfaces.5.1 General GuidelinesBecause UML class diagrams are used for a variety ofpurposes—from understanding your requirements to describ-ing your detailed design—you will need to apply a differentstyle in each circumstance. This section describes style guide-lines pertaining to different types of class diagrams.87. Identify Responsibilities on Domain Class ModelsWhen creating a domain class diagram, often as part ofyour requirements modeling efforts, focus on identifying 47
  58. 58. 48 THE ELEMENTS OF UML 2.0 STYLE Table 3. Visibility Options on UML Class Diagrams Visibility Symbol Accessible to Public + All objects within your system Protected # Instances of the implementing class and its subclasses Private - Instances of the implementing class Package ∼ Instances of classes within the same packageresponsibilities for classes instead of on specific attributes oroperations. For example, the Invoice class is responsible for pro-viding its total, but whether it maintains this as an attributeor simply calculates it at request time is a design decision thatyou’ll make later.There is some disagreement about this guideline because itimplies that you should be taking a responsibility-driven ap-proach to development. Craig Larman (2002) suggests a data-driven approach, where you start domain models by identi-fying only data attributes, resulting in a model that is littledifferent from a logical data model. If you need to create alogical data model, then do so, following AM’s practice, Ap-ply the Right Artifact(s) (Chapter 17). However, if you wantto create a UML class diagram, then you should consider thewhole picture and identify responsibilities.88. Indicate Visibility Only on Design ModelsThe visibility of an operation or attribute defines the level ofaccess that objects have to it, and the UML supports four typesof visibility that are summarized in Table 3. Visibility is animportant design issue. On detailed design models, you shouldalways indicate the visibility of attributes and operations, anissue that typically is not pertinent to domain or conceptualmodels. Visibility on an analysis or domain model will alwaysbe public (+), and so there is little value in indicating this.
  59. 59. U M L C L A S S D I AG R A M S 4 9 Analysis Design Order Order Placement Date - deliveryDate: Date Delivery Date - orderNumber: int Order Number - placementDate: Date Calculate Total - taxes: Currency Calculate Taxes - total: Currency # calculateTaxes(Country, State): Currency # calculateTotal(): Currency getTaxEngine() {visibility=implementation} Figure 18. Analysis and design versions of a class.89. Indicate Language-Dependent Visibility withProperty StringsIf your implementation language includes non-UML-supported visibilities, such as C++’s implementation visibil-ity, then a property string should be used, as you can see inFigure 18.90. Indicate Types on Analysis Models Only When theType Is an Actual RequirementSometimes the specific type of an attribute is a requirement.For example, your organization may have a standard definitionfor customer numbers that requires that they be nine-digitnumbers. Perhaps existing systems, such as a legacy databaseor a predefined data feed, constrain some data elements to aspecific type or size. If this is the case, you should indicate thisinformation on your domain class model(s).91. Be Consistent with Attribute Names and TypesIt would not be consistent for an attribute named customer-Number to be a string, although it would make sense for it tobe an integer. However, it would be consistent for the namecustomerID to be a string or an integer.
  60. 60. 50 THE ELEMENTS OF UML 2.0 STYLE 0..* 1..* Student Course Name Student # ... Constraints Enrollment {must be 18 years Enrollment Date of age or older} Enroll Drop Cancel Figure 19. Modeling association classes.92. Model Association Classes on Analysis DiagramsAssociation classes, also called link classes, are used to modelassociations that have methods and attributes. Figure 19 showsthat association classes are depicted as classes attached viadashed lines to associations—the association line, the class,and the dashed line are considered to be one symbol in theUML. Association classes typically are modeled during anal-ysis and then refactored during design (either by hand orautomatically by your CASE tool) because mainstream pro-gramming languages do not (yet) have native support for thisconcept.93. Do Not Name Associations That HaveAssociation ClassesThe name of the association class should adequately describeit. Therefore, as you can see in Figure 19, the association doesnot need an additional adornment indicating its name.94. Center the Dashed Line of an Association ClassThe dashed line connecting the class to the association pathshould be clearly connected to the path and not to eitherclass or to any adornments of the association, so that your
  61. 61. U M L C L A S S D I AG R A M S 5 1meaning is clear. As you can see in Figure 19, the easiest way toaccomplish this is to center the dashed line on the associationpath.5.2 Class Style GuidelinesA class is effectively a template from which objects are cre-ated (instantiated). Classes define attributes, information thatis pertinent to their instances, and operations—functionalitythat the objects support. Classes also realize interfaces (moreon this later). Note that you may need to soften some of thesenaming guidelines to reflect your implementation language orany purchased or adopted software.95. Use Common Terminology for Class NamesClass names should be based on commonly accepted termi-nology to make them easier for others to understand. Forbusiness classes, this would include names based on domainterminology such as Customer, OrderItem, and Shipment and,for technical classes, names based on technical terminologysuch as MessageQueue, ErrorLogger, and PersistenceBroker.96. Prefer Complete Singular Nouns for Class NamesNames such as Customer and PersistenceBroker are preferable toCust and PBroker, respectively, because they are more descrip-tive and thus easier to understand. Furthermore, it is commonpractice to name classes as singular nouns such as Customer in-stead of Customers. Even if you have a class that does representseveral objects, such as an iterator (Gamma, Helm, Johnson,and Vlissides 1995) over a collection of customer objects, aname such as CustomerIterator would be appropriate.97. Name Operations with Strong VerbsOperations implement the functionality of an object; there-fore, they should be named in a manner that effectively
  62. 62. 52 THE ELEMENTS OF UML 2.0 STYLEcommunicates that functionality. Table 4 lists operation namesfor analysis class diagrams as well as for design class diagrams—the assumption being that your implementation languagefollows Java naming conventions (Vermeulen et al. 2000)—indicating how the operation name has been improved in eachcase.98. Name Attributes with Domain-Based NounsAs with classes and operations, you should use full descriptionsto name your attribute so that it is obvious what the attributerepresents. Table 5 suggests a Java-based naming conventionfor analysis names that are in the Attribute Name format, al-though attribute name and Attribute name formats are also fineif applied consistently. Table 5 also suggests design names thattake an attributeName format, although the attribute nameformat is just as popular depending on your implementationlanguage.99. Do Not Model Scaffolding CodeScaffolding code includes the attributes and operations re-quired to implement basic functionality within your classes,such as the code required to implement relationships withother classes. Scaffolding code also includes getters and set-ters, also known as accessors and mutators, such as getItem()and setItem() in Figure 20, which get and set the value of at-tributes. You can simplify your class diagrams by assumingthat scaffolding code will be created (many CASE tools cangenerate it for you automatically) and not model it. Figure 20depicts the difference between the OrderItem class withoutscaffolding code and with it—including the constructor, thecommon static operation findAllInstances() that all businessclasses implement (in this system), and the attributes itemand order and their corresponding getters and setters to main-tain its relationships with the Order class and Item class,respectively.
  63. 63. Table 4. Example Names for Operations Good Analysis Initial Name Name Good Design Name Issue Open Acc Open Account openAccount() An abbreviation was replaced with the full word to make it clear what is meant. Mailing Label Print Print Mailing Label printMailingLabel() The verb was moved to the53 beginning of the name to make it active. purchaseparkingpass() Purchase Parking purchaseParkingPass() Mixed case was applied to Pass increase the readability of the design-level name. Save the Object Save save() The name was shortened because the term “TheObject” did not add any value.
  64. 64. Table 5. Example Names for Attributes Good Analysis Good Design Initial Name Name Name Issue fName First Name firstName Do not use abbreviations in attribute names. firstname First Name firstName Capitalizing the second word of the design name makes the attribute name easier to read. personFirstName First Name firstName This depends on the context of the attribute, but if this is an attribute of the “Person” class, then including “person” merely lengthens the name without providing any value.54 nameLast Last Name lastName The name “nameLast” was not consistent with “firstName” (and it sounded strange anyway). hTTPConnection HTTP Connection httpConnection The abbreviation for the design name should be in all lowercase. firstNameString First Name firstName Indicating the type of the attribute, in this case “string,” couples the attribute name to its type. If the type changes, perhaps because you decide to reimplement this attribute as an instance of the class “NameString,” then you will need to rename the attribute. OrderItemCollection Order Items orderItems The second version of the design name is shorter and easier to understand.
  65. 65. U M L C L A S S D I AG R A M S 5 5 With Scaffolding Without Scaffolding OrderItem OrderItem# numberOrdered: int # numberOrdered: int- item: Item- order: Order + findForItem(Item) : Vector + findForOrder(Order) : Vector<<constructor>> + OrderItem(Order) : OrderItem # calculateTaxes(): Currency+ findAllInstances() : Vector # calculateTotal(): Currency+ findForItem(Item) : Vector - getTaxEngine()+ findForOrder(Order) : Vector+ getNumberOrdered(): int+ getTotal(): Currency+ setNumberOrdered(amount: int)# calculateTaxes(Country, State): Currency# calculateTotal(): Currency# getItem(): Item# getOrder(): Order- getTaxEngine()- setItem(Item)- setOrder(Order) Figure 20. OrderItem class with and without scaffolding code.100. Center Class NamesAs you have seen in the figures in this chapter, it is commonto center the names of classes.101. Left-Justify Attribute Operation and NamesIt is common practice, as you see in Figure 20 to left-justifyboth attribute and operation names within class boxes.102. Do Not Model KeysA key is a unique identifier of a data entity or table. Un-less you are using a UML class diagram to model the log-ical or physical schema of a database (Ambler 2003), youshould not model keys in your class. Keys are a data con-cept, not an object-oriented concept. A particularly commonmistake of novice developers is to model foreign keys inclasses, the data attributes needed to identify other rowsof data within the database. A UML profile for physicaldata modeling is maintained at www.agiledata.org/essays/umlDataModelingProfile.html.
  66. 66. 56 THE ELEMENTS OF UML 2.0 STYLE103. Never Show Classes with Just Two CompartmentsIt is allowable within the UML to have a class with one ormore compartments. Although compartments may appearin any order, traditionally the topmost compartment indi-cates the name of the class and any information pertinent tothe class as a whole (such as a stereotype); the second op-tional compartment typically lists the attributes; and the thirdoptional compartment typically lists the operations. Other“nonstandard” compartments may be added to the class toprovide information such as lists of exceptions thrown ornotes pertaining to the class. Because naming conventionsfor attributes and operations are similar, and because peoplenew to object development may confuse the two concepts, itisn’t advisable to have classes with just two compartments(one for the class name and one listing either attributesor operations). If necessary, include a blank compartmentas a placeholder, as you can see with the Student class inFigure 19.104. Label Uncommon Class CompartmentsIf you do intend to include a class compartment that isn’t oneof the standard three—class name, attribute list, operationslist—then include a descriptive label such as Exceptions, Ex-amples, or Constraints centered at the top of the compart-ment, as you can see with the Student class in Figure 19.105. Include an Ellipsis ( . . . ) at the End of anIncomplete ListYou know that the list of attributes of the Student class ofFigure 19 is incomplete because of the ellipsis at the end ofthe list. Without the ellipsis, there would be no indication thatthere is more to the class than what is currently shown (Evitts2000).
  67. 67. U M L C L A S S D I AG R A M S 5 7106. List Static Operations/Attributes Before InstanceOperations/AttributesStatic operations and attributes typically deal with early aspectsof a class’s life cycle, such as the creation of objects or findingexisting instances of the classes. In other words, when you areworking with a class you often start with statics. Therefore itmakes sense to list them first in their appropriate compart-ments, as you can see in Figure 20 (statics are underlined).107. List Operations/Attributes in Order ofDecreasing VisibilityThe greater the visibility of an operation or attribute, thegreater the chance that someone else will be interested in it. Forexample, because public operations are accessible to a greateraudience than protected operations, there is a likelihood thatgreater interest exists in public operations. Therefore, list yourattributes and operations in order of decreasing visibility sothat they appear in order of importance. As you can see inFigure 20, the operations and attributes of the OrderItem classare then listed alphabetically for each level of visibility.108. For Parameters That Are Objects, List OnlyTheir TypesAs you can see in Figure 20, operation signatures can becomequite long, extending the size of the class symbol. To savespace, you can forgo listing the types of objects that are passedas parameters to operations. For example, Figure 20 lists cal-culateTaxes(Country, State) instead of calculateTaxes(country:Country, state: State), thus saving space.109. Develop Consistent Operation andAttribute SignaturesOperation names should be consistent with one another. Forexample, in Figure 20, all finder operations start with the

×