1 OCL – The Object Constraint Language in UML OCL website: Textbook: “ The Objection Constraint Language: Precise Modeling with.

Slides:



Advertisements
Similar presentations
Formal Methods of Systems Specification Logical Specification of Hard- and Software Dr. Armin Wolf Fraunhofer Institut für Rechnerarchitektur.
Advertisements

The role of OCL in the Model Driven Architecture Jos Warmer Klasse Objecten
1 CIS224 Software Projects: Software Engineering and Research Methods Lecture 11 Brief introduction to the UML Specification (Based on UML Superstructure.
ICE1341 Programming Languages Spring 2005 Lecture #6 Lecture #6 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
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.
OCL2 April A presentation of OCL 2 Object Constraint Language Christian Hein, Fraunhofer FOKUS April 2006.
ISBN Chapter 3 Describing Syntax and Semantics.
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 9, Object Design: Object Constraint Language.
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 8, Object Design: Object Constraint Language.
CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.
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.
272: Software Engineering Fall 2008 Instructor: Tevfik Bultan Lecture 4: Object Constraint Language.
1 Specifying Object Interfaces. 2 Major tasks in this stage: --are there any missing attributes or operations? --how can we reduce coupling, make interface.
CS 330 Programming Languages 09 / 16 / 2008 Instructor: Michael Eckmann.
MORE ON CLASS MODELS Lecture Outline Aggregation and composition Roles Navigability Qualified association Derived association Constraints Association.
Describing Syntax and Semantics
Common Mechanisms in UML
UML Class Diagrams: Basic Concepts. Objects –The purpose of class modeling is to describe objects. –An object is a concept, abstraction or thing that.
1 Formal Specifications for Complex Systems (236368) Tutorial #7 OCL Object Constraint Language.
UML – Part 1 Introduction to concepts and syntax. Valmor Adami Jr.
SEG4110 – Advanced Software Engineering and Reengineering TOPIC E Object Constraint Language (OCL)
Understanding Advanced UML Concepts Gerd Wagner
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,
Navigation of Class Models So far we have shown how class models can express the structure of an application Here, we’ll show how to express the behavior.
Introduction to UML 1 Quick Tour Why do we model? What is the UML? Foundation elements Unifying concepts Language architecture Relation to other OMG technologies.
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.
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.
CS3773 Software Engineering Lecture 04 UML Class Diagram.
These courseware materials are to be used in conjunction with Software Engineering: A Practitioner’s Approach, 6/e and are provided with permission by.
CS551 - Lecture 8 1 CS551 Modelling with Objects (Chap. 3 of UML) Yugi Lee STB #555 (816)
Unified Modeling Language © 2002 by Dietrich and Urban1 ADVANCED DATABASE CONCEPTS Unified Modeling Language Susan D. Urban and Suzanne W. Dietrich Department.
® IBM Software Group © 2006 IBM Corporation Rational Software France Object-Oriented Analysis and Design with UML2 and Rational Software Modeler 03. Classes,
Engineering 5895: Software Design 9/11/01Class Diagrams 1.
Fall 2010 CS4310 Requirements Engineering A Brief Review of UML & OO Dr. Guoqiang Hu Department of Computer Science UTEP 1.
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.
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.
These courseware materials are to be used in conjunction with Software Engineering: A Practitioner’s Approach, 6/e and are provided with permission by.
IM NTU Software Development Methods, Fall2006 Software Development Methods, Fall 2006 OCL 2006/12/ Object Constraint Language (OCL) Yih-Kuen Tsay.
Object Constraint Language
1 Kyung Hee University Constraints Spring Kyung Hee University Graphical Notations  Graphical notations are well suited for displaying structural.
Object Constraint Language (OCL) OCL provides a way to develop more precise models using UML What is a constraint in Object Constraint Language? A constraint.
Formal Methods in Software Engineering1 Today’s Agenda  Quiz 2 next class  Presentation Schedule  Quick Review  Build Models Using OCL.
1 / 48 Formal a Language Theory and Describing Semantics Principles of Programming Languages 4.
(14-2) UML Instructor - Andrew O’Fallon CptS 122 (December 2, 2015) Washington State University.
Chapter 16: UML Class Diagrams
Formal Methods in Software Engineering1 Today’s Agenda  Quiz 1 Return  Project Discussion  Quick Review  Finish Introduction to OCL.
Class Diagram Lecture # 1. Class diagram A Class Diagram is a diagram describing the structure of a system shows the system's classes Attributes operations.
Interpreting the Object Constraint Presented by: Ed Kausmeyer.
Object Design More Design Patterns Object Constraint Language Object Design Specifying Interfaces Review Exam 2 CEN 4010 Class 18 – 11/03.
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.
Object-Oriented Analysis and Design
Chapter 8, Object Design: Object Constraint Language
Extending UML.
The Object Constraint Language
Chapter 9, Object Design: Object Constraint Language
CSCE 606: Interfaces and Contracts
UML Class Diagrams: Basic Concepts
Specifying Object Interfaces
UML: Unified Modeling Language
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 Constraint Language (OCL)
Formal Methods in Software Engineering 1
Presentation transcript:

1 OCL – The Object Constraint Language in UML OCL website: Textbook: “ The Objection Constraint Language: Precise Modeling with UML ”, by Jos Warmer and Anneke Kleppe This presentation includes some slides by: Yong He, Tevfik Bultan, Brian Lings, Lieber.

2 History First developed in 1995 as IBEL by IBM’s Insurance division for business modelling IBM proposed it to the OMG’s call for an object-oriented analysis and design standard. OCL was then merged into UML 1.1. OCL was used to define UML 1.2 itself.

3 Companies behind OCL Rational Software, Microsoft, Hewlett- Packard, Oracle, Sterling Software, MCI Systemhouse, Unisys, ICON Computing, IntelliCorp, i-Logix, IBM, ObjecTime, Platinum Technology, Ptech, Taskon, Reich Technologies, Softeam

4 UML Diagrams are NOT Enough! We need a language to help with the spec. We look for some “add-on” instead of a brand new language with full specification capability. Why not first order logic? – Not OO. OCL is used to specify constraints on OO systems. OCL is not the only one. But OCL is the only one that is standardized.

5 OCL – fills the missing gap: Formal specification language  implementable. Supports object concepts. “Intuitive” syntax – reminds OO programming languages. But – OCL is not a programming language:  No control flow.  No side-effects.

6 Advantages of Formal Constraints Better documentation  Constraints add information about the model elements and their relationships to the visual models used in UML  It is way of documenting the model More precision  OCL constraints have formal semantics, hence, can be used to reduce the ambiguity in the UML models Communication without misunderstanding  UML models are used to communicate between developers, Using OCL constraints modelers can communicate unambiguously

7 Where to use OCL? Specify invariants for classes and types Specify pre- and post-conditions for methods As a navigation language To specify constraints on operations Test requirements and specifications

8 Example: A Mortgage System 1.A person may have a mortgage only on a house he/she owns. The start date of a mortgage is before its end date.

9 OCL specification of the constraints: 1. context Mortgage context Mortgage invariant: self.security.owner = self.borrower invariant: security.owner = borrower 2. context Mortgage context Mortgage invariant: self.startDate < self.endDateinvariant: startDate < endDate

10 More Constraints Examples All players must be over 18. The number of guests in each room doesn’t exceed the number of beds in the room. context Player invariant: self.age >=18 context Room invariant: guests -> size <= numberOfBeds Room roomguest Guest numberOfBeds: Integer * Player age: Integer

11 Constraints (invariants), Contexts and Self A constraint (invariant) is a boolean OCL expression – evaluates to true/false. Every constraint is bound to a specific type (class, association class, interface) in the UML model – its context. The context objects may be denoted within the expression using the keyword ‘self’. The context can be specified by:  Context  A dashed note line connecting to the context figure in the UML models A constraint might have a name following the keyword invariant.

12 Example of a static UML Model Problem story: A company handles loyalty programs (class LoyaltyProgram) for companies (class ProgramPartner) that offer their customers various kinds of bonuses. Often, the extras take the form of bonus points or air miles, but other bonuses are possible. Anything a company is willing to offer can be a service (class Service) rendered in a loyalty program. Every customer can enter the loyalty program by obtaining a membership card (class CustomerCard). The objects of class Customer represent the persons who have entered the program. A membership card is issued to one person, but can be used for an entire family or business. Loyalty programs can allow customers to save bonus points (class loyaltyAccount), with which they can “buy” services from program partners. A loyalty account is issued per customer membership in a loyalty program (association class Membership). Transactions (class Transaction) on loyalty accounts involve various services provided by the program partners and are performed per single card. There are two kinds of transactions: Earning and burning. Membership durations determine various levels of services (class serviceLevel).

13 LoyaltyProgram enroll(c:Customer) Service condition: Boolean pointsEarned: Integer pointsBurned: Integer description: String 0..*deliveredServices Membership LoyaltyAccount points: Integer earn(i: Integer) burn(i: Integer) isEmpty(): Boolean Customer name: String title:String isMale: Boolean dateOfBirth: Date CustomerCard valid: Boolean validForm: Date goodThru: Date color: enum{silver, gold} printedName: String 0..* age(): Integer program owner card0..* card ProgramPartner numberOfCustomers: Integer partners 1..* ServiceLevel name: String availableServices 0..* {ordered}1..* * actualLevel Transaction points: Integer date:Date program(): LoyaltyProgram 0..* transactions card transactions 0..* transactions 0..* BurningEarning Date $now: Date isBefore(t:Date): Boolean isAfter(t:Date): Boolean =(t:Date): Boolean level generatedBy partner 1 account

14 Using OCL in Class Diagrams LoyaltyAccount points: Integer earn(i: Integer) burn(i: Integer) isEmpty(): Boolean { points >= 0 } > points = - i class invariant postcondition for burn operation > result = (points=0) > points >= i and i >= 0 precondition for burn operation > points = + i > i >= 0

15 Invariants on Attributes Invariants on attributes: context Customer invariant agerestriction: age >= 18 context CustomerCard invariant correctDates: validFrom.isBefore(goodThru) The type of validFrom and goodThru is Date. isBefore(Date):Boolean is a Date operation. The class on which the invariant must be put is the invariant context. For the above example, this means that the expression is an invariant of the Customer class.

16 Invariants using Navigation over Association Ends – Roles (1) Navigation over associations is used to refer to associated objects, starting from the context object: context CustomerCard invariant: owner.age >= 18 owner  a Customer instance. owner.age  an Integer. Note: This is not the “right” context for this constraint! If the role name is missing – use the class name at the other end of the association, starting with a lowercase letter. Preferred: Always give role names.

17 Invariants using Navigation over Association Ends – Roles (2) context CustomerCard invariant printedName: printedName = owner.title.concat(‘ ‘).concat(owner.name) printedName  a String. owner  a Customer instance. owner.title  a String. owner.name  a String. String is a recognized OCL type. concat is a String operation, with the signature concat(String): String.

18 Invariants using Navigation from Association Classes Navigation from an association class can use the classes at the association class end, or the role names. The context object is the association class instance – a tuple. “The owner of the card of a membership must be the customer in the membership”: context Membership invariant correctCard: card.owner = customer

19 Invariants using Navigation through Association Classes Navigation from a class through an association class uses the association class name to obtain all tuples of an object: “The cards of the memberships of a customer are only the customer’s cards”: context Customer invariant correctCard: cards->includesAll(Membership.card) This is exactly the same as the previous constraint: “ The owner of the card of a membership must be the customer in the membership”: context Membership invariant correctCard: card.owner = customer The Membership correctCard constrain is better!

20 Invariants using Navigation through Associations with “Many” Multiplicity Navigation over associations roles with multiplicity greater than 1 yields a Collection type. Operations on collections are accessed using an arrow ->, followed by the operation name. “A customer card belongs only to a membership of its owner”: context CustomerCard invariant correctCard: owner.Membership->includes(membership) owner  a Customer instance. owner.Membership  a set of Membership instances. membership  a Membership instance. includes is an operation of the OCL Collection type.

21 Navigating to collections CustomerAccountTransaction context Customer account produces a set of Accounts context Customer account.transaction produces a bag of transactions If we want to use this as a set we have to do the following account.transaction -> asSet 0..*

22 Navigation to Collections “The partners of a loyalty program have at least one delivered service”: context LoyaltyProgram invariant minServices: partners.deliveredservices->size() >= 1 “The number of a customer’s programs is equal to that of his/her valid cards”: context Customer invariant sizesAgree: Programs->size() = cards->select(valid=true)->size()

23 Navigation to Collections “When a loyalty program does not offer the possibility to earn or burn points, the members of the loyalty program do not have loyalty accounts. That is, the loyalty accounts associated with the Memberships must be empty”: context LoyaltyProgram invariant noAccounts: partners.deliveredservices-> forAll(pointsEarned = 0 and pointsBurned = 0) implies Membership.account->isEmpty() and, or, not, implies, xor are logical connectives.

24 The OCL Collection types Collection is a predefined OCL type  Operations are defined for collections  They never change the original Three different collections:  Set (no duplicates)  Bag (duplicates allowed)  Sequence (ordered Bag) With collections type, an OCL expression either states a fact about all objects in the collection or states a fact about the collection itself, e.g. the size of the collection. Syntax:  collection->operation

25 Collection Operations  size  isEmpty  notEmpty  sum ( )  count ( object )  includes ( object )  includesAll ( collection )

26 Collections cont.  select ( e:T | )  reject ( e:T | )  collect ( e:T | )  forAll ( e:T* | )  exists ( e:T | )  iterate ( e:T 1 ; r:T 2 = | ) b.e. stands for: boolean expression v.e. stands for: value expression

27 context StoreCard invariant: printName = owner.title.concat(owner.name) context Customer cards  forAll ( printName = owner.title.concat(owner.name) ) Changing the context Customer printName:String points: Integer 1..* ownercards StoreCard name:String title: String golduser: Boolean age( ):Integer earn(p:Integer) Note switch of context!

28 takestaken_by Example UML diagram StudentModule Assessment ExamCoursework 0..*1..* 0..* for_module set_work submits submitted_by name: String code: String credit: Integer weight: Integer hours: Integerdate: String

29 Constraints a) Modules can be taken iff they have more than seven students registered b) The assessments for a module must total 100% c) Students must register for 120 credits each year d) Students must take at least 90 credits of CS modules each year e) All modules must have at least one assessment worth over 50% f) Students can only have assessments for modules which they are taking

