forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBook.java
More file actions
51 lines (37 loc) · 1.33 KB
/
Copy pathBook.java
File metadata and controls
51 lines (37 loc) · 1.33 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
47
48
49
50
51
package modern.challenge;
import java.util.NoSuchElementException;
import java.util.Optional;
public class Book {
// Avoid
public String findStatusAvoid() {
// fetch an Optional prone to be empty
Optional<String> status = Optional.empty();
if (status.isPresent()) {
return status.get();
} else {
throw new NoSuchElementException("Status cannot be found");
}
}
// Prefer (before Java 10)
public String findStatusPrefer1() {
// fetch an Optional prone to be empty
Optional<String> status = Optional.empty();
return status.orElseThrow(
() -> new NoSuchElementException("Status cannot be found"));
// or without message
// return status.orElseThrow(NoSuchElementException::new);
}
// Prefer (Java 10+)
public String findStatusPrefer2() {
// fetch an Optional prone to be empty
Optional<String> status = Optional.empty();
return status.orElseThrow(); // NoSuchElementException
}
// Throw another exception
public String findStatusPrefer3() {
// fetch an Optional prone to be empty
Optional<String> status = Optional.empty();
return status.orElseThrow(
() -> new IllegalStateException("Status cannot be found"));
}
}