-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOtherExamples.java
60 lines (52 loc) · 1.48 KB
/
OtherExamples.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.function.Predicate;
public class OtherExamples {
/** (page 6) Simplify 'if else' */
boolean isEmpty(String s) {
if (s == null || s.isEmpty()) return true;
return false;
}
/** (pages 26-27) Introduce var 'data[0]' */
void handle(String[] data) {
if (data.length > 0) {
System.out.println("Begin handling " + data[0]);
before(data[0]);
} else {
System.out.println("Begin handling");
before(null);
}
process(data);
if (data.length > 0) {
System.out.println("End handling " + data[0]);
before(data[0]);
} else {
System.out.println("End handling");
before(null);
}
}
private void process(String[] data) {
//...
}
private void before(String s) {
//...
}
/** (pages 30-31) Eliminate tail recursion */
static boolean contains(int n, Predicate<Integer> p) {
return n >= 0 && (p.test(n) || contains(n - 1, p));
}
/** (page 32) Move 'return' closer to computation */
static int compare(int x, int y) {
int result;
if (x < 0 && y > 0) {
result = -2;
} else if (x > 0 && y < 0) {
result = 2;
} else if (x == 0 && y < 0) {
result = 1;
} else if (x == 0 && y > 0) {
result = -1;
} else {
result = 0;
}
return result;
}
}