CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

60
CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit

Transcript of CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

Page 1: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431:Interfaces and

Contracts

Some material from Bruegge, Dutoit

Page 2: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Outline

• Context

• OO Interfaces

• Object Constraint Language (OCL)

• Constraints in UML• OCL• Simple predicates• Pre-conditions• Post-conditions• Contracts• Sets, Bags, and Sequences

Page 3: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Context1. Requirements elicitation

Functional model (use cases, formal specifications etc.) Non-functional requirements

2. Analysis Analysis Object Model (class diagrams) Dynamic Model (state charts, sequence diagrams)

3. System design (we have not discussed yet) Design goals Subsystem decomposition

4. Object designÞ Object design model (class diagrams)Þ Interface contracts, syntactic and semanticÞ Library APIs, error handling

5. ImplementationÞ Interface contracts, syntactic and semanticÞ Library APIs, error handlingÞ Source code

6. Testing Deliverable system

Page 4: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Object Design

• Purpose• Prepare for implementing the system model• Transform the system model for better

implementability, extensibility, performance, …

• Explore ways to implement the system model

• The result of object design should match the structure of the implementation

Page 5: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Activities• Reuse: identify and adapt existing solutions

• Off-the-shelf components• Libraries• Design patterns

• Interface specification• Specs of each class interface• APIs of subsystems

• Object model restructuring• To improve some characteristics (extensibility,

understandability, etc.)

• Object model optimization• Greater speed, lower memory use, etc.

Page 6: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Executive Summary

• UML models can be gradually refined to include more details about interfaces

• UML+OCL: Notations and language to express contracts (pre/post conditions, invariants) in UML

• Interesting part is constraints that span multiple classes (constraints over UML associations)

• Language neutral constraints

Page 7: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Outline

• Context

• OO Interfaces

• Object Constraint Language (OCL)

• Constraints in UML• OCL• Simple predicates• Pre-conditions• Post-conditions• Contracts• Sets, Bags, and Sequences

Page 8: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Refining the Object Model

• Full type signatures• Function name• Inputs and outputs and types• E.g. function prototype in C/C++

• Access control• What is public and private

• Contracts• Between object and user

Page 9: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Full Type Signatures in UML

Page 10: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Access Control in UML

Page 11: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Access Control Guidelines• Expose as little as possible

• But the “basis” should be complete—and efficient• The less exposed, the more freedom to change the

class implementation• Fewer things to learn and document

• Access attributes only via operations (except when no class invariant)

• Hide substructures• Do not apply an operation to the result of another

operation• Write a new operation that combines the two operations• “Law of Demeter”

Page 12: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Law of Demeter1

• Method M of an object O may only invoke the methods of the following kinds of objects:

• O itself• M’s parameters• Any objects created/instantiated within M• O’s direct component objects• Global variables, accessible by O, in the scope of M

• Example violation: x.y.foo().bar()• Layered architectures satisfy the law• One goal: compositionality

• The meaning of a complex expression is determined by the meanings of its immediate constituent expressions and the rules used to combine them

• Testimonial (from JPL):We have found, however, that breaking the LoD is very expensive! On Mars Pathfinder, the integration costs of the law breaking parts of the system were at least an order of magnitude higher, and we had to pay that cost on every integration cycle – not just once! We should have paid the cost once by implementing a more sophisticated protocol that did obey the LoD.

1Karl Lieberherr and Ian Holland, Assuring Good Style for Object-Oriented Programs, IEEE Software, Sep. 1989, pp. 38-48.

Page 13: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Outline

• Context

• OO Interfaces

• Object Constraint Language (OCL)

• Constraints in UML• OCL• Simple predicates• Pre-conditions• Post-conditions• Contracts• Sets, Bags, and Sequences

Page 14: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Object Constraint Language (OCL)• Formal language for expressing constraints over a set of objects

and their attributes in a model• Used for constraints that cannot otherwise be expressed in a diagram —

Precisely model the well-formedness rules of UML models• Developed by IBM in 1995

• “Business Engineering Language”

• Constraints are conditions on all states and transitions between states of a system implementing a given model

• Restricts possible (or allowed) system states• Commonly pre- and post-conditions, and invariants

