0% found this document useful (0 votes)
33 views44 pages

Tut 06

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views44 pages

Tut 06

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

COMPS356

Software Engineering
and Project Management
Presentation Outlines

• Review of last tutorial

• Unit 4:
– Reuse and object design (Part 2)

• Q&A
Review of Last Tutorial

• Reuse and Object Design (Part 1)


– Reuse concepts
• Application object, solution object
• Inheritance
– 6 design patterns
• Bridge
• Adapter
• Strategy
• Abstract Factory
• Command
• Composite
Unit 4:

Reuse and object design (Part


2)
Basic concepts for
Interface specification
Basic Concepts

• Overview of interface specification


– For each object, we try to
• Identification of missing attributes and operations
• Specification of type signatures and visibility
• Specification of preconditions and postconditions
• Specification of invariants
• Inheriting contracts
Basic Concepts
• Example

Student

name : String
Attributes age : integer Type
class : String
getExamScore( ) : integer
Operations getAge( ) : integer
setAge(integer age)

Visibility, Signature and Contract (preconditions, postconditions and invariants)


will be shown later.
Basic Concepts
• Class implementor
– responsible for the internal design and coding of
a class based on the class’s interface specification

public class Student


{
// A class implementor for student

void setAge(int age) {


this.age = age;
}
}
Basic Concepts
• Class user
– makes use of a class by instantiating an object
and/or invoking its methods.

public class Administrator


{ ClassB
...
// A class user that make use of
// student objects ClassA
Student stu = new Student();
stu.setAge(25);
}

– Class Administrator takes dual role of class user of Student and


the class implementor of administrator.
Basic Concepts
• Class extender
– implements a new class by inheriting from an existing class.

public class Prefect extends Student {


...
void setServiceClass( String serviceClass ) { Student
this.serviceClass = serviceClass;
}
String getServiceClass() {
return serviceClass; Prefect
}
}

– Prefect takes the dual role of class extender of Student and the
class implementor of prefect
Basic Concepts
• Types

– used to specify the allowed range of values an attribute / operation


parameters / returned values can take

– For OO languages, types can be classes as well

– Examples
• int, long, double, char, String, etc.

• Examples for attributes, parameters, returned values:


– int age;
– void setAge( int age );
– int getAge( );
– void setServiceClass( String serviceClass );
– String getServiceClass( );
Basic Concepts
• Signature

– a complete specification for the operation including the operation


name, the types of its parameters and return value.

– operations with the same name but a different number or type of


parameters are said to have different signatures

– Example
• int max ( int x, int y, int z )
• int max ( int w, int x, int y, int z )
• double max ( double x, double y, double z )
• int max (int a, int b, int c)
Basic Concepts
• Visibility

– Public
• attribute or operation can be accessed from any other class.

– Protected
• attribute or operation can be accessed by the defining class and its
derived classes.

– Private
• attribute or operation can only be accessed by the class in which it
is defined.
Basic Concepts
• Notification for visibility
– Notation convention
+ for public
# for protected Student
- for private
- name : String
- age : int
# class : String
+ getExamScore( )
+ getAge( )
+ setAge()
Basic Concepts
• How to determine the visibility?

– Use private
• For attribute or operation we consider to be internal detail of the class.

– Use protected
• For attribute or operation we think would be useful to subclasses only.

– Use public
• For attribute or operation we think would be useful to all classes.

– Remember: Don’t try to make everything public!


Basic Concepts
Exercise

• In the following diagram, for the class Staff:


– Which one is class implementer?
– Which one is class extender?
– Which one is class user?

1..n 1
Staff Shop

Manager
Basic Concepts
Exercise

