Docsity

Understanding OCL (Object Constraint Language) in UML (Unified Modeling Language), Exams of Computer Science

Toggle sidebar
bg1
September 2001 OMG-Unified Modeling Language, v1.4 6-1
Object Constraint Language
Specification 6
This chapter introduces and defines the Object Constraint Language (OCL), a formal
language to express side-effect-free constraints.
Contents
This chapter contains the following topics.
6.1 Overview
This chapter introduces and defines the Object Constraint Language (OCL), a formal
language used to express constraints. These typically specify invariant conditions that
must hold for the system being modeled. Note that when the OCL expressions are
evaluated, they do not have side effects; that is, their evaluation cannot alter the state of
Topic Page
“Overview” 6-1
“Introduction” 6-3
“Relation to the UML Metamodel” 6-4
“Basic Values and Types” 6-7
“Objects and Properties” 6-11
“Collection Operations” 6-22
“The Standard OCL Package” 6-28
“Predefined OCL Types” 6-29
“Grammar” 6-45
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32

Partial preview of the text

Download Understanding OCL (Object Constraint Language) in UML (Unified Modeling Language) and more Exams Computer Science in PDF only on Docsity!

September 2001 OMG-Unified Modeling Language, v1.4 6-

Object Constraint Language

Specification 6

This chapter introduces and defines the Object Constraint Language (OCL), a formal language to express side-effect-free constraints.

Contents

This chapter contains the following topics.

6.1 Overview

This chapter introduces and defines the Object Constraint Language (OCL), a formal language used to express constraints. These typically specify invariant conditions that must hold for the system being modeled. Note that when the OCL expressions are evaluated, they do not have side effects; that is, their evaluation cannot alter the state of

Topic Page

“Overview” 6- “Introduction” 6- “Relation to the UML Metamodel” 6- “Basic Values and Types” 6- “Objects and Properties” 6- “Collection Operations” 6- “The Standard OCL Package” 6- “Predefined OCL Types” 6- “Grammar” 6-

6-2 OMG-Unified Modeling Language, v1.4 September 2001

the corresponding executing system. In addition, to specifying invariants of the UML metamodel, UML modelers can use OCL to specify application-specific constraints in their models.

OCL is used in the UML Semantics chapter to specify the well-formedness rules of the metaclasses comprising the UML metamodel. A well-formedness rule in the static semantics chapters in the UML Semantics section normally contains an OCL expression, specifying an invariant for the associated metaclass. The grammar for OCL is specified at the end of this chapter. A parser generated from this grammar has correctly parsed all the constraints in the UML Semantics section, a process which improved the correctness of the specifications for OCL and UML.

6.1.1 Why OCL?

A UML diagram, such as a class diagram, is typically not refined enough to provide all the relevant aspects of a specification. There is, among other things, a need to describe additional constraints about the objects in the model. Such constraints are often described in natural language. Practice has shown that this will always result in ambiguities. In order to write unambiguous constraints, so-called formal languages have been developed. The disadvantage of traditional formal languages is that they are usable to persons with a strong mathematical background, but difficult for the average business or system modeler to use.

OCL has been developed to fill this gap. It is a formal language that remains easy to read and write. It has been developed as a business modeling language within the IBM Insurance division, and has its roots in the Syntropy method.

OCL is a pure expression language; therefore, an OCL expression is guaranteed to be without side effect. When an OCL expression is evaluated, it simply returns a value. It cannot change anything in the model. This means that the state of the system will never change because of the evaluation of an OCL expression, even though an OCL expression can be used to specify a state change (for example, in a post-condition).

OCL is not a programming language; therefore, it is not possible to write program logic or flow control in OCL. You cannot invoke processes or activate non-query operations within OCL. Because OCL is a modeling language in the first place, not everything in it is promised to be directly executable.

OCL is a typed language, so that each OCL expression has a type. To be well formed, an OCL expression must conform to the type conformance rules of the language. For example, you cannot compare an Integer with a String. Each Classifier defined within a UML model represents a distinct OCL type. In addition, OCL includes a set of supplementary predefined types (these are described in Section 6.8, “Predefined OCL Types,” on page 6-29).

