UML Class Diagrams - web.ti.bfh.ch · UML Class Diagrams Prof. Dr. Eric Dubuis Berner...
Transcript of UML Class Diagrams - web.ti.bfh.ch · UML Class Diagrams Prof. Dr. Eric Dubuis Berner...
Berner Fachhochschule
Engineering and Information Technology
UML Class DiagramsProf. Dr. Eric DubuisBerner Fachhochschule,Engineering and Information Technology @ BielCourse "UML and Design Patterns" of module "Software Engineering and Design",version February 2011 (X)
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 1 of 32
Berner Fachhochschule
Engineering and Information Technology
Learning GoalsYou'll learn:
● Modeling UML classes
● UML class properties, attributes, and operations
● Multiplicities of associations
● Programming interpretations of UML classes
● Bidirectional associations
● Generalization
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 2 of 32
Berner Fachhochschule
Engineering and Information Technology
Readings● [Fowler]: UML Distilled, Martin Fowler, third ed., Addison-Wesley, 2004. ISBN 0-321-
19368-7.
● [Jeckle]: UML 2 glasklar, Mario Jeckle et al., 2. Auflage, Hanser Verlag, 2004. ISBN 3-446-22952-3. See also: http://www.uml-glasklar.com
● [UML-Home]: http://www.uml.org/#UML2.0
● [UML-Specification]: http://www.omg.org/technology/documents/modeling_spec_catalog.htm#UML
Not all readings are cited in the text that follows.
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 3 of 32
Berner Fachhochschule
Engineering and Information Technology
Why Modeling?Models abstract from concrete (implementation) details. Models allow, for example:
● to express structures
● to express structural relationships
● to express temporal behavior
● to express state-based behavior
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 4 of 32
A B
Wait DoItevent
otherEvent
A B1 0..*
A B
C
10..*
A B C
loop
Berner Fachhochschule
Engineering and Information Technology
Why Modeling (cont'd)Models allows (in general more easily than code):
● to communicate (first, early) ideas on parts of the software
● to document aspects of the software
And:
● code can be generated from models(MDA: model driven architecture; executable UML)
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 5 of 32
Berner Fachhochschule
Engineering and Information Technology
Modeling LevelsModels can express different degree of details. Thus, you can:
● create models for the conceptual-analytical level:
○ abstractness: high, details not expressed
○ preciseness: low
○ details: none
○ executable: no
● create models for the design level:
○ abstractness: lower
○ preciseness: higher
○ details: (some) details are expressed
○ executable: perhaps
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 6 of 32
implementation language independent
AB
C
10..*A
B
C
... ... ...
...
... ...
D
... ...
C'
... ...
0..*1
11
abstract model is transformed into a more refined one
Berner Fachhochschule
Engineering and Information Technology
What is the UML?The UML ...
● provides a set of (graphical) notations for the
○ modeling and
○ documentation
○ and ...
of (software) systems
● has notational elements for expressing
○ the static (structural) and
○ the dynamic (temporal)
aspects of a system
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 7 of 32
Berner Fachhochschule
Engineering and Information Technology
Some UML Diagramsclass diagram object diagram package diagram
use case diagram sequence diagram activity diagram
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 8 of 32
Berner Fachhochschule
Engineering and Information Technology
Sample Class Diagram (borrowed from [Fowler])
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 9 of 32
X
X
OrderdateReceived: Date [0..1]isPaid: Boolean [1]number: String [1]price: Moneydispatchclose
Customername [1]address [0..1]dispatchclose
OrderLinedateReceived: Date [0..1]isPaid: Boolean [1]
Product
Corporate CustomercontactNamecreditRatingcreditLimit
Personal CustomercreditCardNumber
Employee
billForMonth(Integer)remind()
* 1
1
* {ordered}lineItems
*1
0..1*
salesRep
{getCreditCardRating() == “poor”}
X
X
X String
Date
Money
Boolean
{if Order.customer.getCreditRatingis “poor” then Order.isPrepaid mustbe true}
multiplicity
association
class
comment
generalization
attributes
operations
notnavigable
rolename
constraint
classes used as types of attributes
Berner Fachhochschule
Engineering and Information Technology
UML Class
Attributes● Format:
visibility? /? name :type? multiplicity? =default? {property}*1
● Examples + customer : int- address : String [1 .. *]# code : String = “Test” {readOnly}
1 “X?” denotes zero or one occurrence, “{X}*” denotes zero or more occurrences of the referenced X.
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 10 of 32
OrderdateReceived: Date [0..1]isPaid: Boolean [1]number: String [1]price: Moneydispatchclose
class namea class
attributes
operations
compartment
(each of it is optional)
Berner Fachhochschule
Engineering and Information Technology
Attributes (cont'd)● Visibility:
○ private: “-”, protected: “#”, package: “~”, public: “+”
Convention: If no visibility markers are given then read “private” visibility for attributes.
● / : derived attribute: value can be calculated from other properties (= attributes, etc.)
● Name:
Typically corresponds to the name of a field in Java.
● Type:
Restriction on the range of values of an attribute.
● Multiplicity: see below
● Default value: The value for a newly created object if the attribute isn't specified during creation.
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 11 of 32
Meaning: UML gives not a precise definition.Convention here: as in Java
Berner Fachhochschule
Engineering and Information Technology
Attributes (cont'd)
● {property-string} indicates additional properties of the attribute. Explained in chapter “Advanced Concepts of UML Class Diagrams”.
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 12 of 32
Berner Fachhochschule
Engineering and Information Technology
Associations● properties as attributes
● properties as associations
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 13 of 32
Order+dateReceived: Date [0..1]+isPaid: Boolean [1]+lineItems: OrderLine [*] {ordered} OrderLine
Boolean
Date
multi-valued property / attribute
Order BooleanDate
OrderLine
multiplicity
0..1 *
*
1
association
navigability
association
association
lineItems {ordered}A B Can navigate fromto:A :B
Cannot navigate from to:A :B
A B
Berner Fachhochschule
Engineering and Information Technology
Associations (cont'd)● The name of a property goes at the target end of the association, together with its multipli
city.
● There is a small difference, however, for expressing multiplicities:
○ multiplicities can be expressed at both ends of an association line
● When using attributes or associations?
Use attributes for “small things”:
■ booleans, strings, dates
Use associations to relate “classes with business meaning”:
■ orders, order items, products, customers
■ employee, employee, ...
Notice: Attributes and associations, respectively, are properties of a class.
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 14 of 32
Berner Fachhochschule
Engineering and Information Technology
MultiplicityMultiplicity of a property (I.e., attribute or association):
● An indication of how many values may fill the property.
● Format on an attribute:
[indication]
Examples:
● A car has four wheels:wheels : Wheel [4]
● A student registers with many modules:modules : Module [0..*]
● A student has one address: address : Address [1]
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 15 of 32
see next slide
Berner Fachhochschule
Engineering and Information Technology
Multiplicity (cont'd)The most common multiplicity indications:
● 0..1:The property may or may not have a value.
● 1..1:The property has exactly (and always) a value. Usually denoted as “1” only. Default ([Fowler]).
● 0..*: The property has zero or more values.
● 1..*:The property has one or more values.
● n..m:The property has at least n and at most m values.
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 16 of 32
shorthand: *
Berner Fachhochschule
Engineering and Information Technology
Programming Interpretation of Properties● There is no one way to interpret properties in code.
● Most common way:
a UML public property is mapped onto:
■ a private field plus getter and setter methods (as in Java)
■ a property (as in C#)
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 17 of 32
!
Berner Fachhochschule
Engineering and Information Technology
Programming Interpretation: Single-Valued PropertyUML class diagram excerpt:
A first, implementation-focused interpretation of property “price”:
1 public class OrderLine {2 private int quantity; private Money price;3 private Product product;4 ...5 public int getQuantity() { return this.quantity; }6 public void setQuantity(int q) { this.quantity = q; }7 public Money getPrice() {8 return this.price.multiply(this.quantity);9 }10}
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 18 of 32
OrderLineProduct+price {readOnly}
+quantity
Value Object:an object whose attributes cannot be changed after initialization!
1
*) See: http://www.martinfowler.com/eaaCatalog/valueObject.html
*)
+product
Returns a new Money object having the value of the base price multiplied by quantiy.
Berner Fachhochschule
Engineering and Information Technology
Programming Interpretation: Single-Valued Property (cont'd)Another, more interface-oriented interpretation of property “price”:
1 public class OrderLine {2 private int quantity;3 private Product product;4 ...5 // get/set quantity as before67 public Money getPrice() {8 Money priceOfProduct = this.product.getPrice();9 Money subTotal =10 priceOfPruduct. multiply(this.quantity);11 return subTotal;12 }13}
==> No field for price!
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 19 of 32
OrderLine
Product
+price {readOnly}+quantity
+price
+product1
Berner Fachhochschule
Engineering and Information Technology
Class Money: Value Object1 public final class Money {2 private final BigDecimal value;3 4 public Money(BigDecimal value) {5 if (val == null) throw new IllegalArgumentException(“Value ...”);6 this.value = value;7 }8 9 public BigDecimal getValue() {10 return this.value;11 }12 public Money multiply(int factor) {13 return new Money(this.value.multiply(factor));14 }15}
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 20 of 32
“final” means that value can be assigned only once (in the constructor)
test necessary to guarantee properly initialized object
an instance of BigDecimal is immutable
multiplies a Money object by a factor and returns a NEW Money object
“final” class means that there cannot be subclasses
Berner Fachhochschule
Engineering and Information Technology
Programming Interpretation: Multivalued AttributesIf an attribute is multivalued, this implies that
● a collection is used for the values
If the multiplicity of a property is
● ordered (with / without duplicates)
○ the collection must be ordered:List<OrderLine>, ...
● not duplicates (with / without order)
○ the collection should, strictly, be unordered:Set<Order>, ...
○ but often used: List<Order>, ...
● no arrays (“[]”), please: OrderLine[] lineItems;
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 21 of 32
How many?
==> you don't know
So don't use an array!(Unless there are otherforces...)
Berner Fachhochschule
Engineering and Information Technology
Programming Interpretation: Multivalued Attributes (cont'd)Multivalued properties yield a different interface to single-valued properties:
1 public class Order {2 private List<OrderLine> lineItems = new ArrayList<OrderLine>();34 public List<OrderLine> getLineItems() 5 return Collections.unmodifiableList(6 this.lineItems);7 }8 public void addLineItem(OrderLine item) {9 this.lineItems.add(item);10 }11 public void removeLineItem(OrderLine item) {// Option: discussed during the lecture.12 this.lineItems.remove(item);13 }14}
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 22 of 32
Principle:
“Information Hiding”, i.e., the client of this class need not know which concrete implementation is used for the list.
Alternatively, you may return a boolean indicating whether the underlying collection was changed or not.
Berner Fachhochschule
Engineering and Information Technology
Bidirectional AssociationsBidirectional association:
A pair of properties linked together.
Example:
The Car class has the property:
● owner : Person [0..1]
The Person class has the property:
● cars : Car [0..*]
By convention, omitting the arrows at both ends of the association is still a bidirectional association.1
1 In UML, omitting the arrows leaves the navigability undefined.
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 23 of 32
CarPerson0..1
+owner
*
+cars
You may omit the arrows “<” or “>” or the “X” sign. However, you must use these signs to express navigability.
Berner Fachhochschule
Engineering and Information Technology
Bidirectional Associations (cont'd)You can name an association, the name is “owns”:
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 24 of 32
CarPerson0..1
+owner
*
+cars
owns
Here, too:You may omit the arrows “<” or “>” or the “X” sign. However, you must use these signs to express navigability.
Berner Fachhochschule
Engineering and Information Technology
Bidirectional Associations (cont'd)Implementing a bidirectional association is a little bit tricky. Key point: both properties have to be kept in sync.
For example:
1 public class Car {2 private Person owner;3 public Person getOwner() { return this.owner; }45 public void setOwner(Person p) {6 if (this.owner != null) { this.owner.friendCars().remove(this); }7 this.owner = p;8 if (this.owner != null) { this.owner.friendCars().add(this); }9 }10}
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 25 of 32
Idea:Bidirectional association is managed by the “Car” side.
Berner Fachhochschule
Engineering and Information Technology
Class Person looks like (assuming the same package):
1 public class Person {2 private Set<Car> cars = new HashSet<Car>();3 public Set<Car> getCars() {4 return Collections.unmodifiableSet(this.cars);5 }6 public void addCar(Car aCar) {7 if (aCar != null && !this.cars.contains(c)) {8 aCar.setOwner(this);9 }10 Set<Car> friendCars() {1112 return this.cars;1314 }15}
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 26 of 32
If a Person instance gets a new car then the updating of the association is delegated to the Car instance.
“Friends” (here: Car objects) are allowed to update the collection of cars.Notice the visibility!
Berner Fachhochschule
Engineering and Information Technology
OperationsOperations are the actions that a class knows to carry out.
● Format:
visibility? name (parameter*): return-type? {property*}?
● Examples
+ getName() : String {query}
# runTest (in count : int = 5) : int
- op3 (inout p1 : Address)
~ op4 (out p2 String [1..*] {ordered}) : SomeType
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 27 of 32
SomeClass-attr1 : Type1...
+method1(p1 T1, ...): Tr.
attributes
operations
Berner Fachhochschule
Engineering and Information Technology
Operations (cont'd)● Visibility:
○ private: “-”, protected: “#”, package: “~”, public: “+”
Convention: If no visibility markers are given then read “public” visibility for operations.
● The name is a string.
● Parameter: a parameter for the operation, see below.
● Return-type: The type of the returned value, if there is one.
● Property-string: Properties of the operation. Among others, such properties are:
○ {query}
○ {modifier}
○ ...
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 28 of 32
Principle:
Command-Query Separation Principle[B. Meyer]
object state not changed
object state changed
Berner Fachhochschule
Engineering and Information Technology
Operations (cont'd)● Format of a parameter:
direction? name: type? =default-value?
● The name, type, and default are the same as for attributes.
● direction:
○ nothing or “in”:The parameter is input.
○ “out”:The parameter is output:
○ “inout”:The parameter is input and output.
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 29 of 32
Idea:
Program and use a Holder class in Java.
no corresponding possibility in Java ...
Berner Fachhochschule
Engineering and Information Technology
Operations (cont'd)● Modifier versus query operations, Command-Query separation principle (Betrand Meyer)
○ modifier: changes the (observable) state of an object
○ query: gets a value (or a collection of values) from an object without changing thestate of the object
● Operation versus method:
○ operation: invoked on an object (~ procedure declaration or signature)
○ method: the operation's code or body
● setting/getting (getter) methods
○ getting method: returns a value (or a collection of values)from a field / property
○ setting method: puts a value (or a collection of values) intoa field / property
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 30 of 32
Berner Fachhochschule
Engineering and Information Technology
GeneralizationFrom the example above:
● PersonalCustomer and CorporateCustomer have similarities (attributes, operations).
● The similarities can be placed in a general Customer class (the supertype).
On a conceptual level,
● CorporateCustomer is a subtype of Customer if all instances of CorporateCustomer are also instances of Customer.
● CorporateCustomer is then said to be a special kind of Customer.
● Everything we say about a Customer – associations, attributes, operations – is true also for CorporateCustomer.
One programming language interpretation:
● (implementation/class) inheritance.
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 31 of 32
Order Customer
Personal C.Corporate C.Employee
* 1
1*
Berner Fachhochschule
Engineering and Information Technology
Generalization (cont'd)Important principle
● Substitutability:
Wherever the type Customer is used in the program, an instance of CorporateCustomer can be used instead.
● Instances of different classes may behave differently (due to polymorphism), but the caller need not worry about this.
● This substitutability is also referred to as the
Liskov Substitution Principle (LSP for short)
BFH/TI/Software Engineering and Design/UML and Design Patterns/UML Class Diagrams/February 2011 (X)/Prof. Dr. E. Dubuis Page 32 of 32
Important Principle:
Liskov Substitution Principle (LSP)