-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAboutRequireNotNull.java
More file actions
46 lines (38 loc) · 1.45 KB
/
AboutRequireNotNull.java
File metadata and controls
46 lines (38 loc) · 1.45 KB
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
package java7;
import com.sandwich.koan.Koan;
import java.util.Objects;
import static com.sandwich.koan.constant.KoanConstants.__;
import static com.sandwich.util.Assert.assertEquals;
public class AboutRequireNotNull {
@Koan
public void failArgumentValidationWithRequireNotNull() {
// This koan demonstrates the use of Objects.requireNotNull
// in place of traditional argument validation using exceptions
String s = "";
try {
s += validateUsingRequireNotNull(null);
} catch (NullPointerException ex) {
s = "caught a NullPointerException";
}
assertEquals(s,"caught a NullPointerException");
}
@Koan
public void passArgumentValidationWithRequireNotNull() {
// This koan demonstrates the use of Objects.requireNotNull
// in place of traditional argument validation using exceptions
String s = "";
try {
s += validateUsingRequireNotNull("valid");
} catch (NullPointerException ex) {
s = "caught a NullPointerException";
}
assertEquals(s, "5");
}
private int validateUsingRequireNotNull(String str) {
// If you're only concerned with null values requireNotNull
// is concise and the point of the NullPointerException it
// throws is clear, though you can optionally provide a
// description as well
return Objects.requireNonNull(str).length();
}
}