As a specification language, all implementation issues are out of scope and cannot be expressed in OCL.

The evaluation of an OCL expression is instantaneous. This means that the states of objects in a model cannot change during evaluation.

6-4 OMG-Unified Modeling Language, v1.4 September 2001

Figure 6-1 Class Diagram Example

6.3 Relation to the UML Metamodel

6.3.1 Self

Each OCL expression is written in the context of an instance of a specific type. In an OCL expression, the reserved word self is used to refer to the contextual instance. For instance, if the context is Company, then self refers to an instance of Company.

6.3.2 Specifying the UML context

The context of an OCL expression within a UML model can be specified through a so- called context declaration at the beginning of an OCL expression. The context declaration of the constraints in the following sections is shown.

Person isMarried : Boolean isUnemployed : Boolean birthDate : Date age : Integer firstName : String lastName : String sex : Sex

income(Date) : Integer

accountNumber:Integer

Bank

customer

Company name : String numberOfEmployees : Integer

stockPrice() : Real

manager 0..* managedCompanies

employee employer

wife

husband 0..

Job title : String startDate : Date salary : Integer

Marriage place : String date : Date

male female

«enumeration» Sex

September 2001 OMG-UML , v1.4 Relation to the UML Metamodel 6-

If the constraint is shown in a diagram with the proper stereotype and the dashed lines to connect it to its contextual element, there is no need for an explicit context declaration in the test of the constraint. The context declaration is optional.

6.3.3 Invariants

The OCL expression can be part of an Invariant which is a Constraint stereotyped as an «invariant». When the invariant is associated with a Classifier, the latter is referred to as a “type” in this chapter. An OCL expression is an invariant of the type and must be true for all instances of that type at any time. (Note that all OCL expressions that express invariants are of the type Boolean.)

For example, if in the context of the Company type in Figure 6-1 on page 6-4, the following expression would specify an invariant that the number of employees must always exceed 50: self.numberOfEmployees > 50

where self is an instance of type Company. (We can view self as the object from where we start the expression.) This invariant holds for every instance of the Company type.

The type of the contextual instance of an OCL expression, which is part of an invariant, is written with the context keyword, followed by the name of the type as follows. The label inv: declares the constraint to be an «invariant» constraint. context Company inv : self.numberOfEmployees > 50

In most cases, the keyword self can be dropped because the context is clear, as in the above examples. As an alternative for self, a different name can be defined playing the part of self: context c : Company inv : c.numberOfEmployees > 50

This invariant is equivalent to the previous one.

Optionally, the name of the constraint may be written after the inv keyword, allowing the constraint to be referenced by name. In the following example the name of the constraint is enoughEmployees. In the UML metamodel, this name is an attribute of the metaclass Constraint that is inherited from ModelElement. context c : Company inv enoughEmployees: c.numberOfEmployees > 50

6.3.4 Pre- and Postconditions

The OCL expression can be part of a Precondition or Postcondition, corresponding to «precondition» and «postcondition» stereotypes of Constraint associated with an Operation or Method. The contextual instance self then is an instance of the type that owns the operation or method as a feature. The context declaration in OCL uses the

September 2001 OMG-UML , v1.4 Basic Values and Types 6-

6.3.6 General Expressions

Any OCL expression can be used as the value for an attribute of the UML metaclass Expression or one of its subtypes. In that case, the semantics section describes the meaning of the expression.

6.4 Basic Values and Types

In OCL, a number of basic types are predefined and available to the modeler at all times. These predefined value types are independent of any object model and part of the definition of OCL.

The most basic value in OCL is a value of one of the basic types. Some basic types used in the examples in this document, with corresponding examples of their values, are shown in Table 6-1.

OCL defines a number of operations on the predefined types. Table 6-2 gives some examples of the operations on the predefined types. See Section 6.8, “ Predefined OCL Types,” on page 6-29 for a complete list of all operations.