• Originally part of the UML standard• OCL can now be used with any Meta-Object Facility (MOF) meta-model

• Specification language, not a programming language• Declarative• No side effects, atomic execution• Strongly typed

Page 15: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Aside: meta-meta-meta…• What is this meta business about?

• “meta” – about itself, e.g. metadata is data about data

• Concepts of Model-Driven Engineering (MDE)• A model represents a particular aspect of a system under

construction, operation or maintenance• A model is written in the language of one specific metamodel• A metamodel is an explicit specification of abstraction, based on

shared agreement. A metamodel acts as a filter to extract some relevant aspects from a system and to ignore all other details.

• A metametamodel defines a language to write metamodels. There are several possibilities to define a metametamodel. Usually the definition is reflexive, i.e. the metametamodel is self-defined.

• What we write with UML are models, UML itself is a metamodel

Page 16: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Meta-Object Facility (MOF)• OMG standard for MDE

Page 17: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Who Uses OCL• Not many

• Some success stories in ensuring consistency of specification of a model, and conformance of data to the specification

• Supported by OMG

• Some tools exist (e.g. plug-in for Eclipse IDE), Rational, …

• Many software development projects tend to favor agile processes, test-driven development

• Not so formal in specifying constraints• Care less about language independence• Main medium is code, test — diagrams used in informal discussions

• Then why study OCL?• Constraints exist, a formal way to think about and specify them• Useful to have in one’s toolbox• There is no de-facto standard formal language for expressing contracts and

constraints; if not de-facto standard, OCL is at least standard

Page 18: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Outline

• Context

• OO Interfaces

• Object Constraint Language (OCL)

• Constraints in UML• OCL• Simple predicates• Pre-conditions• Post-conditions• Contracts• Sets, Bags, and Sequences

Page 19: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Contract• Contract: An agreement between two parties

• Both parties accept obligations• Specification of what a party is entitled to expect on

which both parties can found their rights• The remedy for breach of a contract is usually an

award of money to the injured party

• Object-oriented contract: Describes the services that are provided by an object if certain conditions are fulfilled

• Services = “obligations”, conditions = “rights”• The remedy for breach of an OO-contract is the

generation of an exception

Page 20: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Modeling OO Contracts

• Natural Language

• Mathematical Notation

• Models and contracts:• A language for the formulation of constraints with the

formal strength of the mathematical notation and the easiness of natural language:

⇒ UML + OCL (Object Constraint Language)

• Uses the abstractions of the UML model

• OCL is based on predicate calculus

Page 21: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Contracts and Formal Specification

• Contracts enable the caller and the provider to share the same assumptions about the class

• A contract is an exact specification of the interface of an object

• A contract include three types of constraints:• Invariant:

• A predicate that is always true for all instances of a class

• Pre-condition (“rights”):• Must be true before an operation is invoked

• Post-condition (“obligation”):• Must be true after an operation is invoked

Page 22: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Formal Specification

• A contract is called a formal specification, if the invariants, rights and obligations in the contract are unambiguous

Page 23: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Expressing Constraints in UML Models

• A constraint can also be depicted as a note attached to the constrained UML element by a dependency relationship

Page 24: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Why Not Use Contracts in Requirements Analysis?

• Many constraints represent domain level information

• Why not use them in requirements analysis?• Constraints increase the precision of requirements• Constraints can yield more questions for the end

user• Constraints can clarify the relationships among

several objects

• Constraints are sometimes used during requirements analysis, however there are trade-offs

Page 25: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Requirements vs. Object Design Trade-offs

• Communication among stakeholders• Can the client understand formal constraints?

• Level of detail vs. rate of requirements change• Is it worth precisely specifying a concept that will

change?

• Level of detail vs. elicitation effort• Is it worth the time interviewing the end user?• Will these constraints be discovered during object design

anyway?

• Testing constraints• If tests are generated early, do they require this level of

precision?

Page 26: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Outline

• Context

• OO Interfaces

• Object Constraint Language (OCL)

• Constraints in UML• OCL• Simple predicates• Pre-conditions• Post-conditions• Contracts• Sets, Bags, and Sequences

Page 27: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL Basic Concepts

• OCL expressions• Return True or False• Are evaluated in a specified context, either a class

