Download presentation
Presentation is loading. Please wait.
Published byMyrtle Newton Modified over 9 years ago
1
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 8, Object Design: Object Constraint Language
2
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 2 Outline of the Lecture OCL Simple predicates Preconditions Postconditions Contracts Sets, Bags, and Sequences
3
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 3 OCL: Object Constraint Language Formal language for expressing constraints over a set of objects and their attributes in a model Used to write constraints that cannot otherwise be expressed in a diagram Developed by IBM Originally part of the UML standard OCL can now be used with any MOF meta-model OCL is used in the QVT specification for model transformations (Queries-Views-Transformations specification) Declarative No side effects, No control flow Based on Sets and Multi Sets.
4
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 4 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.
5
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 5 OCL Simple Predicates Example: context Tournament inv: self.getMaxNumPlayers() > 0 In English: “The maximum number of players in any tournament should be a postive number.” Notes: “self” denotes all instances of “Tournament” OCL uses the same dot notation as Java.
6
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 6 OCL Preconditions 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 precondition is an operation isPlayerAccepted(p) is an operation defined by the class Tournament.
7
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 7 OCL Postconditions Example: context Tournament::acceptPlayer(p) post: self.getNumPlayers() = self@pre.getNumPlayers() + 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.
8
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 8 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
9
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 9 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
10
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 10 Java Implementation of Tournament class (Contract as a set of 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) {…} }
11
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 11 Constraints can involve more than one class How do we specify constraints on 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).
12
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 12 Example from ARENA: League, Tournament and Player players *tournaments {ordered} Tournament +start:Date +end:Date +acceptPlayer(p:Player) * League +start:Date +end:Date +getActivePlayers() * Player +name:String +email:String *players tournaments* 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.
13
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 13 Instance Diagram: 2 Leagues tttExpert:League chessNovice:League alice:Player bob:Player marc:Player joe:Player zoe:Player winter:Tournament start=Jan 12 end= Jan 14 Xmas:Tournament start=Dec 23 end= Dec 25, 5 Players, 2 Tournaments
14
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 14 3 Types of Navigation through a Class Diagram 1. Local attribute2. Directly related class3. Indirectly related class Tournament League * * Player * League Player * * Tournament start:Date end:Date Any constraint for an arbitrary UML class diagram can be specified using only a combination of these 3 navigation types!
15
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 15 Specifying the Model Constraints in OCL Local attribute navigation players *tournaments {ordered} Tournament +start:Date +end:Date +acceptPlayer(p:Player) * League +start:Date +end:Date +getActivePlayers() * Player +name:String +email:String *players tournaments* Directly related class navigation context Tournament inv: end - start <= 7 context Tournament::acceptPlayer(p) pre: league.players->includes(p)
16
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 16 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
17
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 17 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)
18
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 18 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.
19
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 19 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 auftreten) 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 OCL- expression expr is true.
20
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 20 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
21
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 21 Loyalty Program Problem Statement A customer loyalty program (LoyaltyProgram) associated 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 obtainining 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. Source: Jos Warmer& Anneke Kleppe, The Object Constraint Language: Getting your models ready for MDA, 2 nd edition, Addison Wesley, 2003.
22
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 22 22 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 programs owner card 0..* card ProgramPartner numberOfCustomers: Integer partners 1..* ServiceLevel name: String availableServices 0..* {ordered}1..* 0..1 0..* 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 1 1 1 1 1 1 1 1 1 level generatedBy partner 1 account
23
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 23 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 name: String titel: String age: Integer birthday: Date getage(): Integer Customer valid: Boolean validSince: Date expires: Date color: enum { silver, gold} printedName : String customerCard owner card * card denotes a set of customercards
24
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 24 24 OCL Constraints on the Loyalty Account LoyaltyAccount points: Integer earn(i: Integer) burn(i: Integer) isEmpty(): Boolean { points >= 0 } > points = points@pre - i class invariant postcondition for burn operation > result = (points=0) > points >= i and i >= 0 precondition for burn operation > points = points@pre + i > i >= 0
25
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 25 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 2 LoyaltyProgram servicelevel->size = 2 enroll(k: Customer) LoyaltyProgram {ordered} name: String ServiceLevel * servicelevel denotes a sequence
26
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 26 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“ LoyaltyProgram enroll(c:Customer) ServiceLevel name: String 1..* 1 {ordered}
27
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 27 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” Navigation through several 1:n-Associations ProgramPartner nrcustomer = loyaltyprogram->customer->size nrcustomer: Integer ProgramPartner name: String titel: String age: Integer Dateof Birth: Date age(): Integer Customer 1..* enroll(k:Customer) LoyaltyProgram programs *.* customer denotes a multiset of objects of type Customer loyaltyprogram denotes a set of objects of type L oyaltyProgram Context ProgramPartner inv nrcustomer = loyaltyprogram->customer->size
28
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 28 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.
29
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 29 Example of a Conversion programPartner 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 nrcustomer: Integer programPartner name: String titel: String age: Integer dateOfBirth: Date age(): Integer Customer 1..* entroll(k:Customer) LoyaltyProgram programs *.*
30
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 30 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.
31
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 31 Another Navigation Example: A Mortgage System
32
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 32 Another Navigation Example: A 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 before its end date.”
33
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 33 Formal Specification of the Constraints in OCL context Mortgage inv: security.owner = borrower context Mortgage inv: startDate < endDate 1.“A person can have a mortgage only on the house owned by that person” 2. “The start date of a mortgage must before its end date.”
34
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 34 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.
35
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 35 ForAll Example (From Arena) 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)) Player players * matches * * tournaments players * Match -start:Date -end:Date Tournament +start:Date +end:Date +acceptPlayer(p:Player) Date now: Date isBefore(t:Date): Boolean isAfter(t:Date): Boolean equals(t:Date): Boolean
36
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 36 Exists Example Problem Statement: “Each Tournament conducts at least one Match on the first day of the Tournament” context Tournament inv: matches->exists(m:Match| m.start.equals(start)) Player players * matches * * tournaments players * Match -start:Date -end:Date Tournament +start:Date +end:Date +acceptPlayer(p:Player) Date now: Date isBefore(t:Date): Boolean isAfter(t:Date): Boolean =(t:Date): Boolean
37
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 37 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-for-eclipse- 2.0.tar.gz/download
38
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 38 Readings about Contracts B. Meyer Object-Oriented Software Construction, 2nd edition, Prentice Hall, 1997. B. Meyer, Design by Contract: The Lesson of Ariane, Computer, IEEE, Vol. 30, No. 2, pp. 129-130, January 1997. http://archive.eiffel.com/doc/manuals/technology/contract/arian e/page.html http://archive.eiffel.com/doc/manuals/technology/contract/arian e/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)
39
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 39 Summary Constraints are predicates (often boolean expressions) on UML model elements Contracts are constraints on a class that enable class users, implementors 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.
40
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 40 Backup and Additional Slides
41
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 41 Additional Constraints on this Model 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.
42
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 42 Additional Constraints on this Model 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.
43
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 43 Additional Constraints on this Model 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.
44
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 44 ForAll Example (2) English: “A match can only involve players who are accepted in the tournament” context Match inv: players->forAll(p| p.tournaments->exists(t| t.matches->includes(self))) context Match inv: players.tournaments.matches.includes(self) Player players * matches * * tournaments players * Match -start:Date -end:Date Tournament +start:Date +end:Date +acceptPlayer(p:Player)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.