The complete list of operations provided for each type is described at the end of this chapter. Collection, Set, Bag, and Sequence are basic types as well. Their specifics will be described in the upcoming sections.

6.4.1 Types from the UML Model

Each OCL expression is written in the context of a UML model, a number of classifiers (types/classes, ...), their features and associations, and their generalizations. All classifiers from the UML model are types in the OCL expressions that are attached to the model.

Table 6-1 Basic Types

type values Boolean true, false Integer 1, -5, 2, 34, 26524, ... Real 1.5, 3.14, ... String 'To be or not to be...'

Table 6-2 Operations on predefined types

type operations Integer *, +, -, /, abs() Real *, +, -, /, floor() Boolean and, or, xor, not, implies, if-then-else String toUpper(), concat()

6-8 OMG-Unified Modeling Language, v1.4 September 2001

6.4.2 Enumeration Types

Enumerations are Datatypes in UML and have a name, just like any other Classifier. An enumeration defines a number of enumeration literals, that are the possible values of the enumeration. Within OCL one can refer to the value of an enumeration. When we have Datatype named Sex with values ‘female’ or ‘male’ they can be used as follows: context Person inv: sex = Sex::male

6.4.3 Let Expressions and «definition» Constraints

Sometimes a sub-expression is used more than once in a constraint. The let expression allows one to define an attribute or operation that can be used in the constraint. context Person inv : let income : Integer = self.job.salary->sum() let hasTitle(t : String) : Boolean = self.job->exists(title = t) in if isUnemployed then self.income < 100 else self.income >= 100 and self.hasTitle(‘manager’) endif

A let expression may be included in an invariant or pre- or postcondition. It is then only known within this specific constraint. To enable reuse of let variables/operations one can use a Constraint with the stereotype «definition», in which let variables/operations are defined. This «definition» Constraint must be attached to a Classifier and may only contain let definitions. All variables and operations defined in the «definition» constraint are known in the same context as where any property of the Classifier can be used. In essence, such variables and operations are psuedo-attributes and psuedo-operations of the classifier. They are used in an OCL expression in exactly the same way as attributes or operations are used. The textual notation for a «definition» Constraint uses the keyword ‘def’ as shown below: context Person def : let income : Integer = self.job.salary->sum() let hasTitle(t : String) : Boolean = self.job->exists(title = t)

The names of the attributes / operations in a let expression may not conflict with the names of respective attributes/associationEnds and operations of the Classifier. Also, the names of all let variables and operations connected with a Classifier must be unique.

6-10 OMG-Unified Modeling Language, v1.4 September 2001

When it is certain that the actual type of the object is the subtype, the object can be re- typed using the operation oclAsType(OclType). This operation results in the same object, but the known type is the argument OclType. When there is an object object of type Type1 and Type2 is another type, it is allowed to write: object.oclAsType(Type2) --- evaluates to object with type Type

An object can only be re-typed to one of its subtype s; therefore, in the example, Type must be a subtype of Type.

If the actual type of the object is not a subtype of the type to which it is re-typed, the expression is undefined (see Section 6.4.10, “Undefined Values,” on page 6-11).

6.4.6 Precedence Rules

The precedence order for the operations, starting with highest precedence, in OCL is:

- @pre - dot and arrow operations: ‘.’ and ‘->’ - unary ‘not’ and unary minus ‘-’ - ‘*’ and ‘/’ - ‘+’ and binary ‘-’ - ‘if-then-else-endif’ - ‘<’, ‘>’, ‘<=’, ‘>=’ - ‘=’, ‘<>’ - ‘and’, ‘or’ and ‘xor’ - ‘implies’

Parentheses ‘(’ and ‘)’ can be used to change precedence.

6.4.7 Use of Infix Operators

The use of infix operators is allowed in OCL. The operators ‘+’, ‘-’, ‘*’. ‘/’, ‘<‘, ‘>’, ‘<>’ ‘<=’ ‘>=’ are used as infix operators. If a type defines one of those operators with the correct signature, they will be used as infix operators. The expression: a + b

