the object constraint language n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
The Object Constraint Language PowerPoint Presentation
Download Presentation
The Object Constraint Language

Loading in 2 Seconds...

play fullscreen
1 / 46

The Object Constraint Language - PowerPoint PPT Presentation


  • 119 Views
  • Uploaded on

The Object Constraint Language. Jos Warmer and Anneke Kleppe. OCL: The Constraint Language of the UML, Journal of Object-Oriented Programming, 2(2):10-13, May 1999. Jos Warmer and Anneke Kleppe. The Object Constraint Language, second edition, Addison-Wesley, 2003. 1. Outline. Motivation

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'The Object Constraint Language' - kylan-chan


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
the object constraint language

The Object Constraint Language

Jos Warmer and Anneke Kleppe. OCL: The Constraint Language of the UML, Journal of Object-Oriented Programming, 2(2):10-13, May 1999.

Jos Warmer and Anneke Kleppe. The Object Constraint Language, second edition, Addison-Wesley, 2003.

1

outline
Outline
  • Motivation
  • Basics of OCL
  • OCL types
  • OCL collections
  • Other features

2

motivation problem
Motivation---Problem

UML diagrams don’t tell everything

Can’t express a rich semantics of and all relevant information about an application

Lack expressiveness

Q: What does the following class diagram tell?

parents

0..2

Person

children

0..*

motivation problem1
Motivation---Problem

Is this a valid object diagram?

Q: What’s wrong with it?

Q: How to fix it using Z?

joe: Person

Person

parents

0..2

children

0..*

parents

children

motivation solution
Motivation---Solution

Specify constraints explicitly

A person can’t be one’s own parents or children, e.g.,

this  parents

parents

0..2

Person

children

0..*

inv: not parents->includes(self)

exercise
Exercise

Formulate constraints for a derived association.

Person

parents

0..2

0..*

ancestors

children

0..*

0..*

/family tree

descendants

what is ocl
What Is OCL?

Standard “add-on” to UML

OCL expressions dependent on types from UML diagrams

Language for expressing additional information (e.g., constraints and business rules) about UML models

characteristics of ocl
Characteristics of OCL

Constraint and query languages

UML 1.1: Constraints

UML 2.0: Queries, reference values, conditions, business rules

Math foundation but no math symbols

Set theory and predicate logic

Strongly typed language

Checking possible

Declarative language

What vs. how (algorithmic or procedural)

No side effect

High level of abstraction (platform independence)

outline1
Outline

Motivation

Basics of OCL

OCL types

OCL collections

Other features

9

basics of ocl
Basics of OCL

Associating OCL expressions to UML models

Directly to diagrams as notes

Separate accompanying texts, e.g.,

context Person

inv: age >= 0

inv: age >= 0

Person

-age

basic specifying invariants
Basic: Specifying Invariants

Invariants: state conditions that must be always be met by all instances of context types (classes or interfaces)

self: contextual instance, an instance to which the OCL expression is attached

context Company inv:

self.numberOfEmployees > 50

contextc: Company inv:

c.numberOfEmployees > 50

context c: Company invenoughEmployees:

c.numberOfEmployees > 50

An explicit specification of contextual instance, c

an optional label

basic pre and post conditions
Basic: Pre and Post-conditions

context Account::deposit(amt: Integer): void

pre: amt > 0

post: balance = balance@pre + amt

context Account::deposit(amt: Integer): void

preargumentOk: amt > 0

postbalanceIncreased: balance = balance@pre + amt

pre-value, referring to previous value

optional label

Pre and post-conditions: conditions that must be true at the moment when an operation begins and ends its execution.

referring to pre value and result
Referring to Pre-value and Result

context Account::payInterest(rate: Real): void

post: balance = balance@pre + calcInterest@pre(rate)

context Account::getBalance(): Integer

post: result = balance

@pre: denotes the value of a property at the start of an operations

result: denotes the result of an operation

navigating in ocl expressions
Navigating in OCL Expressions

Customer

Account

context Account

inv: self.owner … -- evaluate to a single Customer

self.customer …

context Customer

inv: self.accounts->size() … -- evaluate to a collection

self.account … -- of accounts

single line (--) or multiple lines (/* … */)

0..*

1

accounts

owner

Arrow notation for collection operations

  • Use dot notation to navigate through associations
    • Direction and multiplicity matter
    • Use role names or class names
exercise1
Exercise

spouse

0..1

Write pre and post-conditions

Pair (5 minutes)

exercise2
Exercise

Formulate constraints or business rules for the following class diagram.

16

exercise3
Exercise

Model the following software by drawing a class diagram and formulating the constraints the class diagram has to satisfy. The software system automates test taking by allowing an instructor to prepare test questions and students to take tests.

