PRACTICAL - PowerPoint PPT Presentation

1 / 74
About This Presentation
Title:

PRACTICAL

Description:

... OCL expression can be used to specify a state change, e.g. in a post-condition ... direction of potential messages between instances of one class and instances of ... – PowerPoint PPT presentation

Number of Views:16
Avg rating:3.0/5.0
Slides: 75
Provided by: comp55
Category:

less

Transcript and Presenter's Notes

Title: PRACTICAL


1
  • PRACTICAL
  • OBJECT-ORIENTED
  • DESIGN WITH UML
  • 2e

Chapter 12 Constraints
2
Constraints
  • Most of UMLs notation is graphical
  • this is good for expressing structural properties
  • Most systems have properties or business rules
    that cannot be shown on diagrams
  • eg that the balance in a bank account must be
    within the range 0 to 250,000
  • Such properties can be added to a model in the
    form of constraints

3
A Simple Constraint
  • Constraints are Boolean assertions
  • they are attached to one or more model element
  • this shows a note containing a class constraint

4
UML Constraints
  • Constraints can be expressed using informal
    English
  • UML defines a some standard constraints to handle
    common situations
  • the xor constraint
  • the subset constraint
  • The formal language OCL can be used to write
    precise, general constraints

5
The xor Constraint
  • The xor constraint asserts that two associations
    are mutually exclusive
  • a customer can hold a savings account or a
    deposit account, but not both

6
The subset Constraint
  • The subset constraint asserts that objects linked
    by one association are also linked by another
  • the chair of a committee is also a member of it

7
The Need for General Constraints
  • Many constraints cannot be handled by these
    general means
  • eg we might want to rule out this situation

8
Formulating a Constraint
  • We could express the constraint as follows
  • find the holder of any given debit card
  • find the holder of the account it belongs to
  • you must reach the same customer each time
  • OCL the Object Constraint Language
  • a user-friendly formal language
  • expresses constraints precisely and concisely
  • well-adapted for use with UML

9
Requirements for OCL
  • Expressions written in the OCL are used to
    specify additional integrity constraints on a
    model.
  • A constraint language should provide
  • the ability to specify what model elements are
    being constrained
  • the ability to navigate through the model to
    identify related objects and data values
  • the ability to make assertions about the entities
    reached through navigation

10
OCL Software (USE)
  • A model can be animated to validate the
    specification against non-formal requirements.
    System states (snapshots of a running system) can
    be created and manipulated during an animation.
    For each snapshot the OCL constraints are
    automatically checked. Information about a system
    state is given by graphical views. OCL
    expressions can be entered and evaluated to query
    detailed information about a system state. OCL
    cannot change state, only USE system adds, sets,
    and deletes variables.

11
  • The OCL cannot change state, only the USE system
    adds, sets, and deletes variables.
  • The picture below gives a general view of the USE
    approach.

12
USE example
13
OCL overview
  • OCL is a specification language defined in UML
    and compliments the graphical aspects of UML by
    providing a language for formally expressing the
    constraints of the model.
  • OCL is an expression language. It has no side
    effects, this means that the state of the system
    will never change because of an OCL expression,
    even though an OCL expression can be used to
    specify a state change, e.g. in a post-condition
  • A constraint is a restriction on one or more
    values of an OO model. There are many constraints
    that cannot be expressed with a UML diagrams.

14
USE constraints
  • The number of employees working in a department
    must be greater or equal to the number of
    projects controlled by the department.
  • Employees get a higher salary when they work on
    more projects.
  • The budget of a project must not exceed the
    budget of the controlling department.
  • Employees working on a project must also work in
    the controlling department.

15
USE OCL
  • Department -- the number of employees working in
    a department must -- be greater or equal to the
    number of projects -- controlled by the
    department
  • context Department
  • inv MoreEmployeesThanProjects self.employee-gtsize
    gt self.project-gtsize

16
USE OCL
  • employees get a higher salary when they work on
    more projects
  • context Employee
  • inv MoreProjectsHigherSalary Employee.allInstance
    s-gtforAll(e1, e2 e1.project-gtsize gt
    e2.project-gtsize implies e1.salary gt e2.salary)

17
USE OCL
  • the budget of a project must not exceed the
    budget of the controlling department
  • context Project
  • inv BudgetWithinDepartmentBudget self.budget lt
    self.department.budget