or an operation• All constraints apply to all instances

Page 28: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL Simple Predicates

• Example:context Tournament inv:

!self.getMaxNumPlayers() > 0

• In English:“The maximum number of players in any tournament should be a positive number.”

• Notes:• “self” denotes all instances of “Tournament”• OCL uses dot notation• Also uses “->” but meaning a little different

Page 29: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL Pre-Conditions

• Example:context Tournament::acceptPlayer(p) pre:

not self.isPlayerAccepted(p)

• In English:“The acceptPlayer(p) operation can only be invoked if player p has not yet been accepted in the tournament.”

• Notes:• The context of a pre-condition is an operation• isPlayerAccepted(p) is an operation defined by

the class Tournament

Page 30: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL Post-Conditions

• Example:context Tournament::acceptPlayer(p) post:

self.getNumPlayers() = [email protected]() + 1

• In English:“The number of accepted player in a tournament increases by one after the completion of acceptPlayer()”

• Notes:• self@pre denotes the state of the tournament before

the invocation of the operation• self denotes the state of the tournament after the

completion of the operation

Page 31: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL Contract for acceptPlayer() in Tournament

context Tournament::acceptPlayer(p) pre:

not isPlayerAccepted(p)

context Tournament::acceptPlayer(p) pre:

getNumPlayers() < getMaxNumPlayers()

context Tournament::acceptPlayer(p) post:

isPlayerAccepted(p)

context Tournament::acceptPlayer(p) post:

getNumPlayers() = @pre.getNumPlayers() + 1

Page 32: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL Contract for removePlayer() in Tournament

context Tournament::removePlayer(p) pre:

isPlayerAccepted(p)

context Tournament::removePlayer(p) post:

not isPlayerAccepted(p)

context Tournament::removePlayer(p) post:

getNumPlayers() = @pre.getNumPlayers() - 1

Page 33: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Java Implementation of Tournament class (Contract as JavaDoc comments)public class Tournament {

/** The maximum number of players

* is positive at all times.

* @invariant maxNumPlayers > 0

*/

private int maxNumPlayers;

/** The players List contains

* references to Players who are

* are registered with the

* Tournament. */

private List players;

/** Returns the current number of

* players in the tournament. */

public int getNumPlayers() {…}

/** Returns the maximum number of

* players in the tournament. */

public int getMaxNumPlayers() {…}

/** The acceptPlayer() operation

* assumes that the specified

* player has not been accepted

* in the Tournament yet.

* @pre !isPlayerAccepted(p)

* @pre getNumPlayers()<maxNumPlayers

* @post isPlayerAccepted(p)

* @post getNumPlayers() =

* @pre.getNumPlayers() + 1

*/

public void acceptPlayer (Player p) {…}

/** The removePlayer() operation

* assumes that the specified player

* is currently in the Tournament.

* @pre isPlayerAccepted(p)

* @post !isPlayerAccepted(p)

* @post getNumPlayers() =

* @pre.getNumPlayers() - 1

*/

public void removePlayer(Player p) {…}

}

Page 34: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Constraints Can Involve More Than One Class

• How do we specify constraints on a group of classes?

• Starting from a specific class in the UML class diagram, we navigate the associations in the class diagram to refer to the other classes and their properties (attributes and Operations)

Page 35: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Example from ARENA: League, Tournament, Player

• Constraints:1. A Tournament’s planned

duration must be under one week

2. Players can be accepted in a Tournament only if they are already registered with the corresponding League

3. The number of active Players in a League are those that have taken part in at least one Tournament of the League

Page 36: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Instance Diagram: 2 Leagues, 5 Players, 2 Tournaments

Page 37: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Three Types of Navigation Through a Class Diagram

Any constraint for an arbitrary UML class diagram can be specified using a combination of these

Page 38: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Specifying the Model Constraints in OCL

Page 39: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL-Collection• The OCL-Type Collection is the generic superclass

of a collection of objects of Type T

• Subclasses of Collection are• Set: Set in the mathematical sense. Every element can

appear only once• Bag: A collection, in which elements can appear more

than once (also called multiset)• Sequence: A multiset, in which the elements are ordered

• Example for Collections:• Set(Integer): a set of integer numbers• Bag(Person): a multiset of persons• Sequence(Customer): a sequence of customers

