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.

1 Like

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

Came here to report this and found an existing thread.

I’d also argue that Sonar should not report this issue for optional boolean parameters.

Using a Boolean is less preferable, because when the reader of the code sees a Boolean, they must think about nullability and how to handle it (either add extra validation to ensure it is not null, or add an extra nullability annotation).

On the other hand, when boolean is used, there is less cognitive load for the reader of the code, as they only have to consider two states (true/false vs. true/false/null).

I think that the scope of this rule is to enforce deterministic behaviors.

The behavior of Spring framework is already deterministic - for any optional request parameters of boolean type Spring always sets the value to false for missing parameters.

Hey there, thanks for raising these arguments. I think that while my main argument still stands, I also agree that it’s not nice to enforce cognitive overload for cases where the default false value is ok with the controller’s logic.

I created this ticket to relax the rule for boolean parameters!