Product Design Product Design
Object-Oriented analysis and design Object-Oriented analysis and design
Copyright Copyright ©© 2005 Reich 2005 Reich
Prof. Yoram ReichProf. Yoram ReichSchool of Mechanical EngineeringSchool of Mechanical Engineering
Faculty of EngineeringFaculty of EngineeringTel Aviv UniversityTel Aviv University
This presentation includes This presentation includes material copyrighted by material copyrighted by
others. Please do not others. Please do not distribute.distribute.
Copyright © 2003-2005 Yoram Reich 2
Origin of OO and the way we practice it today
A response of the software industry to manage complex software projects
Several methods emerged and consolidated into a standard: UML – Uniform Modeling Language
New contenders: OPM – Object Process Methodology …
Copyright © 2003-2005 Yoram Reich 3
Object
An object has a label and attributes There are methods that can be done on objects There is an interface between the object and the world
outside it that allows executing the methods Examples:
A point A bicycle
An object in the real world is complex An object in OO analysis is a model that includes what is
necessary for our task
Copyright © 2003-2005 Yoram Reich 4
Class
A description of a scheme that describes objects – “type” Examples:
Point class Bicycle class Polygon objects
A class is not a set of objects Object creation from a class - instantiation
abstract
Polygon classAttributes
VerticesBorder colorFill colorFill pattern
OperationsDrawEraseMove
Copyright © 2003-2005 Yoram Reich 5
Class: Visibility Prefixes
UML visibility prefixes (used for information hiding) Prefix + indicates that an attribute or operation is public
Visible everywhere Prefix – denotes that the attribute or operation is private
Visible only in the class in which it is defined Prefix # denotes that the attribute or operation is protected
Visible either within the class in which it is defined or within subclasses of that class
Example: Class diagram with visibility prefixes added
Bank Account Class
- accountBalance
+ deposit( )+ withdraw( )
Attribute accountBalance is visible only within the Bank Account Class
Operations deposit and withdraw are accessible from anywhere within the software product
Copyright © 2003-2005 Yoram Reich 7
Class hierarchy and Inheritance
Polymorphic method/operation: This method will be called the same in different objects but might be implemented differently. Helps understanding and ease of references.
Copyright © 2003-2005 Yoram Reich 9
Concrete and abstract classes
This method will be called the same in different objects but might be implemented differently. Helps understanding and ease of references.
Serves to structure the problem but is not implemented.
Implemented in the final system.
Copyright © 2003-2005 Yoram Reich 10
Aggregation
Example: “A car consists of a chassis, an engine, wheels, and seats”
The open diamonds denote aggregation Aggregation means part–whole relationship
The diamond is placed at the “whole” (car) end, not the “part” (chassis, engine, wheels, or seats) end of the line connecting a part to the whole
Copyright © 2003-2005 Yoram Reich 12
Composition Aggregation example: Every chess board consists of 64 squares
This relationship goes further It is an instance of composition, a stronger form of aggregation
Aggregation Models the part–whole relationship
Composition Also models the part–whole relationship but, in addition, Every part may belong to only one whole, and If the whole is deleted, so are the parts
Example: A number of different chess boards Each square belongs to only one board If a chess board is thrown away, all 64 squares on that board go as well
Composition is depicted by a solid diamond
Copyright © 2003-2005 Yoram Reich 14
Association: from objects to classes
Bounded by
2
(Line) L1
L1L5
L4
L3
L2
P1
P2
(Line) L5
(Line) L4
(Line) L3
(Line) L2 (Point) P1
(Point) P2
Line
name
Point
name2+
intersects
Instancediagram
Sampledata
Classdiagram
Copyright © 2003-2005 Yoram Reich 15
Association as a class
An example of association:
A radiologist consults a lawyer The optional navigation triangle shows the direction of the
association
The association between the two classes may be modeled as a class Example: Suppose the radiologist consults the lawyer on a number
of occasions, each one for a different length of time A class diagram is needed such as that depicted in the next slide
Copyright © 2003-2005 Yoram Reich 18
Class diagram windowing system +display()
+undisplay()+raise()+lower()
-x1 : double-y1 : double-x2 : double-y2 : double
window
+scroll()
-x-offset-y-offset
scrolling window
+add-element()+delete-element()
-cx1-cy1-cx2-cy2
canvas
+insert()+delete()
-string
text window
-item_name
panel
-fill_color-fill_pattern
closed shape
-x-y-label
panel item
+draw()
-x1-x2-y1-y2
line
scrolling canvas
-color-line_width
shape
-x-y
point
+draw()
polygon
+draw()
-x-y-a-b
ellipse
1-vertices3..*
-window1-elements*
1
*
-string-depressed
button choice item
-max_length-current_string
text item
-string-value
choice entry
1
-choices*cur choice
1
*
+display()+undisplay()+raise()+lower()
-p1 : point-p2 : point
window alternativeRight now window is defined by 2 points explicitly: (x1,y1), (x2,y2). An alternative definition is that it would be defined by two points whose type is of point type. In this case, it makes sense to connect the point and window alternative classes by an aggregation link.
Copyright © 2003-2005 Yoram Reich 20
Object Oriented analysis and design ( ( עצמיםמונחהמידול Key properties
Modularity – מודולריותקיבוץ חלקים למכלולים בלתי תלויים אחד בשני
Abstraction – הפשטה /Generalization– הכללהתאור העצמים ע"י היררכיההתמקדות בדברים עיקריים
Encapsulation – הכמסההפרדה בין תכונות להתנהגות החיצונית והפנימית
Inheritance – ירושה .תת מחלקה יורשת את כל הדברים של מחלקת העל.כל עצם שמיוצר ממחלקה לוקח איתו את כל הפעולות והתכונות מאותה מחלקה
Overloading – העמסת יתר כשמגיעים למטה למחלקות שמתארות עצמים קיימים, יש לפרט מה הפונקציה עושה. למשל איך
לעשות את כל הנקודות ברדיוס מסוים. – של מעגל? Displayעושים -לכן נתן משמעות אחרת לאותה פונקציה בהתאם לעצם שאליו היא מודבקת. בדוגמא הDisplay
. במילים אחרות Displayמציגה אלמנט גיאומטרי כללי ובכל עצם ועצם מרחיבים את המושג העמסת יתר זה שעל אותו שם מעמיסים הרבה מובנים. העמסה מתקשרת לירושה: לכל העצמים
אך כל אחד מהעצמים מישם זאת אחרת.Displayהגרפיים יש אפשרות ל-Aggregation– איסוף
קשר המעיד על יחס של הכלה בין שני עצמים. כאשר הירושה אינה מתאימה בצורה מדויקתהאגריגציה יכולה לספק במקרה זה פתרון חזק יותר, וזאת מפני שאגרגציה עושה שימוש בעצמים
מלאים והמוכלים בעצמם כך שהם אינם מציגים שום נושאים חדשים אשר יתכן ולא יעמדו במבחן
Copyright © 2003-2005 Yoram Reich 21
UML – Uniform Modeling Language
The standard notation for drawing OO diagrams Consist of several diagrams:
Structured aspect: Use cases diagram Static diagram – Class diagramStatic diagram – Class diagram
Dynamic aspect Interaction diagrams
• Sequence diagram• Collaboration diagram
State diagram Implementation aspect
Package diagram Component diagram Deployment diagram
Copyright © 2003-2005 Yoram Reich 23
CRC (Class Responsibility Collaborators) cards
A social process in which project participants work with scenarios and 3x5 in cards to identify classes, their responsibility in different scenarios and their class collaborators
The cards merely support quick addition/removal/modification of classes as well as their interaction with respect to different scenarios
Reminiscent of brainstorming (e.g., deep dive)
Copyright © 2003-2005 Yoram Reich 26
Use-Case Diagrams
A use case is a model of the interaction between External users of a product (actors) and The product itself
More precisely, an actor is a user playing a specific role
A use-case diagram is a set of use cases Generalization of actors is supported
The open triangle points toward the more general case
Copyright © 2003-2005 Yoram Reich 27
Stereotypes
A stereotype in UML is a way of extending UML There could be numerous stereotypes:
The «include» stereotype The names of stereotypes appear between guillemets
Example: «This is my own construct» Example:
All three primary U.S. tax forms need to be printed The other three use cases incorporate Print Tax Form
Copyright © 2003-2005 Yoram Reich 28
Stereotypes (continued)
In the «extend» relationship, one use case is a variation of the standard use case
Stereotypes support reusability
generalization
Copyright © 2003-2005 Yoram Reich 30
Interaction Diagrams
Interaction diagrams show how objects interact with one another
UML supports two types of interaction diagrams Sequence diagrams Collaboration diagrams
Copyright © 2003-2005 Yoram Reich 31
Sequence Diagrams A message is optionally followed by a message sent
back to the object that sent the original message Even if there is a reply, it is not necessary that a
specific new message be sent back Instead, a dashed line ending in an open
arrow indicates a return from the original message, as opposed to a new message
Iteration an indeterminate number of times is modeled by an asterisk (Kleene star)
Example: Elevator *move up one floor The message means: “move up zero or
more floors”
An object can send message to self A self-call
Example: The elevator has arrived at a floor The elevator doors open and a timer starts At the end of the timer period the doors close again The elevator controller sends a message to itself to start its timer — this self-
call is shown in the UML diagram
Copyright © 2003-2005 Yoram Reich 32
Collaboration Diagrams
Collaboration diagrams are equivalent to sequence diagrams All the features of sequence diagrams are equally
applicable to collaboration diagrams
Use a sequence diagram when the transfer of information (and not timing) is the focus of attention
Use a collaboration diagram when concentrating on the classes
Copyright © 2003-2005 Yoram Reich 33
Collaboration Diagrams
Object: The objects interacting with each other in the system. Messages: An arrow pointing from the commencing object to the destination
object shows the interaction between the objects. The number represents the order/sequence of this interaction.
Relation/ association from class diagram
Copyright © 2003-2005 Yoram Reich 34
Statecharts
An event also causes transitions between states
Example: The receipt of a message
The elevator is in state Elevator Moving It performs an operation: Move up one floor
while guard [no message received yet] is true, until it receives message Elevator has arrived at floor
Receipt of this message [event] causes the guard to be false It also enables a transition to state Stopped at Floor
In this state, performs activity Open the elevator doors
Copyright © 2003-2005 Yoram Reich 35
Statecharts
There are two places where an operation can be performed in a statechart
When a state is entered Activity
As part of a transition Action
Technical difference: An activity can take several seconds An action takes places essentially instantaneously
An event can be specified in terms of words like “when” or “after”
Example: when (cost > 1000) or after (2.5 seconds)
Copyright © 2003-2005 Yoram Reich 36
Statecharts
Superstates combine related states
States A, B, C, and D all have transitions to Next State Combine them into superstate ABCD Combined
Now there is only one transition The number of arrows is reduced from four to only one
States A, B, C, and D all still exist in their own right
Copyright © 2003-2005 Yoram Reich 38
Steps of OOA (Object Oriented Analysis)1. Use-case modeling
Determine how the product is used (without regard to sequencing)2. Class modeling (“object modeling”)
Determine the classes, their attributes and the interrelationships Purely data-oriented
3. Dynamic modeling Determine the actions performed by or to each class Purely action-oriented
Iterative process
Copyright © 2003-2005 Yoram Reich 39
Elevator Problem: OOA
1. Use-Case Modeling Use case: Generic description of overall functionality
Scenario: Instance of a use case Get comprehensive insight into behavior of product
Copyright © 2003-2005 Yoram Reich 42
Class Modeling
Extract classes and their attributes Represent them using an class diagram Deduce the classes from use cases and their scenarios Often there are many scenarios
Possible danger: too many candidate classes
Copyright © 2003-2005 Yoram Reich 43
Two Approaches to Class Modeling
Noun extraction Always works
CRC classes Need to have domain expertise
Copyright © 2003-2005 Yoram Reich 44
Noun Extraction
Stage 1. Concise Problem Definition Define product in single sentence
Buttons in elevators and on the floors control the motion of n elevators in a building with m floors.
Stage 2. Informal Strategy Incorporate constraints, express result in a single
paragraph Buttons in elevators and on the floors control movement of n elevators
in a building with m floors. Buttons illuminate when pressed to request the elevator to stop at a specific floor; illumination is canceled when the request has been satisfied. When an elevator has no requests, it remains at its current floor with its doors closed.
See how the sentence in stage 1 transformed itself into the paragraph in stage 2.
Copyright © 2003-2005 Yoram Reich 45
Noun Extraction (cont)
Stage 3. Formalize the Strategy Identify nouns in informal strategy. Use nouns as candidate classes
Buttons in elevators and on the floors control movement of n elevators in a building with m floors. Buttons illuminate when pressed to request the elevator to stop at a specific floor; illumination is canceled when the request has been satisfied. When an elevator has no requests, it remains at its current floor with its doors closed.
Nouns
button, elevator, floor, movement, building, illumination, request, door floor, building, door are outside problem boundary — exclude movement, illumination, request are abstract nouns — exclude (may
become attributes or other things) Candidate classes: Elevator and Button Subclasses: Elevator Button and Floor Button
Copyright © 2003-2005 Yoram Reich 46
First Iteration of Class Diagram
Problem Buttons do not communicate directly with elevators We need an additional class: Elevator Controller
Copyright © 2003-2005 Yoram Reich 47
Second Iteration of Class Diagram
All relationships are now 1-to-n Makes design and
implementation easier (makes system operation less
robust – everything depends on one controller)
Copyright © 2003-2005 Yoram Reich 48
CRC Cards
Used since 1989 for OOA For each class, fill in card showing
Name of Class Functionality (Responsibility) List of classes it invokes (Collaboration) Now automated (CASE tool component) – but this looses its flexibility
Strength When acted out by team members, powerful tool for highlighting
missing or incorrect items Weakness
Domain expertise is needed
Copyright © 2003-2005 Yoram Reich 49
Dynamic Modeling
Produce UML state diagram State, event, predicate
distributed over state diagram UML “guards” are in
brackets
Nothing happens. The button is already lit, so pushing it does not change anything
The elevator moves in the direction of the floor. A check is done and based on it, the controller responses. If a stop was requested, stop at floor and subsequently continue.
Syntax of links: [action, present state]e.g., [button pushed, button unlit]
Copyright © 2003-2005 Yoram Reich 50
Testing during the OOA Phase
CRC cards are an excellent testing technique
Collected from previous steps
Bold letters specify the classes
Copyright © 2003-2005 Yoram Reich 51
CRC Cards
Consider responsibility1. Turn on elevator button
Totally unacceptable for object-oriented paradigm Responsibility-driven design ignored Information hiding ignored (how would I know how to turn it on?)
Responsibility 1.Turn on elevator button
should be1. Send message to Elevator Button to turn itself on
Copyright © 2003-2005 Yoram Reich 52
CRC Cards (cont)
A class has been overlooked Elevator doors have a state that changes during
execution (class characteristic) Add class Elevator Doors
Reconsider class model Then reconsider dynamic model,
use-case model
Once the class elevator doors is added, it will have to get its own state diagram (each class has one for itself). We now have one state change from this: transition from closed doors to open doors
Copyright © 2003-2005 Yoram Reich 53
Second Iteration of CRC Card
Bold letters specify the classes now also in the responsibility part
Copyright © 2003-2005 Yoram Reich 55
Second Iteration of Normal Scenario
Previous version. Notice the differences with the new version to the left.
Copyright © 2003-2005 Yoram Reich 57
Elevator Problem: Collaboration diagram
The messages that are passed between objects must be addressed later in the design.
Each such message should get an action in the receiving class to allow it to respond to this message.
Copyright © 2003-2005 Yoram Reich 58
Elevator Problem: Construct Detailed Class Diagram
To which class do we assign an action? Criteria
Information hiding Responsibility-driven design
Examples“close doors” is assigned to Elevator Doors“move one floor down” is assigned to Elevator
Copyright © 2003-2005 Yoram Reich 59
Elevator Problem: Detailed class diagram
nm
These actions address the messages passed to the button to lit or unlit itself. Here they are abstract actions.
Actions inherited and given concrete meaning to address messages 10 and 13 in the collaboration and sequence diagrams
Compare these action with the actions mentioned in the dynamic modeling (state diagram)
Copyright © 2003-2005 Yoram Reich 60
Elevator Problem: OOA (cont)
All three models (class, sequence, and collaboration) are now fine
We should rather say: All three models are fine for now
We may need to return to the object-oriented analysis phase during subsequent design and implementation stages
Copyright © 2003-2005 Yoram Reich 61
Elevator Problem
A 2nd example of more complicated design The solution is provided with less details
Copyright © 2003-2005 Yoram Reich 63
Elevator example: Use case diagram
Process Car Calls: This use case includes several scenarios, which will be described in detail in later sections of this paper. These scenarios includes that the elevator receives car calls from the passengers, turns on or turns off the light of car call buttons, updates the record of car calls stored in system controlling parts, etc.
Process Hall Calls: Similar to Car Call processing, this use case includes that the elevator receives hall calls from the passengers, turns on or turns off the light of hall call buttons, updates the record of hall calls in system controlling parts, etc.
Move/Stop the Car: The main function of an elevator, detailed action will include the changing of driving speed, how to make the decision of stop, and driving directions of the car.
Indicating Moving Direction: The elevator should have this mechanism to let the passengers know the current moving direction of the car such that the passenger might decide whether to enter the car or not.
Indicating Car Position: Similarly, the elevator should let the passengers know whether his/her destination floor is reached so that the passenger may decide to leave the car.
Open/Close the Doors: The elevator should be able to open and close the doors for the passengers to get in and out of the car. The functional areas of this use case should also enable the passengers to make door reversals when the doors are closing and the passenger wants to get in the car.
Trigger Emergency Brake: There is safety mechanism within the car to make sure that an unsafe state is not transiently generated.
Copyright © 2003-2005 Yoram Reich 64
Elevator example: Class diagram
Was not present before
Was not present before
Was not present before
Was not present before
Copyright © 2003-2005 Yoram Reich 65
Elevator example: Class diagram
Problems: Overburdening central object: ElevetorControl Most other objects are idle most of the time Competition over computing resources for controlling
multiple objects (several elevators) Low overall system efficiency
Addition of control objects – distributed control
Copyright © 2003-2005 Yoram Reich 80
name : CString Course
description : CString creditHours : short timeOfDay location
create( ) getCourseInfo( ) save( ) getCourseNumber( ) getName( ) getDescription( ) getTimeOfDay( ) getLocation( ) getProfessor( )
Copyright © 2003-2005 Yoram Reich 81
save( )
teaches
untitled( )
submit( )
RegistrationForm
phone
3..10 RegistrationUser
name
address IDNumber
(from People) CourseOffering
ddaysOffered timeOfDay location
addStudent( ) addProfessor( ) isFull( )
4 registersFor
4
CourseMaintenanceForm
verifyID( )
setID( ) createCourse( ) setCourseInfo( )
close( )
(from Interfaces) Add/Drop (from Interfaces)
primar
0..*
CourseSelection (from Interfaces)
alternat
(from Interfaces)
NewCourseForm
Set name( ) Set description( ) Set time and day( ) Set location( ) Set professor( )
(from Interfaces)
Curriculum
Course name : CString description : CString creditHours : short timeOfDay location
create( ) getCourseInfo( )
getCourseNumber( ) getName( ) getDescription( ) getTimeOfDay( ) getLocation( ) getProfessor( )
1..*
1 1 1
0..*
4 1..4
2
1
Copyright © 2003-2005 Yoram Reich 82
Stereotypes (continued)
Example: A separate use case to model the situation of the potential seller of a painting turning down Osbert’s offer
Copyright © 2003-2005 Yoram Reich 83
Sequence Diagrams
Example: Dynamic creation followed
by destruction of an object lifelines in the sequence
diagram An active object is denoted
by a thin rectangle (activation box) in place of the dashed line
Creation of the : Masterpiece Class object is denoted by the lifeline starting at the point of dynamic creation
Destruction of that object after it receives message denoted by heavy X 9: Destroy object
Copyright © 2003-2005 Yoram Reich 84
Sequence Diagrams
A message is optionally followed by a message sent back to the object that sent the original message
Even if there is a reply, it is not necessary that a specific new message be sent back
Instead, a dashed line ending in an open arrow indicates a return from the original message, as opposed to a new message
There is a guard on the message 9: [offer rejected] Destroy object
Only if Osbert’s offer is rejected is message 9 sent A guard (condition) is something that is true or false
The message sent only if the guard is true The purpose of a guard
To ensure that the message is sent only if the relevant condition is true
Copyright © 2003-2005 Yoram Reich 87
Statecharts
An event also causes transitions between states
Example: The receipt of a message
The elevator is in state Elevator Moving It performs operation
Move up one floor
while guard [no message received yet] is true, until it receives message Elevator has arrived at floor
Receipt of this message [event] causes the guard to be false It also enables a transition to state Stopped at Floor
In this state, activity Open the elevator doors
is performed
Copyright © 2003-2005 Yoram Reich 88
Example: Four states are unified into Osbert Combined
Statecharts (contd)
Copyright © 2003-2005 Yoram Reich 89
Statecharts
The most general form of a transition label is event [guard] / action
If event
has taken place and [guard]
is true, the transition occurs, and, while it is occurring,
actionis performed
The transition label is Elevator arrived at floor [a message is received] / Open the elevator doors
The guard [a message has been received]
is true when the event Elevator has arrived at floor
has occurred and the message has been sent The action to be taken is
Open the elevator doors
Copyright © 2003-2005 Yoram Reich 90
Elevator
Our elevator has the basic function that all elevator systems have, such as moving up and down, open and close doors, and of course, pick up passengers.
The elevator is supposed to be used in a building having floors numbered from 1 to MaxFloor, where the first floor is the lobby.
There are car call buttons in the car corresponding to each floor. For every floor except for the top floor and the lobby, there are two hall call buttons for the passengers to call for going up and down. There is only one down hall call button at the top floor and one up hall call button in the lobby.
When the car stops at a floor, the doors are opened and the car lantern indicating the current direction the car is going is illuminated so that the passengers can get to know the current moving direction of the car.
The car moves fast between floors, but it should be able to slow down early enough to stop at a desired floor.
In order to assure system safety, emergency brake will be triggered and the car will be forced to stop under any unsafe conditions.