18
USE OCL
  • employees working on a project must also work in
    the -- controlling department
  • context Project
  • inv EmployeesInControllingDepartment
    self.department.employee-gtincludesAll(self.employe
    e)

19
The Context of a Constraint
  • Every OCL constraint has a context
  • this relates the constraint to the model elements
    being constrained
  • Constraints can be shown on diagrams
  • in the constrained element or in an attached note

20
Textual Constraints
  • Constraints are more often written as text
    accompanying a model
  • they start with a context declaration defining
    the context
  • context SavingsAccount inv
  • self.balance gt 0
  • and self.balance lt 250000
  • inv indicates that the constraint is an
    invariant

21
Constraint Syntax
  • A dot . is used to refer to a feature of a
    model element, such as an attribute value
  • self refers to the context object
  • it can be omitted if preferred
  • the context object and the constraint itself can
    be named
  • context accSavingsAccount inv limits
  • acc.balance gt 0
  • and acc.balance lt 250000

22
Constraint Syntax
  • A dot . is used to refer to a feature of a
    model element, such as an attribute value
  • self refers to the context object
  • it can be omitted if preferred
  • the context object and the constraint itself can
    be named
  • context SavingsAccount inv limits
  • self.balance gt 0
  • and self.balance lt 250000

23
An Payroll System
  • Further examples are based on this model

24
Whole-Part relationship
  • The UML provides a two ways to record the nature
    of a whole-part relationship. Why use them? This
    relationship frequently occurs in application
    domains
  • Aggregation We can describe a 'wholepart'
    relationship where the part is not mandatory.
    For example the whole could be an invoice which
    is made up from the invoice lines (the parts). It
    would be possible to add, remove or replace one
    of the parts and still have a meaningful
    relationship an invoice would still be an
    aggregation of invoice lines if another invoice
    line were to be added. For aggregation, you
    simply add an open diamond to the end of the
    association to indicate the class that is to act
    as the whole.
  • Composition We can describe a 'wholepart'
    relationship where the part is mandatory. For
    example the association that holds between a
    chess-board and the squares on it. If you were to
    remove (or add) a square you would no longer have
    a recognizable chess-board. A chess-board and its
    squares are much more intimately related than an
    invoice and its invoice lines because a chess
    board cannot exist unless it has 64 squares. The
    chess-board and square association is a
    particular kind of aggregation known as a
    composition. Composition, as a stronger form of
    aggregation, is shown as a solid black diamond.

25
Qualified Associations
26
Qualified Associations
  • If the system you are modeling includes a
    mechanism for identifying objects uniquely, you
    can use qualified associations to record this
    information. For example, a bank usually
    identifies individual bank accounts by a unique
    account number. The use of account numbers to
    uniquely identify accounts would be noted in the
    glossary.

27
Qualified Associations
  • Given the combination of a bank and an account
    number, there is either zero or one associated
    account. The advantage of this approach is that
    you have put more information into the model and
    have placed less reliance upon people using the
    glossary.
  • This illustrates the general point that a
    qualified association often replaces an
    association with a multiplicity of with a
    multiplicity of either 1 or 0..1. In the UML, a
    qualifier is considered to be an attribute of an
    association. It tells you about the properties of
    the concept that relates the classes at the ends
    of the association. In practice, qualifiers can
    be found in the attributes of one of the classes.
  • Why use them? Qualified associations are a way of
    capturing the uniqueness of some manner of
    identifying objects, such as in the case of
    account numbers in a bank.

28
Derived associations
  • Derived associations are probably the most common
    kind of derived element, closely followed by
    derived attributes. Any attribute can be marked
    as a derived attribute using the forward slash
    notation. For instance, a Person might have
    attributes of dateOfBirth and ageInYears. These
    are not independent, so the age could be marked
    as a derived attribute, as in /ageInYears.

29
Derived associations
  • Typically, the rule by which one attribute is
    derived from another would be held in the
    glossary but you could also express it in a note
    attached to the appropriate element in a model.
    For example, the value of ageInYears is obtained
    by comparing dateOfBirth with the current date. A
    derived attribute can be represented in OCL.

