1 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,

Slides:



Advertisements
Similar presentations
1 Mireille Blay-Fornarino – 2007/2008 EPU département SI, Master STIC Survol de Object Constraint Language & IDM À partir du cours Contracts, Patterns.
Advertisements

Formal Methods of Systems Specification Logical Specification of Hard- and Software Dr. Armin Wolf Fraunhofer Institut für Rechnerarchitektur.
Lecture 7 Constraints and Invariants Formal Modeling and Analyzing a Flash File System.
Semantics Static semantics Dynamic semantics attribute grammars
By Karen Richart. The Object Constraint Language (OCL)  Formal specification language that could be used for constraining the model elements that occur.
1 The Object Constraint Language: Expressing Constraints in the UML (Most slides created by Robert B. France, Professor Department of Computer Science,
1 CHAPTER 4 RELATIONAL ALGEBRA AND CALCULUS. 2 Introduction - We discuss here two mathematical formalisms which can be used as the basis for stating and.
Rigorous Software Development CSCI-GA Instructor: Thomas Wies Spring 2012 Lecture 11.
OCL2 April A presentation of OCL 2 Object Constraint Language Christian Hein, Fraunhofer FOKUS April 2006.
Object Constraint Language in Together Dan Massey Y&L Consulting.
Copyright © 2006 Addison-Wesley. All rights reserved.1-1 ICS 410: Programming Languages Chapter 3 : Describing Syntax and Semantics Axiomatic Semantics.
ISBN Chapter 3 Describing Syntax and Semantics.
UML Class Diagram. UML Class Diagrams2 Agenda What is a Class Diagram? Essential Elements of a UML Class Diagram Tips.
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 9, Object Design: Object Constraint Language.
Formal Methods of Systems Specification Logical Specification of Hard- and Software Prof. Dr. Holger Schlingloff Institut für Informatik der.
Lecturer: Sebastian Coope Ashton Building, Room G.18 COMP 201 web-page: Lecture.
Practical Object-Oriented Design with UML 2e Slide 1/1 ©The McGraw-Hill Companies, 2004 Class and Object Diagrams PRACTICAL OBJECT-ORIENTED DESIGN WITH.
Describing Syntax and Semantics
SEG4110 – Advanced Software Engineering and Reengineering TOPIC E Object Constraint Language (OCL)
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Understanding Advanced UML Concepts Gerd Wagner
A presentation of OCL 2 Object Constraint Language Fraunhofer FOKUS.
1 COSC 4406 Software Engineering COSC 4406 Software Engineering Haibin Zhu, Ph.D. Dept. of Computer Science and mathematics, Nipissing University, 100.
111 Writing Protocols in OCL CS 4311 Jos B. Warmer and Anneke G. Kleppe, OCL: The Constraint Language of the UML, JOOP, May Jos B. Warmer and Anneke.
Lab 04.
111 Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract,
UML Model architecture Object Constraint Language Lectures P9-P11 T120B pavasario sem.
ISBN Chapter 3 Describing Semantics -Attribute Grammars -Dynamic Semantics.
CS551 - Lecture 8 1 CS551 Modelling with Objects (Chap. 3 of UML) Yugi Lee STB #555 (816)
® IBM Software Group © 2006 IBM Corporation Rational Software France Object-Oriented Analysis and Design with UML2 and Rational Software Modeler 03. Classes,
1 OCL The Role of OCL in UML. 2 רשימת הנושאים  מבוא  מרכיבי השפה  דוגמאות  מקורות.
UML Class Diagram Trisha Cummings. What we will be covering What is a Class Diagram? Essential Elements of a UML Class Diagram UML Packages Logical Distribution.
9-1 © Prentice Hall, 2007 Chapter 9: Analysis Classes Object-Oriented Systems Analysis and Design Joey F. George, Dinesh Batra, Joseph S. Valacich, Jeffrey.
CONTENTS Processing structures and commands Control structures – Sequence Sequence – Selection Selection – Iteration Iteration Naming conventions – File.
Lecture 1: UML Class Diagram September 12, UML Class Diagrams2 What is a Class Diagram? A class diagram describes the types of objects in the system.
Propositional Calculus CS 270: Mathematical Foundations of Computer Science Jeremy Johnson.
IM NTU Software Development Methods, Fall2006 Software Development Methods, Fall 2006 OCL 2006/12/ Object Constraint Language (OCL) Yih-Kuen Tsay.
Institute for Software Integrated Systems Vanderbilt University Object Constraint Language Himanshu Neema Krishnakumar Balasubramanian Jeff Parsons November.
Chapter 3 Part II Describing Syntax and Semantics.
Object Constraint Language
1 Kyung Hee University Constraints Spring Kyung Hee University Graphical Notations  Graphical notations are well suited for displaying structural.
1 XML Data Management XPath Principles Werner Nutt.
Formal Methods in Software Engineering1 Today’s Agenda  Quiz 2 next class  Presentation Schedule  Quick Review  Build Models Using OCL.
© 2004 Benet Devereux Lecture #4 OCL and SCR/Parnas Tables.
Update on the GELLO Expression and Query Language Margarita Sordo Brigham and Women’s Hospital Harvard Medical School HL7 Clinical Decision Support TC.
Chapter 16: UML Class Diagrams
7-1 © Prentice Hall, 2007 Topic 7: Analysis Classes Object-Oriented Systems Analysis and Design Joey F. George, Dinesh Batra, Joseph S. Valacich, Jeffrey.
Chapter 16 UML Class Diagrams.
Interpreting the Object Constraint Presented by: Ed Kausmeyer.
A UML-Based Pattern Specification Technique Presented by Chin-Yi Tsai IEEE TRANSACTION ON SOFTWARE ENGINEERING, VOL. 30, NO. 3, MARCH 2004 Robert B. France,
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
An association between class Flight and class Person, indicating that a certain group of persons are the passengers on a flight, will have multiplicity.
Jan Pettersen Nytun, UIA, page 1. Jan Pettersen Nytun, UIA, page 2 HISTORY COLLECTION TYPES AND QUERING IN OCL FORMAL LANGUAGE - STATEMENT EXAMPLES CONSTRAINTS.
The Object Constraint Language
Extending UML.
Chapter 16 UML Class Diagrams.
Modeling the OCL Standard Library
The Object Constraint Language
Chapter 9, Object Design: Object Constraint Language
Seminar 3 UML Class Diagram.
UML Class Diagram.
LECTURE 11: Specifying Systems – State Diag’s & OCL
A Specification Language
The Object Constraint Language
Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract, Computer,
Object Oriented System Design Class Diagrams
Introduction to UML - Prof. Prasad P. Mahale
Object Constraint Language (OCL)
Formal Methods in Software Engineering 1
Introduction to UML - Prof. Prasad P. Mahale
Presentation transcript:

1 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 Jos Warmer and Anneke Kleppe. The Object Constraint Language, second edition, Addison-Wesley,

2 Outline Motivation Basics of OCL OCL types OCL collections Other features 2

3 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 Person * children

4 Motivation---Problem Is this a valid object diagram? –Q: What’s wrong with it? –Q: How to fix it using Z? parents joe: Person children parents Person * children

5 Motivation---Solution Specify constraints explicitly A person can’t be one’s own parents or children, e.g., this  parents inv: not parents->includes(self) parents Person * children

6 Exercise Formulate constraints for a derived association. parents Person * children 0..* /family tree ancestors descendants

7 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

8 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)

