forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBook.java
More file actions
46 lines (33 loc) · 1.1 KB
/
Copy pathBook.java
File metadata and controls
46 lines (33 loc) · 1.1 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 modern.challenge;
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 {
return computeStatus();
}
}
// Avoid
public String findStatusAlsoAvoid() {
// fetch an Optional prone to be empty
Optional<String> status = Optional.of("AVAILABLE");
// computeStatus() is called even if "status" is not empty
return status.orElse(computeStatus());
}
// Prefer
public String findStatusPrefer() {
// fetch an Optional prone to be empty
Optional<String> status = Optional.of("AVAILABLE");
// computeStatus() is called only if "status" is empty
return status.orElseGet(this::computeStatus);
}
private String computeStatus() {
// some code used to compute status
System.out.println("Computing status ...");
return "THE_COMPUTED_STATUS";
}
}