Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCE 606: Interfaces and Contracts

Similar presentations


Presentation on theme: "CSCE 606: Interfaces and Contracts"— Presentation transcript:

1 CSCE 606: Interfaces and Contracts
Some material from Bruegge, Dutoit

2 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

3 CSCE 606 Interfaces and Contracts
Context Requirements elicitation  Functional model (use cases, formal specifications etc.)  Non-functional requirements Analysis  Analysis Object Model (class diagrams)  Dynamic Model (state charts, sequence diagrams) System design (we have not discussed yet)  Design goals  Subsystem decomposition Object design Object design model (class diagrams) Interface contracts, syntactic and semantic Library APIs, error handling Implementation Source code Testing  Deliverable system 9/19/2018 CSCE 606 Interfaces and Contracts

4 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

5 CSCE 606 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. 9/19/2018 CSCE 606 Interfaces and Contracts

6 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

7 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

8 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 9/19/2018 CSCE 606 Interfaces and Contracts

9 Full Type Signatures in UML
9/19/2018 CSCE 606 Interfaces and Contracts

10 CSCE 606 Interfaces and Contracts
Access Control in UML 9/19/2018 CSCE 606 Interfaces and Contracts

11 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” Example invariant: months have 28 to 31 days 9/19/2018 CSCE 606 Interfaces and Contracts

12 CSCE 606 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. But inefficiency of many little wrapper methods, fundamental problem of layering vs. maintainability 1Karl Lieberherr and Ian Holland, Assuring Good Style for Object-Oriented Programs, IEEE Software, Sep. 1989, pp 9/19/2018 CSCE 606 Interfaces and Contracts

13 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

14 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 9/19/2018 CSCE 606 Interfaces and Contracts

15 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 9/19/2018 CSCE 606 Interfaces and Contracts

16 Meta-Object Facility (MOF)
OMG standard for MDE M0 = real world objects, M1 = User model 9/19/2018 CSCE 606 Interfaces and Contracts

17 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

18 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

19 CSCE 606 Interfaces and Contracts
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 9/19/2018 CSCE 606 Interfaces and Contracts

20 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

21 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 9/19/2018 CSCE 606 Interfaces and Contracts

22 CSCE 606 Interfaces and Contracts
Formal Specification A contract is called a formal specification, if the invariants, rights and obligations in the contract are unambiguous 9/19/2018 CSCE 606 Interfaces and Contracts

23 Expressing Constraints in UML Models
A constraint can also be depicted as a note attached to the constrained UML element by a dependency relationship 9/19/2018 CSCE 606 Interfaces and Contracts

24 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 9/19/2018 CSCE 606 Interfaces and Contracts

25 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? 9/19/2018 CSCE 606 Interfaces and Contracts

26 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

27 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

28 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

29 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

30 CSCE 606 Interfaces and Contracts
OCL Post-Conditions Example: context Tournament::acceptPlayer(p) post: self.getNumPlayers() = + 1 In English: “The number of accepted player in a tournament increases by one after the completion of acceptPlayer()” Notes: 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 9/19/2018 CSCE 606 Interfaces and Contracts

31 OCL Contract for acceptPlayer() in Tournament
context Tournament::acceptPlayer(p) pre: not isPlayerAccepted(p) getNumPlayers() < getMaxNumPlayers() context Tournament::acceptPlayer(p) post: isPlayerAccepted(p) getNumPlayers() + 1 9/19/2018 CSCE 606 Interfaces and Contracts

32 OCL Contract for removePlayer() in Tournament
context Tournament::removePlayer(p) pre: isPlayerAccepted(p) context Tournament::removePlayer(p) post: not isPlayerAccepted(p) getNumPlayers() - 1 9/19/2018 CSCE 606 Interfaces and Contracts