Page 40: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL Sets, Bags and Sequences

• Sets, Bags and Sequences are predefined in OCL and subtypes of Collection. OCL offers a large number of predefined operations on collections. They are all of the form:collection->operation(arguments)

Page 41: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL-Operations for OCL-Collections (1)

• size: Integer• Number of elements in the collection

• includes(o:OclAny): Boolean• True, if the element o is in the collection

• count(o:OclAny): Integer• Counts how many times an element is contained in the

collection

• isEmpty: Boolean• True, if the collection is empty

• notEmpty: Boolean• True, if the collection is not empty

• The OCL-Type OclAny is the most general OCL-Type

Page 42: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL-Operations for OCL-Collections (2)

• union(c1:Collection)• Union with collection c1

• intersection(c2:Collection)• Intersection with Collection c2 (contains only elements,

which appear in the collection as well as in collection c2)

• including(o:OclAny)• Collection containing all elements of the Collection and

element o

• select(expr:OclExpression)• Subset of all elements of the collection, for which the

OCLexpression expr is true

Page 43: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

How Do We Get OCL-Collections?

• A collection can be generated by explicitly enumerating the elements from the UML model

• A collection can be generated by navigating along one or more 1-N associations in the UML model

• Navigation along a single 1:n association yields a Set• Navigation along a couple of 1:n associations yields a

Bag (Multiset)

• Navigation along a single 1:n association labeled with the constraint {ordered} yields a Sequence

Page 44: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Loyalty Program Problem Statement

A customer loyalty program (LoyaltyProgram) associates many program partners (ProgramPartner) that offer different kinds of bonuses called services (Service) with customers. A customer (Customer) can enter a loyalty program by filling out a form and obtaining a customer card (CustomerCard). A customer can enter many loyalty programs. A customer can have multiple cards. A customer card is uniquely associated with a single customer.

Each customer card is associated with a loyalty account (LoyaltyAccount) and characterized by a service level (ServiceLevel). The loyalty account allows customers to save bonus points in their account. The basic service level is silver. Customers who make a lot of transactions get a higher level of service, gold or platinum. Based on the service level and the saved bonus points, customers can “buy” services from a program partner for a specific number of points. So, earning and buying points are types of transactions (Transaction) on a loyalty account involving services provided by the program partners. They are always only performed for a single customer card.

J. Warmer and A. Kleppe, The Object Constraint Language: Getting your models ready for MDA, 2nd edition, Addison Wesley, 2003.

Page 45: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Page 46: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Navigation Through a 1-to-N Association (Directly Related Class Navigation)

• Example: A Customer should not have more than 4 cards

Context Customer inv:

card-> size <= 4

• Alternative writing style

Customer

Card->size <= 4

card denotes a set of customercards

Page 47: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

OCL Constraints on the Loyalty Account

Page 48: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Navigation Through a Constrained Association

• Navigation through an association with the constraint {ordered} yields a sequence

• Problem Statement: The number of service levels must be 2LoyaltyProgramservicelevel->size = 2

servicelevel denotes a sequence

Page 49: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Operations on OCL-Type Sequence

first: T The first element of a sequence

last: T The last element of a sequence

at(index:Integer): T Element index in the sequence

Problemstatement: The first level in the loyalty program has the name ‘Silver’. The highest level you can reach is ‘Platinum’

OCL-Invariants:LoyaltyProgram:servicelevel->first.name = “Silver”LoyaltyProgram:servicelevel->last.name = “Platinum”

Page 50: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Navigation Through Several 1:n-Associations

Problem Statement: “The number of customers registered by a program partner must be equal to the number of customers belonging to a loyalty program offered by the program partner”

Context ProgramPartner inv

Nrcustomer = loyaltyprogram->customer->size

ProgramPartner

Nrcustomer = loyaltyprogram->customer->size

loyaltyprogram denotes a set of objects of type LoyaltyProgram

customer denotes a multiset of objects of

type Customer

Page 51: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Conversion Between OCL-Collections

• OCL offers operations to convert OCL-Collections:

• asSet• Transforms a multiset or sequence into a set

• asBag• Transforms a set or sequence into a multiset

