# Lecture 7 Constraints and Invariants Formal Modeling and Analyzing a Flash File System.

## Presentation on theme: "Lecture 7 Constraints and Invariants Formal Modeling and Analyzing a Flash File System."— Presentation transcript:

Lecture 7 Constraints and Invariants Formal Modeling and Analyzing a Flash File System

Project signup 10 projects: – 2 research, 4 startup, 4 engineering First deadline: proposal 10/10 – 10 minutes presentation, 2 minutes question/feedback – Other documents (instruction will follow 10/3) What to do: – Research: background reading, understand the problems – Startup: business modeling and plans – Engineering: start modeling process Teamwork: what have been done for individual team members

Definition of constraints and invariants OCL expressions – context inv – context init – context def – context pre/post – context derive : OCL basic types and operations – Boolean – Integer – String – Enum OCL Environment: OCLE, a freely available OCL tool: http://lci.cs.ubbcluj.ro/ocle.http://lci.cs.ubbcluj.ro/ocle Review Lecture 6 Constraints and Invariants, OCL

OCL Collection Types

Significance of Collections in OCL Most expressions return collections rather than single elements 10..*FlightAirplane type : enum of cargo, passenger type : enum of cargo, passenger flights

Types of Collection Set: – Non-ordered, unique – Example: Set {1, 2, 5, 88} OrderedSet: – Ordered, unique – Example: OrderedSet {apple, grape, orange} Bag: – Non-ordered, non-unique – Example: Bag {1, 2, 5, 88, 5} Sequence: – Ordered, non-unique – Example: Sequence {2, 3, 4, 5} Sequence {2..5}

Types of Collection

Collection Operations Syntax: – collection collectionOperation – operation.size() is not the same as operation size() context Membership inv: account.isEmpty() context Membership inv: account isEmpty() Use of the (arrow) operator instead of the. (dot) operator

Dot (navigation) vs. arrow (collection) Any OCL expression can navigate through the model by following the path of the association The context of the expression is the starting point. Role names are used to identify the navigated association.

Example: navigations context Flight inv: origin <> destination inv: origin.name = Amsterdam context Airport inv: arrivingFlights.maxNrPassengers < 1000 Airport Flight * * departTime: Time /arrivalTime: Time duration : Interval maxNrPassengers: Integer origin desti- nation name: String arriving Flights departing Flights

Standard Operations on collection types isEmpty(): true if collection has no elements notEmpty(): true if collection has at least one element size(): number of elements in collection count(elem): number of occurrences of elem in collection includes(elem): true if elem is in collection excludes(elem): true if elem is not in collection includesAll(coll): true if all elements of coll are in collection

The equals and notEquals Operation The equals operation results in true if all elements in the two collections are the same. – For sets, all elements in first set must be equal to second set, and vice versa – For ordered sets, order must also be the same – For bags, all elements and the number of times they appear must be same – For sequence, order of elements must be equal, in addition to rules applicable for bags notEquals is the opposite

The including and excluding operations The including operation results in a new collection with one element added to the original collection. – For sets and ordered sets, element is added only if its not already present in the collection. – For sequence or an ordered set, the element is added after all elements in the original collection. The excluding operation results in a new collection with an element removed from the original collection. – For sets and ordered sets, it removes only one element – For bag or sequence, all occurrences of the given element are removed.

Other collection operations asSet, asSequence, asBag, and asOrderedSet Operations – Instances of all four concrete collection types can be transformed into instances of another concrete collection type The union operation combines two collections into a new one The intersection operation results in another collection containing the elements in both collections minus operation (denoted by -) results in a new set containing all the elements in the set on which the operation is called, but not in the parameter set. – Only applicable on sets and ordered sets The symmetricDifference operation results in a set containing all elements in the set on which the operation is called or in the parameter set, but not both. – Defined on sets only

Loop Operators collect(expr) – returns the collections of objects that result from evaluating expr for each element in the source collection select(expr) – returns a subcollection of the source collection containing all elements for which expr is true reject(expr) – returns a subcollection of the source collection containing all elements for which expr is false Exists(expr) – returns true if there is at least one element in the source collection for which expr is true forAll(expr) – returns true if expr is true for all elements in the source collection iterate(…) – iterates over all elements in the source collection collectNested(expr) – returns a collection of collections that result from evaluating expr for each element in the source collection one(expr) – returns true if there is exactly one element in the source collection for which expr is true Any(expr) – returns a random element of the source collection for which the expression expr is true sortedBy(expr) – returns a collection containing all elements of the source collection ordered by expr

Operations on OrderedSets and Sequences only first() and last() at(index) indexOf(object) insertAt(index, object) subSequence(lower, upper) subOrderedSet(lower, upper) append(object) and prepend(object)

Classification of Operations Note 1: In this example: - c is an Sequence of Account objects. -x is an object instance of Account. Note 2: Collections are immutable. Thus, c->append(), in our example, would create a new Sequence.

An Example Airport Flight Passenger Airline * * * * \$minAge: Integer age: Integer needsAssistance: Boolean departTime: Time /arrivalTime: Time duration : Interval maxNrPassengers: Integer origin desti- nation name: String {ordered} arriving Flights departing Flights CEO 0..1 flights passengers book(f : Flight) 0..1 airline Time difference(t:Time):Interval before(t: Time): Boolean plus(d : Interval) : Time \$midnight: Time month : String day : Integer year : Integer hour : Integer minute : Integer Interval equals(i:Interval):Boolean \$Interval(d,h,m : Integer) : Interval nrOfDays : Integer nrOfHours : Integer nrOfMinutes : Integer 1 1 1 1

Example: collect operation context Airport inv: self.arrivingFlights -> collect(airLine) ->notEmpty airp1 airp2 f1 f2 f3 f4 f5 airline1 airline2 airline3 departing flights arriving flights All arriving flights must be associated with an airline

The select operation Syntax: collection select(elem : T | expression) collection select(elem | expression) collection select(expression) The select operation results in the subset of all elements for which expression is true

Example: select operation context Airport inv: self.departingFlights select(duration<4) notEmpty departing flights arriving flights airp1 airp2 airline1 airline2 airline3 f5 duration = 2 f1 duration = 2 f4 duration = 5 f2 duration = 5 f3 duration = 3 There must be at least one departing flight whose duration is less than 4

The forAll operation Syntax: – collection->forAll(elem : T | expr) – collection->forAll(elem | expr) – collection->forAll(expr) The forAll operation results in true if expr is true for all elements of the collection

Example: forAll operation context Airport inv: self.departingFlights->forAll(departTime.hour>6) departing flights arriving flights airp1 airp2 airline1 airline2 airline3 f5 depart = 8 f1 depart = 7 f4 depart = 9 f2 depart = 5 f3 depart = 8 All departing flights must leave after 6

The exists operation Syntax: collection->exists(elem : T | expr) collection->exists(elem | expr) collection->exists(expr) The exists operation results in true if there is at least one element in the collection for which the expression expr is true.

Example: exists operation context Airport inv: self.departingFlights->exists(departTime.hour<6) departing flights arriving flights airp1 airp2 airline1 airline2 airline3 f5 depart = 8 f1 depart = 7 f4 depart = 9 f2 depart = 5 f3 depart = 8

Iterate The iterate operation for collections is the most generic and complex building block. Collection iterate(elem : Type; answer : Type = | )

Iterate example Example iterate: context Airline inv: Flights select(maxNrPassengers > 150) notEmpty Is identical to: context Airline inv: Flights iterate (f : Flight; answer : Set(Flight) = Set{ } | if f.maxNrPassengers > 150 then answer including(f) else answer endif ) notEmpty

Postcondition Example @pre indicates the value of an attribute or association at the start of the execution of the operation – context Loyalty::enroll(c : Customer) pre : not (participants includes (c)) post : participants = participants@pre including(c) – Another post condition could be: membership for the new customer has loyalty account with zero points and no transactions post: Membership select (m: Membership | m.participants = c) forAll( account notEmpty() and account.points = 0 and account.transactions isEmpty() )

isSent operator – (denoted by ^) indicates that communication has taken place – context Subject::hasChanged() post: observer^update(12, 14) – context Subject::hasChanged() post: observer^update(? : Integer, ? : Integer) message operator ^^ – During execution of an operation many messages may have been sent that represent call to the same operation observer^^update(12, 14) Advanced Constructs

Local variables Let var : Type = in Example: context Airport inv: Let supportedAirlines : Set (Airline) = self.arrivingFlights collect(airLine) in (supportedAirlines notEmpty) and (supportedAirlines size < 500)

Local Variable Local variable can be used to represent a value of sub-expression using the let expression Variable must be declared with a name, type, and an expression that specifies its value context person inv: let income : Integer = self.job.salary sum() in if isUnemployed then income < 100 else income >= 100 endif

Local Variable context person inv: let income : Integer = self.job.salary sum() carSize : Real = self.car.engine.maxPower in if isUnemployed then income < 100 and carSize < 1.0 else income >= 100 and carSize >= 1.0 endif

OCL as a query language Airport Flight * * departTime: Time /arrivalTime: Time duration : Interval maxNrPassengers: Integer origin destination name: String arriving Flights departing Flights 1 1 Return all the departing flights from a given airport context Airport::departures():Set(Flight) body: result=departingFlights Return all the airports served by an airline context Airline::served():Set(Airport) body: result=flights.destination->asSet

Exercise A Smokestack is like a Stack. It is last-in-first-out (LIFO), but it has a maximum depth. If the smokestack is full, pushing a new element on will result in the bottommost element being deleted (turned to smoke). Operations are push, pop, top, isEmpty, isFull.

Class Diagram

OCL Constraint System context Smokestack inv maximumDepth: s->size() <= maxSize post Smokestack (m:Integer): maxSize = m -- constructor post push(e:Object): if s->size()<maxSize then s=s@pre->prepend(e) else s=(s@pre->subSequence(1,maxSize-1))->prepend(e) pre pop(): s->notEmpty() post pop(): s=s@pre->subSequence(2,s@pre->size) pre top(): s->notEmpty() post top(): result = s->first() post isEmpty(): result = s->isEmpty() post isFull(): result = s->size() = maxSize

An Review of Constraints, OCL Constraints: condition/restriction – Design level/code level constraints Use of the OCL – class invariants, operation pre/post conditions, query – guards for state diagram OCL as a language: formal, declarative, typed

OCL Expressions Context: any model elements(class, attributes, association) Use of expressions: – Adding extra info context init/derive, def – Constraints context inv/pre/post – Query context body

OCL Types and Operations Basic Types and Operations – Integer, Real, Boolean, String – Enum (user-defined types) Collection types and Operations – Set, Bag, Ordered Set, Sequence

OCL Advanced Constructs Let in If then else IsSent ^ Message ^^

OCL examples Context CustomerCard inv: goodThru.isAfter(Date::Now) CustomerCard goodThru: Date Date isAfter(t:Date): Boolean

OCL examples Context CustomerCard inv: owner.programs->size()>0 LoyaltyProgramCustomers CustomerCard 0…* 1 owner cards programs

To do Homework 3: OCL (Due 9/30 Friday 7:00pm) – Use references if the constructs are not covered in class Reading Assignment (Due 9/28 Wed in class) – Pi method – The way of Z (Chapters 1, 2, 3, 8, 9, 10)

Wild & Crazy Idea Session Role of female in Software Industry 40% labor force 1% of wealth - wsj

Similar presentations