Object-Oriented Analysis and Design
Lecture 13: Class Design
Objectives: Class Design
Define the purpose of Class Design and
where in the lifecycle it is performed
Identify additional classes and relationships
needed to support implementation of the
chosen architectural mechanisms
Identify and analyze state transitions in
objects of state-controlled classes
Refine relationships, operations, and
attributes
Object Oriented Analysis and Design 2
Class Design in Context
[Early
Elaboration [Inception
Iteration] Iteration (Optional)]
Define a Candidate Perform
Architecture Architectural
Synthesis
Analyze Behavior
(Optional)
Refine the
Architecture
Class
Design Designer Define Design the
Components Database
Object Oriented Analysis and Design 3
Class Design Overview
Project Specific
Guidelines
Class
Design Design Classes
Supplementary
Specifications
Object Oriented Analysis and Design 4
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Nonfunctional Requirements in General
Checkpoints
Object Oriented Analysis and Design 5
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 6
Class Design Considerations
Class stereotype
Boundary
Entity
Control
Applicable design patterns
Architectural mechanisms
Persistence
Distribution
etc.
Object Oriented Analysis and Design 7
How Many Classes Are Needed?
Many, simple classes means that each class
Encapsulates less of the overall system
intelligence
Is more reusable
Is easier to implement
A few, complex classes means that each class
Encapsulates a large portion of the overall
system intelligence
Is less likely to be reusable
Is more difficult to implement
A class should have a single well-focused purpose. A
class should do one thing and do it well!
Object Oriented Analysis and Design 8
Strategies for Designing Boundary Classes
User interface (UI) boundary classes
What user interface development tools will be used?
How much of the interface can be created by the
development tool?
External system interface boundary classes
Usually model as subsystem
MainWindow SubWindow
MainForm
Button DropDownList
Object Oriented Analysis and Design 9
Strategies for Designing Entity Classes
Entity objects are often passive and persistent
Performance requirements may force some re-factoring
See the Identify Persistent Classes step
Analysis Design
<< Entity >> FatClass
FatClass
- privateAttr
- privateAttr
- commonlyUsedAttr1 + getCommonlyUsedAttr1()
- commonlyUsedAttr2 + getCommonlyUsedAttr2()
- rarelyUsed1 + getRarelyUsedAtt1()
- rarelyUsed2 + getRarelyUsedAtt2()
1 0..1
FatClassDataHelper FatClassLazyDataHelper
- commonlyUsedAttr1 - rarelyUsedAttr1
- commonlyUsedAttr2 - rarelyUsedAttr2
Object Oriented Analysis and Design 10
Strategies for Designing Control Classes
What happens to Control Classes?
Are they really needed?
Should they be split?
How do you decide?
Complexity
Change probability
Distribution and performance
Transaction management
Object Oriented Analysis and Design 11
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 12
Operations: Where Do You Find Them?
Messages displayed in interaction diagrams
: ClassA : ClassB : ClassA : ClassB
1 : V/Perform Responsibility\ 1 : \performResponsibility (): result\
Other implementation dependent functionality
Manager functions
Need for class copies
Need to test for equality
Object Oriented Analysis and Design 13
Name and Describe the Operations
Create appropriate operation names
Indicate the outcome
Use client perspective
Are consistent across classes
Define operation signatures
operationName([direction]parameter : class,..) :
returnType
• Direction is in, out or inout with the default in
if absent
Provide short description, including
meaning of all parameters
Object Oriented Analysis and Design 14
Guidelines: Designing Operation Signatures
When designing operation signatures,
consider if parameters are:
Passed by value or by reference
Changed by the operation
Optional
Set to default values
In valid parameter ranges
The fewer the parameters, the better
Pass objects instead of “data bits”
Object Oriented Analysis and Design 15
Operation Visibility
Visibility is used to enforce encapsulation
May be public, protected, or private
Private
operations
Public Protected
operations operations
Object Oriented Analysis and Design 16
How Is Visibility Noted?
The following symbols are used to specify
export control:
+ Public access
# Protected access
- Private access
Class1
- privateAttribute
+ publicAttribute
# protectedAttribute
- privateOperation ()
+ publicOPeration ()
# protecteOperation ()
Object Oriented Analysis and Design 17
Scope
Determines number of instances of the
attribute/operation
Instance: one instance for each class instance
Classifier: one instance for all class instances
Classifier scope is denoted by underlining the
attribute/operation name
Class1
- classifierScopeAttr
- instanceScopeAttr
+ classifierScopeOp ()
+ instanceScopeOp ()
Object Oriented Analysis and Design 18
Example: Scope
<<Entity>>
Student
- name
- address
- studentID
- nextAvailID : int
+ addSchedule ([in] theSchedule : Schedule, [in] forSemester : Semester)
+ getSchedule ([in] forSemester : Semester) : Schedule
+ hasPrerequisites ([in] forCourseOffering : CourseOffering) : boolean
# passed ([in] theCourseOffering : CourseOffering) : boolean
+ getNextAvailID () : int
Object Oriented Analysis and Design 19
Example: Define Operations
<<control>>
<<Interface>>
RegistrationController 0..* ICourseCatalogSystem
1
+ submitSchedule()
+ getCourseOfferings()
+ saveSchedule()
+ initialize()
+ getCourseOfferings() : CourseOfferingList
+ getCurrentSchedule ( [in] forStudent : Student, [in] forSemester : Semester) : Schedule
+ deleteCurrentSchedule()
+ new ( [in] forStudentID : String) 0..1
+currentSchedule
+ getStudent ( [in] anID : int) : Student
0..1
0..1
<<Entity>>
Schedule
+ registrant 0..1 0..*
0..* 0..*
<<Entity>>
Student
+ getTuition() : double
+ addSchedule ( [in] aSchedule : Schedule) +alternateCourses
+ getSchedule ( [in] forSemester : Semester) : Schedule 1
+ deleteSchedule ( [in] forSemester : Semester) +primaryCourses
+ hasPrerequisites ( [in] forCourseOffering : CourseOffering) : boolean 0..2 0..4
# hasPassed ( [in] aCourseOffering : CourseOffering) : boolean
+ getNextAvailID() : int <<Entity>>
+ getStudentID() : int CourseOffering
+ getName() : String
+ getAddress() : String
Object Oriented Analysis and Design 20
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 21
Define Methods
What is a method?
Describes operation implementation
Purpose
Define special aspects of operation
implementation
Things to consider:
Special algorithms
Other objects and operations to be used
How attributes and parameters are to be
implemented and used
How relationships are to be implemented and
used
Object Oriented Analysis and Design 22
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 23
Define States
Purpose
Design how an object’s state affects its
behavior
Develop statecharts to model this behavior
Things to consider :
Which objects have significant state?
How to determine an object’s possible states?
How do statecharts map to the rest of the
model?
Object Oriented Analysis and Design 24
What is a Statechart?
A directed graph of states (nodes) connected by
transitions (directed arcs)
Describes the life history of a reactive object
Guard Condition
Event Action
State1 State2
Event(args)[guard condition]/action
Transition
State State
Object Oriented Analysis and Design 25
Special States
Initial state
The state entered when an
object is created State1
Mandatory
Can only have one initial
state
Final state
Indicates the object’s end
of life State2
Optional
May have more than one
Object Oriented Analysis and Design 26
Identify and Define the States
Significant, dynamic attributes
The maximum number of students per course offering is 10
numStudents < 10 numStudents < = 10
Open Closed
Existence and non-existence of certain links
<< Entity >>
Professor Link to Professor Link to Professor
Exists Doesn’t Exist
0..1 Assigned Unassigned
0..*
<< Entity >>
CourseOffering
Object Oriented Analysis and Design 27
Identify the Events
Look at the class interface operations
<< Entity >>
CourseOffering 0..* << Entity >>
Professor
+ addProfessor() 0..1
+ removeProfessor()
Events: addProfessor, removeProfessor
Object Oriented Analysis and Design 28
Identify the Transitions
For each state, determine what events cause
transitions to what states, including guard
conditions, when needed
Transitions describe what happens in response
to the receipt of an event
<< Entity >>
CourseOffering << Entity >>
0..*
Professor
+ addProfessor() 0..1
+ removeProfessor()
Unassigned
removeProfessor addProfessor
Assigned
Object Oriented Analysis and Design 29
Add Activities and Actions
Activities StateA
Are associated with a state Entry/anAction Action
Start when the state is
entered
Take time to complete
Event[condition]/action
Interruptible
Actions Activity
Associated with a transition
StateB StateC
Take an insignificant amount
Do/anActivity Exit/someAction
of time to complete
Are non-interruptible
Object Oriented Analysis and Design 30
Example: Statechart
addStudent / numStudents = numStudents + 1
/ numStudents = 0 removeStudent [numStudents >0]/ numStudents = numStudents - 1
Unassigned
closeRegistration
cancel Canceled
addProfessor
do: Send cancellation notices
close
removeProfessor cancel
[ numStudents = 10 ]
cancel
Full
close[ numStudents < 3 ] close
addStudent / closeRegistration [ has Professor assigned ]
[ numStudents = 10 ]
numStudents = numStudents + 1
Assigned closeRegistration[ numStudents >= 3 ] Committed
do: Generate class roster
close[ numStudents >= 3 ]
removeStudent[ numStudents > 0] / numStudents = numStudents - 1
Object Oriented Analysis and Design 31
Example: Statechart with Nested States and History
superstate
/ numStudents = 0 Open closeRegistration Closed
close Canceled
Unassigned do: Send cancellation notices
cancel
cancel
substate
Full
close[ numStudents < 3 ]
remove a professor
[ numStudents = 10 ] close
add a professor
closeRegistration [ has Professor assigned ]
closeRegistration[ numStudents >= 3 ] Committed
Assigned
do: Generate class roster
addStudent /
numStudents = numStudents + 1
H close[ numStudents >= 3 ]
removeStudent[ numStudents > 0] / numStudents = numStudents - 1
Object Oriented Analysis and Design 32
Which Objects Have Significant State?
Objects whose role is clarified by state
transitions
Complex use cases that are state-controlled
It is not necessary to model objects such
as:
Objects with straightforward mapping to
implementation
Objects that are not state-controlled
Objects with only one computational state
Object Oriented Analysis and Design 33
How Do Statecharts Map to the Rest of the Model?
Events may map to operations
Methods should be updated with state-specific
information
States are often represented using attributes
This serves as input into the “Define Attributes” step
Open [numStudents=10] Full
<< Entity >>
addStudent / numStudents = numStudents + 1
CourseOffering
- numStudents
+ addStudent()
(Stay tuned for derived attributes)
Object Oriented Analysis and Design 34
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 35
Attributes: How Do You Find Them?
Examine method descriptions
Examine states
Examine any information the class itself
needs to maintain
Object Oriented Analysis and Design 36
Attribute Representations
Specify name, type, and optional default value
attributeName : Type = Default
Follow naming conventions of implementation
language and project
Type should be an elementary data type in
implementation language
Built-in data type, user-defined data type, or
user-defined class
Specify visibility
Public: +
Private: -
Protected: #
Object Oriented Analysis and Design 37
Derived Attributes
What is a derived attribute?
An attribute whose value may be calculated
based on the value of other attribute(s)
When do you use it?
When there is not enough time to re-calculate
the value every time it is needed
When you must trade-off runtime performance
versus memory required
Object Oriented Analysis and Design 38
Example: Define Attributes
<< Control >> << interface >>
RegistrationController ICourseCatalogSystem
0..1
0..1
0..1
+ registrant + currentSchedule << Entity >>
Schedule
0..1 - semester : Semester
0..*
<< Entity >> 1 0..* 0..*
Student
+ alternateCourses + primaryCourses
- name 0..2 0..4
- address
<< Entity >>
- nextAvailID : int
- studentID : int
CourseOffering
- dateOfBirth : Date - number : String = “100”
- startTime : Time
- endTime : Time
- day : String
- /numStudents : int = ()
Object Oriented Analysis and Design 39
Exercise 1: Class Design
Given the following:
The architectural layers, their packages,
and their dependencies
Design classes for a particular use case
(continued)
Object Oriented Analysis and Design 40
Exercise 1: Class Design (cont.)
Identify the following:
Attributes, operations, and their
complete attribute signatures
Attribute and operation scope
and visibility
Any additional relationships
and/or classes to support the
defined attributes and attribute
signatures
Class(es) with significant state-
controlled behavior
The important states and
transitions for the identified class
(continued)
Object Oriented Analysis and Design 41
Exercise 1: Class Design
Produce the following:
Design Use-Case Realization
• Statechart for one of the
classes that exhibits
state-controlled behavior
• Class diagram (VOPC) that
includes all operations, operation
signatures, attributes, and
attribute signatures
Object Oriented Analysis and Design 42
Exercise 1: Review
Compare your results
Is the name of each operation
descriptive and understandable? Does
the name of the operation indicate its
outcome?
Does each attribute represent a single
conceptual thing? Is the name of each
attribute descriptive and does it
correctly convey the information it
stores? Payroll System
Is the state machine understandable?
Do state names and transitions reflect
the context of the domain of the
system? Does the state machine
contain any superfluous states or
transitions?
Object Oriented Analysis and Design 43
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 44
Define Dependency
What Is a Dependency?
A relationship between two objects
Client Supplier
Purpose
Determine where structural relationships are
NOT required
Things to look for :
What causes the supplier to be visible to the
client
Object Oriented Analysis and Design 45
Dependencies vs. Associations
Associations are structural
relationships
Dependencies are non-
structural relationships Supplier2
In order for objects to “know
each other” they must be visible
Local variable reference
Client
Parameter reference Dependency
Global reference
Field reference Association
Supplier1
Object Oriented Analysis and Design 46
Associations vs. Dependencies in Collaborations
An instance of an association is a link
All links become associations unless they have
global, local, or parameter visibility
Relationships are context-dependent
Dependencies are transient links with:
A limited duration
A context-independent relationship
A summary relationship
A dependency is a secondary type of relationship in that it doesn't tell
you much about the relationship. For details you need to consult the
collaborations.
Object Oriented Analysis and Design 47
Local Variable Visibility
The op1() operation contains a local
variable of type ClassB
Class Diagram Collaboration Diagram
ClassA :ClassA
+ op1 ( )
ClassB :ClassB
Object Oriented Analysis and Design 48
Parameter Visibility
The ClassB instance is passed to the
ClassA instance
Class Diagram Collaboration Diagram
ClassA :ClassA
+ op1 ( [in] aParam : ClassB )
ClassB :ClassB
Object Oriented Analysis and Design 49
Global Visibility
The ClassUtility instance is visible because
it is global
Class Diagram Collaboration Diagram
ClassA :ClassA
+ op1 ( )
ClassB :ClassB
+ utilityOp ( )
Object Oriented Analysis and Design 50
Identifying Dependencies: Considerations
Permanent relationships — Association (field visibility)
Transient relationships — Dependency
Multiple objects share the same instance
• Pass instance as a parameter (parameter visibility)
• Make instance a managed global (global visibility)
Multiple objects don’t share the same instance (local
visibility)
How long does it take to create/destroy?
Expensive? Use field, parameter, or global visibility
Strive for the lightest relationships possible
Object Oriented Analysis and Design 51
Example: Define Dependencies (before)
<<Control>> <<interface>>
RegistrationController ICourseCatalogSystem
0..* 1
+ // submit schedule () + courseCatalog + getCourseOfferings ( [in] forSemester : Semester) : CourseOfferingList
+ // save schedule ()
+ // create schedule with offerings ()
+ // get course offerings () <<entity>>
0..1 Schedule
0..1
+ currentSchedule - semester : Semester
0..1
+ submit ()
+ //save ()
+ registrant # any conflicts? ()
+ //create with offerings()
0..*
0..* 0..*
0..1 1 alternateCourses + primaryCourses
<<Entity>> 0..2 0..4
Student
<<Entity>>
CourseOffering
- name
- address
- StudentID : int - number : String = "100"
- startTime : Time
+ addSchedule ( [in] aSchedule : Schedule ) - endTime : Time
+ getSchedule ( [in] forSemester : Semester ) : Schedule - day : String
+ hasPrerequisites ( [in] forCourseOffering : CourseOffering ) : boolean
# passed ( [in] aCourseOffering : CourseOffering ) : boolean + addStudent ( [in] aStudentSchedule : Schedule)
+ removeStudent ( [in] aStudentSchedule : Schedule)
+ new ()
+ setData ()
Object Oriented Analysis and Design 52
Example: Define Dependencies (after)
<<Control>> <<interface>>
RegistrationController ICourseCatalogSystem
+ // submit schedule () + getCourseOfferings ( [in] forSemester : Semester) : CourseOfferingList
+ // save schedule ()
+ // create schedule with offerings ()
+ // get course offerings ()
Global visibility <<entity>>
0..1 Schedule
0..1
+ currentSchedule - semester : Semester
0..1
+ submit ()
+ //save ()
+ registrant
Field visibility # any conflicts? () Field
+ //create with offerings()
0..*
visibility
0..* 0..*
0..1 1 alternateCourses + primaryCourses
<<Entity>> 0..2 0..4
Student
<<Entity>>
CourseOffering
- name
- address
- StudentID : int - number : String = "100"
- startTime : Time
+ addSchedule ( [in] aSchedule : Schedule ) - endTime : Time
+ getSchedule ( [in] forSemester : Semester ) : Schedule - day : String
+ hasPrerequisites ( [in] forCourseOffering : CourseOffering ) : boolean
# passed ( [in] aCourseOffering : CourseOffering ) : boolean + addStudent ( [in] aStudentSchedule : Schedule)
+ removeStudent ( [in] aStudentSchedule : Schedule)
+ new ()
+ setData ()
Parameter visibility
Object Oriented Analysis and Design 53
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 54
Define Associations
Purpose
Refine remaining associations
Things to look for :
Association vs. Aggregation
Aggregation vs. Composition
Attribute vs. Association
Navigability
Association class design
Multiplicity design
Object Oriented Analysis and Design 55
What Is Composition?
A form of aggregation with strong
ownership and coincident lifetimes
The parts cannot survive the whole/aggregate
Whole Part
Whole Part
Composition
Object Oriented Analysis and Design 56
Aggregation: Shared vs. Non-shared
Shared Aggregation
Multiplicity > 1
Whole 1..* 0..* Part
Non-shared Aggregation
Multiplicity = 1 Multiplicity = 1
Whole 1 0..* Part Whole 1 0..* Part
Composition
By definition, composition is non-shared aggregation
Object Oriented Analysis and Design 57
Aggregation or Composition?
Consideration
Lifetimes of Class1 and Class2
Class1 Class2
aggregation
Class1 Class2
composition
Object Oriented Analysis and Design 58
Example: Composition
Student 1 Schedule
0..*
RegisterForCoursesForm 1 RegistrationController
1
Object Oriented Analysis and Design 59
Attributes Vs Composition
Use composition when
Properties need independent identities
Multiple classes have the same properties
Properties have a complex structure and
properties of their own
Properties have complex behavior of their own
Properties have relationships of their own
Otherwise use attributes
Object Oriented Analysis and Design 60
Example: Attributes vs. Composition
Attribute
<<entity>>
Student <<entity>>
- name Schedule
- address - semester : Semester
- nextAvailID : int
1 + submit ()
- StudentID : int
- dateofBirth : Date + //save ()
0..*
# any conflicts? ()
+ addSchedule () + //create with offerings ()
+ getSchedule () + new ()
+ delete Schedule () Composition of + passed ()
+ hasPrerequisites ()
separate class
# hasPassed ()
Object Oriented Analysis and Design 61
Review: What Is Navigability?
Indicates that it is possible to navigate from
a associating class to the target class using
the association
<<Control>>
RegistrationController
<<Entity>> <<Entity>>
Schedule CourseOffering
Object Oriented Analysis and Design 62
Navigability: Which Directions Are Really Needed?
Explore interaction diagrams
Even when both directions seem required, one
may work
Navigability in one direction is infrequent
Number of instances of one class is small
<<Entity>> <<Entity>>
Schedule + primaryCourses CourseOffering
0..* 0..4
?
<<Entity>> <<Entity>> <<Entity>> <<Entity>>
Schedule + primaryCourses CourseOffering Schedule + primaryCourses CourseOffering
0..* 0..4 0..* 0..4
Object Oriented Analysis and Design 63
Example: Navigability Refinement
Total number of Schedules
is small, or <<Entity>> <<Entity>>
+ primaryCourses CourseOffering
Never need a list of the Schedule
Schedules on which the 0..* 0..4
CourseOffering appears
Total number of
CourseOfferings is small, or <<Entity>> <<Entity>>
Schedule + primaryCourses CourseOffering
Never need a list of
CourseOfferings on a 0..* 0..4
Schedule
Total number of
CourseOfferings and <<Entity>> <<Entity>>
Schedules are not small Schedule + primaryCourses CourseOffering
Must be able to navigate in 0..* 0..4
both directions
Object Oriented Analysis and Design 64
Association Class
A class is <<Entity>>
“attached” to an
ScheduleOfferingInfo
- status
association + // is selected ()
+ // mark as selected ()
Contains
+ // mark as cancelled ()
properties of a + alternateCourses
0..2
relationship <<Entity>>
Schedule
0..*
+ primaryCourses
<<Entity>>
CourseOffering
Has one 0..*
0..4
instance per link
<<Entity>>
PrimaryScheduleOfferingInfob
- grade
+ // is enrolled in? ()
+ // mark as enrolled in ()
+ // mark as committed ()
Object Oriented Analysis and Design 65
Example: Association Class Design
+ alternateCourses
0..* 0..2
<<Entity>> <<Entity>>
Schedule CourseOffering
+ primaryCourses
0..*
0..4
<<Entity>>
PrimaryScheduleOfferingInfob
- grade
+ // is enrolled in? ()
+ // mark as enrolled in ()
+ // mark as committed ()
Design Decisions
<<Entity>> 0..* + alternateCourses 0..2
<<Entity>>
Schedule CourseOffering
1 1
- theCourseOffering 0..*
0..4
- primaryCourseOfferingInfo <<Entity>>
PrimaryScheduleOfferingInfob
- grade
+ // is enrolled in? ()
+ // mark as enrolled in ()
+ // mark as committed ()
Object Oriented Analysis and Design 66
Multiplicity Design
Multiplicity = 1, or Multiplicity = 0..1
May be implemented directly as a simple
value or pointer
No further “design” is required
<<Entity>> <<Entity>>
Professor 0..1 0..* CourseOffering
+ Instructor
Multiplicity > 1
Cannot use a simple value or pointer
Further “design” may be required
Needs a <<Entity>> <<Entity>>
container for Professor 0..1 0..* CourseOffering
CourseOfferings + Instructor
Object Oriented Analysis and Design 67
Multiplicity Design Options
<<Entity>> <<Entity>>
Professor 0..1 0..* CourseOffering
+ Instructor
Explicit Modeling of a Container Class Detail Container via Note
<<Entity>>
Professor 0..1 0..* CourseOfferingList
List
+ Instructor
<<Entity>> <<Entity>> <<Entity>>
CourseOffering Professor 0..1 0..* CourseOffering
+ Instructor
Object Oriented Analysis and Design 68
What is a Parameterized Class (template)?
A class definition that defines other classes
Often used for container classes
Some common container classes:
• Sets, lists, dictionaries, stacks, queues
Formal Arguments Item
ParameterizedClass List
Object Oriented Analysis and Design 69
Instantiating a Parameterized Class
Formal Arguments
ParameterizedClass
<<bind>> (ActualArgument)
InstantiatedClass ActualArgument
Object Oriented Analysis and Design 70
Example: Instantiating a Parameterized Class
Before 1 <<Entity>>
CourseOfferingList CourseOffering
0..*
After Item
List
<<bind>> (CourseOffering)
1 <<Entity>>
CourseOfferingList ActualArgument
0..*
Object Oriented Analysis and Design 71
Multiplicity Design: Optionality
If a link is optional, make sure to include an
operation to test for the existence of the link
Professor 0..1 CourseOffering
0..*
+ isTeaching () : boolean + hasProfessor () : boolean
Object Oriented Analysis and Design 72
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods Light
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 73
Review: Generalization
One class shares Account
the structure and/or Superclass
+ balance
+ name
behavior of one or (Parent) + number
more classes (Ancestor) + withdraw ()
+ createStatement ()
“Is a kind of”
relationship
Generalization
In Analysis, use Relationship
sparingly
Checking Savings
+ getInterest ()
Subclasses
(Child)
(Descendants)
Object Oriented Analysis and Design 74
Abstract and Concrete Classes
Abstract classes cannot have any objects
Concrete classes can have objects
Discriminator Animal Abstract class
+ communicate () Abstract operation
Communication There are no direct instances of Animal
Lion Tiger
+ communicate () + communicate ()
All objects are either lions or tigers
Object Oriented Analysis and Design 75
Multiple Inheritance: Problems
Name clashes on
attributes or operations Repeated inheritance
AnimateObject
Animal FlyingThing
+ color + color
+ getColor () + getColor () Animal FlyingThing
+ color + color
+ getColor () + getColor ()
Bird
Bird
Resolution of these problems is implementation-dependent
Object Oriented Analysis and Design 76
Generalization Constraints
Complete
End of the inheritance tree
Incomplete
Inheritance tree may be extended
Disjoint
Subclasses mutually exclusive
Doesn’t support multiple inheritance
Overlapping
Subclasses are not mutually exclusive
Supports multiple inheritance
Object Oriented Analysis and Design 77
Example: Generalization Constraints
Asset Multiple
Inheritance
not supported
{disjoint}
Bank Account Real Estate Security
{disjoint,complete} {disjoint}
Stock Bond
Savings Checking
End of inheritance hierarchy
Object Oriented Analysis and Design 78
Example: Generalization Constraints (cont.)
Multiple Vehicle
inheritance
supported
{overlapping}
LandVehicle WaterVehicle
AmphibiousVehicle
Object Oriented Analysis and Design 79
Generalization vs. Aggregation
Generalization and aggregation are often
confused
Generalization represents an “is a” or “kind-of”
relationship
Aggregation represents a “part-of” relationship
Window Scrollbar
Is this correct?
WindowWithScrollbar
Object Oriented Analysis and Design 80
Generalization vs. Aggregation
Window Scrollbar
WindowWithScrollbar
Window A WindowWithScrollbar “is a” Window
A WindowWithScrollbar “contains a” Scrollbar
1
WindowWithScrollbar Scrollbar
1
Object Oriented Analysis and Design 81
Generalization: Share Common Properties and Behavior
Follows the “is a” style of programming
Class substitutability
Animal List
+ communicate () + insertTop ([in] item)
+ insertBottom ([in] item)
+ removeTop ()
+ removeBottom ()
+ insert ([in] item, [in] position)
Lion Tiger
Stack
+ communicate () + communicate ()
Do these classes follow the “is a” style of programming?
Object Oriented Analysis and Design 82
Generalization: Share Common Properties and Behavior (cont.)
Animal List
+ communicate () + insertTop ([in] item)
+ insertBottom ([in] item)
+ removeTop ()
+ removeBottom ()
+ insert ([in] item, [in] position)
Lion Tiger
Stack
+ communicate () + communicate ()
Object Oriented Analysis and Design 83
Generalization: Share Implementation: Factoring
Supports the reuse of the implementation of
another class
Cannot be used if the class you want to
“reuse” cannot be changed
List SequentialContainer
+ insertTop ([in] item) + insertTop ([in] item)
+ insertBottom ([in] item) + removeTop ()
+ removeTop ()
+ removeBottom ()
+ insert ([in] item, [in] position)
Stack List
Stack + insertBottom ([in] item)
+ removeBottom ()
+ insert ([in] item, [in] position)
Object Oriented Analysis and Design 84
Generalization Alternative: Share Implementation: Delegation
Supports the reuse of the implementation of
another class
Can be used if the class you want to “reuse”
cannot be changed
List Stack
+ insertTop ([in] item) + insertBottom ([in] item)
+ insertBottom ([in] item) + removeBottom ()
+ removeTop () + insert ([in] item, [in] position)
+ removeBottom ()
+ insert ([in] item, [in] position) 1
1
Stack List
Object Oriented Analysis and Design 85
Implementation Inheritance
Ancestor public List
operations, attributes, + insertTop ([in] item)
and relationships are + insertBottom ([in] item)
+ removeTop ()
NOT visible to clients + removeBottom ()
+ insert ([in] item, [in] position)
of descendent class
instances
Descendent class
<<implementation>>
must define all access Stack
to ancestor
operations, attributes, push() and pop() can access
and relationships methods of List but instances
of Stack cannot
Object Oriented Analysis and Design 86
Review: What Is Polymorphism?
The ability to hide many different
implementations behind a single interface
Manufacturer B
Manufacturer A Manufacturer C
OO Principle:
Encapsulation
Object Oriented Analysis and Design 87
Generalization: Implement Polymorphism
Animal
+ communicate ()
Lion Tiger
+ communicate () + communicate ()
Without Polymorphism With Polymorphism
if animal = “Lion” then Animal communicate
Lion communicate
else if animal = “Tiger” then
Tiger communicate
end
Object Oriented Analysis and Design 88
Polymorphism: Use of Interfaces vs. Generalization
Interfaces support implementation-independent
representation of polymorphism
Realization relationships can cross generalization
hierarchies
Interfaces are pure specifications, no behavior
Abstract base class may define attributes and
associations
Interfaces are totally independent of inheritance
Generalization is used to re-use implementations
Interfaces are used to re-use behavioral specifications
Generalization provides a way to implement
polymorphism
Object Oriented Analysis and Design 89
Polymorphism via Generalization Design Decisions
Provide interface only to descendant classes?
Design ancestor as an abstract class
All methods are provided by descendent classes
Provide interface and default behavior to
descendent classes?
Design ancestor as a concrete class with a default
method
Allow polymorphic operations
Provide interface and mandatory behavior to
descendent classes?
Design ancestor as a concrete class
Do not allow polymorphic operations
Object Oriented Analysis and Design 90
What Is Metamorphosis?
Metamorphosis
1. A change in form, structure, or function;
specifically the physical change undergone by
some animals, as of the tadpole to the frog.
2. Any marked change, as in character,
appearance, or condition.
~ Webster’s New World Dictionary, Simon &
Schuster, Inc., 1979
Metamorphosis exists in the real world.
How should it be modeled?
Object Oriented Analysis and Design 91
Example: Metamorphosis
In the university, there are full-time students and
part-time students
Full-time students have an expected graduation date
but part-time students do not
Part-time students may take a maximum of three
courses but there is no maximum for full-time students
PartTimeStudent FullTimeStudent
+ name + name
+ address + address
+ studentID + studentID
+ maxNumCourses + gradDate
Object Oriented Analysis and Design 92
Modeling Metamorphosis: One Approach
A generalization relationship may be created
What happens if a Student
part-time student + name
+ address
becomes a full-time + studentID
student?
PartTimeStudent FullTimeStudent
+ maxNumCourses + gradDate
Object Oriented Analysis and Design 93
Modeling Metamorphosis: Another Approach
Inheritance may be used to model common
structure, behavior, and/or relationships to
the “changing” parts
Student Student
+ name + name 1
Classification
+ address + address
+ studentID + studentID 1
PartTimeStudent FullTimeStudent PartTimeClassification FullTimeClassification
+ maxNumCourses + gradDate + maxNumCourses + gradDate
Object Oriented Analysis and Design 94
Modeling Metamorphosis: Another Approach (cont.)
Metamorphosis is accomplished by the object
“talking” to the changing parts
: StudentManager : Student : PartTimeClassification : FullTimeClassification
1 : \changeToFullTime\
2 : \delete\
3 : \create\
Object Oriented Analysis and Design 95
Metamorphosis and Flexibility
This technique also adds to the flexibility of the
model
ResidentInformation Student
+ dorm 0..1 + name 1
+ room + address Classification
+ roomKeyID + studentID
1 1
studentID
ParttimeClassification FulltimeClassification
+ maxNumCourses + gradDate
Object Oriented Analysis and Design 96
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 97
Resolve Use-Case Collisions
Multiple use cases may simultaneously access
design objects
Options
Use synchronous messaging => first-come first-
serve order processing
Identify operations (or code) to protect
Apply access control mechanisms
• Message queuing
• Semaphores (or “tokens”)
• Other locking mechanism
Resolution is highly dependent on implementation
environment
Object Oriented Analysis and Design 98
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 99
Handle Non-Functional Requirements in General
Analysis Class Analysis Mechanism(s)
Student Persistency, Security
Schedule Persistency, Security
CourseOffering Persistency, Legacy Interface
Course Persistency, Legacy Interface
RegistrationController Distribution
Analysis Design Implementation
Mechanism Mechanism Mechanism
(Conceptual) (Concrete) (Actual)
Legacy
Persistency JDBC
Data
SomeDesignClass
RDBMS
New
Persistency ObjectStore
Data
Design
OODBMS
Guidelines
Remote Method
Distribution Java 1.2 from Sun
Invocation (RMI)
Analysis Design Implementation
Object Oriented Analysis and Design 100
Class Design Steps
Create Initial Design Classes
Define Operations
Define Methods
Define States
Define Attributes
Define Dependencies
Define Associations
Define Generalizations
Resolve Use-Case Collisions
Handle Non-Functional Requirements in General
Checkpoints
Object Oriented Analysis and Design 101
Checkpoints: Classes
Clear class names
One well-defined abstraction
Functionally coupled attributes/behavior
Generalizations were made.
All class requirements were addressed
Demands are consistent with statecharts.
Complete class instance life cycle is described.
The class has the required behavior.
Object Oriented Analysis and Design 102
Checkpoints: Operations
Operations are easily understood
State description is correct
Required behavior is offered
Parameters are defined correctly
Messages are completely assigned operations
Implementation specifications are correct
Signatures conform to standards
All operations are needed by Use-Case
Realizations
Object Oriented Analysis and Design 103
Checkpoints: Attributes
A single concept
Descriptive names
All attributes are needed by Use-
Case Realizations
Object Oriented Analysis and Design 104
Checkpoints: Relationships
Descriptive role names
Correct multiplicities
Object Oriented Analysis and Design 105
Review: Class Design
What is the purpose of Class Design?
In what ways are classes refined?
Are statecharts created for every class?
What are the major components of a
statechart? Provide a brief description of
each.
What kind of relationship refinements occur?
What is the difference between an
association and a dependency?
What is done with operations and attributes?
Object Oriented Analysis and Design 106
Exercise 2: Class Design
Given the following:
The Use-Case Realization for a use
case and/or the detailed design of a
subsystem
The design of all participating design
elements
(continued)
Object Oriented Analysis and Design 107
Exercise 2: Class Design (cont.)
Identify the following:
The required navigability for each
relationship
Any additional classes to support the
relationship design
Any associations refined into
dependencies
Any associations refined into
aggregations or compositions
Any refinements to multiplicity
Any refinements to existing
generalizations
Any new applications of generalization
• Make sure any metamorphosis is
considered (continued)
Object Oriented Analysis and Design 108
Exercise 2: Class Design (cont.)
Produce the following:
An updated VOPC, including the
relationship refinements
(generalization, dependency,
association)
(continued)
Object Oriented Analysis and Design 109
Exercise 2: Review
Compare your results
Do your dependencies represent
context independent
relationships?
Are the multiplicities on the
relationships correct?
Does the inheritance structure
capture common design
Payroll System
abstractions, and not
implementation considerations?
Is the obvious commonality
reflected in the inheritance
hierarchy?
Object Oriented Analysis and Design 110