is conceptually equal to the expression: a.+(b)

that is, invoking the ‘+’ operation on a with b as the parameter to the operation.

The infix operators defined for a type must have exactly one parameter. For the infix operators ‘<‘, ‘>’, ‘<=’, ‘>=’, ‘<>’, ‘and’, ‘or’, and ‘xor’ the return type must be Boolean.

September 2001 OMG-UML , v1.4 Objects and Properties 6-

6.4.8 Keywords

Keywords in OCL are reserved words. That means that the keywords cannot occur anywhere in an OCL expression as the name of a package, a type or a property. The list of keywords is shown below:

6.4.9 Comment

Comments in OCL are written following two successive dashes (minus signs). Everything immediately following the two dashes up to and including the end of line is part of the comment. For example: -- this is a comment

6.4.10 Undefined Values

Whenever an OCL expression is being evaluated, there is a possibility that one or more of the queries in the expression are undefined. If this is the case, then the complete expression will be undefined.

There are two exceptions to this for the Boolean operators:

- True OR-ed with anything is True - False AND-ed with anything is False

The above two rules are valid irrespective of the order of the arguments and the above rules are valid whether or not the value of the other sub-expression is known.

6.5 Objects and Properties

OCL expressions can refer to Classifiers; for example, types, classes, interfaces, associations (acting as types), and datatypes. Also all attributes, association-ends, methods, and operations without side-effects that are defined on these types, etc. can be used. In a class model, an operation or method is defined to be side-effect-free if the

if implies then endpackage else package endif context not def let inv or pre and post xor in

September 2001 OMG-UML , v1.4 Objects and Properties 6-

The right-hand-side of this definition may refer to the operation being defined; that is, the definition may be recursive as long as the recursion is not infinite. The type of result is the return type of the operation, which is Integer in the above example.

To refer to an operation or a method that doesn’t take a parameter, parentheses with an empty argument list are mandatory: context Company inv : self.stockPrice() > 0

6.5.4 Properties: Association Ends and Navigation

Starting from a specific object, we can navigate an association on the class diagram to refer to other objects and their properties. To do so, we navigate the association by using the opposite association-end: object.rolename

The value of this expression is the set of objects on the other side of the rolename association. If the multiplicity of the association-end has a maximum of one (“0..1” or “1”), then the value of this expression is an object. In the example class diagram, when we start in the context of a Company; that is, self is an instance of Company, we can write: context Company inv : self.manager.isUnemployed = false inv : self.employee ->notEmpty()

In the first invariant self.manager is a Person, because the multiplicity of the association is one. In the second invariant self.employee will evaluate in a Set of Persons. By default, navigation will result in a Set. When the association on the Class Diagram is adorned with {ordered}, the navigation results in a Sequence.

Collections, like Sets, Bags, and Sequences are predefined types in OCL. They have a large number of predefined operations on them. A property of the collection itself is accessed by using an arrow ‘->’ followed by the name of the property. The following example is in the context of a person: context Person inv : self.employer->size() < 3

This applies the size property on the Set self.employer , which results in the number of employers of the Person self. context Person inv : self.employer->isEmpty()

This applies the isEmpty property on the Set self.employer. This evaluates to true if the set of employers is empty and false otherwise.

6-14 OMG-Unified Modeling Language, v1.4 September 2001

6.5.4.1 Missing Rolenames

When a rolename is missing at one of the ends of an association, the name of the type at the association end, starting with a lowercase character, is used as the rolename. If this results in an ambiguity, the rolename is mandatory. This is the case with unnamed rolenames in reflexive associations. If the rolename is ambiguous, then it cannot be used in OCL.

6.5.4.2 Navigation over Associations with Multiplicity Zero or One

Because the multiplicity of the role manager is one, self.manager is an object of type Person. Such a single object can be used as a Set as well. It then behaves as if it is a Set containing the single object. The usage as a set is done through the arrow followed by a property of Set. This is shown in the following example: context Company inv : self.manager->size() = 1

