Class models

advertisement
Lecture 4
Class Models
(Based on Fowler (2004, Chapters 3 & 5) and
Stevens and Pooley (2006, Chapters 5 & 6))
David Meredith
d.meredith@gold.ac.uk
www.titanmusic.com/teaching/cis224-2007-8.html
CIS224
Software Projects: Software Engineering
and Research Methods
1
Class diagrams
Copy
• UML class diagrams document the static structure of a
system
– What classes there are
– How the classes are related
• Each class represented in UML diagram as a rectangle
containing the name of the class
2
What makes a class model good?
• Ultimate aim:
– Build, as quickly and cheaply as possible, a
system which satisfies the users’
requirements
• Objects must provide every piece of required
behaviour
– Build a system which will be easy to maintain
and adapt to future requirements
• Use encapsulated modules with low coupling and
high cohesion
• Use classes which represent enduring types of
domain concepts
3
How to build a good class model
• Can use any method you like!
• Unlikely to get it right first time
• Classes that correspond to classes of domain
object (e.g., book, copy of book, library member)
are easiest to identify
• What drives the design?
– Data-driven design (DDD)
• “Identify all the data and divide it up into classes before
considering classes’ responsibilities”
• Noun identification technique
– Responsibility-driven design (RDD)
• “Identify all the responsibilities of the system and divide
between classes before considering the data”
• Class-responsibility-collaboration (CRC) cards
• In practice, DDD and RDD can be used together
4
Identifying classes in DDD:
Noun identification
1. Identify candidate classes by selecting all
nouns and noun phrases in the
requirements specification
Use singular form of each noun or phrase
Do not include “or” or “and” in a single class name
2. Discard inappropriate candidate classes
to get initial class list
5
Noun identification technique:
Discarding candidate classes
• Consider discarding candidate classes if they are
– Redundant
• Different nouns or phrases correspond to the same class (e.g., “library
member”, “member of the library”)
– Vague
• Not clear what the noun or phrase means
– Events or operations
• Is the event or operation a thing with state, behaviour and identity?
If not, discard it!
– e.g., “short term loan”
– Part of the meta-language
• Nouns and phrases that refer to aspects of the project, not domain objects
– e.g., “requirements”, “system”
– Outside the scope of the system
• Nouns and phrases that refer to objects that are not inside the system
– e.g., “library”
– Actors often discarded for this reason if no need to represent them by objects
within the system
– Attributes
• Nouns and phrases that refer to simple things with no interesting behaviour
of their own
– e.g., name of library member, duration of loan
• May also be other reasons to discard a candidate class…
6
What sorts of things are
represented by classes?
• Most commonly:
– Tangible or ‘real-world’ objects and concepts
• e.g., book, copy, course, hovercraft
– Roles
• e.g., library member, customer, manager
• Less commonly
– Events
• e.g., loan, arrival, departure
– Interactions
• e.g., match, meeting
• Events and interactions can help with identifying
associations between classes representing domain
concepts and roles
• Main class that just provides program entry point usually
not included in class model
– e.g., class containing main method in Java
7
Associations
• Classes correspond to nouns
Associations correspond to verbs
• An association between two classes often
represents a real-world relationship between the
classes of real-world things or concepts
represented by the classes
• Just as an object is an instance of a class, a link
is an instance of an association
– A link connects a pair of objects (not classes)
– e.g., link between objects representing David
Meredith and copy 4 of Fowler (2004) might represent
the fact that David Meredith borrows or returns copy 4
of Fowler (2004)
8
Associations
• Class A and class B are associated if an
object of class A has to know about an
object of class B, i.e.,
– An object of class A sends a message to an
object of class B
– An object of class A creates an object of
class B
– An object of class A has an attribute whose
values are objects of class B or collections of
objects of class B
– An object of class A receives a message with
an object of class B as an argument
9
Associations
• Class model should represent well the
real-world relationships between domain
concepts
– Class model should make sense to a domain
expert
• Class model should also permit a sensible
implementation that realizes the required
use cases
• Satisfying both these criteria leads to a
system that is easy to maintain because it
10
is easy to understand
Association in a class diagram
0..1 borrows
0..*
1..*
LibraryMember
1
Copy
Book
is a copy of
0..1 reserves
0..*
• May be two or more different associations between
same pair of classes
– e.g., LibraryMember has reserved Copy, LibraryMember has
Copy on loan
– Represented by multiple labelled lines on class diagram
11
Attributes and Operations
Book
0..1
borrows
title : String
1 author : String
0..*
1..*
Copy
LibraryMember
is a copy of
0..1 reserves
0..*
isBorrowable() : Boolean
copyBorrowed(c : Copy)
copyReturned(c : Copy)
• In order for the objects of a class to have state and
behaviour, the class must have attributes and
operations:
– Attributes: variables inside objects where data is stored
• Declared in second compartment of class icon
• Do not include attributes that implement associations (e.g.,
copies : Copy[1..*])
• Types of attributes should not be classes in the diagram
– Operations: the messages that the objects in a class understand
and respond to
• Declared in third compartment of class icon
• Provide selector, arguments and return type
• Same operation may be implemented by different methods in
different classes related by inheritance
12
Generalization
Book
LibraryMember
0..1
borrows 0..*
1..*
Copy
name : String
borrow(c : Copy)
return(c : Copy)
reserve(c : Copy)
numItemsOnLoan() : Integer
title : String
1 author : String
is a copy of
0..1 reserves
isBorrowable() : Boolean
copyBorrowed(c : Copy)
copyReturned(c : Copy)
0..*
.
borrows 0..*
MemberOfStaff
0..1
0..1 reserves
Journal
0..*
borrow(j : Journal)
return(j : Journal)
reserve(j : Journal)
numItemsOnLoan() : Integer
• MemberOfStaff is specialization of LibraryMember
– Can do everything that a LibraryMember can do and more (e.g.,
borrow a journal)
– MemberOfStaff should conform to interface of LibraryMember
• Liskov substitution principle
– May override methods in LibraryMember
13
• Should be no “conceptual gulf” between what a derived class and its
base class do on receipt of the same message
Generalization
• Class B may be a specialization of class A if
– every member of class B is a member of class A
• e.g., Every member of the class MemberOfStaff is a member of the
class LibraryMember
– All members of class B share one or more properties or
behaviours that they do not share with the other members of
class A
• e.g., all members of the class MemberOfStaff can borrow journals
whereas the other membes of class LibraryMember cannot
• But inheritance increases coupling so only use when
necessary
– Every member of the class Border Collie is a member of the
class Dog
– But may not need subclass Border Collie if the only relevant
property or behaviour that Border Collies do not share with other
dogs is the name of their breed
• Could implement this as an attribute called Breed in an object of
class Dog
14
Class models and class diagrams
• Each system has only one class model or static
structural model which describes the static
structure of the system, particularly the classes
and the relationships between them
• Maybe two or more class diagrams used to
graphically represent the single class model of a
system (e.g., at different levels of detail)
• May represent the same class more than once
on the same class diagram, but all icons
representing a class must be consistent with the
single class that they all represent
• Suggestion: only represent a class once on any
given diagram unless using a tool that enforces
15
consistency
Aggregation
1..*
Degree programme
12..*
Course
• An aggregation is a special association that
shows that objects of one class are parts of
objects of another class
– e.g., degree programme consists of 12 or more
courses
• Each instance of the “part” class may be
associated with more than one instance of the
“whole” class
– e.g., the course CIS109 is part of several different
computing degree programmes
16
Composition
1
ChessBoard
64
Square
• A composition is a special association that shows that
each object of one class is part of at most one object of
another class
• If an object of the “whole” class is copied or deleted, so
are all the objects of the “part” class that are associated
with it
– e.g., an object representing a chess board may contain a
collection of objects of class Square
• Each Square object only associated with one ChessBoard object
• Square objects deleted or copied when ChessBoard object deleted
17
or copied
Examples of aggregation and
composition
• Are the associations between the following
examples of aggregation or composition?
– Player and Team
• Aggregation
– Wheel and Car
• Composition
– Account and Customer
• Composition (What about joint accounts?)
– Song and Playlist
• Aggregation
18
Role names on associations
Personal tutor
Tutee
Lecturer
Student
1
is the personal tutor of
0..*
• Can label roles of classes within relationship
represented by association in class model
19
Navigability of associations
Student
Course
0..*
12..*
is taking
getStudentList() : Student[0..*]
• If class A must know about class B, then draw arrow with stick
arrowhead from class A (source) to class B (target)
– Each object of class Course must know which students are taking that
course in order to generate a list of students for that course (e.g., to
print registers)
– Each Course object must be able to send messages to the Student
objects that are linked to it (e.g., to retrieve the names of the students)
– Each Course object might have an attribute
students : Students[0..*]
would not explicitly give this attribute in the attribute compartment of the
Course icon because implied by the directed association
• If class A knows about class B, then class A cannot be reused
without class B
– Increases coupling
– Don’t introduce navigability unless required!
• Does the association between Student and Course need to be
bidirectional?
– What if we want to know the courses that each student is taking?
20
Bidirectional navigability
and non-navigability
Course
Student
0..*
getCourseList() : Course[12..*]
is taking
1
ChessBoard
12..*
getStudentList() : Student[0..*]
64
X
Square
• Show bidirectional navigability by putting arrow heads at
both ends of the association
• Leaving both arrowheads off means unspecified
navigability
• Fact that class A does not know about class B indicated
by placing a cross on the association near class B (new
21
in UML 2.0)
Qualified associations
ChessBoard
row : {1..8}
column : {1..8}
1
1
Square
OrderLine
Order
0..1
Product
quantity
• Multiplicity of 1 at Square end of association indicates that, if we
take a ChessBoard object, b, then there is exactly 1 Square object
associated with any specific pair of values assigned to the row and
column attributes of b
• Only one or zero lines in any given order associated with a particular
product
– Order object has (at most) one OrderLine per product
22
Derived associations
is taking
Student
Course
teaches
/teaches
Lecturer
• Fact that Lecturer class is associated with Student class
is implied by association between Lecturer and Course
and association between Course and Student
• Three options:
– Can leave out association between Lecturer and Student
– Can put it in as an ordinary association
– Can indicate that it can be derived from other associations by
preceding label with a forward slash, /
• Indicates that association exists by virtue of other associations – no
need to be implemented separately
23
Constraints
Copy
Book
0..1
borrows
1..*
Copy
1
MemberOfStaff
{xor}
1
1..*
0..12
{ (number of Copies borrowed)
+ (number of Journals borrowed)
<= 12 }
borrows
0..12
0..1
Journal
Journal
• A constraint is a condition that must be satisfied by a correct
implementation of a design
• In UML, a constraint must be given between braces, e.g., {xor},
{total number of items borrowed must be no more than 12}
• Can use either formal language, such as Object Constraint
Language (OCL), or natural language or a programming language to
express a constraint
24
Association classes
0..*
12..*
Student
Course
0..*
12..*
Student
Course
1
1
is taking
mark : Integer
year : Integer
12..*
0..*
Result
mark : Integer
year : Integer
• An association class allows an association to have
attributes and operations
• Where do we store the result a student gets for a
course? In the Student object or in the Course object?
• Can make an association class and store result there
• Alternatively can make a Result class and associate it
with the Course object and the Student object
• If student takes course twice, can make two Result
objects, but cannot make two association objects
– Can only be at most one association object for any given pair of
25
linked objects
Interfaces and abstract classes
Order
orderLines : OrderLine[0..*]
List
ArrayList
«interface»
Collection
Collection
equals
add
AbstractList
«interface»
List
Order
orderLines : OrderLine[0..*]
equal
get
add
get
dependency
(requires interface)
•
Abstract operation is declared but not implemented
–
•
ArrayList
get
add
Class name written in italics
Abstract class cannot be instantiated
All operations of an interface are abstract (i.e., no implementation provided)
Dependency arrow used to show that class requires interface
Dashed generalization arrow shows that class provides interface
–
–
•
•
Written in italics in class icon
Class is abstract if at least one of its operations is abstract
–
–
•
•
•
implementation
(provides interface)
Weak form of inheritance
Class may provide more than one interface
Good idea to depend on as general a class as possible to allow for different implementations
Order depends on List interface
–
get, equals and add operations dynamically bound to implementations in ArrayList
26
Dependency
Employee data gateway
Benefits window
Employee
Benefits data gateway
•
Class A depends on class B if a change in class B may necessitate a change in class A
–
•
•
A is client, B is supplier or server
Dependency indicated by dashed arrow with stick head on class diagram
Difference between dependency and assocation:
–
Dependency indicates relationship between class definitions
•
–
Association indicates relationship between objects within classes
•
•
•
Objects of class A need to know about objects of class B
Can usually be more specific about the nature of a dependency than merely stating that it
exists (e.g., generalization, implementation of interface)
Dependency can exist between A and B if
–
–
–
•
•
•
Change in definition of class A may necessitate change in defiinition of class B
A sends a message to B
A has an attribute of class B
A has an operation parameter of class B
Change in Employee might mean Benefits window has to be changed
Change in Benefits window will not affect Employee
Change in Employee data gateway may also necessitate change in Benefits window, but
27
only if it necessitates change in public interface of Employee
Summary
•
•
•
UML class diagrams document static structure of system
Object-oriented approach should allow us to build, cheaply and quickly, systems that
can be adapted to satisfy changes in requirements
Can use various techniques for identifying the classes in a system
–
•
Classes often represent tangible "real-world" objects and concepts
–
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
(e.g., noun identification technique)
less often, they represent events and interactions
Associations represent the relationships between classes
Classes are associated if one has to know about the other
Two classes can be connected by two or more associations
Multiplicities
Attributes and operations
Generalization
Distinction between class models and class diagrams
Aggregation and composition
Role names
Navigability
Qualified associations
Derived associations
Constraints
Association classes
Interfaces and abstract classes
Dependency
28
Download