30 Constraint (a) a) Modules can be taken iff they have more than seven students registered Note: when should such a constraint be imposed? context Module invariant: taken_by  size > 7

31 Constraint (b) b) The assessments for a module must total 100% context Module invariant: set_work.weight  sum( ) = 100

32 Constraint (c) c) Students must register for 120 credits each year context Student invariant: takes.credit  sum( ) = 120

33 Constraint (d) d) Students must take at least 90 credits of CS modules each year context Student invariant: takes  select(code.substring(1,2) = ‘CS’).credit  sum( ) >= 90

34 Constraint (e) e) All modules must have at least one assessment worth over 50% context Module invariant: set_work  exists(weight > 50)

35 Constraint (f) f) Students can only have assessments for modules which they are taking context Student invariant: takes  includesAll(submits.for_module)

36 Invariants using Navigation through Cyclic Association Classes Navigation through association classes that are cyclic requires use of roles to distinguish between association ends: object.associationClass[role] The accumulated score of an employee is positive: context Person invariant: employeeRanking[bosses].score->sum()>0 Every boss must give at least one 10 score: context Person invariant: employeeRanking[employees]->exists(score = 10) Person EmploymentRanking * *employees bosses score

37 Invariants using Navigation through Qualified Association To navigate qualified associations you need to index the qualified association using a qualifier object.navigation[qualifierValue,...]  If there are multiple qualifiers their values are separated using commas Example context LoyaltyProgram serviceLevel[1].name = ‘basic’ context LoyaltyProgram serviceLevel->exists(name = ‘basic’) LoyaltyProgram enroll(c:Customer) ServiceLevel name: String 0..1 levelNumber: Integer

