File: UseEnumSwitch.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (32 lines) | stat: -rw-r--r-- 852 bytes parent folder | download
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
Consider using `switch` instead of `if`/`else` for enums. That is, prefer this:

```java
switch (foo.getBar()) {
  case BAZ:
    doSomething();
    break;
  default:
    doSomethingElse();
}
```

instead of this:

```java
if (foo.getBar().equals(Bar.BAZ)) {
  doSomething();
} else {
  doSomethingElse();
}
```

Switches on `enums` have a few small advantages worth considering:

*   It sidesteps the `equals` vs. `==` debate.
*   You get to call `BAZ` by its simple name without a static import. That's
    good because you might not want to see it appear unqualified in other parts
    of the file where the context would not make its meaning so clear.
*   You have the option of
    [protection against missing cases][MissingCasesInEnumSwitch] if you want it.

[`MissingCasesInEnumSwitch`]: https:errorprone.info/bugpattern/MissingCasesInEnumSwitch