Skip to content

Document the behavior of default branches present for version skew #5032

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions docs/bugpattern/MissingCasesInEnumSwitch.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,41 @@ switch statement on an enum type to either handle all values of the enum, or
have a default statement group.

[style]: https://google.github.io/styleguide/javaguide.html#s4.8.4.3-switch-default

## Library skew

If libraries are compiled against different versions of the same enum it's
possible for the switch statement to encounter an enum value despite it
otherwise being thought to be exhaustive. If there is no default branch code
execution will simply fall out of the switch statement.

Since developers may have assumed this to be impossible, it may be helpful to
add a default branch when library skew is a concern, however, you may not want
to give up checking to ensure that all cases are handled. Therefore if a default
branch exists with a comment containing "skew", the default will not be
considered for exhaustiveness. For example:

```java
enum TrafficLightColour { RED, GREEN, YELLOW }

void approachIntersection(TrafficLightColour state) {
switch (state) {
case GREEN:
proceed();
break;
case YELLOW:
case RED:
stop();
break;
default: // In case of skew we may get an unknown value, always stop.
stop();
break;
}
}
```

In this case the default branch is providing runtime safety for unknown enum
values while also still enforcing that all known enum values are handled.

Note: The [UnnecessaryDefaultInEnumSwitch](UnnecessaryDefaultInEnumSwitch.md)
check will not classify the default as unnecessary if it has the "skew" comment.
5 changes: 5 additions & 0 deletions docs/bugpattern/UnnecessaryDefaultInEnumSwitch.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,8 @@ If it can complete normally, the default should be merged with an added
UNRECOGNIZED case.

[complete normally]: https://docs.oracle.com/javase/specs/jls/se10/html/jls-14.html#jls-14.1

## Library skew

A default branch that has a comment containing "skew" will not be classified as
unnecessary. See: [MissingCasesInEnumSwitch](MissingCasesInEnumSwitch.md).
Loading