9 Outline Motivation Basics of OCL OCL types OCL collections Other features 9

10 Basics of OCL Associating OCL expressions to UML models –Directly to diagrams as notes –Separate accompanying texts, e.g., context Person inv: age >= 0 Person -age inv: age >= 0

11 Basic: Specifying Invariants Invariants: state conditions that must be always be met by all instances of context types (classes or interfaces) context Company inv: self.numberOfEmployees > 50 context c: Company inv: c.numberOfEmployees > 50 context c: Company inv enoughEmployees: c.numberOfEmployees > 50 self: contextual instance, an instance to which the OCL expression is attached An explicit specification of contextual instance, c an optional label

12 Basic: Pre and Post-conditions Pre and post-conditions: conditions that must be true at the moment when an operation begins and ends its execution. context Account::deposit(amt: Integer): void pre: amt > 0 post: balance = + amt context Account::deposit(amt: Integer): void pre argumentOk: amt > 0 post balanceIncreased: balance = + amt optional label pre-value, referring to previous value

13 Referring to Pre-value and denotes the value of a property at the start of an operations result: denotes the result of an operation context Account::payInterest(rate: Real): void post: balance = + context Account::getBalance(): Integer post: result = balance

14 Navigating in OCL Expressions Use dot notation to navigate through associations –Direction and multiplicity matter –Use role names or class names 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 Customer Account 0..* 1 accountsowner Arrow notation for collection operations single line (--) or multiple lines (/* … */)