The sub-expression self.manager is used as a Set, because the arrow is used to access the size property on Set. This expression evaluates to true.

The following example shows how a property of a collection can be used. context Company inv : self.manager->foo

The sub-expression self.manager is used as Set, because the arrow is used to access the foo property on the Set. This expression is incorrect, because foo is not a defined property of Set. context Company inv : self.manager.age> 40

The sub-expression self.manager is used as a Person, because the dot is used to access the age property of Person.

In the case of an optional (0..1 multiplicity) association, this is especially useful to check whether there is an object or not when navigating the association. In the example we can write: context Person inv : self.wife->notEmpty() implies self.wife.sex = Sex::female

6.5.4.3 Combining Properties

Properties can be combined to make more complicated expressions. An important rule is that an OCL expression always evaluates to a specific object of a specific type. After obtaining a result, one can always apply another property to the result to get a new result value. Therefore, each OCL expression can be read and evaluated left-to-right.

Following are some invariants that use combined properties on the example class diagram:

6-16 OMG-Unified Modeling Language, v1.4 September 2001

self.employeeRanking[bosses]->sum() > 0

the self.employeeRanking[bosses] evaluates to the set of EmployeeRankings belonging to the collection of bosses. And in the expression context Person inv : self.employeeRanking[employees]->sum() > 0

the self.employeeRanking[employees] evaluates to the set of EmployeeRankings belonging to the collection of employees. The unqualified use of the association class name is not allowed in such a recursive situation. Thus, the following example is invalid: context Person inv : self.employeeRanking->sum() > 0 -- INVALID!

In a non-recursive situation, the association class name alone is enough, although the qualified version is allowed as well. Therefore, the examples at the start of this section could also be written as: context Person inv : self.job[employer]

6.5.6 Navigation from Association Classes

We can navigate from the association class itself to the objects that participate in the association. This is done using the dot-notation and the role-names at the association- ends. context Job inv : self.employer.numberOfEmployees >= 1 inv : self.employee.age > 21

Navigation from an association class to one of the objects on the association will always deliver exactly one object. This is a result of the definition of AssociationClass. Therefore, the result of this navigation is exactly one object, although it can be used as a Set using the arrow (->).

6.5.7 Navigation through Qualified Associations

Qualified associations use one or more qualifier attributes to select the objects at the other end of the association. To navigate them, we can add the values for the qualifiers to the navigation. This is done using square brackets, following the role-name. It is permissible to leave out the qualifier values, in which case the result will be all objects at the other end of the association. context Bank inv : self.customer

This results in a Set(Person) containing all customers of the Bank. context Bank inv : self.customer[8764423]

September 2001 OMG-UML , v1.4 Objects and Properties 6-

This results in one Person, having accountnumber 8764423.

If there is more than one qualifier attribute, the values are separated by commas, in the order which is specified in the UML class model. It is not permissible to partially specify the qualifier attribute values.

6.5.8 Using Pathnames for Packages

Within UML, different types are organized in packages. OCL provides a way of explicitly referring to types in other packages by using a package-pathname prefix. The syntax is a package name, followed by a double colon: Packagename::Typename

This usage of pathnames is transitive and can also be used for packages within packages: Packagename1::Packagename2::Typename

6.5.9 Accessing overridden properties of supertypes

Whenever properties are redefined within a type, the property of the supertypes can be accessed using the oclAsType() operation. Whenever we have a class B as a subtype of class A, and a property p1 of both A and B, we can write: context B inv : self.oclAsType(A).p1 -- accesses the p1 property defined in A self.p1 -- accesses the p1 property defined in B

Figure 6-3 shows an example where such a construct is needed.

Figure 6-3 Accessing Overridden Properties Example

In this model fragment there is an ambiguity with the OCL expression on Dependency: context Dependency inv :

D e p en de n cy

targ et

source

M od elE lem e n t

N ote value: Uninterprete d

September 2001 OMG-UML , v1.4 Objects and Properties 6-