38 Classes and Subclasses Consider the following constraint context LoyaltyProgram invariant: partners.deliveredServices.transaction.points->sum() < 10,000 If the constraint applies only to the Burning subclass, we can use the operation oclType of OCL: context LoyaltyProgram invariant: partners.deliveredServices.transaction ->select(oclType = Burning).points->sum() < 10,000

39 Classes and Subclasses “ The target of a dependency is not its source” context Dependency invariant: self.source <> self Is ambiguous: Dependency is both a ModelElement and an Association class. context Dependency invariant: self.oclAsType(Dependency).source <> self invariant: self.oclAsType(ModelElement).source -> isEmpty() ModelElement NoteDependency * * target source

40 OCL Constraints A constraint is a restriction on one or more values of (part of) an object model/system. Constraints come in different forms:  invariant constraint on a class or type that must always hold  pre-condition constraint that must hold before the execution of an op.  post-condition constraint that must hold after the execution of an op.  guard constraint on the transition from one state to another. We study only class constraints (invariants).

41 OCL Expressions and Constraints Each OCL expression has a type. Every OCL expression indicates a value or object within the system.  1+3 is a valid OCL expression of type Integer, which represents the integer value 4. An OCL expression is valid if it is written according to the rules (formal grammar) of OCL. A constraint is a valid OCL expression of type Boolean.

