Using UML, Patterns, and Java ... Reference: “The Unified Modeling Language
User Guide”,. Addison Wesley .... UML provide other notations that we will be.
Using UML, Patterns, and Java
Object-Oriented Software Engineering
Chapter 2 Modeling with UML
What is UML?
UML (Unified Modeling Language)
An emerging standard for modeling object-oriented software
Resulted from the convergence of notations from three leading objectoriented methods:
OMT (James Rumbaugh)
OOSE (Ivar Jacobson)
Booch (Grady Booch)
Reference: “The Unified Modeling Language User Guide”, Addison Wesley, 1999.
Supported by several CASE tools
Rational ROSE, TogetherJ, ……
Designed for a broad range of applications, providing constructs for a broad range of systems and activities
Functional model, object model, dynamic model
UML First Pass
Functional model: Use case diagram
Describe the functional behavior of the system as seen by the user
Object model: Class diagram
Describe the static structure of the system in terms of Objects, Attributes, Associations, and Operations
Used in different phases of the software life cycle
Requirement and analysis: analysis object model application concepts
System design: system design model descriptions of subsystem interfaces
Object design: object design model detailed descriptions of solution objects
Dynamic model: Interaction diagram, State machine diagram, Activity diagram
Describe the internal behavior of the system
Interaction diagram describe behavior as a sequence of messages exchanged among a set of objects
State machine diagram describe behavior in terms of states of an individual object and the possible transitions between states
Activity diagram describe behavior in terms of control and data flows
Use Case Diagram
To represent the functionality of the system
Used during requirements elicitation and analysis
Focus on the behavior of the system from an external point of view
Use case
Describe a function provided by the system
Yield a visible result for an actor
Actor
Any entity that interacts with the system
A user, another system, the system’s physical environment
Identification of actors and use cases system boundary
Differentiating tasks accomplished by the system or by its environment
Actors are outside the boundary of the system
Use cases are inside the boundary of the system
A Simple Watch Example: Use Case Diagram Use case
Package Watch
Actor ReadTime
WatchUser
SetTime
WatchRepairPerson
ChangeBattery
Use case diagrams represent the functionality of the system from user’s point of view
Class Diagram
To describe the structure of the system
Classes
Abstractions that specify the common structure and behavior of a set of objects
Objects
Instances of classes being created, modified and destroyed during the execution of the system
Has state including the values of its attributes and its links with other objects
Components of class diagram
Classes
Objects
Attributes, operations, associations
A Simple Watch Example: Class Diagram Class diagrams represent the structure of the system Association
Class Multiplicity
Watch 1
2 PushButton state push() release()
Attribute
1 LCDDisplay blinkIdx blinkSeconds() blinkMinutes() blinkHours() stopBlinking() refresh()
Operations
1
1
1
2 Battery load
1 Time now
Interaction/State Machine Diagram Interaction Diagram
Formalize the dynamic behavior of the system and visualize the communication among objects
Objects involved in use case (participating objects) Represent interactions taking place among these objects
State Machine Diagram
Describe the dynamic behavior of an individual object as a number of states and transitions between these states
State: a particular set of values for an object
Transition: a future state the object can move to and the conditions for the changes
Differences
Interaction diagram: Focuses on the messages exchanged between objects as a result of external events created by actors
State machine diagram: Focuses on the transitions between states as a result of external events for an individual object
A Simple Watch Example: Sequence Diagram Actor :WatchUser
Message
Object :Watch
:LCDDisplay
pressButton1()
blinkHours()
pressButton1()
blinkMinutes()
pressButton2()
:Time
incrementMinutes() refresh()
pressButtons1And2()
commitNewTime() stopBlinking()
Activation
Lifeline
Sequence diagrams represent the behavior as interactions
A Simple Watch Example: State Machine Diagram State
Event
Initial state [button2Pressed] [button1&2Pressed] BlinkHours IncrementHrs
Transition
[button1Pressed]
[button2Pressed] [button1&2Pressed] BlinkMinutes IncrementMin.
[button1Pressed] [button2Pressed] [button1&2Pressed] BlinkSeconds IncrementSec.
StopBlinking
Final state
Represent behavior as states and transitions
Activity Diagram
Describe the behavior of a system in terms of activities
Activities: modeling elements that represent the execution of a set of operations
The execution of an activity can be triggered by
The completion of other activities
The availability of objects
External events
Similar to flowchart
Control flow: the order in which operations occur
Data flow: the objects that are exchanged among operations
A Simple Example: Activity Diagram Activity Control flow
Synchronization
Activity diagrams represent the behavior of system with respect to activities
Other UML Notations UML provide other notations that we will be introduced in subsequent lectures, as needed.
Implementation diagrams
Component diagrams Deployment diagrams Introduced in lecture on System Design
Object constraint language
Introduced in lecture on Object Design
What is Modeling?
Modeling consists of building an abstraction of reality
Abstractions are simplifications because
They ignore irrelevant detail
They only represent the relevant details.
What is relevant or irrelevant depends on the purpose of the model
Scale model of the air frame test its aerodynamic properties
Relevant: exterior surface of the airplane
Irrelevant: Instrument panel, engine
Flight simulator train pilots
Relevant: layout and behavior of flight instruments
Irrelevant: details about the exterior of the plane
Why Model Software? Why model software?
Software is getting increasingly more complex
Windows XP > 40 million lines of code A single programmer cannot manage this amount of code in its entirety.
Code is not easily understandable by developers who did not write it
We need simpler representations for complex systems
Modeling is a mean for dealing with complexity
Systems, Models and Views
A system is an organized set of communicating parts
A model is an abstraction describing a subset of a system
A view depicts selected aspects of a model
A notation is a set of graphical or textual rules for depicting views
Views and models of a single system may overlap each other
Examples:
System: Aircraft
Models: Flight simulator, scale model
Views: All blueprints, electrical wiring, fuel system
Systems, Models and Views (Cont.) Flightsimulator Blueprints Aircraft
System
Model 2 View 2 View 1 View 3 Model 1
Scale Model
Electrical Wiring
Systems, Models and Views (Cont.) In UML Notations *
System
*
Model
Described by
View
Depicted by
Airplane: System
Scale Model: Model
Blueprints: View
Flight Simulator: Model
Fuel System: View
Electrical Wiring: View
Concepts and Phenomena Phenomenon An object in the world of a domain as you perceive it Example: The lecture you are attending Example: My black watch
Concept Describes the properties of phenomena that are common Example: Lectures on software engineering
Example: Black watches
Concept is a 3-tuple: Name (To distinguish it from other concepts)
Purpose (Properties that determine if a phenomenon is a member of a concept) Members (The set of phenomena which are part of the concept)
Concepts and Phenomena (Cont.) Name
Clock
Purpose
Members
A device that measures time.
Abstraction Classification of phenomena into concepts
Modeling Development of abstractions to answer specific questions about a set of phenomena while ignoring irrelevant details.
Concepts in Software: Type and Instance
Type: An abstraction in the context of programming languages Name: int, Purpose: integral number, Members: 0, -1, 1, 2, -2, . . .
Instance: Member of a specific type
The type of a variable represents all possible instances the variable can take
The following relationships are similar: “type” “instance”
“concept” “phenomenon”
Abstract Data Types & Classes
Abstract data type Special type whose implementation is hidden from the rest of the system. (E.g.: list can be realized with arrays or links)
Class: An abstraction in the context of objectoriented languages
Like an abstract data type, a class encapsulates both state (variables) and behavior (methods) Class Vector
Unlike abstract data types, classes can be defined in terms of other classes using inheritance Superclass vs. Subclass
Watch time date SetDate(d)
CalculatorWatc
calculatorState
EnterCalcMode() InputNumber(n)
Abstract Classes
Inheritance relationship only serves to model shared attributes and operations The generalization class (superclass) is not meant to be instantiated
Not all generalization classes are abstract classes
Sometimes do not correspond to an existing application domain concept, but introduced to Reduce model complexity Promote reuse
Names are italicized to distinguish from normal classes
OrganicCompound
Benzene
Event Classes, Event and Messages
Event classes Abstractions representing a kind of event for which the system has a common response
Event (an instance of an event class) A relevant occurrence in the system E.g.: A stimuli from the actor, a time-out, sending a message between objects
Message By which the sending object requests the execution of an operation in the receiving object Composed of a name and a number of arguments Receiving object: match the name of the message to one of its operations; pass the arguments to the matched operation
Sending object: get the returned result
Examples of message sends UML Sequence diagram
Application and Solution Domain
Application Domain (Requirements Elicitation, Analysis): The environment in which the system is operating The physical environment, the people, their work processes Client domain vs. User domain
Client domain issues: operation cost of the system, impact of the system on the rest of the organization
User domain: functionality, ease of learning and of use
Solution Domain (System Design, Object Design): The available technologies to build the system
Solution domain model is much richer and more volatile than application model
Modeled in much more detail Emerging technologies, deeper understanding of developers, changes in requirements changes to the solution domain models
Object-Oriented Modeling Object-oriented analysis (OOA): Modeling application domain Object-oriented design (OOD): Modeling solution domain
Application Domain Application Domain Model
UML Package
TrafficControl Aircraft
SummaryDisplay
TrafficController
FlightPlan
Solution Domain System Model
Airport
MapDisplay
FlightPlanDatabase TrafficControl
UML Core Conventions
Rectangles are classes or instances
Ovals are functions or use cases
Instances are denoted with an underlined names myWatch:SimpleWatch
Joe:Firefighter
Types are denoted with non underlined names SimpleWatch
Firefighter
Diagrams are graphs Nodes are entities Arcs are relationships between entities
Use Case Diagrams
Passenger
PurchaseTicket
Used during requirements elicitation to represent external behavior
Actors represent roles, that is, a type of user of the system
Use cases represent a sequence of interaction for a type of functionality
The use case model is the set of all use cases. It is a complete description of the functionality of the system and its environment
Actors
An actor models an external entity which communicates with the system: User External system
Physical environment
Passenger
An actor has a unique name and an optional description
Examples: Passenger: A person in the train GPS satellite: Provides the system with GPS coordinates
Use Case A use case represents a class of functionality provided by the system as an event flow.
A use case consists of: PurchaseTicket
Unique name
Participating actors
Flow of events
Entry conditions
Exit conditions
Special requirements
Use Case: Example Name: Purchase ticket Participating actor: Passenger
Entry condition:
Passenger standing in front of ticket distributor. Passenger has sufficient money to purchase ticket.
Exit condition:
Passenger has ticket.
Event flow:
1. Passenger selects the number of zones to be traveled. 2. Distributor displays the amount due. 3. Passenger inserts money, of at least the amount due. 4. Distributor returns change.
5. Distributor issues ticket.
Anything missing?
Exceptional cases!
The Relationship
Passenger
PurchaseTicket
relationships
represent exceptional or seldom invoked cases. The exceptional event flows are factored out of the main event flow for clarity. Use cases representing exceptional flows can extend more than one use case. The direction of a relationship is to the extended use case
OutOfOrder
Cancel
NoChange
TimeOut
The Relationship
represents behavior that is factored out of the use case.
Passenger
PurchaseMultiCard PurchaseSingleTicket
NoChange
relationship
CollectMoney
behavior is
factored out for reuse, not because it is an exception. The direction of a relationship is to the using use case (unlike relationships).
Cancel
The Relationship
relationship represents another mechanism for
reducing model complexity.
One use case can specialize another more general one by adding more detail.
The direction of a > relationship is to the general use case
Authenticate WithPassword Authenticate
Authenticate WithCard
Use Case Diagram: Another Example FRIEND: First Responder Interactive Emergency Navigational Database
Use Case Diagrams: Summary
Use case diagrams represent external behavior
Use case diagrams are useful as an index into the use cases
Use case descriptions provide meat of model, not the use case diagrams Use case name Participating actors Flow of events
Entry/Exit condition Special requirements
All use cases need to be described for the model to be useful
Relationships Communication, extend, include, inheritance
Class Diagrams
Class diagrams represent the structure of the system
Used during requirements analysis to model application domain concepts during system design to model subsystems during object design to specify the detailed behavior and attributes of classes TarifSchedule
Table zone2price Enumeration getZones() Price getPrice(Zone)
Trip
*
*
zone:Zone Price: Price
Classes
Type
Name TarifSchedule zone2price getZones() getPrice()
Attributes
Operations
TarifSchedule Table zone2price Enumeration getZones() Price getPrice(Zone)
Signature TarifSchedule
• A class represents a concept • A class encapsulates state (attributes) and behavior (operations) Each attribute has a type Each operation has a signature The class name is the only mandatory information
Instances/Objects tarif2006:TarifSchedule zone2price = { {‘1’, 0.20}, {‘2’, 0.40}, {‘3’, 0.60}}
:TarifSchedule zone2price = { {‘1’, 0.20}, {‘2’, 0.40}, {‘3’, 0.60}}
• An instance represents a phenomenon • The attributes are represented with their values • The name of an instance is underlined
• The name can contain only the class name of the instance (anonymous instance)
Actor vs Class vs Object • Actor • An entity outside the system to be modeled, interacting with the system (“Passenger”)
• Class • An abstraction modeling an entity in the application or solution domain
• The class is part of the system model (“User”, “Ticket distributor”, “Server”)
• Object • A specific instance of a class (“Joe, the passenger who is purchasing a ticket from the ticket distributor”).
Associations
TarifSchedule
TripLeg
Enumeration getZones() Price getPrice(Zone)
Price Zone
*
*
Associations denote relationships between classes The multiplicity of an association end denotes how many objects the instance of a class can legitimately reference.
1-to-1 and 1-to-many Associations Country
1
name:String
1
Captical name:String
1-to-1 association Point Polygon
*
x: Integer y: Integer
draw()
1-to-many association
Many-to-Many Associations Company StockExchange
*
*
: zero to many
a…b: a to b
*
tickerSymbol
a: any integer including 0 a…*: a to many
From Problem Statement To Object Model Problem Statement: A stock exchange lists many companies. Each company is uniquely identified by a ticker symbol
Class Diagram:
StockExchange *
* Lists
Company tickerSymbol
From Problem Statement to Code Problem Statement: A stock exchange lists many companies. Each company is uniquely identified by a ticker symbol Class Diagram: StockExchange
*
Lists
*
Company tickerSymbol
Java Code public class StockExchange { private Vector m_Company = new Vector(); };
Associations are mapped to Attributes!
public class Company { public int m_tickerSymbol; private Vector m_StockExchange = new Vector(); };
Association Class Associations can have attributes and operations attached to them, be depicted by a class symbol and be connected to the association symbol with a dashed line. Establishment EstTime: Time Founder: String
Country name:String
1
1
Capital name:String
Qualifiers Without qualification Directory
1
*
File filename
With qualification Directory
filename
1
0..1
File
Qualifiers can be used to reduce the multiplicity of an association
Qualification: Another Example Company StockExchange
StockExchange
*
*
tickerSymbol
*
1
*
tickerSymbol
Company
Aggregation • An aggregation is a special case of association denoting a “consists-of” hierarchy
Exhaust system
• The aggregate is the parent class, the components are the children classes 1 TicketMachine
0..2
Muffler
Tailpipe
diameter
diameter
3 ZoneButton
A solid diamond denotes composition: A strong form of aggregation where the life time of the component instances is controlled by the aggregate. That is, the parts don’t exist on their own (“the whole controls/destroys the parts”)
Inheritance Button
CancelButton
ZoneButton
• Inheritance is another special case of an association denoting a “kind-of” hierarchy
• Inheritance simplifies the analysis model by introducing a taxonomy • The children classes inherit the attributes and operations of the parent class
Packages • Packages help you to organize UML models to increase their readability • We can use the UML package mechanism to organize classes into subsystems Account
Bank
Customer
• Any complex system can be decomposed into subsystems, where each subsystem is modeled as a package
Object Modeling in Practice Foo Amount CustomerId Deposit()
Withdraw() GetBalance()
Class Identification: Name of Class, Attributes and Methods Is Foo the right name?
Object Modeling in Practice: Brainstorming “Dada”
Foo
Amount
Amount
CustomerId
CustomerId
Deposit() Withdraw() GetBalance()
Deposit() Withdraw() GetBalance() Account
Amount CustomerId
Is Foo the right name?
Deposit() Withdraw() GetBalance()
Object Modeling in Practice: More classes Account
Bank
Name
Amount AccountId CustomerId Deposit() Withdraw() GetBalance()
Customer Name CustomerId
1) Find New Classes 2) Review Names, Attributes and Methods
Object Modeling in Practice: Associations Account
*
? Bank Name
has
Amount AccountId CustomerId AccountI d Deposit() Withdraw() GetBalance()
*
Customer owns 1
Name CustomerId
1) Find New Classes
2) Review Names, Attributes and Methods 3) Find Associations between Classes 4) Label the generic assocations 5) Determine the multiplicity of the assocations 6) Review associations
Practice Object Modeling: Find Taxonomies Account Bank
*
Name
Savings Account
Withdraw()
Customer Amount AccountId CustomerId AccountI d Deposit() Withdraw() GetBalance()
Checking Account
Withdraw()
*
owns
Name
CustomerId()
Mortgage Account
Withdraw()
Practice Object Modeling: Simplify, Organize Account Amount AccountId CustomerId AccountI d Deposit() Withdraw() GetBalance()
Savings Account
Withdraw()
Checking Account
Withdraw()
Show Taxonomies separately
Mortgage Account
Withdraw()
Practice Object Modeling: Simplify, Organize Account Bank Name
*
Customer Amount AccountId CustomerId AccountI d Deposit() Withdraw() GetBalance()
*
owns
Name
CustomerId()
Miller’s Law George A. Miller. The Magical Number Seven, Plus or Minus Two: Some Limits on Our Capacity for Processing Information. Psychological Review, 1956, 101(2): 343-352. Use the 7±2 heuristics, or better 5±2
Sequence Diagrams
Focus on Controlflow • Used during analysis
Passenger
TicketMachine
selectZone()
• To refine use case descriptions • to find additional objects (“participating objects”)
• Used during system design insertCoins()
pickupChange()
pickUpTicket()
TicketMachine • to refine subsystem interfaces zone2price Messages ->by • Instances are represented selectZone() rectangles. ActorsOperations by stickyon insertCoins() participating Object figures pickupChange() • Lifelines are represented by pickUpTicket()
dashed lines • Messages are represented by arrows • Activations are represented by narrow rectangles.
Sequence Diagrams can also model the Flow of Data Passenger
ZoneButton
selectZone()
TarifSchedule
Display
lookupPrice(selection) price
Dataflow
displayPrice(price)
…continued on next slide...
• The source of an arrow indicates the activation which sent the message • Horizontal dashed arrows indicate data flow, for example return results from a message
Sequence Diagrams: Iteration & Condition …continued from previous slide... Passenger
ChangeProcessor
*insertChange(coin) Iteration
CoinIdentifier
Display
CoinDrop
lookupCoin(coin) price displayPrice(owedAmount)
[owedAmount