In the example statemachine above, values for s can be On , Off , Off::Standby , Off::NoPower. If the classifier of object has the above associated statemachine valid OCL expressions are: object.oclInState(On) object.oclInState(Off) object.oclInstate(Off::Standby) object.oclInState(Off:NoPower)

If there are multiple statemachines attached to the object’s classifier, then the statename can be prefixed with the name of the statemachine containing the state and the double semicolon ::, as with nested states.

The operation oclIsNew evaluates to true if, used in a postcondition, the object is created during performing the operation; that is, it didn’t exist at precondition time.

6.5.11 Features on Classes Themselves

All properties discussed until now in OCL are properties on instances of classes. The types are either predefined in OCL or defined in the class model. In OCL, it is also possible to use features defined on the types/classes themselves. These are, for example, the class -scoped features defined in the class model. Furthermore, several features are predefined on each type.

A predefined feature on each type is allInstances , which results in the Set of all instances of the type in existence at the specific time when the expression is evaluated. If we want to make sure that all instances of Person have unique names, we can write: context Person inv : Person.allInstances->forAll(p1, p2 | p 1 <> p2 implies p1.name <> p2.name)

The Person.allInstances is the set of all persons and is of type Set(Person). It is the set of all persons that exist at the snapshot in time that the expression is evaluated.

Note – The use of allInstances has some problems and its use is discouraged in most cases. The first problem is best explained by looking at the types like Integer, Real and String. For these types the meaning of allInstances is undefined. What does it mean for an Integer to exist? The evaluation of the expression Integer.allInstances results in an infinite set and is therefore undefined within OCL. The second problem with allInstances is that the existence of objects must be considered within some overall context, like a system or a model. This overall context must be defined, which is not done within OCL. A recommended style is to model the overall contextual system explicitly as an object within the system and navigate from that object to its containing instances without using allInstances.

6-20 OMG-Unified Modeling Language, v1.4 September 2001

6.5.12 Collections

Single navigation results in a Set, combined navigations in a Bag, and navigation over associations adorned with {ordered} results in a Sequence. Therefore, the collection types play an important role in OCL expressions.

The type Collection is predefined in OCL. The Collection type defines a large number of predefined operations to enable the OCL expression author (the modeler) to manipulate collections. Consistent with the definition of OCL as an expression language, collection operations never change collections; isQuery is always true. They may result in a collection, but rather than changing the original collection they project the result into a new one.

Collection is an abstract type, with the concrete collection types as its subtypes. OCL distinguishes three different collection types: Set, Sequence, and Bag. A Set is the mathematical set. It does not contain duplicate elements. A Bag is like a set, which may contain duplicates; that is, the same element may be in a bag twice or more. A Sequence is like a Bag in which the elements are ordered. Both Bags and Sets have no order defined on them. Sets, Sequences, and Bags can be specified by a literal in OCL. Curly brackets surround the elements of the collection, elements in the collection are written within, separated by commas. The type of the collection is written before the curly brackets: Set { 1 , 2 , 5 , 88 } Set { 'apple' , 'orange', 'strawberry' }

A Sequence: Sequence { 1, 3, 45, 2, 3 } Sequence { 'ape', 'nut' }

A bag: Bag {1 , 3 , 4, 3, 5 }

Because of the usefulness of a Sequence of consecutive Integers, there is a separate literal to create them. The elements inside the curly brackets can be replaced by an interval specification, which consists of two expressions of type Integer, Int-expr1 and Int-expr2 , separated by ‘..’. This denotes all the Integers between the values of Int- expr1 and Int-expr2 , including the values of Int-expr1 and Int-expr2 themselves: Sequence{ 1..(6 + 4) } Sequence{ 1..10 } -- are both identical to Sequence{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }

The complete list of Collection operations is described at the end of this chapter.

Collections can be specified by a literal, as described above. The only other way to get a collection is by navigation. To be more precise, the only way to get a Set, Sequence, or Bag is:

  1. a literal, this will result in a Set, Sequence, or Bag: Set {1 , 2, 3 , 5 , 7 , 11, 13, 17 }