Title: Object-Oriented Knowledge Representation
1Object-OrientedKnowledge Representation
2Outline
- Object-oriented languages
- Review key concepts of object-orientation
- History of OO languages
- Motivation for OO software engineering and
knowledge representation - First generation OOKR languages
- Semantic networks
- Frames
- Comparison with Classical First-Order Logic
(CFOL) - UML
- The variety of UML diagrams
- Class diagrams
- Object diagrams
- Meta-knowledge representation and MOF
- Ontologies
- What is an ontology?
- Elements of an ontology
- Services provided by an ontology
- The pluridisciplinary origin of ontological
engineering - Typology of ontologies
- Sub-fields and general issues in ontological
engineering - OCL
- What is OCL?
- Motivating examples
- OCL expression contexts
- The link between the OCL and UML metamodels
- The OCL metamodel
- OCL Types
- Inheritance and encapsulation in OCL
- Local variale definitions
- The OCL operator library
- OCL vs. UML
- OCL vs. Java
3Review of Key Object-Orientation Concepts
- Class (or concept, or category) abstract
represention of a set of individuals with common
structural and/or behavioral properties - A class defines a complex type
- Object (or individual, or instance) individual
instance of a given class - An object conforms to the complex type defined by
its class - An object is created by instantiating its class
(constructor method) - Each object possess a unique identifier (oid)
that distinguish it from other instance of the
same class sharing the same properties - The structural properties of a class are a set of
attributes (also called fields or slots) names,
each one constrained to be of a certain subset of
types (primitive types or classes) - The structural properties of an object are
specific values for these attributes within the
ranges defined by its class - The behavioral properties of a class are a set of
operations (also called methods, procedures or
functions) that its instance can execute - The signature of a class is the set of
constraints on its attributes and on the
parameters and return value of its operations - The properties of a class have various
visibilities such as public, protected and
private allowing their encapsulation - Classes are organized in a generalization
hierarchy - Properties are inherited down the hierarchy from
a class to its subclasses and its objects
4Inheritance
- Allows concise knowledge representation through
reuse of especifications and implementations
among classes and objects down a generalization
hierarchy - Types of inheritance
- Structural inheritance
- Attribute signature inheritance (constraint
inheritance) - Value inheritance
- Behavioral inheritance
- Operation signature inheritance (constraint
inheritance) - Operation code inheritance
- Inheritance multiplicity
- Simple inheritance (each class restricted to
having a single superclass, and each object
restricted to belong to a single class) - Multiple inheritance of different properties from
different sources - Multiple inheritance of same property from
different sources - Inheritance monotonicity
- Monotonic inheritance simple without overriding
- Non-monotonic inheritance with overriding,
logically equivalent to default reasoning,
semantics beyond Classicial First-Order Logic
5A Brief History of OO Languages
Distributed System
Programming
Knowledge Representation
Databases
Software Engineering
1965
Today
Simula
Semantic Networks
Sketchpad
Smalltalk
Frames
Today
C
OQL
Next lecture
Advanced AI courses
UML1.0
Description Logics
SQL99
Java
OCL
Advanced AI coursed
Today
Frame Logics
MOF
Advanced AI courses
C
Semantic Web Languages
UML2.0
Today
2005
6Motivation for OO in Software Engineering
- Improved productivity, quality, legibility and
maintainability in developing software artifacts - Software reuse instead of rewriting or cut and
paste - More intuitive
- Divide software in abstract entities and
relations that directly match common cognitive
abstraction of modeled domain - Easy to learn
- Unifying notation
- Single representation paradigm for all software
process stages - Single, unified modeling language (UML)
7Initial Motivation for OOin Knowledge
Representation
- Reasoning at the level of categories
- Inheritance as reasoning task
- Representing structural knowledge with a notation
that is more intuitive than formal logic - Easier to acquire, understand, maintain, etc.
- Reasoning about classifying instances into
categories and inheritance can internally reuse a
logic-based theorem prover, but in a way that is
transparent-hidden from the domain expert - Benefits of software engineering carrying over to
knowledge (base) engineering
8Categories
- The organization of objects in categories is a
vital part of knowledge representation - Most human reasoning occurs at the abstract
level of general categories (intentional
knowledge), rather than at the level of
individual objects (extensional knowledge) - Partial information
- coming for example from the sensors of an agent,
- about an object can be sufficient to classify it
into a set of fixed categories - about which general knowledge has been
formalized - The missing information
- needed for example for an agent to make a
decision about how to handle the object or
predict its behavior - about the object can then be derived from the
properties of the category - Complex taxomonies involving generalization and
composition relationships among categories form a
rich network of abstract knowlege onto which to
base the reasoning of an agent
9Properties of Categories
- Disjointness
- No common elements
- Ex. male and female
- Exhaustive decomposition
- Covers the entire set of entities in the
represented domain - Ex. an animal that is not male, must be female
- Partition
- Exhaustive decomposition into disjoint categories
- Counter-example citizenships
- Composition
- A category of objects has another category of
objects as one of its constituing parts - Ex. Brazil is part of South America, a chapter
is part of a book
10Semantic Networks
- Knowledge visual modeling category-oriented
- Each category and object is represented by a
newtwork node - Each relationship between categories is
represented by a network link - Special hierarchical relationships is-a
(inheritance) and part-of - Efficient algorithms for deriving object
properties, according to category conformance - Derivation by value inheritance
- Derivation by link path query
11Semantic Networks - Example
Logical assertion n-ary Fly
Semantic network with four objects and four
categories
12Abstract Syntax of semantic networks in UML
? OOP/OOSE Classes Objects
- OOP/OOSE
- attributes
- other associations
? OOSE aggregation composition associations
? OOP/OOSE subclass instance relationships
Node
Link
Attribute Specification
IS-A
PART-OF
Single Value Specification
Multiple Value Specification
13Semantic Networks vs. Classical First-Order Logic
(CFOL) intentional knowledge
- Mary ?FemalePersons
- SisterOf (Mary, John)
- ?x x ?Persons ? x ? Mammals
- ?x x ?Persons ? ?y HasMother (x, y) ? y ?
FemalePersons - ?x x ?Persons ? Legs (x, 2)
- Note that this property has only status of
default knowledge, since it can be overrided at
the instance level to represent exceptions such
as John - Default knowledge reasoning is non-monotonic and
as such cannot be represented in CFOL
14Semantic Networks vs. CFOL extensional knowledge
- Fly (Shankar, NewYork, NewDelhi, Yesterday)
15Semantic Networks - limitations
- Main Limitations
- Incomplete to implement the majority of
intelligent systems - No well founded declarative semantics (shortcut
from konwledge level to implementation level
without using logical formalism) - Frames try to overcome first limitation
- Description logics try to overcome second
limitation - Other Limitations
- Search in large semantic networks may be very
inefficient - Nodes and links definitions are not homogenous
- Inheritance may cause difficulties while handling
exceptions - There can be conflicts between inherited features
- Behavior and procedural knowledge is difficult to
represent sequence and time are not defined - Less expressive than first-order logic There
are no quantifiers
16Frames
- A frame has a name as its identification and
describes a complex object using a set of
attributes - A Frame System is a hierarchical organized set of
frames. - They are an evolution of semantic networks
- Nodes are replaced by frames
- Edges are replaced by attributes (slots)
- They implement monotonic reasoning (ex,
inheritance without overriding) and non-monotonic
(ex, inheritance with overriding) - Procedures may be attached to a frame
- They describe knowledge or some procedure related
to an attribute.
17Frames
- Categories (classes) and instances (objects)
represented by Frames - A frame is composed by slots
- A slot is composed by facets
- Facets may be
- Value specification (known or by default)
- Constraint over value (type, cardinality)
- Procedures (triggers for when the slot is
acessed, modified or necessary to derive some
fact during reasoning) - Frames hierarchically organized with multiple
inheritance of slots - Inheritance is complex (without no formal
definition) due to the variety of facets and
interactions - Reasoning is implemented comgining inheritance
and triggers - Frames used for
- Knowledge representation
- Inference engine implementation
- Knowledge acquisition interface implementation
- Reasoning explanation interface implementation
- Frames are always an extension of some host
programming language (Lisp, C, Prolog, etc.)
18Frames example
Frame Course in KB University Slot enrolls
Type Student Cardinality.Min 2
Cardinality.Max 30 Slot taughtby Type
(UNION GradStudent
Professor) Cardinality.Min 1
Cardinality.Max 1
Frame BasCourse in KB University Is-a Course
Slot taughtby Type Professor
Frame Professor in KB University Slot degree
Default PhD.
Frame Student in KB University
Frame AdvCourse in KB University Is-a Course
Slot enrolls Type (INTERSECTION
GradStudent (NOT
Undergrad)) Cardinality.Max 20
Frame GradStudent in KB University Is-a
Student Slot degree Default Bachelor
Frame Undergrad in KB University Is-a Student
19Abstract Syntax for Frames im UML
? OOP/OOSE Classes Objects
- OOP/OOSE
- Attributes
- Associations
No corresponding concepts in OOP/OOSE
? OOP/OOSE Methods Activities
? OOSEConstraints
? OOP/OOSE subclass instance relationships
IS-A
Frame
Slot
Facet
Host Language Procedure
Procedural Attachment
Constraint
Value Specification
Cardinality Constraint
Single Value Specification
Min Int Max Int
Multiple Value Specification
Type Constraint
Input Parameter
Return Value
20Frames limitations
- Non-declarative Behavior Knowledge prevents
direct codification from domain expert - No formal semantic
- Implementation ad-hoc of deduction e adbduction,
usually inefficient - There are no inductive inference engines for
frame learning - It does not include encapsulation concepts nor
components from moder OO programming languages
21UML as KR Language
- Class diagram
- Modern, well-founded version of semantic
networks - Activity diagram
- Modern, well-founded version of flow charts
- Graphical syntax for procedures
- Class diagrams Activity diagrams
- Graphical syntax of expressive power
approximately equivalent to that of Frames - Strengths
- Universal standard, well-thought, well-known and
well-tooled (CASE) - Facilitates convergence between software and
knowledge engineering - Limitations
- Lack of full UML compilers to executable
languages - Lack of inference engine to automatically
reasoning with knowlege represented only as UML
models - No mathematically defined formal semantics yet
- Thus
- Only useful at the knowledge level
- Need to be used in conjunction with other
language(s) that provide the formalization and/or
implementation level
22UML Classifiers Simplified Meta-Model
Type
Classifier
Feature
generalizes
Class
Interface
Association
DataType
StructuralFeature
BehavioralFeature
Parameter
AssociationClass
PrimitiveType
Enumeration
Operation
Constraint
Property
Boolean
Integer
String
Real
AssociationEnd
Attribute
23Classes Operations
- Common signature of services provided by the
class members - Fields
- Visibility
- Name
- Input parameter
- Direction
- Name
- Type
- Multiplicity
- Default value
- Property
- Return type
- Property
- Object methods called on objects
- Class methods called to manipulate class
attributes - Operations for KR as many fields as possible!
24UML Relations Simplified Meta-Model
Relation
Association
Generalization
Dependency
AssociationClass
Aggregation
QualifiedAssociation
GeneralizationSet
Realization
Composition
PowerType
25Associations
- Association
- Generic relation between N classifiers
- Fields
- One or two Names
- Navigation direction
- Two Ends, each with
- One Multiplicity Range (default 1)
- Zero to One role
- Zero to one Qualifier
- Qualifier needed to distinguish different
instances of a one-to-many or many-to-many
association - Navigation
- Role if present
- Otherwise destination class name
- Associations for KR as many fields as possible!
26Association Classes
- Class connected to an association and not to any
of its ends - Allows associating properties and behaviors to an
association - One object of the association class for each link
of the connected association - A one-to-many or many-to-many association class
cannot be substituted by a simple class and a
pair of simple associations - Example
- Ca has objects A1, A2, A3, A4
- Cb has objects B1, B2, B3, B4
- Extent of association class Cc between Ca and Cb
with multiplicity at both ends has necessarily
16 instances - Class Cc associated to Ca through association
Aca and to Cb through association Acb could have
only 4 instances
Difference with ?
4
Elevator control
Queue
Elevator
27Ternary Associations
- Single association between 3 classes
- Different from two binary associations
- Different from one binary association class
- Example
- Ca has objects A1, A2
- Cb has objects B1, B2
- Cc has objects C1, C2
- No link in the ternary association Ca-Cb-Cc
corresponding to pair of links A1-B1, B2-C1
28Aggregation Associations
- Association with part-whole semantics
- Associate composite class to its building blocks
- Static, definitional characteristic of the
whole class - In contrast to composite structure diagrams that
model dynamic, configuration characteristic of
the containing class - Shared aggregation
- Many-to-many aggregation
29Composition Associations
- Special case of one-to-one or one-to-many
aggregation where part(s) cannot exist(s) without
the unique whole - Deletion of the whole must therefore always be
followed by automatic deletion of the parts
30Class generalizations
- Taxonomic relation between a class and one of its
more general direct super-class - Special case of generalization between any two
classifiers - Several generalizations form a taxonomic tree
free of generalization cycles - Sub-classifier inherits the features from all its
direct super-classifiers - Private attributes and operations not accessible
from sub-classes - Protected attributes and operations accessible
from sub-classes but not from associated classes - UML generalizations allow multiple
inheritanceand overriding - Instances of a sub-class must satisfy all the
constraints on all its super-classes (principle
of substitutability)
31Abstract Classes
- Class that cannot be instantiated
- Only purpose factor gradual refinements of
common and distinct structures and behaviors down
a taxonomic hierarchy - Abstract operation common signatures of distinct
implementations specified in subclasses - Supports polymorphism generic call signature to
distinct operations, with automatic dispatch to
the implementation appropriate to each specific
call instance
32Generalization Sets
- Subclass set that can be labeled as
- complete or incomplete
- overlapping or disjoint
- Complete and disjoint generalization sets form a
partition of the super-class - Sub-subclass can specialize members of two
overlapping generalization sets
33Objects and Links
- Object Diagram contains
- Specific (named) or generic (named after role,
unnamed) instances of classes - Possibly several instances of the same class
- Specific instances of associations (links) among
objects - Possibly several instances of the same
association - Illustrates specific instantiation patterns of
associated class diagram
34UML x Semantic Networks Example
- Corresponding Class Diagram
35UML x Semantic Network Example
- Corresponding Class Diagram
36UML x Frames Example
Frame Course in KB University Slot enrolls
Type Student Cardinality.Min 2
Cardinality.Max 30 Slot taughtby Type
(UNION GradStudent
Professor) Cardinality.Min 1
Cardinality.Max 1
Frame Student in KB University
Frame GradStudent in KB University Is-a
Student Slot degree Default Bachelor
Frame Undergrad in KB University Is-a Student
Frame Professor in KB University Slot degree
Default PhD.
Frame AdvCourse in KB University Is-a Course
Slot enrolls Type (INTERSECTION
GradStudent (NOT
Undergrad)) Cardinality.Max 20
Frame BasCourse in KB University Is-a Course
Slot taughtby Type Professor
37UML Unified Modeling Language
- UML advantages as knowledge representation
language - Standard notation and edition tools
- Well-defined Links composition, agreggation,
inheritance, ... - It works at the knowledge level
- Graphical easy modeling
38Comparison Table
Semantic Networks Frames UML OCL Predicate Logic
Originated field IA IA SE IA
Inference engine for automated reasoning Yes Yes No Yes
Complete well founded formal declarative semantics No No No Yes
Knowledge Representation Structural Struc. Declar. Bheavior. Procedural Struct. Declar. Behavior. Procedu-ral Struct. Declar.
Easy visual syntax Yes No Yes No
39O que é uma ontologia?
- Definição especificação (semi-)formal explÃcita
de uma concepção compartilhada - Concepção modelo das entidades, relações,
axiomas e regras de algum domÃnio - Formal
- processável por máquina
- permitindo raciocÃnio automático
- com semântica lógica formal
- Compartilhada por uma comunidade, permitindo
entendimento - Conceitos de computação relacionados
- Base de conhecimento reutilizável
- Esquema de banco de dados
40Elementos de uma ontologia
- Hierarquia de conceitos
- entidades
- cada entidade definida por conjunto de pares
atributo-valor - correspondem
- as classes dos modelos orientado a objetos
- as entidades do modelo relacional
- aos termos do modelo lógico
- atributos propriedades x atributos relações
- preenchidos por valores atômicas (tipos
primitivos) x por outros conceitos - Status epistemológico do valor
- Exatamente conhecida, default, probabilista
- relações
- sem hierarquia x em hierarquia paralela a
hierarquia de entidades - correspondem
- associações, agregações e atributos dos modelos
OO cujos valores são objetos - as relações do modelo relacional
- aos predicados do modelo lógico
41Elementos de uma ontologia
- Restrições
- sobre valores possÃveis dos atributos dos
conceitos - correspondem
- as assinaturas de classes em modelos OO
- as axiomas universalmente quantificados em
modelos lógicos - as restrições de integridade nos esquema de BD
- Regras dedutivas
- sobre atributos de (conjunto de) conceitos
- permitem inferência automática da existência de
instâncias de conceitos a partir da existência de
outras instâncias - correspondem
- as regras dos sistemas especialistas e
programação em lógica - aos métodos dos modelos OO
- as visões em BD
42Elementos de uma ontologia
- Instâncias de conceitos
- definição de entidade e relações especÃficos
(indivÃduos) - correspondem
- aos fatos de sistemas especialistas e programação
em lógica - aos objetos dos modelos OO
- aos dados dos BD
43Serviços suportados por uma ontologia
- Consultas e manipulação
- correspondem
- métodos de acesso a valor e de reflexão em
linguagens OO - consultas de interrogação e manipulação em BD
- ask, tell e retract das bases de conhecimento
- sobre conceitos
- Quais são as entidades E relacionadas a entidade
0 via relações r1, r2? - Quais são as relações R mais gerais que r1?
- Definição d de entidade E é consistente com o
resto da ontologia? - sobre instâncias
- um indivÃduo I com propriedades P1, ..., Pn é
instância de quais conceitos? - RaciocÃnio automático
- geralmente dedutivo
44Origem e motivação para ontologias
Gerenciamento do Conhecimento em
Organizações desde 90
Integração de Dados desde 95
Ontologias
Engenharia de Software requisitos e reuso desde
90
Filosofia desde 350 A.C.
Sistemas Multi-agentes desde 95
Recuperação de Informação na Web desde 00
45Tipologia das ontologias
- Especialista modela um domÃnio particular
restrito - Geral
- modela o conhecimento de senso comum
compartilhado por todos os seres humanos - parte de mais alto nÃvel, reutilizável em vários
domÃnios - Conceitual fundamentada na capacidade de
raciocinar - LingüÃstica fundamenta no vocabulário de uma(s)
lÃngua(s) - De meta-dados especializada na descrição de
recursos on-line, no entanto sobre qualquer
domÃnio - De tarefas e métodos modela procedimentos e
comportamentos abstratos no lugar de entidades ou
relações
46(No Transcript)
47Sub-problemas de modelagem de uma ontologia geral
- Categorias e conjuntos
- Medidas
- Objetos compostos
- Tempo
- Espaço
- Mudanças
- Eventos e processos
- Objetos fÃsicos
- Substâncias
- Objetos mentais e crenças
48Problemática geral e questões sobre ontologias
- Divisão
- como delimito as classes e os atributos?
- quais são as distinções que trazem valor
agregado? - Escopo
- qual conhecimento incluir?
- qual a fronteira do meu domÃnio?
- Granularidade
- até que nÃvel de detalhe modelar os domÃnio?
- problema da ramificação?
- Validação
- como avalio a qualidade do modelo?
- como escolho entre várias modelagem alternativas
(as vezes propostas por pessoas diferentes)? - como identificar aspectos importantes que estão
faltando?
49Problemática geral e questões sobre ontologias
- Muito difÃcil responder a essas perguntas porque
- Almejados reuso e relativa independência de
aplicação impedem ser guiado completamente pelos
requisitos de uma aplicação restrita - Para ontologias gerais de senso comum pior devido
a imensidão em largura e profundidade do
conhecimento a modelar - Metodologias ainda incipientes
- Methontology
- Sensus http//www.isi.edu/natural-language/resour
ces/sensus.html - No entanto, já existe tentativa de padronização
http//suo.ieee.org/ - http//www.fipa.org/
50What is OCL? Definition and Role
- A textual specification language to adorn UML
and MOF diagrams and make them far more
semantically precise and detailed - OCL2 integral part of the UML2 standard
- OCL complements UML2 diagrams to make UML2
- A domain ontology language that is
self-sufficient at the knowledge level to
completely specify both structure and behaviors - A complete input for the automated generation of
a formal specification at the formalization level
to be verified by theorem provers - A complete input for the automated generation of
source code at the implementation level to be
executed by a deployment platform - OCL complements MOF2 diagrams to make MOF2
- An object-oriented declarative abstract syntax
and semantics specification language that is
self-sufficient at the meta-knowledge/meta-modelin
g level - OCL forms the basis of model transformation
languages - such as Atlas Transformation Language (ATL) or
Query-View-Transform (QVT) - which declaratively specify through rewrite
transformation rules the automated generation of
formal specifications and implementations from a
knowledge level ontology - OCL expressions are reused in the left-hand side
and right-hand side of such rules - To specify objects to match in the source
ontology of the transformation - To specify objects to create in the target
formal specification or code of the transformation
51What is OCL?Characteristics
- Formal language with well-defined semantics
based on set theory and first-order predicate
logic, yet free of mathematical notation and thus
friendly to mainstream programmers - Object-oriented functional language
constructors syntactically combined using
functional nesting and object-oriented navigation
in expressions that take objects and/or object
collections as parameters and evaluates to an
object and/or an object collection as return
value - Strongly typed language where all expression and
sub-expression has a well-defined type that can
be an UML primitive data type, a UML model
classifier or a collection of these - Semantics of an expression defined by its type
mapping - Declarative language that specifies what
properties the software under construction must
satisfy, not how it shall satisfy them - Side effect free language that cannot alter
model elements, but only specify relations
between them (some possibly new but not created
by OCL expressions) - Pure specification language that cannot alone
execute nor program models but only describe them - Both a constraint and query language for UML
models and MOF meta-models
52What is OCL?How does it complement UML?
- Structural adornments
- Specify complex invariant constraints (value,
multiplicity, type, etc) between multiple
attributes and associations - Specify deductive rules to define derived
attributes, associations and classes from
primitive ones - Disambiguates association cycles
- Behavioral adornments
- Specify operation pre-conditions
- Specify write operation post-conditions
- Specify read/query operation bodies
- Specify read/query operation initial/default
value
53OCL Motivating Examples
- Diagram 1 allows Flight with unlimited number of
passengers - No way using UML only to express restriction that
the number of passengers is limited to the number
of seats of the Airplane used for the Flight - Similarly, diagram 2 allows
- A Person to Mortgage the house of another Person
- A Mortgage start date to be after its end date
- Two Persons to share same social security number
- A Person with insufficient income to Mortgage a
house
1
2
54OCL Motivating Examples
context Flightinv passengers -gt size()
lt plane.numberOfSeats
1
context Personinv PersonallInstances() -gt
isUnique(socSecNr) context PersongetMortgage(su
mMoney,securityHouse) pre self.mortgages.monthl
yPayment -gt sum() lt self.salary 0.3
context Mortgage inv security.owner
borrower inv startDate lt endDate
2
55OCL Expression Contexts
56OCL Contexts Default Value and Query
Specifications
- Initial values
- context LoyaltyAccountpoints integer init
0 - context LoyaltyAccounttransactions
Set(Transaction) init Set - Query operations
- context LoyaltyAccountgetCustomerName()
Stringbody Membership.card.owner.name - context LoyaltyProgramgetServices()
Set(Services)body partner.deliveredServices
-gt asSet()
57OCL ContextsSpecifying Invariants on Attributes
- The context of an invariant constraint is a class
- When it occurs as navigation path prefix, the
self keyword can be omitted - context Customer inv self.name Edward
- context Customer inv name Edward
- Invariants can be named
- context Customer inv myInvariant23
self.name Edward - context LoyaltyAccountinv oneOwner
transaction.card.owner -gt asSet() -gt size()
1 - In some context self keyword is required
- context Membershipinv participants.cards.Members
hip.includes(self)
58OCL Contexts Invariants for Disambiguating
Association Cycles and Plural Multiplicity
- Cycles of association with plural multiplicity
are often underconstrained by class diagrams,
thus not reflecting actual modeled domain
semantics - In the real world a person cannot use the house
of another person as security for a mortgage - context Personinv mortgages.security.owner -gt
forall(onwnerPerson owner self)
59Association Navigation
- Association navigation
- context Transaction def getCustomer()Custome
r self.card.owner - Attribute access
- context Transaction def getCustomerName()Str
ing self.card.owner.name - Abbreviation of collect operator that creates
new collection from existing one, for example
result of navigating association with plural
multiplicity - context LoyaltyAccount inv transactions -gt
collect(points) -gt exists(pInteger
p500) - context LoyaltyAccount inv
transactions.points -gt
exists(pInteger p500) - Use target class name to navigate roleless
association - context LoyaltyProgram inv levels -gt
includesAll(Membership.currentLevel) - Call UML model and OCL library operations
60Generalization Navigation
- OCL constraint to limit points earned from
single service to 10,000 - Cannot be correctly specified using association
navigation - context ProgramPartner inv totalPoints
deliveredServices.transactions
.points -gt sum() lt 10,000 - adds both Earning and Burning points
- Operator oclIsTypeOf allows hybrid navigation
following associations and specialization links - context ProgramPartner inv totalPoints
deliveredServices.transactions -gt
select(oclIsTypeOf(Earning)) .points -gt
sum() lt 10,000
61OCL Contexts Specifying Attribute Derivation
Rules
- context CustomerCardprintedName
- derive owner.title.concat(
).concat(owner.name) - context TransactionReportLine String derive
self.date transaction.date - ...
- context TransactionReport inv dates lines.date
-gt forAll(d d.isBefore(until) and
d.isAfter(from)) - ...
62OCL ContextsSpecifying Pre and Post Conditions
- context LoyaltyAccountisEmpty() Booleanpre
-- nonepost result (points 0) - Keyword _at_pre used to refer in post-condition to
the value of a property before the execution of
the operation - context LoyaltyProgramenroll(cCustomer)pre
c.name ltgt post participants
participants_at_pre -gt including(c) - Keyword oclIsNew used to specify creation of a
new instance (objects or primitive data) - context LoyaltyProgramenrollAndCreateCustomer(n
String,dDate)Customerpost result.oclIsNew()
and result.name n and
result.dateOfBirth d and participant
-gt includes(result) - oclIsNew only specifies that the operation
created the new instance, but not how it did it
which cannot be expressed in OCL
63Links BetweenOCL and UML Meta-Models
64The OCL Expressions Meta-Model
65The OCL Types Meta-Model
66OCL Types
- Value Types
- UML primitive types (including user-defined
enumerations) - OCL collection types (even of user-defined
classifiers ?) - Their instances never change value
- ex, Integer instance 1 cannot be changed to
instance 2, nor can string instance Lew
Alcindor be changed to string instance Kareem
Abdul-Jabbar, nor can enumeration Grade instance
A can be changed to enumeration instance C. - Object types UML classifiers
- Their instances can change value, i.e., the
Person instance p1 can have its name attribute
Lew Alcindor changed to Kareem Abdul-Jabbar
yet remain the same instance p1 - OclAny
- Most generic OCL type, subsuming all others
- General reflective operations are defined for
this type and inherited by all other OCL types
67OCL Types
- Primitive data types (from UML) boolean,
string, integer, real - Type conformance rules
- t1 conforms to t2 if t1 lt t2 in type hierarchy
- t1 collection(t2) conforms to t3
collection(t4) if t2 conforms to t4 - integer lt real
- Type casting
- Operation oclAsType(s) can be invoked on an
expression of type g to recast it as a type s - s must conform to g
- OclVoid
- Undefined value (similar to null values of SQL)
- Tested by oclIsUndefined operation of OclAny type
68OCL Types Collections
- Collection constants can be specified in
extension - Set1, 2, 5, 88, Setapple, orange,
strawberry - OrderedSetblack, brown, red, orange,
yellow, green, blue, purple - Sequence1, 3, 45, 2, 3, Bag1, 3, 4, 3, 5
- Sequence of consecutive integers can be
specified in intension - Sequence1..4 Sequence1,2,3,4
- Collection operations are called using -gt
instead of . - Collection operations have value types
- They do not alter their input only output a new
collection which may contain copies of some input
elements - Most collections operations return flattened
collections - ex, flattenSet1,2,Set3,Set4,5
Set1,2,3,4,5 - Operation collectNested must be used to preserve
embedded sub-structures - Navigating through several associations with
plural multiplicity results in a bag
69OCL Semantics Encapsulation and Inheritance
- By default, OCL expressions ignore attribute
visibility - i.e., an expression that access a private
attribute from another class is not syntactically
rejected - OCL constraints are inherited down the
classifier hierarchy - OCL constraints redefined down the classifier
hierarchy must follow substituability principle - Invariants and post-condition can only become
more restrictive - Preconditions can only become less restrictive
- Examples violating substituability principle
- context Stove inv temperature lt 200
- context ElectricStove inv temperature lt 300
- context Stoveopen()
- pre status StoveStateoff
- post status StoveStateoff and isOpen
- context ElectricStoveopen()
- pre status StoveStateoff and temperature
lt 100 - post isOpen
70OCL Expressions Local Variables
- Let constructor allows creation of aliases for
recurring sub-expressions - context CustomerCard
- inv let correctDate Boolean
validFrom.isBefore(Datenow) and
goodThru.isAfter(Datenow) - in if valid then correctDate false
else correctDate true endif - Syntactic sugar that improves constraint
legibility
71OCL Library Generic Operators
- Operators that apply to expressions of any type
- Defined at the top-level of OclAny
72OCL Library Primitive Type Operators
- Boolean host, parameter and return type boolean
- Unary not
- Binary or, and, xor, , ltgt, implies
- Ternary if-then-else
- Arithmetic host and parameters integer or real
- Comparison (return type boolean) , ltgt, lt, gt
lt, gt, - Operations (return type integer or real) , -,
, /, mod, div, abs, max, min, round, floor - String host string
- Comparison (return type boolean) , ltgt
- Operation concat(String), size(), toLower(),
toUpper(), substring(ninteger,minteger)
73OCL Library Generic Collection Operators
74OCL Library Syntax of Loop Operators
- Loop operators (aka. iterator operations, aka.
iterators) - Common characteristics
- They are all hosted by an OCL expression of type
collection - They all take an OCL expression as input
parameter (called the body of the loop) - They optionally take as second parameter an
iterator variable - The return type of the body expression and the
type of the iterator variable must conform to the
type of the host collections elements - Loop operators iterate over the elements of the
host collection, applying the body expression to
each one of them - Distinguishing characteristics
- How they combine the body expression application
into a new result collection
75OCL LibrarySpecialized Collection Operators
76Example of OCL Expressions with Loop Operators
- context LoyaltyProgram inv self.Membership.accou
nt -gt isUnique(acc LoyaltyAccount
acc.number) - context LoyaltyProgram inv Membership.account
-gt isUnique(acc acc.number) - context LoyaltyProgram inv Membership.account
-gt isUnique(number) - Iterator variable clarifies that number refers
to the number attribute of each collection
element and not to the number of elements in the
collection - Loop expressions with reference to the iterator
requires an iterator variable - context ProgramPartner inv
self.programs.parters -gt
select(pProgramPartner p.self)
77OCL Constraints vs. UML Constraints
context ClassicalGuitar inv strings-gt forAll(s
s.oclIsType(plasticStrings))
context ElectricGuitar inv strings -gt forAll(s
\ s.oclIsType(MetalStrings))
context ClassicGuitar inv strings -gt
forAll(type StringTypeplastic)
context Guitar inv type GuitarTypeclassic
implies strings -gt forAll(type
StringTypeplastic inv type
GuitarTypeclassic implies strings -gt
forAll(type StringTypeplastic
context ElectricGuitar inv strings -gt
forAll(type StringTypemetal)
78OCL vs. Java
- Declarative specification of operation
post-conditions in OCL is far more concise than
corresponding implementation in mainstream
imperative OO language such as Java - This is due mainly to OCLs powerful collection
operators - Example OCL expression self.parters -gt
select(deliveredServices -gt forAll(pointsEarned
0)) - Corresponding Java code
- Iterator it this.getPartners().iterator()
- Set selectResult new HashSet()
- while( it.hasNext() )
- ProgramPartner p (ProgramPartner) it.next()
- Iterator services p.getDeliveredServices().ite
rator() - boolean forAllresult true
- while( services.hasNext() )
- Service s (Service) services.next()
- forAllResult forAllResult
(s.getPointsEarned() 0) -
- if ( forAllResult )
- selectResult.add(p)
-
-
- return result