42 Combining UML and OCL Without OCL expressions, the model would be severely underspecified; Without the UML diagrams, the OCL expressions would refer to non-existing model elements,  there is no way in OCL to specify classes and associations. Only when we combine the diagrams and the constraints can we completely specify the model.

43 Elements of an OCL expression that is associated with a UML model basic types: String, Boolean, Integer, Real. classes from the UML model and their attributes. enumeration types from the UML model. associations from the UML model.

44 What is OCL Anyway? A textual specification language A expression language Is side-effect-free language Standard query language Is a strongly typed language  so expressions can be precise Is a formal language Is part of UML Is used to define UML Is Not a programming language The OCL is declarative rather than imperative Mathematical foundation, but no mathematical symbols  based on set theory and predicate logic  has a formal mathematical semantics

45 What did People Say? OCL is too implementation-oriented and therefore not well-suited for conceptual modelling. Moreover, it is at times unnecessarily verbose, far from natural language.  Alloy modelling language The use of operations in constraints appears to be problematic  An operation may go into an infinite loop or be undefined. Not stand alone language OCL is a local expression. (Mandana and Daniel) I would rather use plain English (Martin Fowler)

46 References The Amsterdam Manifesto on OCL In Object Modeling with the OCL (LNCS2263) p The Object Constraint Language, Precise Modeling with UML, Addison- Wesley, The Object Constraint Language, Precise Modeling with UML 2nd Response to the UML 2.0 OCL RfP (ad/ ) Revised Submission, Version 1.6 January 6, 2003 Some Shortcomings of OCL, the Object Constraint Language of UML Mandana Vaziri and Daniel Jackson, UML CENTER Informal formality? The Object Constraint Language and its application in the UML metamodel Anneke Kleppe, Jos Warmer, Steve Cook A Pratical Application of the Object Constraint Language OCL Kjetil M°age The UML's Object Constraint Language: OCL Specifying Components, JAOO Tutorial – September 2000 Jos Warmer & Anneke Kleppe