30
Derived associations
By preceding a role name with a slash, you
indicate that an association is derivable,
although you do not say how it is derived. That
information should be put in the project glossary.
31
Derived associations
  • Why use them? There are several reasons for
    choosing to identify a derived element. For
    example, during analysis, a derived attribute or
    association may be used to identify and define a
    useful concept such those children in a family
    who are teenagers. Derived attributes and
    associations are a way of optimizing a design and
    give more efficient access paths to data than
    those that exist in the original design. The
    disadvantage is a redundancy in the overall model
    that requires a processing overhead for
    consistency checking. Whatever the reason you
    choose to identify a derived element, its
    presence in a model implies that there is a
    responsibility to consider changing it if there
    is a change in the elements used to derive it.

32
Navigation Expressions
  • Starting from the context object we can follow
    links to arrive at other objects
  • To navigate across an association use
  • the role name at the far end of the association
  • or the name of the class at the far end
  • The dot notation is used to separate these from
    the context object name

33
Simple Navigations
  • The employees working in a department
  • this uses a role name
  • context Department inv
  • self.staff
  • The set of all departments in the company
  • this uses a class name
  • context Company inv
  • self.department

34
Navigations
  • A navigational expression is used to refer to
    notations in which you name an object or object
    attribute by starting at another object and hop
    from one object to another. You use role names to
    identify the next object and attribute names to
    identify which attribute of the object is of
    interest. We must be clear about the direction of
    potential messages between instances of one class
    and instances of another where there is an
    association between the two of them.

35
Navigations
  • In the UML, you can put an open arrowhead at one
    or both ends of an association to indicate that
    it is possible to reach one class from another
    following the direction of the arrow. In doing
    so, you are restricting access to instances of
    the class at end of the association where you
    placed the arrowhead.

36
Navigations
  • Navigational expressions are only about naming
    remote attributes. They are not directly related
    to the sending of messages. Contrast with the Law
    of Demeter, which offers guidelines on the use of
    objects reachable only by following chains of
    role names. Why use them? As class diagrams
    become complex, we need to check for loops.

37
Objects and Collections
  • What does a navigation expression return?
  • if there are many linked objects a collection is
    returned
  • if there is one linked object, the object is
    returned
  • if there are no linked objects, an empty
    collection is returned
  • OCL converts single objects to collections
    wherever necessary
  • it is as if a collection was always returned

38
Iterated traversal
  • More complex navigation expressions can follow a
    chain of associations
  • All the people who work for the company
  • context Company inv
  • self.department.staff
  • This is evaluated in a step-by-step manner
  • first get the collection of departments
  • then get the staff in each department
  • merge these collections of staff to get the result

39
Qualified Associations (1)
  • Navigation towards the qualifier is the same as
    unqualified associations
  • In the other direction, use qualifier values to
    identify individuals
  • the employee with payroll number 314159
  • context Company inv
  • self.employee314159

40
Qualified Associations (2)
  • Qualifiers can be combined with further
    navigation
  • that persons manager
  • context Company inv
  • self.employee314159.manager
  • Or omitted altogether
  • all the companys employees
  • context Company inv
  • self.employee

41
Association Classes
  • Navigate from in the normal way
  • all the employees of a particular grade
  • context Grade inv
  • self.contract.employee
  • Navigate to using association class name
  • the grade of a particular employee
  • context Person inv
  • self.contract.grade

42
OCL Basic Types
  • OCL defines basic types to describe data
  • Boolean
  • Integer
  • Real
  • These can be assumed to be the same as the
    corresponding UML types

43
Model Types
  • UML classes give rise to OCL model types
  • Model types have a number of properties
  • every UML attribute gives rise to a property
  • the far end of an association attached to the
    class gives rise to a property
  • query operations give rise to properties
  • Not every operation is a property
  • OCL expressions must not change object state

44
Property Values
  • Properties are denoted with the dot notation
  • the age and salary of an employee
  • context Person
  • inv self.age()
  • inv self.contract.grade.salary
  • Property expressions can denote collections
  • the names of employees in a department
  • context Department inv
  • self.staff.name

45
Enumerations
  • UML enumerations can be used in constraints
  • a signal must be red or green
  • context Signal inv
  • colour Colourred
  • or colour Colourgreen

46
Collections
  • What is the salary bill for a department?
  • collect the grades of each staff member
  • context Department inv
  • self.staff.contract.grade
  • and add up the salaries
  • But there will be many staff members on the same
    grade
  • a set of grades will give the wrong answer

