12 - OOSC - Object Design (Specifying Interfaces)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Chapter 12:

Object Design (Specifying Interfaces)

Object-Oriented
SoftwareConstruction

Armin B. Cremers, Sascha Alda & Tobias Rho


(based on Bruegge & Dutoit)
Announcement Practice Talk

♦ Michael Mahlberg (TCG – The Consulting Guild GmbH)

“Experiences with (and without!) coupling and


cohesion from industry”

Š Thursday, 29th 2006


Š 16:30 (B-IT Lecture Hall)

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 2
Object Design: Closing the Gap
System
Problem

Application objects

Requir ements gap

Solution objects

Custom objects

Object design gap

Off-the-shelf components

System design gap

Machine
Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 3
Object Design – Interface Design

‹ Requirements analysis activities


Š Identifying first attributes and operations without specifying their types
or their parameters.

‹ Goal of Interface Design:


Š Describe the Interface of each object precisely enough so that objects
realized by individual developers fit together with minimal Integration
problems

‹ Activities:
Š Identify missing attributes and operations from analysis object and
subsystem service
Š Specify Visibility and Signatures
Š Specify Contracts (main focus in this lecture)

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 4
Developers play different Roles during
Object Design

Class User Call Class

Developer Class Implementor Realize Class

Class Extender Refine Class

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 5
Example for the relationship from viewpoint
of abstract class “Game”
Developers responsible for
Developers responsible for the implementation of Game are
the implementation of League are class implementors
class users of Game

League Game
1

*
Tournament TicTacToe Chess

The developer responsible for


the implementation of TicTacToe
is a class extender of Game
Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 6
Add Visibility Information

UML defines three levels of visibility:


‹ Private (Class implementor):
Š A private attribute can be accessed only by the class in which it is
defined.
Š A private operation can be invoked only by the class in which it is
defined.
Š Private attributes and operations cannot be accessed by subclasses or
other classes.
‹ Protected (Class extender):
Š A protected attribute or operation can be accessed by the class in which
it is defined and on any descendent (subclass) of the class.
‹ Public (Class user):
Š A public attribute or operation can be accessed by any class.

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 7
Implementation of UML Visibility
in Java

Tournament
- maxNumPlayers: int
+ getMaxNumPlayers():int
+ getPlayers(): List
# removePlayer(p:Player)
+ acceptPlayer(p:Player)
+ isPlayerAccepted(p:Player):boolean