The system shall allow an instructor to add test questions, Each question is a multiple choice question consisting of a stem---that presents the problem to be solved or the question to be answered---and a set of options---that are possible answers. Test questions are classified by topics, difficulty levels, and similarity.

The system shall allow an instructor to create a test on specific topics by suggesting a set of questions that meets the instructor's request (e.g., number of questions and their distributions among different topics and difficulty levels).

The system shall allow students to take tests prepared by the instructor.

The system shall grade tests taken by students to calculate test scores.

The system shall allow both the instructor and the students view their scores. However, students are allowed to view only their tests.

17

outline2
Outline

Motivation

Basics of OCL

OCL types

OCL collections

Other features

18

types in ocl
Types in OCL

Two different kinds

Predefined types (as defined in standard library)

Basic types: Integer, Real, String, Boolean

Collection types: Set, OrderedSet, Bag, Sequence

User-defined types: classes, interfaces, and enumerations.

Value vs. object types

Immutable vs. mutable types

All predefined types are value types, i.e., there is no mutation operation defined.

19

basic types
Basic Types

Several basic types with operations

integer and real
Integer and Real
  • No restriction on size and precision
  • Operations: =, <>, <, >, <=, >=, +, -, *, /, mod, div, abs, max, min, round, floor
  • Prefix vs. infix operations, e.g.,

5.max(10)

5.+(10)

5 + 10

  • Axioms of associativity and commutitivity hold:

a + (b + c) = (a + b) + c

a + b = b + a

string
String
  • Operations: concat, size, toLower, toUpper, substring, =, <>
  • Constants: 'cs 5381'
  • 1-based index for substring, substring(l,u)

Q: Pre- and post-conditions of substring?

boolean
Boolean
  • Operations: or, and, xor, not, =, <>, implies, if-then-else-endif
  • Order of evaluation and "undefined" value
    • Undefined represented by OclVoid, conforming to all types (cf. isUndefined() from OclAny)
    • Mostly strict interpretation except for boolean operators
    • Q: Truth table for: and, or, xor, implies, not?
oclany
OclAny
  • Supertype of all types
  • Operations useful for every type of OCL instance, e.g.,
    • = (o2: OclAny): Boolean
    • <> (o2: OclAny): Boolean
    • oclIsUndefined(): Boolean
    • oclIsTypeOf(t: OclType): Boolean
    • oclIsKindOf(t: OclType): Boolean
    • oclIsNew(): Boolean
    • oclAsType(t: OclType): OclType
    • T::allInstances(): Set(T)

*Both = and <> are mostly redefined by subtypes

Q: Use of oclAsType?

Accessing subtype's features and supertype's overridden features

Q: Difference between oclIsTypeOf and oclIsKindOf?

using and navigating user defined types

Customer

Account

Using and Navigating User-defined Types
  • Can use (class) attributes and query operations of user-defined types
  • Can use associations and aggregations
    • Use role names or, if unambiguous, type names
    • If multiplicity > 1, collections based on properties
      • Set: {unique} (default)
      • OrderedSet: {unique, ordered}
      • Bag: {notUnique}
      • Sequence: {notUnique, ordered}

context Account

inv: self.owner.name <> ''

context Customer

inv: self.accounts->size() > 0

0..*

1

accounts

owner

navigating user defined types

Customer

Account

Bank

Navigating User-defined Types
  • Navigating more than one association with multiplicity "many"
    • Bag
    • Sequence if at least one is marked {ordered}

context Bank

inv: self.customers.accounts->forAll(balance > 0)

0..*

0..*

customers

accounts

using enumeration

Account

<<enumeration>>

AccountType

gold

silver

1

type

Using Enumeration
  • Use “::” notation

context Account

inv: type = AccountType::gold implies minBalance > 10000 and

type = AccountType::silder implies minBalance > 5000

using association class

Student

Course

Outcome

score: Integer

Using Association Class
  • Use class name (with a lowercase character) and role names

context Course

inv: self.outcome->forAll(score > 90)

context Outcome

inv: score > 90

Inv: students.enrolled -- the student associated with this outcome

0..*

0..*

students

outline3
Outline

Motivation

Basics of OCL

OCL types

OCL collections

Other features

29

collections in ocl
Collections in OCL
  • Why?
    • Multiple objects produced by navigating associations
  • Standard collection types
    • Parameterized with elements types, e.g., Set(Account)
    • Value/immutabletypes, not reference types
    • One abstract and four concrete types
      • Collection
      • Set, OrderedSet, Bag, Sequence
      • Determined based on properties of associations, e.g., unique, ordered, and sorted.