47
Collection Types
  • OCL defines three types of collection
  • sets an object can only appear once in a set
  • bags an object can appear more than once
  • sequences objects in a sequence are ordered
  • Navigation from a single object returns a set
  • because there can only be one link to an object
  • Navigation from a set returns a bag
  • so we get a bag of grades in the example

48
Operations on Collections
  • We can add up the elements in a collection
  • the total salary bill for a department
  • context Department inv
  • staff.contract.grade-gtsum()
  • collection operations are preceded by -gt
  • Or find the number of different grades
  • convert the bag to a set and get its size
  • context Department inv
  • staff.contract.grade-gtasSet()-gtsize()

49
Selecting elements
  • Sometimes we are only interested in some elements
    in a collection
  • employees with a salary greater than 50,000
  • context Company inv
  • self.employee-gtselect(pPerson
  • p.contract.grade.salary gt 50000)

50
The Select Operation
  • The local variable is optional but can clarify
    expressions
  • select returns a collection that can be used
    for further navigation
  • the managers of highly paid employees
  • context Company inv
  • employee-gtselect
  • (contract.grade.salary gt 50000).manager

51
The Collect Operation
  • We can collect together the values of an
    expression applied to every element of a
    collection
  • the ages of all employees in a department
  • context Department inv
  • staff-gtcollect(pPerson p.age())
  • the companys salary bill after a 10 pay rise
  • context company inv
  • contract.grade
  • -gtcollect(salary1.1)-gtsum()

52
Shorthand for Collect
  • Often we want to collect all the values of a
    particular attribute over a collection
  • context Department inv
  • self.staff-gtcollect(name)
  • This is usually abbreviated to the familiar
  • context Department inv
  • self.staff.name

53
Basic Constraints
  • Write navigation expressions to denote the data
    values of interest
  • Use relational operations to express the
    constraint
  • an employee works for the company that their
    department is in
  • context Person inv
  • self.employer self.department.company

54
Constraints on Collections
  • Various properties of collections can be tested
  • two ways of saying that all employees are aged 18
    or more
  • context Department inv
  • employee-gtselect(age()lt18)-gtisEmpty()
  • context Department inv
  • employee-gtselect(age()lt18)-gtsize() 0

55
Collection predicates
  • We can check that an object is in a collection
  • every grade used is known to the company
  • context Person inv
  • employee.grade-gtincludes(contract.grade)
  • And that one collection is included in another
  • a departments staff all belong to the company
  • context Department inv
  • company.employee-gtincludesAll(staff)

56
Combining Constraints
  • Combine constraints using Boolean operators
  • not, and, or, xor
  • OCL also has an implies operator
  • every employee over 50 gets at least 25000
  • context Person inv
  • age() gt 50 implies
  • contract.grade.salary gt 25000

57
Iterative Constraints
  • Iterative constraints apply a Boolean expression
    to every member of a collection
  • The forAll quantifier checks if a property is
    true for all members of a collection
  • there is an employee at every grade
  • context Company inv
  • self.grade-gtforAll( g Grade
  • not g.contract-gtisEmpty())

58
The exists Quantifier
  • The exists quantifier checks if a property is
    true for at least one member of a collection
  • every department has a head (defined as someone
    with no manager)
  • context Department inv
  • staff-gtexists(e Person
  • e.manager-gtisEmpty())

59
All Class Instances
  • Simple constraints apply to all instances
  • the salary for every grade is more than 20000
  • context Grade inv
  • salary gt 20000
  • The allInstances operation does this explicitly
  • context Company inv
  • Grade.allInstances-gtforAll(g
  • g.salary gt 20000)