33 Java Implementation of Tournament class (Contract as JavaDoc comments)
public class Tournament { /** The maximum number of players * is positive at all times. 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 public int getMaxNumPlayers() {…} /** The acceptPlayer() operation * assumes that the specified * player has not been accepted * in the Tournament yet. !isPlayerAccepted(p) getNumPlayers()<maxNumPlayers isPlayerAccepted(p) getNumPlayers() = + 1 */ public void acceptPlayer (Player p) {…} /** The removePlayer() operation * assumes that the specified player * is currently in the Tournament. isPlayerAccepted(p) !isPlayerAccepted(p) - 1 public void removePlayer(Player p) {…} } 9/19/2018 CSCE 606 Interfaces and Contracts

34 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) 9/19/2018 CSCE 606 Interfaces and Contracts

35 Example from ARENA: League, Tournament, Player
Constraints: A Tournament’s planned duration must be under one week Players can be accepted in a Tournament only if they are already registered with the corresponding League The number of active Players in a League are those that have taken part in at least one Tournament of the League 9/19/2018 CSCE 606 Interfaces and Contracts

36 Instance Diagram: 2 Leagues, 5 Players, 2 Tournaments
9/19/2018 CSCE 606 Interfaces and Contracts

37 Three Types of Navigation Through a Class Diagram
Any constraint for an arbitrary UML class diagram can be specified using a combination of these 9/19/2018 CSCE 606 Interfaces and Contracts

38 Specifying the Model Constraints in OCL
9/19/2018 CSCE 606 Interfaces and Contracts

39 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts

40 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) 9/19/2018 CSCE 606 Interfaces and Contracts

41 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 9/19/2018 CSCE 606 Interfaces and Contracts

42 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 9/19/2018 CSCE 606 Interfaces and Contracts

43 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 9/19/2018 CSCE 606 Interfaces and Contracts

44 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. 9/19/2018 CSCE 606 Interfaces and Contracts

45 CSCE 606 Interfaces and Contracts
9/19/2018 CSCE 606 Interfaces and Contracts

46 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 9/19/2018 CSCE 606 Interfaces and Contracts

47 OCL Constraints on the Loyalty Account
9/19/2018 CSCE 606 Interfaces and Contracts

48 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 servicelevel denotes a sequence 9/19/2018 CSCE 606 Interfaces and Contracts

49 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” servicelevel->last.name = “Platinum” 9/19/2018 CSCE 606 Interfaces and Contracts

50 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 loyaltyprogram denotes a set of objects of type LoyaltyProgram customer denotes a multiset of objects of type Customer 9/19/2018 CSCE 606 Interfaces and Contracts

51 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 9/19/2018 CSCE 606 Interfaces and Contracts

52 CSCE 606 Interfaces and Contracts
Example of 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: nrcustomer = loyaltyprogram->customer->asSet->size 9/19/2018 CSCE 606 Interfaces and Contracts

53 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 9/19/2018 CSCE 606 Interfaces and Contracts

54 Another Navigation Example: Mortgage System
Constraints (in the Problem Statement): “A person can have a mortgage only on the house owned by that person” The start date of a mortgage must be before its end date 9/19/2018 CSCE 606 Interfaces and Contracts

55 Formal Specification of the Constraints in OCL
Constraints (in the Problem Statement): “A person can have a mortgage only on the house owned by that person” context Mortgage inv: security.owner = borrower The start date of a mortgage must be before its end date context Mortgage inv: startDate < endDate 9/19/2018 CSCE 606 Interfaces and Contracts

56 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 9/19/2018 CSCE 606 Interfaces and Contracts

57 CSCE 606 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)) 9/19/2018 CSCE 606 Interfaces and Contracts

58 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 The Dresden OCL Toolkit for Eclipse ocl2-for-eclipse/2.0/ocl2-foreclipse-2.0.tar.gz/download 9/19/2018 CSCE 606 Interfaces and Contracts

59 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 , Jan. 1997 age.html C. A. R. Hoare, An Axiomatic Basis for Computer Programming, Communications of the ACM, 12(10): , October 1969 Good starting point for Hoare logic: 9/19/2018 CSCE 606 Interfaces and Contracts

60 CSCE 606 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 9/19/2018 CSCE 606 Interfaces and Contracts


Download ppt "CSCE 606: Interfaces and Contracts"

Similar presentations


Ads by Google