1 / 60

CSCE 431: Interfaces and Contracts

CSCE 431: Interfaces and Contracts. Some material from Bruegge , Dutoit. Outline. Context OO Interfaces Object Constraint Language (OCL) Constraints in UML OCL Simple predicates Pre-conditions Post-conditions Contracts Sets , Bags, and Sequences. Context. Requirements elicitation

fala
Download Presentation

CSCE 431: Interfaces and Contracts

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Outline • Context • OO Interfaces • Object Constraint Language (OCL) • Constraints in UML • OCL • Simple predicates • Pre-conditions • Post-conditions • Contracts • Sets, Bags, and Sequences CSCE 431 Interfaces and Contracts

  3. 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 • Interface contracts, syntactic and semantic • Library APIs, error handling • Source code • Testing  Deliverable system CSCE 431 Interfaces and Contracts

  4. 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 CSCE 431 Interfaces and Contracts

  5. 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. CSCE 431 Interfaces and Contracts

  6. 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 CSCE 431 Interfaces and Contracts

  7. Outline • Context • OO Interfaces • Object Constraint Language (OCL) • Constraints in UML • OCL • Simple predicates • Pre-conditions • Post-conditions • Contracts • Sets, Bags, and Sequences CSCE 431 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 CSCE 431 Interfaces and Contracts

  9. Full Type Signatures in UML CSCE 431 Interfaces and Contracts

  10. Access Control in UML CSCE 431 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” CSCE 431 Interfaces and Contracts

  12. Law of Demeter1 • Method Mof an object Omay only invoke the methods of the following kinds of objects: • Oitself • 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. CSCE 431 Interfaces and Contracts

  13. Outline • Context • OO Interfaces • Object Constraint Language (OCL) • Constraints in UML • OCL • Simple predicates • Pre-conditions • Post-conditions • Contracts • Sets, Bags, and Sequences CSCE 431 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 CSCE 431 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 CSCE 431 Interfaces and Contracts

  16. Meta-Object Facility (MOF) • OMG standard for MDE CSCE 431 Interfaces and Contracts

  17. 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 CSCE 431 Interfaces and Contracts

  18. Outline • Context • OO Interfaces • Object Constraint Language (OCL) • Constraints in UML • OCL • Simple predicates • Pre-conditions • Post-conditions • Contracts • Sets, Bags, and Sequences CSCE 431 Interfaces and Contracts

  19. 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 CSCE 431 Interfaces and Contracts

  20. 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 CSCE 431 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 CSCE 431 Interfaces and Contracts

  22. Formal Specification • A contract is called a formal specification, if the invariants, rights and obligations in the contract are unambiguous CSCE 431 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 CSCE 431 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 CSCE 431 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? CSCE 431 Interfaces and Contracts

  26. Outline • Context • OO Interfaces • Object Constraint Language (OCL) • Constraints in UML • OCL • Simple predicates • Pre-conditions • Post-conditions • Contracts • Sets, Bags, and Sequences CSCE 431 Interfaces and Contracts

  27. 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 CSCE 431 Interfaces and Contracts

  28. 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 CSCE 431 Interfaces and Contracts

  29. 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 CSCE 431 Interfaces and Contracts

  30. OCL Post-Conditions • 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@predenotes the state of the tournament before the invocation of the operation • selfdenotes the state of the tournament after the completion of the operation CSCE 431 Interfaces and Contracts

  31. 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 CSCE 431 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) context Tournament::removePlayer(p) post: getNumPlayers() = @pre.getNumPlayers() - 1 CSCE 431 Interfaces and Contracts

  33. Java Implementation of Tournament class (Contract as JavaDoccomments) public class Tournament { /** The maximum number of players * is positive at all times. * @invariant maxNumPlayers > 0 */ private intmaxNumPlayers; /** 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 intgetNumPlayers() {…} /** Returns the maximum number of * players in the tournament. */ public intgetMaxNumPlayers() {…} /** 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) {…} } CSCE 431 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) CSCE 431 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 CSCE 431 Interfaces and Contracts

  36. Instance Diagram: 2 Leagues, 5 Players, 2 Tournaments CSCE 431 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 CSCE 431 Interfaces and Contracts

  38. Specifying the Model Constraints in OCL CSCE 431 Interfaces and Contracts

  39. 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 CSCE 431 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) CSCE 431 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 OclAnyis the most general OCL-Type CSCE 431 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 OCLexpressionexpris true CSCE 431 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 CSCE 431 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. CSCE 431 Interfaces and Contracts

  45. CSCE 431 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 Customerinv: card-> size <= 4 • Alternative writing style Customer Card->size <= 4 card denotes a setof customercards CSCE 431 Interfaces and Contracts

  47. OCL Constraints on the Loyalty Account CSCE 431 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 CSCE 431 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” LoyaltyProgram: servicelevel->last.name = “Platinum” CSCE 431 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” ContextProgramPartnerinv Nrcustomer = loyaltyprogram->customer->size ProgramPartner Nrcustomer = loyaltyprogram->customer->size customer denotes a multiset of objects of type Customer loyaltyprogram denotes a set of objects of type LoyaltyProgram CSCE 431 Interfaces and Contracts

More Related