15 Exercise Write pre and post-conditions Pair (5 minutes) Person - sex: Sex + marry(p: Person): void 0..1 spouse

16 Exercise Formulate constraints or business rules for the following class diagram. 16

17 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. 1.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. 2.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). 3.The system shall allow students to take tests prepared by the instructor. 4.The system shall grade tests taken by students to calculate test scores. 5.The system shall allow both the instructor and the students view their scores. However, students are allowed to view only their tests. 17

18 Outline Motivation Basics of OCL OCL types OCL collections Other features 18

19 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

20 Basic Types TypeValuesOperations Booleanfalse, trueor, and, xor, not, =, <>, implies Integer-10, 0, 10, … =, <>,, =, +, -, *, /, mod(), div(), abs(), max(), min(), round(), floor() Real-1.5, 3.14, … String‘Carmen’ =, <>, concat(), size(), toLower(), toUpper(), substring() Several basic types with operations

21 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) Axioms of associativity and commutitivity hold: a + (b + c) = (a + b) + c a + b = b + a

22 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?

23 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?

24 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?

25 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 Customer Account 0..* 1 accountsowner

26 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) Customer Account 0..* accounts Bank 0..* customers

27 Using Enumeration Use “::” notation context Account inv: type = AccountType::gold implies minBalance > and type = AccountType::silder implies minBalance > 5000 > AccountType gold silver Account 1 type

28 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 Course 0..* Outcome score: Integer Student students 0..*

29 Outline Motivation Basics of OCL OCL types OCL collections Other features 29

30 Collections in OCL Why? –Multiple objects produced by navigating associations Standard collection types –Parameterized with elements types, e.g., Set(Account) –Value/immutable types, 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.

31 Collection Types Properties TypeDuplicate?Ordered? Set OrderedSet Bag Sequence NNYYNNYY NYNYNYNY *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}}

32 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 0..* 1 accountsowner context Accountcontext Account inv: not owner->isEmpty() inv: not owner.isEmpty()

33 Collection Operations OperationDescription count(o) excludes(o) excludesAll(c) includes(o) includesAll(c) isEmpty() notEmpty() size() sum() Number of occurrences of o in the collection (self) Is o not an element of the collection? Are all the elements of c not present in the collection? Is o an element of the collection? Are all the elements of c contained in the collection? Does the collection contain no element? Does the collection contain one or more elements? Number of elements in the collection Addition of all elements in the collection Defined on all collection types Type-specific operations append, including, excluding, first, last, insertAt, etc.

34 Exercise Write pre- and post-conditions for: –includes –excludes –includesAll –excludesAll –isEmpty –notEmpty Hint: use forAll operations for includesAll and excludesAll.

35 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)

36 Iteration Operations 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) Customer Account 0..* 1 accountsowner

37 Iteration Operations OperationDescription any(expr) collect(expr) exists(expr) forAll(expr) isUnique(expr) iterate(x: S; y: T| expr) one(expr) reject(expr) select(expr) sortedBy(expr) Returns any element for which expr is true Returns a collection that results from evaluating expr for each element of self Has at least one element for which expr is true? Is expr true for all elements? Does expr has unique value for all elements? Iterates over all elements Has only one element for which expr is true? Returns a collection containing all elements for which expr is false Returns a collection containing all elements for which expr is true Returns a collection containing all elements ordered by expr

38 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)

39 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) Customer 0..* accounts customers Account balance: Integer Bank 0..* Note that results are flattened for “collect” and not for “collectNested”.

40 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)

41 Exercise 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. 0..* 1 accounts Account + getBalance(): Real Customer + getBelowAverage(): Set(Account)

42 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)

43 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?

44 Outline Motivation Basics of OCL OCL types OCL collections Other features 44

45 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() Customer 0..* owners Account balance: Integer

46 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)