Académique Documents
Professionnel Documents
Culture Documents
Agenda
Moral:
Decouples modules
Allows isolated development and
maintenance
Exception: Exposing
Constants
Problem:
VALUES
is final; entries in
VALUES
are not!
Classes and Interfaces
Correct:
private static final Type[] PRIVATE_VALUES = {};
public static final List VALUES =
Collections.unmodifiableList(Arrays.asList
(PRIVATE_VALUES));
Also Correct:
private static final Type[] PRIVATE_VALUES = {};
public static final Type[] values() {
return (Type[]) PRIVATE_VALUES.clone();
}
No possibility of encapsulation
Example: Questionable
Use of Immutable Public
Fields
Easier to design
Easier to implement
Easier to use
Less prone to error
More secure
Easier to share
Thread safe
Classes and Interfaces
10
11
Rule 2: No Overridden
Methods
12
13
14
15
Typical Transformation
return f;
}
16
Disadvantage:
Performance
Typical approach:
(Immutable)
StringBuilder (Companion Mutable Class)
String
17
18
Broken Example,
continued
What does
addCount()
return?
3?
6?
20
Source of Difficulty:
Overridden Methods
equals()
and
hashCode()
21
Composition
22
24 }
This is Cool!
25
26
Note:
Set
is a subtype of
Set
Collection
Issue:
27
28
protected
29
removeRange()
AbstractList
method in
Inheritance is Forever
30
31
32
readResolve(), writeReplace()
must be
33
Bottom Line
34
35
More Interfaces
36
37
38
39
Alternative to Constants in
Interfaces
40
41
Item 20 Continued: A
much better solution
42
// Strategy interface
public interface Comparator<T> { public int compare ( T t1, T t2); }
// Question: Is compare() consistent with equals()
Class StringLengthComparator implements Comparator <String> {
private StringLengthComparator() {}
public static final StringLengthComparator
INSTANCE = new StringLengthComparator();
public int compare (String s1, String s2) {
return s1.length s2.length;
}
}
43
Four flavors
44
Static vs NonStatic
45
Local classes
46