Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Object Oriented
Programming Techniques
Objective
Presenting
Types of classes
Public and Auxiliary
Public
classes
(helper) classes
Type of classes
Top level and inner classes
Top
level classes
Inner
Anonymous
Local
Member
Nested top-level
Type of classes
Top level and inner classes
Inner
classes Anonymous
Type of classes
Top level and inner classes
classes Local
Same as local variables,
Inner
Type of classes
Top level and inner classes
classes Local
Example (from JavaWorld, 08/99)
Inner
Type of classes
Top level and inner classes
classes Member
the body of a class
Can be used anywhere within the body of
the containing class
You declare member classes when you
want to use variables and methods of the
containing class without explicit
delegation
The member class is the only class that
you can declare static
Inner
Defined within
Type of classes
Top level and inner classes
classes Member (2)
Non static inner member classes
Inner
Type of classes
Top level and inner classes
classes Nested top-level
nested top-level class is a member
classes with a static modifier
A nested top-level class is just like any
other top-level class except that it is
declared within another class or interface
Nested top-level classes are typically used
as a convenient way to group related
classes without creating a new package
Inner
A
Note.
10
Example
public interface List {
// mutators
public void addElement(Object le, int i);
public void addFirst(Object le);
public void addLast(Object le);
public Object remove(int i);
public Object removeFirst();
public Object removeLast();
// getters (accessors)
public Object getFirst();
public Object getLast();
public Object getElement(int i);
public int getSize();
// test
public boolean isEmpty();
}
Ioan Salomie - Programming Techniques
11
Example
Class
DLlist
DLnode
list node
auxiliary class
should not be exposed to the clients
resides in the same file as DLlist
12
Example
Class DLnode - alternative 1
public class DLlist implements List {
protected DLnode head, tail;
protected int howMany;
// implementations
}
class DLnode {
Object element;
DLnode next, prev;
}
DLnode class
accessible to all package classes
not accessible to any DLlist subclass, not in
the same package
Ioan Salomie - Programming Techniques
13
Example
Class DLnode - alternative 2
public class DLlist implements List {
protected DLnode head, tail;
protected int howMany;
static protected class DLnode {
Object element;
DLnode next, prev;
}
// implementations
}
DLnode class
accessible to all DLlist subclasses
14
Getters
getAttr()
fields
code conventions
semantic names
the power of names
Ioan Salomie - Programming Techniques
15
Example
public class Point {
protected double x, y;
// constructor, getX, getY, setX, setY
}
public class PolarPoint extends Point {
protected double r, a;
//
}
Invariant constraint
links the two classes:
x = r * Math.cos(a)
y = r * Math.sin(a)
What if r and a were public???
PolarPoint pp = new PolarPoint();
pp.r = 20.9; // => inconsistent state
Ioan Salomie - Programming Techniques
16
Example
Keeping
consistent state
17
Class PolarPoint
public class PolarPoint extends Point {
protected double r, a;
public PolarPoint() { }
public PolarPoint(final double r, final double a) {
this.r = r; this.a = a;
polarToRectangular();
}
public double getRadius() { return r; }
public double getAngle() { return a; }
public void setRadius(final double r) {
this.r = r;
polarToRectangular()
}
public void setAngle(final double a) {
this.a = a;
polarToRectangular()
}
// => (next slide)
18
Class PolarPoint
public void setX(final double x) {
this.x = x;
rectangularToPolar()
}
public void setY(final double y) {
this.y = y;
rectangularToPolar()
}
protected void polarToRectangular() {
x = r * Math.cos(a); y = r * Math.sin(a);
}
protected void rectangularToPolar() {
r = Math.sqrt(x * x + y * y);
a = Math.atan2(y, x);
}
} // end class
19
20
List implementation
Ordered collection - accessed through an
index.
The size of the list can grow as needed
Implementation alternatives
linked list
dynamically resizable array
21
hidden details
changes in implementation
Interface
described by List
Implementations
LinkedList
public class LinkedList implements List {
// implementation body
}
DynamicArray
public class DynamicArray implements List {
// implementation body
}
22
header file
implementation file
Differences
C++
header file and implementation file are
two parts of the same class
header file contains interface and some
implementation
attributes
in-line methods
Java
interface and implementation class are
two different entities
the interface - no implementation
all implementation is included in the class
Ioan Salomie - Programming Techniques
23
(doc) comments
utility
http://java.sun.com/j2se/javadoc/
Formatted comments can be added to
javadoc
classes
methods
fields
javadoc
is invoked to generate
documentation
doc comment
feature description
list of tags
24
@author
multiple tags allowed
feature author (s)
@version
@since
@param
current version
when or in which version the feature appeared
associated with methods, multiple tags
meaning
range values
@return
meaning
possible values or range
@see
@throws
associated documentation
unhandled exception that might be thrown by method
25
Example
/**
* Class Circle defines the abstraction Circle
* A circle object is defined by its center
* point and radius
* @author xxxxx
* @version 0.1 09/04/2009
* @ since JDK 5.0
*/
public class Circle extends Shape2D {
//
}
//**
* get the i-th element of the list
* @param i Position of the element
* @return
Returns the i-th element of the list
* @see
# add(Object le, int i)
*/
public Object getElement(int i) {
//
}
26
contract
27
problems of informal
specifications of contracts
incomplete on some behavior aspects
ambiguity and multiple interpretations
contradictions with other contracts
Advantages
of formally specified
contracts
precision and unambiguousness
run time checking
catch contract violations by the
implementations as well as
misused of the services by the clients
28
languages - support
formally specifying the complete
behavior of software systems
needs mathematical skills
algebraic specification: Larch
model based specification: Z and
VDM
high costs => recommended for highly
critical applications
limited use can be easy and very costeffective
29
contract goals
method pre-conditions
method post-conditions
Pre-condition
boolean expression
Must hold when the method is invoked
Otherwise, exception is thrown
Post-condition
boolean expression
holds when the method invocation returns
30
@nochange
boolean expression saying that the state of the object is
not changed by the method
boolean operators
=> (logical implication)
<=> (logical equivalence)
Ioan Salomie - Programming Techniques
31
Contracts on Accessors
Examples
/**
* returns the # of list items
* @pre true
* @post @nochange
*/
public int getSize();
/**
* returns true if and only if the list is empty
* @pre true
* @post @result <=> getSize() > 0
* @post @nochange
*/
public boolean isEmpty();
32
Examples
@pre
true
@nochange
33
Examples
/**
* returns the i-the list item
* @pre i >= 0 && i < getSize()
* @post @nochange
*/
public Object getElement(int i);
For
34
Examples
/**
* returns the first list item
* @pre !isEmpty()
* @post @result == getElement(0)
* @post @nochange
*/
public Object getFirst();
/**
* returns the last list item
* @pre !isEmpty()
* @post @result == getElement(getSize() - 1)
* @post @nochange
*/
public Object getLast();
Ioan Salomie - Programming Techniques
35
Contracts on mutators
Object
state
on post expressions
36
Contracts on collections
Quantified expressions
Universally
quantified expression
Meaning
x is variable name,
Range expression, specifies the collection
Expression, boolean expression
Ioan Salomie - Programming Techniques
37
Contracts on collections
Range
expressions
[m .. n]
int range
m, n integer expressions
Expression
Expression must evaluate to Collection,
Enumerator or Iterator objects
Defines a range in the collection contains
all objects in the collection, enumeration
or iterator
ClassName
Defines a range consisting of all the
instances of a class
38
Example
Method
/**
* Adds a new element to the list on position i
* @pre el != null && i>=0 && i <= getSize()
* @post getSize() == getSize()@pre + 1
* @post @forall k : [0 .. getSize() -1 ] @
*
(k <i ==> getElement(k)@pre == getElement(k)) &&
*
(k == i ==> el@pre == getElement(k) &&
*
(k > i ==> getElement(k-1)@pre == element(k)
*/
public void addElement (Object el, int i);
39
Example
/**
* Adds a new element at the head of the list
* @pre el != null
* @post getSize() == getSize()@pre + 1
* @post el@pre == getElement(0)
* @post @forall k : [0 .. getSize() -1 ] @
*
(getElement(k-1)@pre == getElement(k))
*/
public void addFirst (Object el);
/**
* Adds a new element at the end of the list
* @pre el != null
* @post getSize() == getSize()@pre + 1
* @post el@pre == getElement(getSize() - 1)
* @post @forall k : [0 .. getSize() -2 ] @
*
(getElement(k)@pre == getElement(k))
*/
public void addLast (Object el);
40
Example
Method
remove
/**
* Remove the element at the i-th position
* @pre getSize() > 0
* @pre i >= 0 && i < getSize()
* @post @result = getElement(i)@pre
* @post getSize() == getSize()@pre - 1
* @post @forall k : [0 .. getSize() -1 ] @
*
(k <i ==> getElement(k)@pre == getElement(k)) &&
*
(k >= i ==> getElement(k+1)@pre == element(k)
*/
public void remove (int i);
41
Example
/**
* Remove the element at the list head
* @pre getSize() > 0
* @post @result = getElement(0)@pre
* @post @forall k : [1 .. getSize() -1 ] @
*
getElement(k+1)@pre == element(k)
*/
public void removeFirst(int i);
/**
* Remove the element at the end
* @pre getSize() > 0
* @post @result = getElement(getSize() - 1)@pre
* @post @forall k : [0 .. getSize() -1 ] @
*
getElement(k)@pre == element(k)
*/
public void removeLast (int i);
42
Contracts and
implementations
All
43
Class invariants
Object
state
Stable
initialized, but not being manipulated
Transient
the object is being manipulated, i.e. a
method is executing on the object
Invariants
of a class
Well-formed state
44
Example
DLlist
45
Example (cont.)
Implementation
main features
(cont.)
For each node reachable from head
prev field of its succeeding node should point
to itself
next field of its preceding node should point to
itself
46
47
tag
@invariant booleanExpression
/**
* @invariant isWellFormed()
*/
@invariant tag can occur many times
AND of all boolean expressions
Entities used in invariants
implication operator
equivalence operator
quantified expressions
Invariants
48
DLL invariant
/**
* @invariant isWellFormed()
*/
public class LinkedList implements List() {
// implementation
protected boolean isWellFormed() {
// invariant implementation
}
protected DLnode head, tail;
protected int count;
static protected class DLnode {
Object item;
DLnode next, previous;
}
}
- Class implementer must ensure that all public methods
preserve the invariants
49
50
Assertions
Run-time checking
assert assertionCondition;
assertCondition - boolean expression
if true, assert has no effects
if false, AssertionError exception is thrown
Ioan Salomie - Programming Techniques
51
Assertions
Assertions
rules
52
Examples
/**
* returns the first list item
* @pre !isEmpty()
* @post @result == getElement(0)
*/
public Object getHead() {
assert !isEmpty();
Object result = (head != null) ?
head.element : null);
assert result == getElement(0);
return result;
}
53
Examples
/**
* Adds a new element to the list on position i
* @pre el != null && i>=0 && i <= getSize()
* @post getSize() == getSize()@pre + 1
*/
public void addElement (Object el, int i) {
assert el != null && i >= 0 && i <= getSize();
assert isWellFormed();
int sizePre = getSize();
if(i<= 0) { addFirst(el); }
else if (i >= count) { addLast(el) }
else {
// i >0 && i < count
DLnode n = head;
for(int j = 0; n != null; && j < i-1; j++) { n = n.next; }
DLnode node = new DLnode();
node.element = el node.next = n.next; node.prev = n;
node.next.prev = node; n.next = node;
count ++
}
int sizePost = getSize();
assert sizePost == sizePre + 1;
assert isWellFormed();
}
Ioan Salomie - Programming Techniques
54
Examples
Comments
55
Defensive programming
Objective
Preventing misuse
How
in unit testing
56
Design guideline
Each
57
Design by contract
Relates to
interfaces
Overriding subclass methods and
implemented interface methods should honor
the contracts
No
No
58