• asSequence• Transforms a set or multiset into a sequence

Page 52: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Example of ConversionprogramPartner

nrcustomer = loyaltyprogram->customer->size

• Caution: This OCL expression may contain a specific customer several times!

• We can get the number of unique customers as follows:programPartner

nrcustomer = loyaltyprogram->customer->asSet->size

Page 53: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Evaluating OCL Expressions When Navigating a UML Class Diagram• The value of any OCL expression is an object or a

collection of objects

• Navigating an association-end with multiplicity 1• Result: a single object

• Navigating an association-end with multiplicity 0..1• Empty set, if there is no object, otherwise a single object

• Navigating several association-ends with multiplicity n• Result: A collection of objects

• If the association is {ordered}, the navigation result is a OCL sequence

• Multiple “1-n” associations result in a OCL multiset (bag)• Otherwise the navigation result is a OCL set

Page 54: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Another Navigation Example: Mortgage System

• Constraints (in the Problem Statement):1. “A person can have a mortgage only on the house owned by that

person”2. The start date of a mortgage must be before its end date

Page 55: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Formal Specification of the Constraints in OCL

• Constraints (in the Problem Statement):1. “A person can have a mortgage only on the house owned by that person”context Mortgage inv: security.owner = borrower2. The start date of a mortgage must be before its end datecontext Mortgage inv: startDate < endDate

Page 56: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Predicate Calculus vs. First-Order Logic

• So far, we have presented OCL as propositional logic• Propositional logic consists of well formed formulas (wffs) constructed of a

set of primitive symbols (true, false), letters (a, b, x, y,...), and a set of operators (and , ∧ or ∨, not ...)∼

• OCL is actually a first order logic over the domain of OCL collections• Any first order logic also supports quantification

• Existential quantification (in symbolic logic: , in OCL: ∃ exists)• The OCL exists operator takes a Boolean expression as parameter. It

evaluates to true if the parameter is true for at least one element of the OCLcollection

• Universal quantification (in symbolic logic: , in OCL: ∀ forAll)• The OCL forAll operator takes a boolean expression as parameter. It

evaluates to true if it is true for all the elements of the OCLcollection

Page 57: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

ForAll Example

Problem Statement: “All Matches in a Tournament must occur within the time frame of the Tournament”context Tournament inv:

matches->forAll(m|

m.start.isAfter(self.start) and

m.start.isBefore(self.end))

Page 58: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Readings About OCL and Tools

• J.B. Warmer, A.G. Kleppe, The Object Constraint Language: Getting Your Models Ready for MDA, Addison-Wesley, 2nd edition, 2003

• The Dresden OCL Toolkit• http://dresden-ocl.sourceforge.net/

• The Dresden OCL Toolkit for Eclipse• http://

sourceforge.net/projects/dresden-ocl/files/dresden-ocl2-for-eclipse/2.0/ocl2-foreclipse-2.0.tar.gz/download

Page 59: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Readings About Contracts

• B. Meyer Object-Oriented Software Construction, 2nd ed., Prentice Hall, 1997

• B. Meyer, Design by Contract: The Lesson of Ariane, IEEE Computer, vol. 30, no. 2, pp. 129-130, Jan. 1997

• http://archive.eiffel.com/doc/manuals/technology/contract/ariane/page.html

• C. A. R. Hoare, An Axiomatic Basis for Computer Programming, Communications of the ACM, 12(10):576-585, October 1969

• Good starting point for Hoare logic: http://en.wikipedia.org/wiki/Hoare_logic)

Page 60: CSCE 431: Interfaces and Contracts Some material from Bruegge, Dutoit.

CSCE 431 Interfaces and Contracts

Summary• Constraints are predicates (often boolean expressions) on UML

model elements

• Contracts are constraints on a class that enable class users, implementers and extenders to share the same assumption about the class (“Design by contract”)

• OCL is the example of a formal language that allows us to express constraints on UML models

• The names of the model elements in the UML model are used in the formulation of the OCL predicates

• The context definition of an OCL expression specifies the model entity for which the OCL expression is defined

• Complicated constraints involving more than one class, attribute or operation can be formulated by using 3 basic navigation types:

• Local attribute navigation, directly related class navigation, indirectly related class navigation