Skip to content

Commit ecd67ed

Browse files
kevinoconnor7Error Prone Team
authored and
Error Prone Team
committed
Document the behavior of default branches present for version skew
PiperOrigin-RevId: 755065063
1 parent e4d7583 commit ecd67ed

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

docs/bugpattern/MissingCasesInEnumSwitch.md

+38
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,41 @@ switch statement on an enum type to either handle all values of the enum, or
2929
have a default statement group.
3030

3131
[style]: https://google.github.io/styleguide/javaguide.html#s4.8.4.3-switch-default
32+
33+
## Library skew
34+
35+
If libraries are compiled against different versions of the same enum it's
36+
possible for the switch statement to encounter an enum value despite it
37+
otherwise being thought to be exhaustive. If there is no default branch code
38+
execution will simply fall out of the switch statement.
39+
40+
Since developers may have assumed this to be impossible, it may be helpful to
41+
add a default branch when library skew is a concern, however, you may not want
42+
to give up checking to ensure that all cases are handled. Therefore if a default
43+
branch exists with a comment containing "skew", the default will not be
44+
considered for exhaustiveness. For example:
45+
46+
```java
47+
enum TrafficLightColour { RED, GREEN, YELLOW }
48+
49+
void approachIntersection(TrafficLightColour state) {
50+
switch (state) {
51+
case GREEN:
52+
proceed();
53+
break;
54+
case YELLOW:
55+
case RED:
56+
stop();
57+
break;
58+
default: // In case of skew we may get an unknown value, always stop.
59+
stop();
60+
break;
61+
}
62+
}
63+
```
64+
65+
In this case the default branch is providing runtime safety for unknown enum
66+
values while also still enforcing that all known enum values are handled.
67+
68+
Note: The [UnnecessaryDefaultInEnumSwitch](UnnecessaryDefaultInEnumSwitch.md)
69+
check will not classify the default as unnecessary if it has the "skew" comment.

docs/bugpattern/UnnecessaryDefaultInEnumSwitch.md

+5
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,8 @@ If it can complete normally, the default should be merged with an added
153153
UNRECOGNIZED case.
154154

155155
[complete normally]: https://docs.oracle.com/javase/specs/jls/se10/html/jls-14.html#jls-14.1
156+
157+
## Library skew
158+
159+
A default branch that has a comment containing "skew" will not be classified as
160+
unnecessary. See: [MissingCasesInEnumSwitch](MissingCasesInEnumSwitch.md).

0 commit comments

Comments
 (0)