'Replace this "switch" statement by 'if' statements to increase readability' misapplied

Please provide

  • Operating system: macOS Ventura
  • SonarLint plugin version: 8.1.0
  • Programming language you’re coding in: Java
  • Is connected mode used: Not Connected

If you are using sealed classes and the enhanced switch expressions with pattern matching, SonarLint emits a java:S1301 warning for code like the following:

switch (result)
{
  case Result.SuccessfulResult<SearchResponse, ResponseFailure> success ->
    resolver.resolve(success.value());

  case Result.FailureResult<SearchResponse,ResponseFailure> failure ->
    resolver.reject(failure.value());
}

The rule seems to be simply counting the number of case labels and determining that if statements would be clearer. It is accurate that if statements can achieve similar results, but I do not agree that the code is any more readable, especially because the enhanced switch statements do not require break statements. I think this rule should be updated to recognize this newer use case and not warn in this common scenario that relies on Maybe/Result monads.

1 Like

Hey there, thank you for the report! This is a really good point, the new syntax allows neat and compact switch blocks even if there are only 2 cases. I created a ticket to take this Java 14 feature, you can track its progress here.

Have a good day!