60
Comparing Class Instances
  • This is necessary to state some properties of the
    instances of a class
  • no two grades have the same salary
  • context Grade inv
  • Grade.allInstances-gtforall(g Grade
  • g ltgt self implies
  • g.salary ltgt self.salary
  • both self and g range over all grades

61
Class Invariants
  • Most constraints state properties of classes that
    are meant to be true at all times
  • These are known as invariants
  • an accounts balance must be in a given range
  • context SavingsAccount inv
  • balance gt 0 and balance lt 25000

62
Preconditions
  • Sometimes constraints are used to define
    properties of operations
  • Preconditions state what must be true before an
    operation is executed
  • you can only withdraw an amount less than the
    balance in an account
  • context SavingsAccountwithdraw(amtReal)
  • pre amt lt balance

63
Postconditions
  • Postconditions specify the result of an operation
  • withdraw withdraws the amount given to it
  • context SavingsAccountwithdraw(amtReal)
  • post balance balance_at_pre amt
  • balance_at_pre denotes the balance before the
    operation executed

64
Stereotyped Constraints
  • Constraints can be stereotyped if they are shown
    on a class diagram

65
Constraints and Generalization
  • Generalization doesnt give rise to any navigable
    relationships
  • Sometimes the run-time type of an object is
    important for a constraint

66
Checking Run-time Type
  • Every customer holds a current account
  • context Customer inv
  • account-gtsize() gt 0 implies
  • account.select(oclIsTypeOf(CurrentAccount))
  • -gtsize() gt 1
  • if the customer holds any accounts at all, at
    least one of them must be a current account
  • oclIsTypeOf returns true if an object belongs
    to the specified type

67
Parallel Generalization
  • Another situation with parallel hierarchies
  • only individuals can hold personal accounts

68
Finding the Type of an Object
  • Check that all the accounts belonging to an
    individual are of the correct class
  • context Individual inv
  • account-gtforAll(a Account
  • a.oclType PersonalAccount)
  • oclType returns the type of any object

69
OCL overview
  • The standard pre-defines a small number of
    constraints (for example the xor constraint over
    a set of associations indicating that only one
    may be manifest for any particular instance).
  • While the advantages of formal specification are
    well known, the disadvantage of traditional
    formal specification languages (e.g. Z) is that
    they are useable to persons with a strong
    mathematical background, but difficult for the
    average business or system modeler to use.
  • OCL is not a programming language, so it is not
    possible to write program logic or flow control
    in OCL. OCL facilitates the concept of an
    executable specification of constraints and some
    code generation e.g. pre/post conditions on
    methods.

70
OCL and testing
  • OCL can be used to test models. With appropriate
    software OCL can be used during analysis and
    design to test general purpose constraints and
    other modeling needs, testing is all done at the
    modeling stage. OCL can also influence code
    tests.
  • To specify and test invariants on classes,
    attributes, associations and types in a class
    model
  • To specify and test type invariants for
    stereotypes
  • To describe and test pre- and post-conditions on
    use-cases, operations and methods

71
OCL and testing
  • To describe and test guards A transition in a
    state transition diagram can be coupled to an
    action. This action is a procedural expression
    that is executed when the transaction fires and
    it targeted at a specific object or at a set of
    objects.
  • As a navigation language. This can help express
    constraints on loops in class diagrams and test
    for looping situations.

72
OCL and testing
  • To specify and test constraints on operations.
  • A message in a sequence or collaboration diagram
    can have an attached condition that specifies in
    what circumstances the message is sent.
  • To express and check parameters. For example,
    messages in collaboration and sequence diagram
    can take parameters.
  • Specify and test multiplicity and mandatory
    constraints.

73
OCL and testing
  • To represent derived associations and test their
    validity.
  • To represent and test end-user queries on a UML
    (with suitable tool can answer queries)
  • To specify and test initial attribute values.
  • Specifying and testing the derivation rules for
    attributes or associations.
  • Specifying and testing the body of a query
    operation
  • Specifying and testing guards on state charts
  • Specifying the targets for messages being sent.

74
More OCL
  • 1 The dates of the current bookings must be equal
    to the current date stored in the booking system
    object
  • 2 Booking times for the same table must not
    overlap.
  • 3 There are exactly ten tables in the restaurant.
  • 4 Only customers who have booked may be allocated
    a table.
  • context BookingSystem
  • inv MustBook self.current-gtforAll(b Booking
    b.date self.date)
  • context Restaurant
  • inv NoOverLap self.bookings-gtforAll(a,b
    Booking (a.duration-gtintersection(b.duration)-gti
    sEmpty) and .)
  • context Restaurant
  • inv TenTables self.table-gtsize10
  • context Restaurant
  • inv mustBook self.bookings-gtforAll(route to
    customer should be the same via both paths)
Write a Comment
User Comments (0)
About PowerShow.com