Chapter 16 UML Class Diagrams “To iterate is human, to recurse, divine.” - anonymous Objectives • Provide a reference for frequently used UML class diagram notation. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 1 Introduction • The UML includes class diagrams to illustrate classes, interfaces, and their associations. – “Static object modeling” • This chapter is a reference, it summarizes the notation, irrespective of the perspective (conceptual or software) Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 2 Fig 16.1 Common UML class diagram notation. officially in UML, the top format is used to distinguish the package name from the class name SuperclassFoo or SuperClassFoo { abstract } 3 common compartments 1. classifier name 2. attributes 3. operations an interface shown with a keyword «interface» Runnable run() unofficially, the second alternative is common - classOrStaticAttribute : Int + publicAttribute : String - privateAttribute assumedPrivateAttribute isInitializedAttribute : Bool = true aCollection : VeggieBurger [ * ] attributeMayLegallyBeNull : String [0..1] finalConstantAttribute : Int = 5 { readOnly } /derivedAttribute java.awt::Font or java.awt.Font plain : Int = 0 { readOnly } bold : Int = 1 { readOnly } name : String style : Int = 0 ... + classOrStaticMethod() + publicMethod() assumedPublicMethod() - privateMethod() # protectedMethod() ~ packageVisibleMethod() «constructor» SuperclassFoo( Long ) methodWithParms(parm1 : String, parm2 : Float) methodReturnsSomething() : VeggieBurger methodThrowsException() {exception IOException} abstractMethod() abstractMethod2() { abstract } // alternate finalMethod() { leaf } // no override in subclass synchronizedMethod() { guarded } getFont(name : String) : Font getName() : String ... Fruit dependency ... ... interface implementation and subclassing SubclassFoo PurchaseOrder 1 ... run() ... - ellipsis “…” means there may be elements, but not shown ... association with multiplicities Dr. Kivanc- aDincer CS319 Week but 7 - as Oct.24,2005 blank compartment officially means “unknown” a convention will be used to mean “no members” ... order 3 Design Class Diagrams (DCD) • The UML has notation for showing design details in static structure: Class Diagrams. • The definition of design class diagrams occurs within the design phase. – The UML does not specifically define design class diagram. • The creation of design class diagrams is dependent upon the prior creation of: – Interaction diagrams identifies the SW classes that participate in the solution, plus the methods of classes. – Conceptual model adds detail to the class definitions. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 4 Fig. 16.2 UML class diagrams in two perspectives. Sale Domain Model conceptual perspective Register 1 Captures 1 ... Register Design Model ... DCD; software perspective endSale() enterItem(...) makePayment(...) Dr. Kivanc Dincer time isComplete : Boolean /total Sale 1 currentSale CS319 Week 7 - Oct.24,2005 time isComplete : Boolean /total makeLineItem(...) 5 Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 6 As we can see…. • A design class diagram illustrates the specifications for SW classes and interfaces. • Typical information included: Classes, associations, and attributes Interfaces, with their operations and constants Methods Attribute type information Navigability Dependencies Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 7 Fig. 16.3 Attribute text vs. Association line notation for a UML attribute. using the attribute text notation to indicate Register has a reference to one Sale instance OBSERVE: this style visually emphasizes the connection between these classes Sale Register currentSale : Sale ... ... ... Register Sale 1 ... currentSale ... ... ... using the association notation to indicate Register has a reference to one Sale instance thorough and unambiguous, but some people dislike the possible Dr. redundancy Kivanc Dincer Register currentSale : Sale ... CS319 Week 7 - Oct.24,2005 Sale 1 currentSale ... ... 8 Fig. 16.4 Idioms in association notation usage in different perspectives. the association name, common when drawing a domain model, is often excluded (though still legal) when using class diagrams for a software perspective in a DCD Register UP Domain Model conceptual perspective UP Design Model DCD software perspective time : DateTime id : Int Sale Register 1 id: Int currentSale ... Dr. Kivanc Dincer Sale 1 Captures-current-sale 1 CS319 Week 7 - Oct.24,2005 time: DateTime ... 9 Fig. 16.5 Applying the guidelines to show attributes in two notations. applying the guideline to show attributes as attribute text versus as association lines Register Sale 1 id: Int currentSale ... Register has THREE attributes: 1. id 2. currentSale 3. location time: DateTime ... Store 1 location address: Address phone: PhoneNumber ... public class Register { private int id; private Sale currentSale; private Store location; } Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 10 How to make a DCD • Identify all the classes participating in the SW solution by analyzing the interaction diagrams. • Draw them in a class diagram. • Duplicate the attributes from the associated concepts in the conceptual model. • Add method names by analyzing the interaction diagrams. • Add type information to the attributes and methods. • Add the associations necessary to support the required attribute visibility. • Add navigability arrows to the associations to indicate the direction of attribute visibility. • Add dependency relationship lines to indicate non-attribute visibility. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 11 Creating the NextGen POS DCD • Identify SW classes and illustrate them. Register ProductCatalog Store Payment Sale ProductSpecification SalesLineItem • Draw a class diagram for these classes. • Include the attributes previously identified in the domain model. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 12 Creating the NextGen POS DCD (2) • Add method names from interaction diagrams Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 13 Method Names: Issues • The following special issues must be considered with respect to method names: – – – – Interpretation of the create() message. Depiction of accessing methods. Interpretation of messages to multi-objects. Language-dependent syntax. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 14 Method names: create • The “create” message is the UML language independent form to indicate instantiation and initialization. • When translating the design to an OOPL, it must be expressed in terms of its idioms for instantiation and initialization. Class Name <<constructor>> SuperclassFoo(Long) Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 15 Method names: Accessing Methods • Accessing methods are those which retrieve (accessor method - get) or set (mutator method) attributes. • It is common idiom to have an accessor and mutator for each attribute, and to declare all attribute private (to enforce encapsulation). • They are also called getter and setter methods. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 16 Method names: Multi-Objects • A message to a multi-object is interpreted as a message to the container/collection object – Java’s map, C++’s map, Smalltalk’s dictionary. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 17 Fig. 16.6 Two ways to show a collection attribute in the UML. Sale SalesLineItem time: DateTime lineItems : SalesLineItem [1..*] or lineItems : SalesLineItem [1..*] {ordered} ... ... ... Two ways to show a collection attribute Sale SalesLineItem time: DateTime ... Dr. Kivanc Dincer 1..* ... lineItems {ordered, List} ... notice that an association end can optionally also have a property string such as {ordered, List} CS319 Week 7 - Oct.24,2005 18 Method Names: Language Dependent Syntax • The basic UML format for methods: methodName(parameterList) • The type of the attributes, method parameters, and method return values may all optionally be shown. • The design class diagram should be created by considering the audience. – If it is being created in a CASE tool with automatic code generation, full and exhaustive details are necessary. – If it is being created for SW developers to read, exhaustive low-level detail may adversely effect the noise-to-value ratio. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 19 Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 20 Adding Associations and Navigability • Navigability is a property of the role which indicates that it is possible to navigate uni-directionally across the association from objects of the source to target class. – Navigability implies visibility. – Navigability is identified from Interaction Diagrams. – Most, if not all, associations in design-oriented class diagrams should be adorned with the necessary navigability arrows. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 21 Showing navigability, or attribute visibility Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 22 Association with navigability • Define an association with a navigability adornment from A to B: – A sends a message to B. – A creates an instance B. – A needs to maintain a connection to B Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 23 Associations with Navigability Adornments Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 24 Adding dependency relationships • Dependency relationship indicates that one element (of any kind, including classes, use cases, and so on) has knowledge of another element. – A dependency is a using relationship that states a change in specification of one thing may affect another thing that uses it, but not necessarily the reverse. • The dependency relationship is useful to depict nonattribute visibility between classes. – – – – Parameters Global or local visibility A dashed arrow line A dashed directed line Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 25 Dependency Relationships Non-Attribute Visibility Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 26 Notation for Method Bodies in DCDs Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 27 Interfaces • The UML has several ways to show interface implementations. • Since both the socket line notation and the dependency line notation used curved lines not common in drawing tools, most people use a dependency arrow and the «interface» stereotype. «interface» Timer getTime() Clock1 getTime( ) Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 28 UML stereotypes • A stereotype represents a refinement of an existing modeling concept and is defined within a UML profile. • UML uses stereotypes encapsulated in guillemots (« and », not << and >> ) to extend many diagram symbols. – Guillemots can be found in the latin-1 symbol set in Windows Insert Symbol command) – Examples: • • • • • • «interface» «extends» «includes» «actor» «create» «destroy» Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 29 Fig. 16.8 Stereotype declaration and use. using the stereotype declaring the stereotype a tool will probably allow a popup to fill in the tag values, once an element has been stereotyped with «authorship» UML extension relationship to a basic UML metamodel term – Element «metaclass» Element «stereotype» Authorship author: String status : String ... Dr. Kivanc Dincer «authorship» Square «authorship» author = “craig” status = “tested” ... CS319 Week 7 - Oct.24,2005 30 Association • An association is a structural relationship that specifies that objects of one thing are connected to objects of another. Navigation • Navigability is a property of the role which indicates that it is possible to navigate uni-directionally across the association from objects of the source to target class. – Navigability implies visibility. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 31 Dependency • A dependency is a using relationship, specifying that a change in the specification of one thing may affect another thing that uses it. the Sale has parameter visibility to a ProductDescription, and thus some kind of dependency ProductDescription ... Sale ... ... updatePriceFor( ProductDescription ) ... SalesLineItem 1..* lineItems Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 ... ... 32 Figure 16.10 Showing dependency. Public class Foo { Public void doX( ) { System.runFinalization( ); . . . } . . . } the doX method invokes the runFinalization static method, and thus has a dependency on the System class System ... Foo runFinalization() ... ... Dr. Kivanc Dincer doX() ... CS319 Week 7 - Oct.24,2005 33 Figure 16.11 Optional dependency labels in the UML. Window Clock «call» getTime() ... a dependency on calling on operations of the operations of a Clock Dr. Kivanc Dincer B A «create» ... a dependency that A objects create B objects CS319 Week 7 - Oct.24,2005 34 Interfaces – Different Notations socket line notation Window1 Timer Window1 uses the Timer interface dependency line notation it has a required interface Window2 has a dependency on the Timer interface when it collaborates with a Clock2 object «interface» Timer Clock2 ... getTime() Timer Window2 Timer Window3 getTime() ... Clock1 implements and provides the Timer interface Clock1 Clock3 ... getTime() ... ... getTime() ... socket line notation lollipop notation indicates Clock3 implements and provides the Timer interface to clients Dr. Kivanc Dincer Timer is a provided interface CS319 Week 7 - Oct.24,2005 Window3 has a dependency on the Timer interface when it collaborates 35 with a Clock3 object Generalization • A generalization is a relationship between a general thing (called the super class or parent) and a more specific kind of that thing (called the subclass or child). • is-a-kind-of relationship. • Is this the same as OO PL inheritance? – In donain modeling, no. – In software modeling, yes. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 36 Aggregation and Composition • Aggregation – (seldomly used) – Whole/part relationship – Has-a relationship • Composition is a type of aggregation and a strong kind of whole/part relationship: 1. An instance of the part belongs to only one composite instance at a time. 2.The part must always belong to a composite, and 3.The composite is responsible for the creation and deletion of its parts. (If the composite is destroyed, its parts must either be destroyed, or attached to another composite.) 1 Hand 0..7 Finger composition 1 Dr. Kivanc Dincer Board composition means -a part instance (Square) can only be part of one composite (Board) at a time -the composite has sole responsibility for management of its parts, especially creation and deletion 40 Square CS319 Week 7 - Oct.24,2005 Sale 1 1..* 37 SalesLineItem Constraints • A UML constraint is a restriction or condition on a UML element. three ways to show UML constraints Stack size : Integer { size >= 0 } push( element ) pop() : Object { post condition: new size = old size + 1 } { post condition: new size = old size – 1 } Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 38 Qualified Association • A Qualified Association has a qualifier that is used to select an object (or objects) from a larger set of related objects, based upon the qualifier key. (a) (b) Product Catalog Product Catalog Contains 1 itemID qualifier Dr. Kivanc Dincer 1..* 1 Contains 1 Product Description Product Description multiplicity reduced to 1 CS319 Week 7 - Oct.24,2005 39 Association Class • An association class allows you treat an association itself as a class, and model it with attributes, operations, and other features. – You will see that it is necessary to use an association class in modeling of some cases. Company a person may have employment with several companies Dr. Kivanc Dincer * Employs * Person Employment salary startDate CS319 Week 7 - Oct.24,2005 40 Figure 16.17 Showing a singleton. 1 ServicesFactory UML notation: in a class box, an underlined attribute or method indicates a static (class level) member, rather than an instance member instance : ServicesFactory accountingAdapter : IAccountingAdapter inventoryAdapter : IInventoryAdapter taxCalculatorAdapter : ITaxCalculatorAdapter UML notation: this '1' can optionally be used to indicate that only one instance will be created (a singleton) getInstance() : ServicesFactory getAccountingAdapter() : IAccountingAdapter getInventoryAdapter() : IInventoryAdapter getTaxCalculatorAdapter() : ITaxCalculatorAdapter ... Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 41 User Defined Compartments DataAccessObject id : Int ... doX() ... exceptions thrown DatabaseException IOException responsibilities serialize and write objects read and deserialize objects ... Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 42 Active Class • An active object runs on and controls its own thread of execution. The class of an active object is an active class. active class «interface» Runnable run() Dr. Kivanc Dincer Clock ... run() ... CS319 Week 7 - Oct.24,2005 43 Realization • A realization is a semantic relationship between classifiers in which one classifier specifies a contract that another classifier guarantees to carry out. • We use realization in two circumstances: – In the context of interfaces. – In the context of collaborations. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 44 When to create DCDs? Although this presentation of design class diagrams follows the creation of interaction diagrams, in practice they are usually created in parallel. : Register : Sale makePayment(cashTendered) makePayment(cashTendered) messages in interaction diagrams indicate operations in the class diagrams Register ... makePayment(…) ... Dr. Kivanc Dincer Sale 1 currentSale classes identified in the interaction diagrams are declared in the class diagrams ... makePayment(…) ... CS319 Week 7 - Oct.24,2005 45 Phases • Inception The Design Model and DCDs will not usually be started until elaboration because it involves detailed design decisions, which are premature during inception • Elaboration – During this phase, DCDs will accompany the UC realization interaction diagrams; they may be created for the most architecturally significant classes of the design. – CASE tools can reverse-engineer (generate) DCDs from source code • Construction – DCDs will continue to be generated from the source code as an aid in visualizing the static structure of the system Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 46 Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 47 Chapter 18 Designing for Visibility “A mathematician is a device for turning coffee into theorems.” - Paul Erdös Objectives • Identify four kinds of visibility. • Design to establish visibility. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 48 Introduction • Visibility is the ability of one object to see or have reference to another. Q. When is visibility necessary? A. To send a message from one object to another, the receiver object must be visible to the sender, so the sender has to have a pointer or reference to the receiver. • Those new to object design sometimes don’t think about and design to achieve necessary visibility. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 49 Q.If A sends messages to B, which must be visible to which? A. “B is visible to A” means “A can send a message to B”. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 50 Visibility • Visibility is related to the scope: – Is one resource (such as an instance) within the scope of another? • The motivation to consider visibility: – For an object A to send a message to an object B, B must be visible to A. How visibility can be achieved from object A to object B: Four kinds of visibility: • Attribute visibility - B is an attribute of A • Parameter visibility - B is a parameter of a method of A • Local visibility - B is a local object in a method of A • Global visibility - B is in some way globally visible. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 51 Attribute Visibility • Attribute visibility from A to B exists when B is an attribute of A. – Relatively permanent visibility because it persists as long as A and B exist – Most common form of visibility public void enterItem(itemID, qty) { ... desc = catalog.getProductDesc(itemID) ... } class Register { ... private ProductCatalog catalog; ... } enterItem (itemID, quantity) : Register : ProductCatalog desc = getProductDesc( itemID ) Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 52 Parameter Visibility • Parameter visibility from A to B exists when B is passed as a parameter to a method of A. – Relatively temporary visibility because it persists only within the scope of the method. – The second most common form of visibility in the OO systems. enterItem(id, qty) 2: makeLineItem(desc, qty) :Register :Sale 1: desc = getProductDesc(id) 2.1: create(desc, qty) :Product Catalog makeLineItem(ProductDescription desc, int qty) { ... sl = new SalesLineItem(desc, qty); ... Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 } sl : SalesLineItem 53 Parameter to Attribute Visibility • It is common to transform parameter visibility into attribute visibility enterItem(id, qty) :Register 2: makeLineItem(desc, qty) :Sale 2: desc = getProductDesc(id) 2.1: create(desc, qty) :Product Catalog sl : SalesLineItem // initializing method (e.g., a Java constructor) SalesLineItem(ProductDescription desc, int qty) { ... description = desc; // parameter to attribute visibility ... } Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 54 Local Visibility • Local visibility from A to B exists when B is declared as a local object within a method of A. – Relatively temporary visibility since it persists only within the scope of the method. enterItem(id, qty) { ... // local visibility via assignment of returning object ProductDescription desc = catalog.getProductDes(id); ... } enterItem (itemID, quantity) : Register : ProductCatalog desc = getProductDesc( itemID ) Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 55 Local Visibility There are two common means by which local visibility is achieved: • Create a new local instance and assign it to a local variable. • Assign the returning object from a method invocation to a local variable. – A variation of this method does not explicitly declare a variable, but one implicitly exists as the result of a returning object from a method invocation Ex: anObject.getAnotherObject.doSomething(); Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 56 Global Visibility • Global visibility from A to B exists when B is global to A. – Relatively permanent visibility since it persists as long as A and B exist. – The least common form of visibility in OO Systems. • Ways to achieve global visibility: – Assign an instance to a global variable. – Use the Singleton pattern Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 57 Singleton Pattern (Gang of Four) • Problem: – Exactly one instance of a class is needed. Objects need a single point of access. • Solution: – Define a class method that returns the singleton object, instantiating it if it does not exist. • Example: – A print queue—many programs must access one queue. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 58 Illustrating Visibility in the UML Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 59 Visibility in the UML • Public: – Any outside classifier with visibility to the given classifier can use the feature; specified by pre-pending the symbol “+”. • Protected: – Any descendant of the classifier can use the feature; specified by pre-pending the symbol “#”. • Private: – Only the classifier itself can use the feature; specified by pre-pending the symbol “-”. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 60 Terms: Classifier and Feature • A classifier is a mechanism that describes structural and behavioral features. – Modeling elements that can have instances are called classifiers. – Classifiers include classes, interfaces, datatypes, signals, components, nodes, use cases, and subsystems. – A classifier has structural feature (in the form of attributes), as well as behavioral features (in the form of operations). • A feature is a property, such as operations or attributes that is encapsulated within entity such as an interface, a class, or a datatype. Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 61 Questions & Answers Q. Which would you use if you wanted a relatively permanent connection? A. attribute, or global Q. Which would you use if you didn't want a permanent connection? A. parameter, or local Q. How would you create a local visibility? A. create a new instance - use result of a method call Q. How would you achieve a global visibility? A. use a global variable in C++, static (or class) variable (in C++ or Java) - use the Singleton pattern (a static method that returns the object) Dr. Kivanc Dincer CS319 Week 7 - Oct.24,2005 62