## Why is this an issue?

Java 21 has introduced enhancements to switch statements and expressions, allowing them to operate on any type, not just specific ones, as in previous versions. Furthermore, case labels have been upgraded to support patterns, providing an alternative to the previous restriction of only accepting constants.

    // As of Java 21
    String patternMatchSwitch(Object obj) {
        return switch (obj) {
            case String s  -> String.format("String %s", s);
            case Integer i -> String.format("int %d", i);
            default        -> obj.toString();
        };
    }

This allows to use the `when` keyword to specify a condition for a case label, also called a guarded case label.

    String guardedCaseSwitch(Object obj) {
        return switch (obj) {
            case String s when s.length() > 0 -> String.format("String %s", s);
            case Integer i when i > 0 -> String.format("int %d", i);
            default        -> obj.toString();
        };
    }

This syntax is more readable and less error-prone than using an if statement inside the case block and should be preferred.

This rule reports an issue when a single `if` statement is used inside a case block.

## How to fix it

Replace the `if` statement with a guarded case label.

### Code examples

#### Noncompliant code example

    void testObject(Object response) {
        switch (response) {
            case String s -> {
                if(s.length() > 80) { // Noncompliant; use the "when" keyword
                    System.out.println("This string is too long");
                }
            }
            case Integer i -> {
                if(i > 80) { // Noncompliant; use the "when" keyword
                    System.out.println("This integer is too big");
                }
            }
            default -> System.out.println("Unknown type");
        }
    }

#### Compliant solution

    void testObject(Object response) {
        switch (response) {
            case String s when s.length() > 80 -> {
                System.out.println("This string is too long");
            }
            case Integer i when i > 80 -> {
                System.out.println("This integer is too big");
            }
            default -> System.out.println("Unknown type");
        }
    }

## Resources

### Documentation

- Java Documentation - Pattern Matching for switch