WhenShouldBeUsed

Since Checkstyle 10.18.0

Description

Ensures that when is used instead of a single if statement inside a case block.

Rationale: Java 21 has introduced enhancements for switch statements and expressions that allow the use of patterns in case labels. The when keyword is used to specify condition for a case label, also called as guarded case labels. This syntax is more readable and concise than the single if statement inside the pattern match block.

See the Java Language Specification for more information about guarded case labels.

See the Java Language Specification for more information about patterns.

Examples

To configure the check:

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

Example of violation:

public class Example1 {

  void testNoGuard(Object o) {
    switch (o) {
      // violation below,  ''when' expression should be used*.'
      case String s -> {
        if (s.isEmpty()) {
          System.out.println("empty string");
        }
      }
      default -> {}
    }

    switch (o) {
      // this example is ok, not a single if statement inside the case block
      case String s -> {
        System.out.println("String");
        if (s.isEmpty()) {
          System.out.println("but empty");
        }
      }
      default -> {}
    }
  }

  void testGuardedCaseLabel(Object o) {
    switch (o) {
      case String s when s.isEmpty() -> {
        System.out.println("empty string");
      }
      default -> {}
    }
  }

}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker