Repository navigation
Expand file tree
/
Copy pathCorrectEnumUsage.java
More file actions
95 lines (83 loc) · 2.26 KB
/
Copy pathCorrectEnumUsage.java
File metadata and controls
95 lines (83 loc) · 2.26 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package testSuite;
import liquidjava.specification.StateRefinement;
import liquidjava.specification.StateSet;
@SuppressWarnings("unused")
@StateSet({"photoMode", "videoMode", "noMode"})
class CorrectEnumUsage {
enum Mode {
Photo, Video, Unknown
}
Mode mode;
@StateRefinement(to="noMode(this)")
public CorrectEnumUsage() {}
@StateRefinement(from="noMode(this) && mode == Mode.Photo", to="photoMode(this)")
@StateRefinement(from="noMode(this) && mode == Mode.Video", to="videoMode(this)")
public void setMode(Mode mode) {
this.mode = mode;
}
@StateRefinement(from="photoMode(this)", to="noMode(this)")
@StateRefinement(from="videoMode(this)", to="noMode(this)")
public void resetMode() {
this.mode = null;
}
@StateRefinement(from="photoMode(this)")
public void takePhoto() {}
@StateRefinement(from="videoMode(this)")
public void takeVideo() {}
public static void main(String[] args) {
// Correct
CorrectEnumUsage st = new CorrectEnumUsage();
st.setMode(Mode.Photo); // noMode -> photoMode
st.takePhoto();
st.resetMode(); // photoMode -> noMode
st.setMode(Mode.Video); // noMode -> videoMode
st.takeVideo();
}
// Each case starts from the state before the switch and knows the value of the selector
public static void capture(Mode mode) {
CorrectEnumUsage st = new CorrectEnumUsage();
switch (mode) {
case Photo:
st.setMode(Mode.Photo);
st.takePhoto();
break;
case Video:
st.setMode(mode);
st.takeVideo();
break;
default:
break;
}
}
public static boolean captureExpression(Mode mode) {
CorrectEnumUsage st = new CorrectEnumUsage();
return switch (mode) {
case Photo -> {
st.setMode(Mode.Photo);
st.takePhoto();
yield true;
}
case Video -> {
st.setMode(Mode.Video);
st.takeVideo();
yield true;
}
default -> false;
};
}
// A switch expression that matches no label throws: it does not reach the code after it
public static void captureOnThread(Thread.State state) {
CorrectEnumUsage st = new CorrectEnumUsage();
boolean running = switch (state) {
case NEW, RUNNABLE, BLOCKED -> {
st.setMode(Mode.Photo);
yield true;
}
case WAITING, TIMED_WAITING, TERMINATED -> {
st.setMode(Mode.Photo);
yield false;
}
};
st.takePhoto();
}
}