• Determine the visibilities (+ / - / #) for the class attributes and methods


below:

ExamResult

examPart1Score : Integer
examPart2Score : Integer
examPart3Score : Integer

setPart1Score(score : Integer)
setPart2Score(score : Integer)
setPart3Score(score : Integer)
getAverageScore()
sum(scores : Integer[])
Basic Concepts
• Contracts for class

– allows everybody to have the same assumption


about the behaviour of the class

– Three main parts


• Invariant
• Precondition
• Postcondition
Basic Concepts
• Contracts for class - Invariant

– something that doesn’t change in the life of the object

– Example
• For a bank account object, if we want to have an invariant that the
account’s balance must be non-negative

getBalance( ) ≥ 0
Basic Concepts
• Contracts for class - Precondition

– a condition that must hold prior to the operation to ensure its


correct execution

– Example
• For the withdrawal() operation on a bank account object, we want to
make sure the withdrawn amount is less than or equal to the
balance

getBalance( ) ≥ amountWithdrawn
Basic Concepts
• Contracts for class - Postcondition

– a condition that guarantees to hold after the operation provided


that the precondition holds before the operation

– Example
• For the withdrawal() operation on a bank account object, we will
write the following postcondition

getBalance( ) = getBalance@pre ( ) - amountWithdrawn


Basic Concepts
• Summary of contract for the class method

Method withdrawn ( amountWithdrawn )

Pre: getBalance( ) ≥ amountWithdrawn

Post: getBalance( ) = getBalance@pre ( ) – amountWithdrawn

Invariant: getBalance( ) ≥ 0
OCL
Object Constraint Language
OCL Concepts
• Object Constraint Language (OCL)

– Part of UML

– A specification language (not a programming language)


• For the description of what needs to be done rather than
how.

– Formal languages for interface specifications


• English, Chinese are natural languages
OCL Concepts
• Object Constraint Language (OCL)
– Usually doesn’t wrote in the class diagram,
as it would be messy

«invariant» «precondition»
getMaxNumPlayers() > 0 getNumPlayers() <
getMaxNumPlayers()
Tournament
«postcondition»
-maxNumPlayers: int isPlayerAccepted(p)
«precondition» +getNumPlayers():int
!isPlayerAccepted(p) +getMaxNumPlayers():int «postcondition»
«precondition» +acceptPlayer(p:Player) !isPlayerAccepted(p)
isPlayerAccepted(p) +removePlayer(p:Player)
+isPlayerAccepted(p:Player):boolean
OCL Concepts
• OCL
– Write outside class diagrams, for example:

– Tournament invariant
context Tournament inv:
self.getMaxNumPlayers( ) > 0

– Tournament pre and post conditions


context Tournament::removePlayer( p: Player )
pre: isPlayerAccepted( p )
post: not isPlayerAccepted( p )
post: getNumPlayers( ) = getNumPlayers@pre ( ) – 1

CC stated that OCL in book chapters got several errors, so please try
to refer to study unit for the correct version of OCL.
OCL Concepts
• Rewrite the contract in OCL

Method withdrawal ( amountWithdrawn )


Pre: getBalance( ) ≥ amountWithdrawn
Post: getBalance( ) = getBalance@pre ( ) – amountWithdrawn
Invariant: getBalance( ) ≥ 0

context Account::withdrawal( amountWithdrawn: int )


pre: getBalance( ) >= amountWithdrawn
post: getBalance( ) = getBalance@pre ( ) – amountWithdrawn

context Account
inv: getBalance( ) >= 0
OCL Concepts
In OCL:

context Account::withdrawal ( amountWithdrawn: int )

In Java:

public class Account {

void withdrawal ( int amountWithdrawn ) {


….
}
}
OCL Basic Type
• OCL basic type

OCL basic type Example values Operations

Boolean true, false and, or, xor, not, implies,


if-then-else
Integer -3, 0, 1, 2, 3, 876, 20381, *, +, -, /, abs( )
...
Real 2.1, 3.1415, ... *, +, -, /, floor( )

String ‘Hello world’, ... toUpper( ), concat( )


OCL Collections
• OCL collections: sets, bags, sequences
– For specifying collection of objects rather than
individual object in OCL

Set: Collection does not contain duplicate elements


Bag: Like a set, except duplicates are permitted
Sequence: Like a bag, and also ordered

– Example
Set { 1, 27, 10 }
Bag { 1, 27, 33, 27, 27, 33, 27 }
Sequence { 1, 27, 27, 27, 33, 33 }
OCL Collections
• Example of using OCL collections in contract

context Tournament::acceptPlayer( p: Player )


pre: self.players->includes( p )
Return type
context League::getPlayers : Set( Player )
post: result = tournaments.players->asSet( )

Note:
- tournaments.players is a bag, hence asSet() is needed to convert it to Set
OCL Navigation
• Navigating an association

– An association has to be existed in the class


diagram for a valid navigation

– Example
• tournament.players Tournament
*
– If role name not exists
in the association, we can
convert the class name *
to be the navigation name Player
OCL Collections
• OCL collection operation

– size( )
• Returns the size of the collection, a non-negative integer

– includes( object )
• Returns whether the object is in the collection or not, a boolean value
(either true of false)

– select( expression )
• Returns a collection
• E.g. students->select( s : Student | s.age >= 15 and s.age <=20 )

Using unmatched type (include return type) is an error,


beware of it.
OCL Quantifiers
• OCL quantifiers

– forAll operation
• forAll (variable | expression)
• Return true if the expression evaluates to true for every element in
the collection.

• Example
players->forAll( p: Player | p.age > 20 )

• If all the players in the set are older than 20, then the above forAll
operation returns true
OCL Quantifiers
• OCL quantifiers

– exists operation
• exists (variable | expression)
• Return true if the expression evaluates to true for at least one
element in the collection.

• Example
players->exists( p: Player | p.age > 20 )

• If one or more of the players in the set are older than 20, then the
above exists operation returns true
OCL Quantifiers
• What are the meaning of the following
invariants?

context t : Tournament
inv: matches->forAll( m:Match |
m.startTime.after( t.startTime ) and
m.endTime.before( t.endTime ) )

context t : Tournament
inv: matches->exists( m:Match |
m.startTime.equals( t.startTime ) )
OCL Boolean Operations
• Propositional calculus
A B not A A and B A implies B
T T F T T
T F F F F
F T T F T
F F T F T

“or”, “xor”, “equivalence” are not mentioned in the table above


OCL Boolean Operations
• Example:
– A: Your kid gets 100 marks in exam
– B: You buy him toys

A B A implies B
– “A implies B = true” means you must buy toys to the kid if he/she got 100 marks in exam

T T T
T F F
F T T
F F T
OCL Boolean Operations
• Example:

A B A implies B
T T T
- Example for implies
context o : OLE T F F
inv: o.users->forAll ( u1, u2 : User |
F T
u1.loginID = u2.loginID implies u1 = u2 ) T
F F T
Invariant using “implies” operation

What is the meaning of the following invariant?

context TournamentControl
inv: tournament.players->forAll( p |
p.tournaments->forAll( t |
t <> tournament implies not t.overlap( tournament ) ) )

• Means if t is not the tournament managed by the TournamentControl


object, t must not overlap with the tournament.
Exercise on “implies”
Suppose we have a class “Product”, having methods:
String getProductType() // “Toys”, “Stationary”, “Clothes” , etc.
int getPrice() // 10, 50, 99, etc.

The “Product” also have a method called “getGift()” which will assign a souvenir for
to the client who purchasing that particular product. Every product will have a gift
except stationeries which is less than $5 dollars.

Try to develop the precondition for the method “getGift()”. It would be nice if you can
make use of the Boolean operator “implies”

Context Product::getGift()
pre: …
Notes on OCL

• To denote a comment in OCL, use


the ‘- -’ notation

• Contracts should not produce side effect


Questions?
End of this tutorial

Next tutorial… Unit 5: Implementation and Testing

You might also like