Skip to content

NewCheck: UseEnhancedSwitch #15180

@mahfouz72

Description

@mahfouz72

child of #14961:

We need to discuss the implementation of a new check that suggests using -> (arrow syntax) instead of : (colon syntax)


  1. -> (arrow syntax)

    • No need for break statements.
    • No fall-through behavior by design.
    • Directly returns a value without the need for braces and yields in switch expressions.
  2. : (colon syntax)

    • Requires break statements to prevent fall-through.
    • Fall-through behavior is possible if break statements are omitted.

Best Practices

Using -> :

  • Preferable in switch expressions where you want to directly return a value.
  • less error-prone since it avoids the need for break statements and eliminates the unintended fall-through behavior.

Using : :

  • Allows for fall-through behavior if that is desired.
  • Suitable for cases where we want to group multiple case labels.

Config

$ cat config.xml 
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
        "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
        "https://checkstyle.org/dtds/configuration_1_3.dtd">

<module name="Checker">
    <module name="TreeWalker">
        <module name="UseEnhancedSwitch"/>
    </module>
</module>

Examples

public class Test {
  void t1(int x)  {
      switch (x) {           // violation, Switch can be replaced with enhanced switch
          case 1: {} break;
          case 2: {} break;
          case 3:{} break;
      }
      switch (x) {    // ok switch with fall through is ignored
          case 1: {} 
          case 2: {} break;
          case 3:{} break;
      }
      switch (x) {
          case 1 -> {}
          case 2 -> {}
          case 3 -> {}
      }
  }

  int t2(int x) {
      int y =  switch (x) {    // violation, Switch can be replaced with enhanced switch
          case 1 : yield 1;
          case 2 : yield 2;
          case 3 : yield 3;
          default: yield 0;
      };
      int yy = switch (x) {
          case 1 -> 1;
          case 2 -> 2;
          case 3 -> 3;
          default -> 0;
      };
      return y;
  }
}

Output

$ java -jar checkstyle-10.19.0-all.jar -c config.xml Test.java 
Starting audit...
[ERROR] D:\Test.java:3:8: Switch using reference types should have a null case. [UseEnhancedSwitch]
[ERROR] D:\Test.java:21:16: Switch using reference types should have a null case. [UseEnhancedSwitch]
Audit done.
Checkstyle ends with 2 errors.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions