Arquitectura de software dirigida por modelos (Model-Driven Architecture) Liliana Favre UNCPBA 2006.

Slides:



Advertisements
Presentaciones similares
Maestría en Data Mining
Advertisements

Cuento del Gato.
Las Palabras Interrogativas
Mr. Redaelli OnlineTaco.com. To Have - Tener Yo tengo – I have Tú tienes – You have (Informal) Usted tiene – You have (Formal) El tiene – He has Ella.
Visual Basic for Applications 3 de Mayo de Archivo en Excel Son 600 nombres Separar las columnas Separar los nombres en varias columnas ¿Cómo hacerlo?
Capítulo 3 Nuevas clases, nuevos amigos PRIMER PASO
Capítulo 2B Los verbos después de las preposiciones
Grupos de Trabajo # 7 - Informe Working Group # 7 – Report General Business and Operational Risks.
Empresa y Sociedad Tema 1. Teoría de la Empresa y de la Sociedad Dr. Antonio Lloret 17 de Enero de 2011.
Centro Cultural Costarricense Norteamericano Academic Department New Policy about Absences & Tardiness.
2003 HYPACK MAX Training Seminar1 Sample Case la Entrada manual de Datos de la Línea de la costa El Metodo de MANUAL –DIG Objectos –Boya (Roja)
In Lecciones 6–9, you learned the preterite tense
Introducción a JAVA COMP 250. Estructura de Selección selection statements selection statements – Escoger cuál acción ejecutar dependiendo de dos ó más.
Relative Pronouns Spanish Three Honors C.12.
Definite Articles ___el chico __la_tarea ___los__papeles ____las_lecciones exceptions __el__mapa ___el_día Maculine (o) Feminine(a,ión,tad,dad)
Esp /5/12 Objective Bell work
The Present Tense of tener (to have)
Bases de Datos Espaciales SPATIAL QUERY LANGUAGES
DOPs y IOPs juntos DOPs & IOPs together.
El Verbo GUSTAR En español gustar means to be pleasing In English, the equivalent is to like.
ANTE TODO It is a misunderstanding to think that ¿Qué? always translates as What?, and that ¿Cuál? and ¿Cuáles? always translate as Which? ¿Qué? and ¿Cuál?
ANTE TODO You have already learned familiar (tú) commands and formal (Ud./Uds.) commands. You will now learn nosotros/as commands, which are used to give.
Los interrogativos.
Informal Speaking AP TestSimulated Conversation. Description The first part in the speaking section will include a task that measures speaking skills.
Entrada: Los verbos en la historia (Entrance: Verbs in the story) Copy the date and title, and log the entry in your table of contents. Take a Realidades.
Repaso del vocabulario, y más descripción
Programando con Hilos POSIX* Intel Software College.
Programación con OpenMP* Intel Software College. Copyright © 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or.
MATLAB.
CONSTRUCCIÓN Y ARQUITECTURA DEL SOFTWARE
UML Lenguaje Unificado de Construcción de Modelos
Procedimientos Almacenados y Disparadores
ALC 11 lunes el 26 de septiembre. Bienvenida lunes el 26 de septiembre Front row face the back row. Back row will read the words on the screen in the.
Español 1 18 y 19 de septiembre de Escribe los meses que combinan con las estaciónes. (Write the months that match with the seasons.) El otoño-
Subject Pronouns and AR verb conjugations As you click through this powerpoint, you will need to answer the questions on your worksheet. At the end, you.
Spanish Ia (Final Exam) Crossfire Initial Activity 1. Brief notes on tener... (or review if you have received them already!) Tener---formas Tener.
SQL Base de Datos LENGUAJES DE CONSULTA AR y CR no pueden ser tomados como base para implementar porque: Poseen sintaxis compleja No permiten.
PL/SQL Francisco Moreno Universidad Nacional. Funciones Si un procedimiento tiene solo un parámetro de salida, se puede remplazar por una función y esta.
Modelo de iluminación simple R = I a.Kr + Σ I i.((1-Ks).Kr. L i.n + Ks. (V.r i ) q ) G = I a.Kg + Σ I i.((1-Ks).Kg. L i.n + Ks. (V.r i ) q ) B = I a.Kb.
Después de completar esta Lección, será capaz de: Limitar las filas recuperadas por una consulta Ordenar las filas recuperadas por una consulta.
Transformación de modelos con ATL
ESTRUCTURAS DE CONTROL
Seminario de Lenguajes A – Opción Ada Seminario de Lenguajes A – Opción Ada – Raúl Champredonde1 Overloading de subprogramas procedure Put(Item: in integer;
Seminario de Lenguajes A – Opción Ada Estructura general de programas –Especificación de contexto –Encabezado –Declaraciones –Cuerpo Seminario de Lenguajes.
Seminario de Lenguajes A – Opción Ada
Seminario de Lenguajes A – Opción Ada Seminario de Lenguajes A – Opción Ada – Raúl Champredonde1 Genéricos –Molde a partir del cual se pueden crear instancias.
Administración de Servidores de Bases de Datos Bases de Datos de Usuarios Caso particular Adaptive Server Enterprise.
La Lección del Repaso Antes de entrar en la clase de Español IV, necesita saber esta información.
UNIVERSIDAD AUTÓNOMA DEL ESTADO DE HIDALGO ESCUELA SUPERIOR DE ZIMAPÁN Licenciatura en Derecho Tema: First conditional L.E.L.I. Paulina Trujillo Castillo.
Articles, nouns and contractions oh my!. The POWER of the article THE 1. There are four ways to express THE in Spanish 2. The four ways are: El La Los.
Me llamo ________ Clase 10 NM La fecha es el Primero de febrero del 2012 Propósito # 27: ¿Cómo vives? Actividad Inicial: Copia y responde en oraciones.
In Spanish, adverbial clauses are commonly introduced by conjunctions
 Making complete sentences How to make complete sentences in Spanish. The following presentation is designed to help you learn how to do the following:
Las Preguntas (the questions) pg
Department of Modern Languages. Gramática nueva In spoken and written Spanish, statements are normally formed by placing the subject at the beginning.
Present Tense of Regular –AR Verbs. An infinitive tells the meaning of a verb without naming any subject or tense. There are three kinds of infinitives,
Subject Pronouns and “Ser”.  What word do you use to talk about yourself?  What word do you use to talk about yourself and someone else?  What word.
 1. Why should a person learn Spanish? Give at least 3 reasons in your explanation.  2. What Spanish experiences have you had? (None is not an option.
Lección 10: Gramática Los participios pasados Pretérito perfecto
Negatives and Questions. Negatives Consider the following sentences: Juan estudia mucho. Marta y Antonio viven en Georgia. Rita y el chico necesitan.
Repaso (parte 2) Español 2. Como escribir una pregunta…  Adónde (to where)  Cómo (how)  Cuál/Cuáles (which ones)  Cuándo (when)  Cuánto (how much)
Quantity How much? How many?
Los números Mathematical problem solving Existence/Non-existence Quantity How much? How many?
Lenguajes de Programación Tema 4. Paradigma Orientado a Objetos Java 1.5 Pedro García López
Estructuras de Datos y Algoritmos TDA LISTA. Metáfora del TDA (repaso) Conjunto de operaciones forman una pared forman una interfase entre los programas.
Clases abstractas no polimórficas para C++ Universidad de Costa Rica Escuela de Ciencias de la Computación e Informática Agenda.
Paradigmas de Lenguajes de Programación Smalltalk (Parte II) 1 er cuatrimestre de 2007.
29/01/031 OCL (Object Constraint Language) Juan Casas Cuevas Mercedes Arenas Fernández Laboratorio de Sistemas de Información Facultad de Informática.
Redes de Petri Coloreadas
The Present Tense of tener (to have)
Transcripción de la presentación:

Arquitectura de software dirigida por modelos (Model-Driven Architecture) Liliana Favre UNCPBA 2006

(OBJECT CONSTRAINT LANGUAGE) EL LENGUAJE OCL (OBJECT CONSTRAINT LANGUAGE)

OCL OCL fue desarrollado por IBM como lenguaje de modelado de negocio. Surgió a partir del método Syntropy. Permite describir expresiones y restricciones en modelos y artefactos orientados a objetos Fue la contribución más importante de IBM a UML 1.1 Lenguaje de especificación “cuasi-formal” que combina cálculo de predicados y teoría de conjuntos. No tiene una semántica formal. El contexto sintáctico está determinado gráficamente. Su sintaxis es simple y está influenciada por la de los lenguajes orientados a objetos. Por ser un lenguaje de especificación no tiene efectos colaterales Es un lenguaje tipado

OCL En UML 1.1, OCL era un lenguaje de constraints Un constraint es una restricción sobre uno o más valores (o partes) de un modelo orientado a objetos. En UML 2.0, OCL puede ser usado para escribir cualquier expresión sobre los elementos en el diagrama. Cada expresión indica un valor o un objeto en el sistema un integer, una referencia a un objeto, una colección de Valores, una colección de referencias a objetos, un mensaje en un diagrama de interacción, un objeto específico en un diagrama de objetos, etc

OCL OCL puede ser usado en modelos UML y metamodelos con diferentes propósitos: Como lenguaje de navegación Para especificar invariantes sobre clases y tipos en modelos de clase Para especificar guardas en diagramas de estado Para describir precondiciones y postcondiciones sobre operaciones y métodos Para especificar invariantes en estereotipos … OCL ha sido usado para definir la semántica de UML

OCL Ejemplo context Flight inv: passengers->size() <=plane.numberOfSeats context Flight::availableSeats(): Integer body: plane.numberOfSeats – passengers->size()

Ejemplo de diagrama de clase

Especificaciones en OCL Las expresiones OCL se escriben en el contexto de una instancia de un tipo específico. Una declaración de contexto precede a la expresión OCL context Company La palabra reservada self se refiere a la instancia contextual

Objetos y propiedades Todos los clasificadores de los diagramas UML (interfaces, tipos de datos, componentes, nodos, casos de uso y subsistemas) son tipos válidos en las expresiones OCL y tienen asociadas propiedades. Las propiedades pueden ser atributos, association-ends, métodos y operaciones sin efectos colaterales (el atributo isQuery es True). El valor de una propiedad de un objeto definido en el diagrama de clases se especifica por un punto seguido por el nombre de la propiedad. self.numberOfEmployees > 50 self.age > 0

Invariantes Un invariante es un constraint con el estereotipo <<invariant>>. Se escribe en una declaración de contexto siguiendo al rótulo inv: context Company inv: self.numberOfEmployees > 50 La palabra reservada self puede omitirse. Un invariante puede referenciarse por un nombre escrito tras el rótulo inv: inv: enoughEmployees : numberOfEmployees > 50

Especificación de operaciones y métodos context nombreTipo:: nombreOperacion (param1:Tipo1,…): TipoR pre: … post: …. body: ….

Precondiciones y postcondiciones Las precondiciones y postcondiciones son constraints con el estereotipo <<precondition>> y <<postcondition>> respectivamente. Se escriben en una declaración de contexto siguiendo a los rótulos pre y post: context Typename::operationName(Param1:Type1,...):ReturnType pre:[ parameterOk:] --expresión OCL de self y parámetros post: [resultOk:] result = ... body:--alguna expresión OCL

Precondiciones-Postcondiciones-Invariantes La notación package Package :: SubPackage context X inv: context X:: OperationName (...) endpackage permite expresar a que Package pertenecen precondiciones, postcondiciones e invariantes

Operaciones y métodos La notación utilizada para operaciones aplicadas a una instancia es nombreInstancia. nombreOperacion ( [argumentos]) context Company self. NumberOfEmployees ( ) denota la aplicación de la operación NumberOfEmployees a la instancia contextual self.

Contratos OCL Un contrato en OCL se define por precondiciones y postcondiciones que pueden referirse a dos conjuntos de valores para cada propiedad de un objeto: el valor de la propiedad al comienzo de la operación y el valor de la propiedad después de completada la operación El valor de la propiedad nombre antes de la ejecución se denota por nombre@pre context Company:: HireEmployee ( p: Person) pre: not employee -> includes ( p) post: employee = employee@pre -> including ( p)

Navegación y asociaciones Se puede navegar una asociación a partir de un objeto específico para acceder a otros objetos conectados por la asociación o a sus propiedades mediante la sintaxis objecto. rol context Person self. employer Si el rol no figura en el diagrama por convención se le asocia el nombre de la clase con letras minúsculas. self. manager es la instancia de Person asociada a la instancia contextual self dado que la multiplicidad es 1. self. managedCompany evalúa a un conjunto de instancias de Company dado que la multiplicidad es 0..*. Si la asociación sobre el diagrama de clases está adornada por {ordered} la navegación retorna una secuencia. OCL provee a los tipos Set, Bag y Sequence como tipos predefinidos.

Navegación y asociaciones El acceso a una propiedad de la colección se denota por coleccion->nombrePropiedad context Person inv: self.employer->size ( ) < 3 self.manager.age > 40 self.manager -> size( ) =1 La multiplicidad de manager es 1, self.manager puede usarse como Person o como Set(Person). En self. manager. age > 40 la subexpresión self. manager es usada como Person porque el punto indica el acceso a la propiedad age de Person. En self. manager -> size()=1 , la expresión self.manager es usada como Set(Person) y la -> accede a la propiedad size sobre conjuntos.

Navegación y asociaciones La navegación desde una Association Class a uno de los objetos de la asociación siempre entrega un objeto. Las asociaciones calificadas usan uno o más atributos calificadores para seleccionar objetos object.navigation[qualifierValue, ...] context Bank self.customer –Set[Person] todos los clientes del banco self.customer [99564242] —la persona con cuenta 99564242

Herencia y propiedades Pueden heredarse diferentes propiedades con nombres idénticos desde diferentes superclases. Esta ambigüedad puede resolverse en OCL precediendo a una propiedad por el camino de herencia. self.A:: p --accede a la propiedad p de A self.B:: p --accede a la propiedad p de B

Propiedades predefinidas sobre objetos OclIsTypeOf (t : Ocltype ): Boolean --Evalúa True si self y t son del mismo tipo OclIsKindOf (t : OclType): Boolean --Evalúa True si t es del tipo o supertipo de un objeto OclIsNew ( ): Boolean --Evalúa True si al ser usado en una postcondición el objeto es creado durante la ejecución de la operación OclAsType ( t : OclType ) : instance of OclType --Evalúa al objeto como del tipo OclType

Propiedades predefinidas sobre objetos OclIsTypeOf (t : Ocltype ): Boolean --Evalúa True si self y t son del mismo tipo context Person inv:self.oclIsTypeOf(Person) – verdadero self. oclIsTypeOf (Company) -- falso OclIsKindOf (t : OclType): Boolean --Evalúa True si t es del tipo o supertipo de un objeto context Set inv: self.oclIsKindOf(Collection) - - Verdadero

Propiedades predefinidas sobre clases allInstances --Es el conjunto de todas las instancias del tipo en el momento en que la expresión es evaluada Person.allInstances() es del tipo Set(Person) y es el conjunto de todas las personas que existen en el sistema cuando la expresión es evaluada

Tipos OCL Tipos predefinidos Tipos definidos por el usuario Básicos (Integer, Real, String, Boolean y Enumerate) Colecciones (Collection, Set, Ordered-Set, Bag, Sequence) Tipos definidos por el usuario Jerarquía de tipos Un tipo t conforma a otro t1 cuando una instancia de tipo t puede ser sustituida por una de tipo t1: -Cada tipo conforma a sus supertipos. -Si t1 conforma a t2, y t2 conforma a t3, luego t1 conforma a t3.

Tipos predefinidos- Boolean b = (b2:Boolean) : Boolean b or (b2 : Boolean) : Boolean b xor (b2: Boolean) : Boolean post: (b or b2) and not (b = b2) b and ( b2: Boolean) : Boolean not b : Boolean post: if b then result = false else result = true endif b implies ( b2: Boolean) : Boolean post: (not b) or ( b and b2) = if b then (expression1:OclExpression) else (expression2 :OclExpression):expression1. evaluationType

Tipos predefinidos- Boolean b = (b2:Boolean) : Boolean b or (b2 : Boolean) : Boolean b xor (b2: Boolean) : Boolean post: (b or b2) and not (b = b2) b and ( b2: Boolean) : Boolean not b : Boolean post: if b then result = false else result = true endif b implies ( b2: Boolean) : Boolean post: (not b) or ( b and b2) = if b then (expression1:OclExpression) else (expression2 :OclExpression):expression1. evaluationType

Tipos predefinidos- Real r = (r2 :Real) : Boolean r < > (r2 :Real) : Boolean r + (r1: Real) : Real r – (r1 :Real) : Real r * (r1 :Real) :Real r / (r1:Real) : Real r. abs : Real post: if r < 0 then result = -r else result = r endif r. floor : Integer post: (result <= r) and result + 1 > r endif

Tipos predefinidos- Real r.max (r2:Real) : Real post: if r >= r2 then result = r else result = r2 endif r.min (r2: Real ) : Real post: if r <= r2 then result = r else result = r2 endif r < ( r2:Real) : Boolean r > ( r2:Real) : Boolean post: result = not (r <= r2) r <= ( r2:Real) : Boolean post: result = (r = r2) or (r < r2) r >= ( r2:Real) : Boolean post: result = (r =r2) or ( r > r2)

Tipos predefinidos- Integer i = (i2 : Integer) : Boolean i + (i2: Integer) : Integer i – ( i2: Integer) : Integer i * (i2: Integer) : Integer i / (i2:Integer) : Real i.abs : Integer i.div (i2: Integer) : Integer i.mod (i2 : Integer) : Integer i.max ( i2 : Integer) : Integer i.min ( i2: Integer) : Integer

Tipos predefinidos- String string = (string2 : String) : Boolean string.size : Integer string.concat (string2: String): String string.toUpper : String string.toLower : String string.substring (lower: Integer, upper: Integer) : String

Tipos predefinidos Enumeration enumeration = ( enumeration2 : boolean ) : Boolean enumeration <> (enumeration2 : Boolean) : Boolean post: result = not (enumeration = enumeration2) context Person inv: gender = Gender::male

Tipos predefinidos Collection Set Sequence Bag OrderedSet

Tipos predefinidos Collection Las operaciones sobre colecciones se denotan por expresiones OCL usando la siguiente notación: <collection> <operation> Operaciones que permiten iterar sobre sus elementos: select, reject, collect, iterate, forAll y exists. Estas operaciones toman cada elemento de la secuencia y evalúan una expresión sobre ellos.

Collection La operación select Sintaxis collection select(element:Type|<boolean-exp-with-element>) collectionselect(element|<boolean-exp-with-element>) collectionselect(<boolean- expr-with-element>) context Company self.employee->select(p:Person| p.age>50)->notEmpty() self.employee->select(p | p.age>50)->notEmpty() self.employee->select(age>50)->notEmpty()

Collection La operación reject Sintaxis collection reject(element:Type|<boolean-exp-with-element>) collectionreject(element|<boolean-exp-with-element>) collectionreject(<boolean- expr-with-element>) context Company self.employee->reject(p:Person| p.isMarried)->notEmpty() self.employee->reject(p | p.isMarried)->notEmpty() self.employee->reject(isMarried)->notEmpty()

Collection La operación Collect La operación collect itera sobre una colección, calcula un valor para cada elemento de la colección, y retorna una colección cuyos elementos son los valores evaluados. El tipo de los elementos en la colección resultante es usualmente diferente del tipo de elementos en la colección original. El resultado sobre un conjunto o un bag es un bag y sobre secuencias una secuencia.

Collection La operación Collect Sintaxis collection collect(element:Type|<boolean-exp-with-element>) collectioncollect(element|<boolean-exp-with-element>) collectioncollect (<boolean- expr-with-element>) context Company self.employee->collect(p:Person| p.birthDate) self.employee->collect(p | p.birthDate) self.employee->collect(birthDate)

Collection La operación Collect Notación concisa collection.propertyname es a equivalente a collection  collect(propertyname) self.employee.birthDate

Collection La operación forAll Sintaxis collection forAll(element:Type|<boolean-exp-with-element>) collectionforAll(element|<boolean-exp-with-element>) collectionforAll(<boolean- expr-element>) self.employee forAll(age > 18) self.employee  forAll (p | p.age > 18) self.employee forAll (person p | p.age > 18)

Collection La operación exists Sintaxis collection exits(element:Type|<boolean-exp-with-elem>) collectionexists(element|<boolean-exp-with-elem>) collectionexists(<boolean- expr>) self.employee exists(forename = “john”) self.employee  exists (p | p.forename = ”john”) self.employee exists (person p | p.forename =”John”)

Collection La operación iterate Sintaxis collection iterate (elem:Type1; result: Type2= <expression> | expr-with-elem-and–result>) result podría ser calculado mediante result = <expression>; while (collection.notEmpty ()) do elem =collection.nextElement(); result = <expression-with-elem-and-result>; endwhile return result;

Collection La operación iterate collection  size : Integer --The number of elements in the collection collection. post: result = collection iterate (elem; acc: Integer = 0| acc+1 ) collection  collect ( x: T | x.property) collection iterate(elem:T;result:T2=Bag{})|resultincluding(x.property)) self.employee->collect(p:Person| p.birthDate) es equivalente a self.employee-> iterate(p:Person;result= Bag{} | resultincluding(p.birthDate))

Collection collection  size : Integer --The number of elements in the collection collection post: result = collection iterate (elem; acc: Integer = 0 | acc+1 ) collection  includes (object: OclAny ) : Boolean --True if object is an element of collection, false otherwise post: result = (collection count (object) > 0) collection -> excludes ( object : OclAny ) : Boolean --True if object is not an element of collection, false otherwise post: result = (collection -> count ( object) = 0)

Collection collection isEmpty : Boolean --Is collection the empty collection? post: result = (collection size=0) collection  notEmpty :Boolean --Is collection not the empty collection? post: result =(collection  size <> 0) collection -> sum ( ) : T --The addition of all elements in collection. Elements must be of a --type supporting the + operation, associative and commutative. post : result = collection -> iterate ( elem; acc: T = 0 | acc + elem)

Collection collection forAll (expr:OclExpression) :Boolean --Results in true if expr evaluates to true for each element in collection; otherwise , result is false. post: result= collection  iterate (elem; acc:Boolean = true acc and exp) collection exists (expr:OclExpression) :Boolean --Results in true if expr evaluates to true for at least one element in collection; otherwise, result is false. post: result = collection  iterate (elem; acc: Boolean = false acc or exp) collection  iterate (expr: OclExpression) : expr.evaluationType( ) --Iterate over the collection.

Collection collection -> any ( expr :OclExpression) : T --Returns any element in the collection for which expr evaluates to true. If there is more than one element for which expression is true, one of them is returned. pre: collection -> exists ( expr) post : collection -> select ( expr) -> includes ( result) collection -> one ( expr : OclExpression ) : Boolean --Results in true if there is exactly one element in the collection for which expr is true. post: collection - > select ( expr) -> size ( ) = 1 collection -> isUnique ( expr : OclExpression ) : Boolean --Results in true if expr evaluates to a differente value for each element in collection; otherwise results is false. post: let values = collection -> collect ( expr) in result = res -> forAll ( e | values -> count ( e) = 1)

Collection collectioncount (object: OclAny):Integer --The number of times that object occurs in collection post: result= collection  iterate( elem; acc:Integer=0 | if elem =object then acc+1 else acc endif) collection  includesAll (c2:Collection(T)) :Boolean --Does collection contain all the elements of c2? post: result= (c2 forAll (elemcollectionincludes(elem)) collection  excludesAll (c2:Collection(T)) : Boolean --Does collection contain none of the elements of c2? post:result=(c2 forAll (elemcollection-> excludes (elem))

Set set  count (object:T) : Integer --The number of occurrences of object in set. post: result < = 1 set  union (set2: Set(T)) : Set (T) --The union of set and set2. post: result -> forAll ( elem | set -> includes ( elem) or set2 -> includes ( elem)) post: set -> forAll ( elem | result -> includes ( elem)) post: set2 -> forAll ( elem | result -> includes ( elem)) set  union (bag: Bag(T)) : Bag (T) post: result -> forAll ( elem | result -> count (elem) = set -> count (elem) + bag -> count (elem)) post: set -> forAll ( elem | result -> includes (elem)) post: bag -> forAll (elem | result -> includes (elem)) set  = (set2: Set): Boolean post: result = (set  forAll (elem | set2  includes(elem) and set2  forAll ( elem | set -> includes(elem

Set set  intersection (set2: Set(T)): Set(T) post: result -> forAll ( elem | set -> includes (elem) and set2 -> includes ( elem)) post: set -> forAll ( elem | set2 -> includes ( elem) = result -> includes (elem)) post: set2 -> forAll ( elem | set -> includes ( elem0 = result -> includes ( elem)) set  intersection (bag: Bag(T)): Set(T) post: result = set  intersection (bag  asSet) set  - (set2: Set(T)): Set(T) post: result -> forAll (elem | set -> includes (elem) and set2 -> excludes (elem)) post: set -> forAll (elem | result -> includes (elem) = set2 -> excludes (elem)) set  including (object: T) : Set(T) --The set containing all elements of set plus object. post: result -> forAll (elem | set -> includes (elem) or (elem = object)) post: set -> forAll (elem | result -> includes (elem)) post: result -> includes (object)

Set set  excluding (object: T) : Set(T) --The set containing all elements of set without object. post: result -> forAll (elem | set -> includes (elem) and (elem <> object) post : set -> forAll (elem | result -> includes (elem)= object < > elem))) post : result -> excludes (object) set  symmetricDifference (set2: Set(T)): Set(T) post: result -> forAll ( elem | set -> includes (elem) xor set2 -> includes (elem)) post: set -> forAll (elem | result -> includes (elem) = set2 -> excludes (elem)) post: set2 -> forAll (elem | result -> includes (elem) = set -> excludes (elem)) set  select (expression: OclExpression) : Set(exp.type) post: result = set  iterate (elem; acc: Set(T) = Set{}  if expression then acc  including (elem) else acc endif ) set  reject (expression: OclExpression) : Set (exp.type) post: result = set  select (not expression)

Set set  collect (expression: OclExpression) : Bag(expression.OclType) --The Bag that results from applying expr to every member of set. post: result=set  iterate (elem; acc:Bag (T) = Bag{} acc including (expression)) set  asSequence ( ) : Sequence (T) --A Sequence that contains all the elements from set, in undefined order. post: result -> forAll (elem | set -> includes(elem)) post: set -> forAll (elem | result -> count (elem) =1) set  asBag ( ) : Bag (T) --The Bag that contains all the elements from set post: result -> forAll (elem | set -> includes (elem)) post: set -> forAll (elem | result -> count (elem) = 1)

Bag bag  = (bag2: Bag(T)) : Boolean post: result = (bag -> forAll (elem | bag -> count (elem) = bag2 -> count (elem)) and bag2 -> forAll (elem | bag2 -> count (elem) = bag-> count(elem))) bag  union (bag2: Bag(T)) : Bag (T) --The union of bag and bag2 post: result -> forAll (elem | result -> count (elem) = bag-> count (elem) + bag2 -> count (elem)) post: bag -> forAll ( elem | result -> count (elem) = bag -> count (elem) + bag2 ->count (elem)) post: bag2 -> forAll (elem | result -> count (elem) = bag -> count(elem) + bag2 -> count(elem))

Bag bag  union (set: Set) : Bag (T) post: result -> forAll (elem | result -> count (elem) = bag -> count (elem) + set -> count (elem)) post: bag -> forAll (elem | result -> count (elem) = bag -> count (elem) + set -> count (elem)) post: set -> forAll (elem | result -> count (elem) = bag -> bag  intersection (bag2: Bag(T)): Bag(T) post: result -> forAll (elem | result -> count (elem) = bag -> count (elem). min (bag2 -> count (elem))) post: bag -> forAll (elem | result -> count (elem) = bag -> count (elem). min (bag2 -> count (elem))) post: bag2 -> forAll (elem | result -> count (elem) = bag -> count (elem). min (bag2-> count (elem))

Bag bag  intersection (set: Set(T)): Set(T) post: result -> forAll (elem | result -> count (elem) = bag -> count (elem). min (set -> count (elem))) post: bag -> forAll (elem | result -> count (elem) = bag -> count (elem). min (set -> count (elem))) post: set -> forAll (elem | result -> count (elem) = bag -> count (elem). min (set-> count (elem))) bag  including (object: T) : Bag(T) --The bag containing all elements of bag plus object post: result -> forAll (elem | if elem = object then result -> count (elem) = bag -> count (elem) +1 else result-> count (elem) = bag-> count (elem) endif) post: bag -> forAll (elem | if elem = object then result-> count (elem) = bag -> count (elem) + 1 else result -> count (elem) = bag -> count(elem) endif)

Bag bag  excluding (object: T) : Bag(T) --The bag containing all elements of bag apart from all ocurrences of object post: result -> forAll (elem | if elem =object then result -> count (elem) = 0 else result -> count(elem) = bag -> count(elem) endif) post: bag -> forAll (elem | if elem = object then result->count(elem) = 0 else result->count(elem) = bag->count(elem) endif)

Bag bag  select (expr: OclExpression) : Bag(T) --The sub-bag of bag for which expr is true. post: result =bag  iterate(elem; acc: Bag (T)=Bag{} if expr then acc including (elem) else acc endi ) bag  reject (expr: OclExpression) : Bag(T) --The sub-bag of bag for which expr is false. post: result = bag  select (not expr) bag  collect (expr: OclExpression) : Bag(expr.OclType) --The Bag of elements that results from applying expr to every member of bag. post: result =bag iterate(elem; acc: Bag(expr.evaluationType( )=T) = Bag{} acc  including(exp))

Bag bag  count (object:T) : Integer --The number of ocurrences of object in bag. bag  asSequence ( ) : Sequence (T) --A Sequence that contains all the elements from bag, in undefined order. post: result -> forAll (elem | bag -> count (elem) = result -> count (elem)) post: bag -> forAll (elem | bag -> count (elem) = bag  asSet ( ) : Set (T) --The Set containing all the elements from bag, with duplicates removed. post: result -> forAll (elem | bag -> includes (elem)) post: bag -> forAll (elem | result -> includes (elem))

Sequence sequence  = (sequence2: Sequence(T)) : Boolean --True if sequence contains the same elements as sequence2 in the same order. post: result= Sequence{1..sequence2  size() } forAll(index: Integer | sequence size() = sequence2 size() ) and sequence  at(index) = sequence2  at(index)) sequence  union (sequence2: Sequence(T)) : Sequence (T) --The sequence consisting of all elements in sequence, followed by all elements --in sequence2. post: result  size() = sequence  size() + sequence2 size() post: Sequence{1..sequence  size } forAll(index:Integer | sequence  at(index) = result at(index)) post: Sequence{1..sequence2  size() } forAll (index:Integer | sequence2  at(index) = result at(index + sequence size() )

Sequence sequence  append (object: T) : Sequence (T) --The sequence of elements , consisting of all elements of sequence, followed object. post: result  size() = sequence  size() +1 post: result  at(result  size()) = object post: Sequence{1..sequence  size() } forAll(index:Integer | result at(index) = sequence  at(index)) sequence  prepend (object: T) : Sequence (T) --The sequence consisting of object, followed by all elements in sequence. post: result  at(1) = object post: Sequence{1..sequence  size ( ) } forAll (index:Integer | sequence  at(index) = result at (index+1))

Sequence sequence  subSequence (lower:Integer, upper: Integer) : Sequence (T) --The sub-sequence of sequence starting at number lower, up to and including --element number upper. pre: 1 <= lower pre: lower <= upper pre: upper <= sequence-> size ( ) post: result -> size( ) = upper – lower + 1 post: Sequence{lower .. upper } forAll( index | result  at (index – lower +1) = sequence  at (index)) sequence  at (i:Integer) : T --The i-th element off sequence pre: i>= 1 and i<= sequence->size ( ) bag  count (object:T) : Integer --The number of ocurrences of object in bag.

Sequence bag  asSequence ( ) : Sequence (T) --A Sequence that contains all the elements from bag, in undefined order. post: result -> forAll (elem | bag -> count (elem) = result -> count (elem)) post: bag -> forAll (elem | bag -> count (elem) = result -> count (elem)) bag  asSet ( ) : Set (T) --The Set containing all the elements from bag, with duplicates removed. post: result -> forAll (elem | bag -> includes (elem)) post: bag -> forAll (elem | result -> includes (elem)) sequence  first : T --The first element in sequence post: result = sequence  at (1)

Sequence sequence  last : T --The last element in sequence post: result = sequence  at (sequence  size ( ) ) sequence  including (object: T) : Sequence(T) --The sequence containing all elements of sequence plus object added as the last element post: result = sequence.append(object) sequence  excluding (object: T) : Sequence(T) --The sequence containing all elements of sequence apart from all ocurrences of object. --The order of the remaining elements is not changed. post: result -> includes (object ) = false post: result -> size ( ) = sequence -> size ( ) – sequence -> count (object) post: result = sequence  iterate(elem; acc: Sequence(T) = Sequence {} | if elem = object then acc else acc  append (elem) endif )

Sequence sequence  select (expr: OclExpression) : Sequence(T) --The subsequence of sequence for which expr is true. post: result = sequence  iterate (elem; acc: Sequence(T) =Sequence {} | if expr then acc including (elem) else acc endif ) sequence  reject (expr: OclExpression) : Sequence(T) --The subsequence of sequence for which expr is false. post: result = sequence  select (not expr) sequence  collect (expr: OclExpression) : Sequence(expr.OclType) --The Sequence of elements that results from applying expr to every member of sequence.

Sequence sequence  select (expr: OclExpression) : Sequence(T) --The subsequence of sequence for which expr is true. post: result = sequence  iterate (elem; acc: Sequence(T) =Sequence {} | if expr then acc including (elem) else acc endif ) sequence  reject (expr: OclExpression) : Sequence(T) --The subsequence of sequence for which expr is false. post: result = sequence  select (not expr) sequence  collect (expr: OclExpression) : Sequence(expr.OclType) --The Sequence of elements that results from applying expr to every member of sequence.

Sequence sequence  collect (expr: OclExpression) : expr.OclType --Iterates over the sequence. Iteration will be done from element at position 1 --up until the element at the last position following the order of the sequence. sequence  asSet ( ) : Set (T) --The Set containing all the elements from sequence, including duplicates. post: result -> forAll (elem | sequence -> includes (elem)) post: sequence -> forAll (elem | result -> includes (elem)) sequence  asBag ( ) : Bag (T) --The Bag containing all the elements from sequence, including duplicates. post: result -> forAll (elem | sequence -> count(elem) = result -> count(elem)) post: sequence -> forAll (elem | sequence -> count (elem) =

Reglas de subtyping- Collection Reglas estándar Type1 conforma a Type2 cuando son idénticos Type1 conforma a Type2 cuando Type1 es subtipo de Type2 Si Type1 conforma a Type2, y Type2 conforma a Type3, luego Type1 conforma a Type3 + Los tipos Set(x), Bag(x) y Sequence(x) son subtipos de Collection Collection(Type1) conforma a Collection(Type2) cuando Type1 conforma a Type2. Esto vale para Set(Type1)/ Set(Type2), Bag(Type1)/ Bag(Type2) y Sequence(Type1)/ Sequence(Type2)

Tipos predefinidos Tuplas Tuple {name:String =´John´, age:Integer = 10} Tuple{a:Collection (Integer) = Set {1,2,3}, b:String = ´foo´, c:Strinh = ´bar´} Los tipos son opcionales y no importa el orden. Los valores de las partes pueden ser expresiones OCL arbitrarias Las partes se acceden por su nombre: Tuple{x:Integer = 5, y:String =´li´}.x = 5

Ejemplo- “Mortgage System”

Ejemplo “Mortgage System” context Mortgage --Una persona pude tener una hipoteca sobre una casa si es el propietario inv: security.owner = borrower inv: startDate < endDate context Person --socSecNr debe ser único inv: Person::allInstances () ->isUnique(socSecNr)

Ejemplo “Mortgage System” context Person::getMortage(sum:Money, security: House) --será permitida una nueva hipoteca si los ingresos son suficientes pre: self.mortgages.monthlyPayment->sum()<= self.salary * 0.30 context Person::getMortgage (sum:money, security: House) --Se admite un nuevo crédito sólo si el valor de la casa es suficiente pre:security.value >= security.mortgages.principal->sum()

Ejemplo “Mortgage System” Ciclos en el diagrama de clases context Person inv: self.mortgages.security.owner -> forAll (owner:Person | owner = self)

Elementos derivados en UML/OCL Un elemento derivado en UML se distingue añadiendo un símbolo ¨/¨ delante de su nombre. Por ejemplo, se puede indicar que un atributo es derivado, es decir que se puede calcular su valor en un cierto objeto si se conoce el valor de los atributos normales del objeto y se tiene acceso a otros objetos que conoce.

Asociaciones derivadas

Valores derivados e iniciales

Ejemplo “Royal and Loyal System”

Valores derivados “Royal and Loyal System” context TransactionReportLine::partnerName :String derive:transaction.generatedBy.partner.name context TransactionReportLine::serviceDesc:String derive:transaction.generatedBy.description context TransactionReportLine::points: Integer context TransactionReportLine:: amount : Real derive: transaction.amount context TransactionReportLine::date : Date derive:transaction.date

Valores derivados “Royal and Loyal System” context TransactionReport::totalEarned : Integer derive: lines.transaction->select(oclIsTypeOf (Earning)). points->sum() context TransactionReport::totalBurned: Integer lines.transaction-> select (oclIsTypeOf (Burning)).Points ->sum()

Valores iniciales “Royal and Loyal System” context Typename::attributeName: Type init:-- una expresión que representa el valor inicial context LoyaltyAccount::points init: 0 context CustomerCard::valid init: true

Definiciones de atributos y operaciones context Customer def: wellUsedCards : Set( CustomerCard ) = cards->select( transactions.points->sum() > 10,000 ) def: loyalToCompanies : Bag( ProgramPartner ) = programs.partners def: cardsForProgram(p: LoyaltyProgram) : Set(Cards) =p.Membership.card

Multiplicidad opcional La multiplicidad de una asociación es opcional si el límite inferior es 0. Cuando un objeto asociado puede o debe estar presente depende del estado de los objetos involucrados context Person inv optionality: mortgages ->notEmpty() implies houses ->notEmpty()

Constraints y asociaciones

Constraints y asociaciones context Person inv: wife.employers-> intersection(self.employers)->isEmpty() and husband.employer>intersection(self.employers>isEmpty() context Company inv: employees.wife-> intersection(self.employees)->isEmpty()

Constraints y asociaciones OR Sólo una de las potenciales asociaciones puede ser instanciada para un simple objeto context Person Inv: managedProject->isEmpty() or performedProject->isEmpty() context Project inv: projectLeader->isEmpty() or projectMember ->isEmpty()

Constraints y asociaciones Subset

Constraints y asociaciones Subset context Flight inv: self.crew->includes(self.pilot) inv: self.crew>includesAll(self.flightAttendants) context Person inv: self.flights->includes(self.captainOn) inv: self.flights->includesAll(self.attendedOn)

Mensajes en postcondiciones Operador hasSent ('^') context Subject::hasChanged() post: observer^update(12, 14) observer^update(12, 14) es True si el mensaje update con argumentos 12 y 14 fue enviado a un objeto observer durante la ejecución de la operación hasChanged().

Expresión LET Posibilita definir una variable que puede ser usada en lugar de una subexpresión context CustomerCard inv: let correctDate: Boolean = self.validFrom.IsBefore (Date::now) and self.goodThru.isAfter (Date::now) in if valid then correctDate = true else correctDate = false endif

Bibliografía OCL: OCL Specification. Version 2.0. Formal document: ptc/03-10-14 www.omg.org Klasse Objecten Website: www.klasse.nl/ocl Warmer, J., Kleppe, A. The Object-Constraint Language. (Second Edition). Addison Wesley (2003)