Rule java:S6814 "Optional REST parameters should have an object type" false positive

Make sure to read this post before raising a thread here:

Then tell us:

  • What language is this for?

Java

  • Which rule?

java:S6814 Optional REST parameters should have an object type

  • Why do you believe it’s a false-positive/false-negative?

Spring supports optional primitive boolean parameters. For example following seems to work:

@RequestParam(value = "test", required = false) final boolean test

Using a debugger I get value false when I do not pass any value for the parameter.

  • Are you using
    • SonarCloud?
    • SonarQube - which version?
      10.4.1
    • SonarLint - which IDE/version?
      • in connected mode with SonarQube or SonarCloud?
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

Add RequestParam of type boolean and optional=true into a Spring controller method and do not pass any value in the request.

Hi Mico, thanks for the report!

While it is true that no runtime errors will be thrown in the case you described, I think that the scope of this rule is to enforce deterministic behaviors.
In the case you described, I would argue that if you want to have an optional boolean @RequestParam, you should use the boxed class Boolean and also add the defaultValue property to it to define what should happen if the user does not provide the parameter.

@GetMapping("/test")
public String testEndpoint(
  @RequestParam(value = "test", required = false, defaultValue = "true") final Boolean test) {
  return "If 'test' is not provided, it will default to 'true'.";
}

Unless you want to manually handle the null case, of course.

So I think the rule should still report in cases like the one you described