collection types
Collection Types
  • Properties

*Ordered doesn’t mean sorted.

  • Constants
    • Set{10, 100}
    • OrderedSet{'apple', 'orange'}
    • Bag{10, 10, 100}
    • Sequence{10, 10, 100}, Sequence{1..10}, Sequence{1..(5 + 5)}
    • Set{Set{1}, Set{10}}
collection operations
Collection Operations

Large number of predefined operations

Arrow notation, e.g., c->size()

Rationale: allow same-named, user-defined operations, e.g., c.size()

Customer

Account

context Account context Account

inv: not owner->isEmpty() inv: not owner.isEmpty()

0..*

1

accounts

owner

collection operations1
Collection Operations
  • Defined on all collection types
  • Type-specific operations

append, including, excluding, first, last, insertAt, etc.

exercise4
Exercise

Write pre- and post-conditions for:

  • includes
  • excludes
  • includesAll
  • excludesAll
  • isEmpty
  • notEmpty

Hint: use forAll operations for includesAll and excludesAll.

exercise5
Exercise

Write pre and postconditions for:

Set

union(s: Set(T)): Set(T)

=(s: Set(T)): Boolean

including(o: T): Set(T)

OrderedSet

append(o: T): OrderedSet(T)

insertAt(i: Integer, o: T): OrderedSet(T)

Bag

excluding(o: T): Bag(T)

Sequence

subSequence(l: Integer, u: Integer): Sequence(T)

iteration operations
Iteration Operations

Customer

Account

0..*

1

accounts

owner

  • Loop over elements by taking one element at a time
  • Iterator variables
    • Optional variable declared and used within body
    • Indicate the element being iterated
    • Always of the element type, thus, type declaration is optional

context Customer

inv: self.accounts->forAll(a: Account | a.owner = self)

inv: accounts->forAll(a | a.owner = self)

inv: accounts->forAll(owner = self)

examples
Examples

accounts->any(a: Account | a.balance > 1000)

accounts->collect(name) -- all the names

accounts->exists(balance > 5000)

accounts->forAll(balance >= 0)

accounts->isUnique(name)

accounts->iterate(a: Account; sum: Integer = 0 | sum + a.balance)

accounts->one(name = “Carmen”)

accounts->reject(balance > 1000)

accounts->select(balance <= 1000)

accounts->sortedBy(balance)

select vs collect

Customer

Bank

0..*

0..*

Account

balance: Integer

accounts

customers

Select vs. Collect
  • Q: Difference between select and collect?
  • Note that the dot notation is short for collect, e.g.,

context Bank

inv: self.customers.accounts->forAll(balance > 0)

inv: self.customers->collect(accounts)->forAll(balance > 0)

Note that results are flattened for “collect” and not for “collectNested”.

the iterate operation
The Iterate Operation
  • Most fundamental and generic loop operation
  • All other loop operations are special cases

iterate(elem: T1; result: T2 = expr | expr-elem-result)

  • Example

Set{1, 2, 3}->sum()

Set{1, 2, 3}->iterate(i: Integer; r: Integer = 0 | r + i)

exercise6
Exercise

1

0..*

accounts

Pair (3 minutes)

Write the pre- and post-conditions of the getBelowAverage operation that returns all the accounts of a customer of which balances are below the average balance of the customer’s accounts.

exercise7
Exercise
  • Write pre- and post-conditions of the following operations in terms of the iterate operation:

size, count, sum, and excluding(o: T): Sequence(T)

  • Define the following operations in terms of the iterate operation:

forAll, any, one, select, reject

E.g., source->exists(vars|body) =

source->iterate(vars; result: Boolean = false| result or body)

initial values and derivation rules
Initial Values and Derivation Rules
  • Specify initial values for attributes and association ends

context Account::balance

init: 0

  • Specify derivation rules for derived attributes and associations

context Person::printedName

derive: lastName.concat(', ').concat(firtName)

Q: How to indicate derived attributes and associations in UML?

Q: Difference between initial values and derivation rules?

outline4
Outline

Motivation

Basics of OCL

OCL types

OCL collections

Other features

44

introducing new attributes and operations

Customer

0..*

Account

balance: Integer

owners

Introducing New Attributes and Operations
  • Can add new attributes and operations to UML models

context Account

def: isJointlyOwned: Boolean = owners->size() > 1

context Account

def: numOfOwners(): Integer = owners->size()

message sending
Message Sending
  • The isSent (^) operator in post-conditions specifies communication (e.g., method call or signal) has taken place.

context Subject::hasChanged()

post: observer^update(10, 20)

context Subject::hasChanged()

post: observer^update(?: Integer, ?: Integer)