public class Tournament {


private int maxNumPlayers;

public Tournament(League l, int maxNumPlayers)


public int getMaxNumPlayers() {…};
protected void removePlayer(Player p) {…};
public List getPlayers() {…};
public void acceptPlayer(Player p) {…};
public boolean isPlayerAccepted(Player p) {…};

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 8
Information Hiding Heuristics

‹ Carefully define the public interface for classes as well as subsystems


(façade)
‹ Always apply the “Need to know” principle.
Š Only if somebody needs to access the information, make it publicly
available, but then only through well defined channels, so you always
know the access.
‹ The fewer an operation knows
Š the less likely it will be affected by any changes
Š the easier the method can be changed
‹ Information hiding is not a major issue during analysis, however
during design it is a problem.

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 9
Information Hiding Design Principles

‹ Only the operations of a class are allowed to manipulate


its attributes
Š Access attributes only via operations.

// Can be accessed directly // Can’t be accessed directly


public Object myAttr = … ; private Object myAttr = … ;
public void getMyAttr(){
return this.myAttr;
}

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 10
Add Type Signature Information

Hashtable
-numElements:int
+put()
+get()
+remove()
+containsKey()
+size()

Hashtable
Attributes and operations -numElements:int
without type information +put(key:Object,entry:Object)
are acceptable during analysis +get(key:Object):Object
+remove(key:Object)
+containsKey(key:Object):boolean
+size():int

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 11
Design by Contract
‹ Idea: Contracts on a class enable caller (client) and callee (class
itself) to share the same assumptions (semantics) about the class.
‹ Problem: Accurate Semantics cannot be added to standard UML
models discussed so far
‹ Solution/Realization: Design By Contract by Betrand Meyer
(“Object-Oriented Software Construction”, Prentice Hall)
Š Process of developing software based on the notion of contracts
between objects
Š Contracts are expressed as assertions (predicates)
Š Assertions comprise preconditions, postconditions and invariants

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 12
Types of Assertions

‹ Precondition:
Š Preconditions are predicates associated with a specific operation and
must be true before the operation is invoked.
Š Preconditions are used to specify constraints that a caller must meet
before calling an operation.

‹ Postcondition:
Š Postconditions are predicates associated with a specific operation and
must be true after an operation is invoked.
Š Postconditions are used to specify constraints that the object (callee)
must ensure after the invocation of the operation.

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 13
Examples of Assertions
Assertion of List method “add”
PreCondition
list != null //List exists
key.instanceOf(String)

List
-list:Collection
+add(key:Object)
+create():void
+remove(key:Object)
+containsKey(key:Object):boolean
+size():int
PostCondition
size = size +1;
containsKey( key ) = true;

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 14
Design by Contract
‹ Parties in the contract: class and client
Š PreCondition binds clients
Š PostCondition binds class
‹ Contract important for Class User (Client) and Class Implementor
(class)
‹ Contract entails benefits and obligations for both parties

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 15
Example

Contract for add


Obligations Benefits
of class List

Only call add() on a Can retrieve item by


Class User non-full and existing List containsKey( );

Make sure that key is in the Does not need to care


Class Implementor List; List has increased by one about Cases, where List
is full or not created

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 16
Class invariants and class correctness

‹ Preconditions and postconditions describe properties of individual


methods
‹ Need for global properties of instances which must be preserved by
all routines
‹ Examples (List)
Š Size of List must not be negative
Š Size of List must be lower than 1000 entries
Š The number of elements must be even

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 17
Class invariants and class correctness

‹ A class invariant is an assertion to be satisfied by all instances of the


class at all “stable” times (instance in stable state):
Š on instance creation
Š before and after every remote call to a routine
Š may be violated during call

‹ A class invariant only applies to public methods; private methods are


not required to maintain the invariant.

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 18
Invariant Rule

‹ An assertion I is a correct class invariant for a class C iff the


following two conditions hold:
Š The constructor of C, when applied to arguments satisfying the
constructor’s precondition in a state where the attributes have
their default values, yields a state satisfying I.
Š Every public method of the class, when applied to arguments and
a state satisfying both I and the method’s precondition, yields a
state satisfying I.

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 19
Design by Contract
Inheritance
‹ What does inheritance mean in relation to Design by Contract?
Î Overridden methods must conceptually do the same job!

‹ Contract Inheritance

‹ Rule of Thumb: Demand no more, promise no less.

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 20
Design by Contract
Inheritance
Demand no more:
‹A method of subclass is allowed to weaken the preconditions of
the method it overrides
‹ An overridden method with a weaker precondition can handle more
cases than its superclass

Promise no less:
‹A method must ensure a stronger postcondition than the method
it overrides
‹ An overridden method with a stronger postcondition ensures more
specific cases to the client upon return

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 21
Design by Contract
Inheritance – Example 1
‹ A method of subclass is allowed to weaken the preconditions of the
method it overrides. Example (1)
List PreCondition P1
-list:Collection list != null //List exists
+add(key:Object)
key.instanceOf(String)
+create():void
+remove(key:Object)
+containsKey(key:Object):boolean
+size():int

Correct!

NewList
New PreCondition P2
+add(key:Object) list != null //List exists

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 22
Design by Contract
Inheritance – Example 2
‹ A method of subclass is allowed to weaken the preconditions of the
method it overrides. Example (2)

List PreCondition P1
-list:Collection list != null //List exists
+add(key:Object)
+create():void key.instanceOf(String)
+remove(key:Object)
+containsKey(key:Object):boolean
+size():int

Violated!

NewList
New PreCondition P2
+add(key:Object) list != null //List exists
key.instanceOf(String)
Length(key) < 10
Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 23
Design by Contract
Inheritance – Example 4
‹ A method must ensure a stronger postcondition as the method it
overrides: Example:

List PostCondition P1
-list:Collection size = size +1;
+add(key:Object) containsKey( key ) = true;
+create():void
+remove(key:Object) size > 10
+containsKey(key:Object):boolean
+size():int

Violated!

NewList
PostCondition P2
+add(key:Object) size = size +1;
containsKey( key ) = true;
size > 2

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 24
Design by Contract
Inheritance – Example 3
‹ A method must ensure a stronger postcondition as the method it
overrides: Example:

List PostCondition P1
-list:Collection size = size +1;
+add(key:Object) containsKey( key ) = true;
+create():void
+remove(key:Object) size > 3
+containsKey(key:Object):boolean
+size():int

Correct!

NewList
New PostCondition P2
+add(key:Object) size = size +1;
containsKey( key ) = true;
size > 9

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 25
Application of Design by Contract

‹ The Liskov Substitution Principle:


Š “If an object of type S can be substituted in all places where an
object of Type T is expected, then S is a subtype of T”

Client T

Š If all preconditions of the methods of type S are weakened and all


postconditions of the methods of type S are stronger than the
methods of type T, then S is a subtype of type T
Š Client do not has to change its code, if object T is substituted by S

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 26
Advantages of Design By Contract

‹ Improves the reliability of programs


‹ Assertions provide accurate documentation for the
implemented classes so that a programmer knows how to
use the classes and what to expect from them;
‹ Assertions provide a way of controlling inheritance
(substitutability)
‹ Assertions can be an important aid to developing critical
systems.

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 27
Expressing constraints in UML Models
‹ OCL 2.0 (Object Constraint Language) is part of UML 2.0
‹ OCL allows constraints to be formally specified on single model elements
(attributes, operations, classes) or groups of model elements
(associations and participating classes)
‹ A constraint is expressed as an OCL expression returning the value true
or false.
‹ OCL is not a procedural language (cannot constrain control flow).
‹ More Info:
Š Introduction of OCL for Together
‹ http://bdn1.borland.com/devcon05/article/1,2006,33187,00.html

Š Tutorial of University of Koblenz


‹ http://www.uni-koblenz.de/~beckert/Lehre/Praktikum-Formale-Entwicklung/oclIntro.pdf

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 28
Expressing constraints in UML Models
‹ OCL expressions for Hashtable operation put():
Š The context keyword indicates the object to which the
expression is valid
Context is a class
Š Invariant:
‹ context Hashtable inv: numElements >= 0 OCL expression

Š Precondition:
‹ context Hashtable::put(key, entry) pre:!containsKey(key)

Š Post-condition:
‹ context Hashtable::put(key, entry) post: containsKey(key) and
get(key) = entry

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 29
Expressing constraints in UML Models

‹ A constraint can also be depicted as a note attached to the


constrained UML element by a dependency relationship.

<<invariant>>
numElements >= 0

<<precondition>> HashTable
!containsKey(key) numElements:int <<postcondition>>
get(key) == entry
<<precondition>> put(key,entry:Object)
containsKey(key) get(key):Object
remove(key:Object)
<<precondition>> containsKey(key:Object):boolean
containsKey(key) size():int <<postcondition>>
!containsKey(key)

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 30
Contract for acceptPlayer in
Tournament

context Tournament::acceptPlayer(p) pre:


not isPlayerAccepted(p)

context Tournament::acceptPlayer(p) pre:


getNumPlayers() < getMaxNumPlayers()

context Tournament::acceptPlayer(p) post:


isPlayerAccepted(p)

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 31
Contract for acceptPlayer in
Tournament

context Tournament::removePlayer(p) pre:


isPlayerAccepted(p)

context Tournament::removePlayer(p) post:


not isPlayerAccepted(p)

context Tournament::removePlayer(p) post:


getNumPlayers() = @pre.getNumPlayers() - 1

@pre.= value returned by


method before invoking
value returned by removePlayer
method after invoking
removePlayer

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 32
OCL Annotations
JavaDoc (iContract)
public class Tournament { /** The acceptPlayer() operation
/** The maximum number of players * assumes that the specified
* is positive at all times. * player has not been accepted
* @invariant maxNumPlayers > 0 * in the Tournament yet.
*/ * @pre !isPlayerAccepted(p)
* @pre getNumPlayers()<maxNumPlayers
private int maxNumPlayers; * @post isPlayerAccepted(p)
* @post getNumPlayers() =
/** The players List contains * @pre.getNumPlayers() + 1
* references to Players who are */
* are registered with the public void acceptPlayer (Player p)
* Tournament. */ {…}
private List players;
/** The removePlayer() operation
/** Returns the current number of * assumes that the specified player
* players in the tournament. */ * is currently in the Tournament.
* @pre isPlayerAccepted(p)
public int getNumPlayers() {…} * @post !isPlayerAccepted(p)
* @post getNumPlayers() =
/** Returns the maximum number of @pre.getNumPlayers() - 1
* players in the tournament. */ */
public int getMaxNumPlayers() {…} public void removePlayer(Player p) {…}

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 33
Constraints can involve more than
one class

♦ Until now: Constraints are valid within a single class


♦ Often, Constraints are necessary to declare assertions
across many classes
Š Make Assumptions about associations between classes
Š Definition of global invariants
♦ Expressions for navigating between classes are necessary
♦ Set-based operations

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 34
Types of Navigation through a Class
Diagram

1. Local attribute 2. Directly related class 3. Indirectly related class


Tournament League League
start:Date *
end:Date
* *
Player Tournament
*

*
Player

Any OCL constraint for any class diagram can be built


using only a combination of these three navigation types!

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 35
Example: League, Tournament and
Player
League
*
+start:Date
+end:Date
+getActivePlayers()

* tournaments
Tournament
+start:Date
+end:Date
+acceptPlayer(p:Player)
* tournaments

* players
players
Player
*
+name:String
+email:String

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 36
Model Refinement with 2 additional
Constraints
♦ A Tournament’s planned duration must be under one week.
♦ Players can be accepted in a Tournament only if they are already
registered with the corresponding League.

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 37
OCL Collections

♦ Collections are data types used to navigate to associated


classes within a constraint expression.
Š OCL Sets
 Used to navigate a single (1:1, 1:n, or n:m) association

League chess:League

*
Player Bob:Player Isa:Player Marc:Player

league.player = {Bob, Isa, Marc}

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 38
OCL Collections

♦ Collections are data types used to navigate to associated


classes within a constraint expression.
Š OCL Bags
 Used to navigate through a series of at least two associations with
one-to-many or many-to-many multiplicity
League chess:League

WM: EM:
* Tournament Tournament
Tournament

* Bob:Player Isa:Player Marc:Player

*
Player
league.tournament.player = {Bob, Isa, Marc,Isa}
Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 39
OCL Collections

♦ OCL provides many operations for accessing collections (via


Access Operator Æ). Examples:
Š includes(Object) – returns true if Object is in Collection
Š union(Collection) – returns a Collection containing elements from
both the original collection and the collection
specified as paramater
Š asSet(Collection) – returns a Set containing each element of the
collection without any duplicate elements (as
opposed to a bag)
♦ Examples:
Š {Bob, Isa, Marc}Æincludes( Timo ) = false;
Š league.tournament.player = {Bob, Isa, Marc,Isa}
league.tournament.playerÆasSet = {Bob, Isa, Marc}

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 40
Specifying the Model Constraints

Local attribute navigation *


League

context Tournament inv: +start:Date


+end:Date
end - start <= Calendar.WEEK +getActivePlayers()

Directly related class navigation


{ordered}
context * tournaments
Tournament::acceptPlayer(p)
pre: Tournament

league.players->includes(p) +start:Date
+end:Date
+acceptPlayer(p:Player)
* tournaments

* players
players
Player
*
+name:String
+email:String

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 41
OCL supports Quantification

♦ OCL forAll quantifier


Š forAll (variable | expression) is true, if expression is true for all
elements in the collection
Š Example: All Matches m in a Tournament t occur within the
Tournament’s time frame:
context Tournament inv:
matches->forAll( m:Match |
m.start.after(t.start) and m.end.before(t.end))
♦ OCL exists quantifier
Š exists ( variable | expression ) is true if there is at least one
element in the collection for which expression is true
Š Example: Each Tournament conducts at least one Match on the
first day of the Tournament:
context Tournament inv:
matches->exists(m:Match | m.start.equals(start))

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 42
Realization of Constrains in
Programming Language: Java
♦ Often realized in terms of conventional exception handling
♦ Assertions to check pre- and postconditions within methods can be
used since JDK 1.4
♦ The validation of Assertions must be enabled (is disabled by default)

Boolean expression (must be true at runtime,an


AssertionError is thrown, otherwise)

Optional indication of a Message-String


for the AssertionError Objekt

Start:
Start:
java Assertions
x=0
java.lang.ArithmeticException:
/ by zero …

Compilation: java –ea Assertions


x=0
/ by 0
Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 43
Realization of OCL in Java

♦ Only view OCL compilers and parsers are available.


♦ Dresden OCL Toolkit
Š Generates Java Code for given OCL assertions
Š Runtime Evaluation of Assertions
Š Web: http://dresden-ocl.sourceforge.net/aboutproject.html
♦ IBM OCL Parser
Š Checking of syntax only, no Code Generation
Š Web: http://www-306.ibm.com/software/awdtools/library/standards/ocl-
download.html
♦ Together Borland

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 44
Summary
♦ There are three different roles for developers during object design
Š Class user, class implementor and class extender
♦ During object design - and only during object design - we specify
visibility rules
♦ Constraints are boolean expressions on model elements
♦ Contracts are constraints on a class enable class users, implementors
and extenders to share the same assumption about the class
(“Design by contract”)
♦ OCL is a language that allows us to express constraints on UML
models
♦ Complicated constratins involving more than one class, attribute or
operation can be expressed with 3 basic navigation types.

Armin B. Cremers, Sascha Alda & Tobias Rho (based on Bruegge & Dutoit) Object-Oriented Software Construction 45

You might also like