Skip to content

Commit 745394e

Browse files
committed
Cleaned up code examples from Chapter 8 (Methods)
1 parent c641e58 commit 745394e

File tree

13 files changed

+146
-30
lines changed

13 files changed

+146
-30
lines changed

src/effectivejava/chapter8/item50/Attack.java renamed to src/effectivejava/chapter8/item50/Attacks.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
package effectivejava.chapter8.item50;
22
import java.util.*;
33

4-
// Two attacks on the internals of an "immutable" period
5-
public class Attack {
4+
// Two attacks on the internals of an "immutable" period (232-3)
5+
public class Attacks {
66
public static void main(String[] args) {
7-
// Attack the internals of a Period instance (page 232)
7+
// Attack the internals of a Period instance (Page 232)
88
Date start = new Date();
99
Date end = new Date();
1010
Period p = new Period(start, end);
1111
end.setYear(78); // Modifies internals of p!
1212
System.out.println(p);
1313

14-
// Second attack on the internals of a Period instance
14+
// Second attack on the internals of a Period instance (Page 233)
1515
start = new Date();
1616
end = new Date();
1717
p = new Period(start, end);

src/effectivejava/chapter8/item50/Period.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package effectivejava.chapter8.item50;
22
import java.util.*;
33

4-
// Broken "immutable" time period class - Page 231-3
4+
// Broken "immutable" time period class (Pages 231-3)
55
public final class Period {
66
private final Date start;
77
private final Date end;
@@ -31,7 +31,7 @@ public String toString() {
3131
return start + " - " + end;
3232
}
3333

34-
// // Repaired constructor - makes defensive copies of parameters
34+
// // Repaired constructor - makes defensive copies of parameters (Page 232)
3535
// public Period(Date start, Date end) {
3636
// this.start = new Date(start.getTime());
3737
// this.end = new Date(end.getTime());
@@ -40,7 +40,7 @@ public String toString() {
4040
// throw new IllegalArgumentException(
4141
// this.start + " after " + this.end);
4242
// }
43-
43+
//
4444
// // Repaired accessors - make defensive copies of internal fields (Page 233)
4545
// public Date start() {
4646
// return new Date(start.getTime());
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package effectivejava.chapter8.item52;
22

3+
// Classification using method overrriding (Page 239)
34
class Champagne extends SparklingWine {
45
@Override String name() { return "champagne"; }
56
}

src/effectivejava/chapter8/item52/CollectionClassifier.java

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,4 @@ public static void main(String[] args) {
2626
for (Collection<?> c : collections)
2727
System.out.println(classify(c));
2828
}
29-
// Repaired static classifier method. (Page 240)
30-
// public static String classify(Collection<?> c) {
31-
// return c instanceof Set ? "Set" :
32-
// c instanceof List ? "List" : "Unknown Collection";
33-
// }
3429
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package effectivejava.chapter8.item52;
2+
3+
import java.math.BigInteger;
4+
import java.util.*;
5+
6+
// Repaired static classifier method. (Page 240)
7+
public class FixedCollectionClassifier {
8+
public static String classify(Collection<?> c) {
9+
return c instanceof Set ? "Set" :
10+
c instanceof List ? "List" : "Unknown Collection";
11+
}
12+
13+
public static void main(String[] args) {
14+
Collection<?>[] collections = {
15+
new HashSet<String>(),
16+
new ArrayList<BigInteger>(),
17+
new HashMap<String, String>().values()
18+
};
19+
20+
for (Collection<?> c : collections)
21+
System.out.println(classify(c));
22+
}
23+
}

src/effectivejava/chapter8/item52/Overriding.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.List;
44

5+
// Classification using method overrriding (Page 239)
56
public class Overriding {
67
public static void main(String[] args) {
78
List<Wine> wineList = List.of(

src/effectivejava/chapter8/item52/SetList.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package effectivejava.chapter8.item52;
22
import java.util.*;
33

4-
// What does this program print? - Page 241
4+
// What does this program print? (Page 241)
55
public class SetList {
66
public static void main(String[] args) {
77
Set<Integer> set = new TreeSet<>();
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package effectivejava.chapter8.item52;
22

3+
// Classification using method overrriding (Page 239)
34
class SparklingWine extends Wine {
45
@Override String name() { return "sparkling wine"; }
56
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package effectivejava.chapter8.item52;
22

3+
// Classification using method overrriding (Page 239)
34
class Wine {
45
String name() { return "wine"; }
56
}

src/effectivejava/chapter8/item53/Varargs.java

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,17 @@
22

33
import java.util.stream.IntStream;
44

5-
// Sample uses of varargs
5+
// Sample uses of varargs (Pages 245-6)
66
public class Varargs {
7-
8-
// Simple use of varargs - Page 245
7+
// Simple use of varargs (Page 245)
98
static int sum(int... args) {
109
int sum = 0;
1110
for (int arg : args)
1211
sum += arg;
1312
return sum;
1413
}
1514

16-
// Simple use of varargs - Page 197
17-
static int sum2(int... args) {
18-
return IntStream.of(args).sum();
19-
}
20-
21-
// // The WRONG way to use varargs to pass one or more arguments! - Page 245
15+
// // The WRONG way to use varargs to pass one or more arguments! (Page 245)
2216
// static int min(int... args) {
2317
// if (args.length == 0)
2418
// throw new IllegalArgumentException("Too few arguments");
@@ -29,7 +23,7 @@ static int sum2(int... args) {
2923
// return min;
3024
// }
3125

32-
// The right way to use varargs to pass one or more arguments - Page 246
26+
// The right way to use varargs to pass one or more arguments (Page 246)
3327
static int min(int firstArg, int... remainingArgs) {
3428
int min = firstArg;
3529
for (int arg : remainingArgs)
@@ -38,7 +32,6 @@ static int min(int firstArg, int... remainingArgs) {
3832
return min;
3933
}
4034

41-
4235
public static void main(String[] args) {
4336
System.out.println(sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
4437
System.out.println(min(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

src/effectivejava/chapter8/item55/Max.java

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
import java.util.*;
44

5-
// Optionals (P. 248) OK (Checked)
5+
// Using Optional<T> as a return type (Pages 249-251)
66
public class Max {
7-
// // Returns maximum value in collection - throws exception if empty
7+
// // Returns maximum value in collection - throws exception if empty (Page 249)
88
// public static <E extends Comparable<E>> E max(Collection<E> c) {
99
// if (c.isEmpty())
1010
// throw new IllegalArgumentException("Empty collection");
@@ -17,7 +17,7 @@ public class Max {
1717
// return result;
1818
// }
1919

20-
// // Returns maximum value in collection as an Optional<E>
20+
// // Returns maximum value in collection as an Optional<E> (Page 250)
2121
// public static <E extends Comparable<E>>
2222
// Optional<E> max(Collection<E> c) {
2323
// if (c.isEmpty())
@@ -31,7 +31,7 @@ public class Max {
3131
// return Optional.of(result);
3232
// }
3333

34-
// Returns max val in collection as Optional<E> - uses stream
34+
// Returns max val in collection as Optional<E> - uses stream (Page 250)
3535
public static <E extends Comparable<E>>
3636
Optional<E> max(Collection<E> c) {
3737
return c.stream().max(Comparator.naturalOrder());
@@ -40,7 +40,9 @@ Optional<E> max(Collection<E> c) {
4040
public static void main(String[] args) {
4141
List<String> words = Arrays.asList(args);
4242

43-
// Using an optional to provide a chosen default value
43+
System.out.println(max(words));
44+
45+
// Using an optional to provide a chosen default value (Page 251)
4446
String lastWordInLexicon = max(words).orElse("No words...");
4547
System.out.println(lastWordInLexicon);
4648
}

src/effectivejava/chapter8/item55/ParentPid.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,17 @@
22

33
import java.util.Optional;
44

5-
// Page 250
5+
// Avoiding unnecessary use of Optional's isPresent method (Page 252)
66
public class ParentPid {
77
public static void main(String[] args) {
88
ProcessHandle ph = ProcessHandle.current();
99

10+
// Inappropriate use of isPresent
1011
Optional<ProcessHandle> parentProcess = ph.parent();
1112
System.out.println("Parent PID: " + (parentProcess.isPresent() ?
1213
String.valueOf(parentProcess.get().pid()) : "N/A"));
1314

15+
// Equivalent (and superior) code using orElse
1416
System.out.println("Parent PID: " +
1517
ph.parent().map(h -> String.valueOf(h.pid())).orElse("N/A"));
1618
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package effectivejava.chapter8.item56;
2+
3+
import java.lang.annotation.Retention;
4+
import java.lang.annotation.RetentionPolicy;
5+
import java.lang.annotation.Target;
6+
import java.lang.annotation.ElementType;
7+
8+
// Documentation comment examples (Pages 255-9)
9+
public class DocExamples<E> {
10+
// Method comment (Page 255)
11+
/**
12+
* Returns the element at the specified position in this list.
13+
*
14+
* <p>This method is <i>not</i> guaranteed to run in constant
15+
* time. In some implementations it may run in time proportional
16+
* to the element position.
17+
*
18+
* @param index index of element to return; must be
19+
* non-negative and less than the size of this list
20+
* @return the element at the specified position in this list
21+
* @throws IndexOutOfBoundsException if the index is out of range
22+
* ({@code index < 0 || index >= this.size()})
23+
*/
24+
E get(int index) {
25+
return null;
26+
}
27+
28+
// Use of @implSpec to describe self-use patterns & other visible implementation details. (Page 256)
29+
/**
30+
* Returns true if this collection is empty.
31+
*
32+
* @implSpec This implementation returns {@code this.size() == 0}.
33+
*
34+
* @return true if this collection is empty
35+
*/
36+
public boolean isEmpty() {
37+
return false;
38+
}
39+
40+
// Use of the @literal tag to include HTML and javadoc metacharacters in javadoc comments. (Page 256)
41+
/**
42+
* A geometric series converges if {@literal |r| < 1}.
43+
*/
44+
public void fragment() {
45+
}
46+
47+
// Controlling summary description when there is a period in the first "sentence" of doc comment. (Page 257)
48+
/**
49+
* A suspect, such as Colonel Mustard or {@literal Mrs. Peacock}.
50+
*/
51+
public enum FixedSuspect {
52+
MISS_SCARLETT, PROFESSOR_PLUM, MRS_PEACOCK, MR_GREEN, COLONEL_MUSTARD, MRS_WHITE
53+
}
54+
55+
56+
// Generating a javadoc index entry in Java 9 and later releases. (Page 258)
57+
/**
58+
* This method complies with the {@index IEEE 754} standard.
59+
*/
60+
public void fragment2() {
61+
}
62+
63+
// Documenting enum constants (Page 258)
64+
/**
65+
* An instrument section of a symphony orchestra.
66+
*/
67+
public enum OrchestraSection {
68+
/** Woodwinds, such as flute, clarinet, and oboe. */
69+
WOODWIND,
70+
71+
/** Brass instruments, such as french horn and trumpet. */
72+
BRASS,
73+
74+
/** Percussion instruments, such as timpani and cymbals. */
75+
PERCUSSION,
76+
77+
/** Stringed instruments, such as violin and cello. */
78+
STRING;
79+
}
80+
81+
// Documenting an annotation type (Page 259)
82+
/**
83+
* Indicates that the annotated method is a test method that
84+
* must throw the designated exception to pass.
85+
*/
86+
@Retention(RetentionPolicy.RUNTIME)
87+
@Target(ElementType.METHOD)
88+
public @interface ExceptionTest {
89+
/**
90+
* The exception that the annotated test method must throw
91+
* in order to pass. (The test is permitted to throw any
92+
* subtype of the type described by this class object.)
93+
*/
94+
Class<? extends Throwable> value();
95+
}
96+
}
97+

0 commit comments

Comments
 (0)