Title: SemiFormal Methods in Software Engineering Object Constraint Language
1Semi-Formal Methods in Software
EngineeringObject Constraint Language
2Why OCL ?
- UML is a pictorial language for software design,
now becoming widely popular. - Although popular UML by itself is not enough to
capture many aspects of OCL. - This set of transparencies review UML and
introduce OCL. - Information on OCL available at
http//www.klasse.nl/ocl/index.htm - Reference book The Object Constraint Language
Precise Modeling with UML by Jos Warmer and
Anneke Kleppe. (Addison Wesley Series on Object
Technology)
3Review UML
- Use Case Diagrams
- Class Diagrams
- Statecharts
- Sequence Diagrams
- Object Collaboration Diagrams
4UML Notation for Use Case Diagram
Use Case
Actor
Use Case A
ltltextendgtgt
ltltextendgtgt
Use Case C
Use Case B
Use Case X
ltltincludegtgt
ltltincludegtgt
Use Case Z
Use Case Y
5Use Cases
- Define system functional requirements in terms of
Actors and Use cases - Each use case defined in terms of sequence of
interactions between Actor and System - Narrative description
- Simple use cases may involve only one interaction
- More complicated use cases may involve several
interactions
6Example Use Case in UML Notation
Withdraw Funds
Actor
7Objects and Classes
- Objects represent things in real world
- Provide understanding of real world
- Form basis for a software solution
- An Object is a single thing
- E.g., Johns car
- Marys account
- A Class (object class) is a collection of objects
with the same (similar) characteristics - E.g., account, employee, car, customer
- An object is underlined in class diagrams
- E.g., objectclass or class
- Each object has an identity and is
distinguishable from others in the class
8UML Notation for Class Diagram
ClassA
1
ClassB
Association
Class Whole
Super class
ClassPart2
ClassPart1
SubclassA2
SubclassA1
Aggregation Hierarchy
Generalization/Specialization
9An Example Class Diagram
Customer
Order
Multiplicitymandatory
Class
dataReceived isPrepaid number String price
Money dispatch() close()
Name address creditRating() String
1
Attribute
Association
Method
if Order.customer.creditrating is poor the
Order.isPrePaid must be true
Corporate
Personal
contractName creditRating creditLimit remind() bil
lForMonth()
creditCard
Constraint
Line Items
OrderLine
Role name
0..1
Employee
Quantityinteger priceMoney dissatisfiedBoolean
Multiplicityoptional
1
Product
10Statechart
- Statechart
- Graphical representation of finite state machine
- States are rounded boxes
- Transitions are arcs
- Statechart relates events and states
- Event
- Causes change of state
- Referred to as state transition
- State represents interval between successive
events - Initial state
- Arc with black ball at end
11UML Notation for Statechart Diagram
Initial State
Event
Superstate A
Substate A1
Event condition/ Action
Entry/ Action Do/ Activity Exit/ Action
Substate A2
Event / Action
Final State
12Example of Account Statechart
Account Opened
Regular Withdrawal
AuthorizedWithdrawal
Account in Good Standing
AccountOverdrawn
Overdraft Paid Off
Deposit
Account closed
13Hierarchical Statecharts
- OR decomposition
- When object is in superstate
- It is in one and only one of substates
- Transition into superstate
- Must be to one and only one of substates
- Aggregation of state transitions
- If same event causes transition out of every
substate - Then aggregate into transition out of superstate
14Hierarchical Statecharts
- Concurrent statecharts
- State of an object described by more than one
statechart - Show different aspects of object, may not be
concurrent - AND decomposition
- Object is in one substate on each statechart
- Objects state is union of all substates
- Same event
- May cause transitions on more than one statechart
- Output event on one statechart
- May be input event on other statechart
- Substate on one statechart
- May be condition on other statechart
15Sequence Diagram
- Shows sequence of object interactions in use case
- Emphasis on messages passed between objects
- Objects represented by vertical lines
- Actor is on extreme left of page
- Messages represented by labeled horizontal arrows
- Only source and destination of arrow are relevant
- Message is sent from sending object to receiving
object - Time increases from top of page to bottom
- Spacing between messages is not relevant
- Message sequence numbering is optional
16 UML Notation for Sequence Diagram
Actor
objectB1 ClassB
objectA
anObject
ClassC
1 Input Message
2 Internal Message
3 Iteration Message
4Condition Conditional Message
17Example Sequence Diagram for Shaft Use Case
ltltexternal input devicegtgt Shaft
ltltdevice interfacegtgt ShaftInterface
ltltentitygtgt Shaft RotationCount
Sh1 Shaft Input
Sh1.1 Update Shaft Rotation Count
18Object Collaboration Diagrams
- Graphically depicts objects participating in a
use case - Show objects as boxes
- Show their message interactions as arrows
- Number sequence of messages
- Message
- Message Event Attributes
- E.g, ATM card inserted (Card id, expiration date)
- Object Collaboration Diagram for each use case
- Some objects only appear on one Object
Collaboration Diagram - Some objects appear in several Object
Collaboration Diagrams
19UML Notation for Collaboration Diagram
1 Input Message
objectA
2 Internal Message
Actor
objectB1 ClassB
3 Iteration Message
anObject
4Condition Conditional Message
ClassC
20Example Collaboration Diagram for Use Case
ltltexternal input devicegtgt Shaft
Sh1 Shaft Input
ltltinput device interfacegtgt ShaftInterface
Sh1.1 Update
ltltentitygtgt ShaftRotation Count
21Object Constraint Language
- Developers claim OCL is easier than Z, VDM.
- Need some mathematical background in Set Theory
and Logic, but is based on UML. - Constraints in OCL is an extension of Assertions
of Bertrand Meyer, implemented in Eiffel. - Assertions pre-conditions post-conditions
invariants - Assertions (Graham) above conditions holding
when methods are running.
22Other Notions of Constraints
- Rambaugh Functional relationships between
entities of the object model. - Restricts values that entities can take.
- Booch Expression of semantics conditions that
must be preserved. - Only properties of steady states must be stated.
- Design by Contract Obligations of a client to a
server
23Declarative vs. Operational Constraints
- Declarative What must hold, not what should be
done to enforce a constraint. Advantages - Do not worry about enforcement or penalty for
violation. - Implementation independent behavior.
- Atomic checking of enforcement.
- Operational Doing what by a runtime system will
enforce a constraint. - Breaking of a Constraint Raise an exception
- Exception to be raised can be determined by using
some rules such as given in Soma (Ian Graham)
24Constraints of OCL
- Definition of a Constraint A restriction on one
or more value of (part of) an object oriented
model. - Properties of OCL
- Expresses properties useful to modelers.
- Precise syntax and semantics (modulo UML)
- Declarative language
- Typed languages
25Loyalty Program
Customer
0..
0..
1.
Enroll(cCustomer)
NameString TitleString isMaleBoolean dateOfBirt
hDate
program
partners
Age()Integer
Membership
1..
0..
owner
Program Partners
0..
Actual Program
1..
ordered
cards
numberOfCustomersInteger
Service Level
Customer Card
card
NameString
Valid Boolean validFromDate goodThruDate Color
enumsilver,gold printedNameString
0..1
Delivered Services
Loyalty Account
0..
Points Integer Earn(iInteger) Burn(iInteger) is
Empty()Boolean
0..
Services
0..
Available Services
transactions
ConditionBoolean pointsEarnedInteger pointsBurne
dInteger descriptionString
Transaction
0..
PointsInteger DateDate
transactions
0..
Program()LoyaltyProgram
transactions
Earning
Burning
Date
nowDate
Date is Utility class
isBefore(tDate)Boolean isAfter(tDate)Boolean
(tDate)Boolean
26Constraints on Attribute Values
Customer name String title String isMale
Boolean dob Date Age() integer
- Constraints on Attribute Values
- customer
- age gt 18
- dob.isBefore(now)
-
Date now Date isBefore(tDate)
Boolean isAfter(tdate) Boolean (t date)
Boolean
27Constraints on Associations
Customer name String title String isMale
Boolean dob Date Age() integer
- Can place constrains on attributes that are
connected over associations - CustomerCard
- PrintedName customer.title.
- concat(customer.name)
- CustomerCard
- PrintedName owner.title.
- concat(owner.name)
owner
0..
cards
CustomerCard Valid Boolean validFrom
Date goodThru Date color enumS,G,P printedName
String
28Collections of Objects
- Not all associations are one-to-one. Hence, have
to deal with sets of objects in some
associations. - OCL has collection operations for this purpose.
- notEmpty( set of objects ), notEmpty(set of
objects ) - includes(object) for membership test
- union( set of objects )
- Intersection( set of objects )
- sum( set of objects)
- Iterate, exists, forAll, includesAll
29Iterations Over Collections
- Select, reject, iterate, forAll, exists.
- CustomerCard
- self.transactions-gtselect(points gt 100)
- LoyaltyAccount
- transaction-gtcollect( points)
- Transaction-gtcollect( points) -gt exists( p
Integer p 500 ) - Self.customer-gtforAll( c Customer c.age() lt
90) - Notice the duality between select and reject
- self.transactions-gtselect(points gt 100)
- self.transaction-gtreject(points lt 100)
30Iterate Construct
- Most General Construct.
- ProgramPartner
- self.service.transaction-gtiterate(
- t transaction
- result integer 0
- if oclType Burning then
- result points
- else
- result
- endif )
-
31Pre Conditions, Post Condition and Invariants
- Two Options
- Can use operations in constraints
- Can write constraints about operations
- Pre and Post Conditions
- _at_pre indicates value before method call
- Pre Post used to indicate conditions
- Example
- LoyaltyProgram
- pre not customer-gtincludes(c)
- post customer customer_at_pre-gtincluding(c)
32Modeling Constraints
- Invariant
- An expression holding true for all instances.
- Precondition
- Must be true at the start of execution of a
method. - Postcondition
- Must be true at the end of execution of a method.
- UML has no way to denote pre and post conditions
other than state them in note boxes. - OCL has a syntactic way to denote them.
33Statecharts and OCL
- Sate charts have states, actions, activities etc.
- They are all constraints on the class diagrams of
the corresponding object. - Hence all information of stat charts have to be
translated to class diagrams.
34Example of Using Statecharts
Account Opened
Regular Withdrawal
AuthorizedWithdrawal
Account in Good Standing
AccountOverdrawn
Overdraft Paid Off
Deposit
Account closed
35Account Class Diagram
- Need to define
- good standing
- Overdrawn
- For account
- Need to ensure
- Id is unique within class
- Close(Id) is allowed only for accounts with 0
balance. - Withdraw and deposit act according to state chart
Account Id Integer Balance Real Open(Id) Close(I
d) RegWithdraw(Id, amount) Deposit(Id, amount)
36Example Continued
- Uniqueness of ID
- Account
- self-gtforAll( c1, c2 c1 ltgt c2 implies c1.id ltgt
c2.id) - Definability of State (Option 1)
- Add an extra attribute, say minBalance.
- GoodStanding (balance gt minBalance)
- AccountOverdrawn (balance lt minBalance)
- Definability of State (Option 2)
- Add an extra BOOLEAN attribute, say Sanding
- State invariant Standing (balance gt
minBalance)
37Stating Pre and Post Conditions
- Regular Withdraw
- AccountregWithdraw(id, amount)
- Pre (account.balance gt account.minBalance) and
- (amount gt 0) and (id self.id)
- Post (account.balance account._at_pre-gtbalance
-amount) and - (account.balance gt account.minBalance)
38Stating Pre and Post Conditions
- Overdraft
- Accountoverdraft(id, amount)
- Pre (account.balance gt account.minBalance) and
- (amount gt 0) and (id self.id)
- Post (account.balance account._at_pre-gtbalance
-amount) and - (account.balance lt account.minBalance)
39Events, Activities
- Events should be mapped to methods, with the
appropriate parameters, conditions, state changes
etc. - Activities, entry actions, and exit actions must
also be mapped to method calls. - Calling activities and actions must be post
conditions of events that have them.
40Inheritance and Constraints
- Liskov Substitution Principle
- Whenever an instance of a class is expected, an
instance of it s subclass can be substituted. - Implications
- An invariant of a super-class is inherited by its
subclass. Hence a subclass may strengthen it, but
not weaken it. - A pre-condition may be weakened, not strengthened
in a re-definition of the method. - A post-condition may be strengthened, not
weakened in a redefinition of an operation.
41Action Semantics
- Extending OCL to Include Actions by Kleppe and
Warmer (UML 2000) conference. - Syntax
- Action If ltconditiongt
- to lttargetSetgt
- send lteventSetgt
42Examples of Actions- 1
- Example 1
- Context cutomerCardinvalidate()
- Pre none
- Post valid false
- Action if customer.special to customer
- send polliteInvalidLetter()
- Action if not customer.special to customer
- send invalidLetter()
43Examples of Actions- 2
- Example 2
- Context cutomerCard
- inv validFrom.isBefore(goodThru)
- Action if goodThru.isAfter(Date.now)
- to self
- send invalidate
44Issues with Action Semantics
- When is ltconditiongt evaluated?
- At postcondition time of operation
- Reason
- To be called in a context where Pre-condition is
true is callers responsibility. - Method has no control over pre-condition.
- Hence, after method execution, ltconditiongt will
be evaluated and action executed.
45Underlying Assumptions
- Every object (component) has two queues
- Output queue, to include outgoing events.
- Input queue to include incoming events.
- Only events generated by current operation should
be specified. - Events send by operations called by the current
operation should not be included.- They need to
be defined in called operations.