Should I use boolean or Boolean in a Spring Boot RestController?

Viewed 40

Make it any difference to use in the following snippet boolean filterMode or Boolean filterMode? Are they any best practice ? Or its completley irrelevant?

@GetMapping
public NOTMATTER getResultByBoolean(
 @RequestParam(value = "filterMode", required = false) boolean filterMode) {

  //.....

}
3 Answers

Yes it will matter. As you have specified the parameter to be optional, if it is not supplied then default values will be different

// Boolean - default value is null
// boolean - default value is false

There is a difference between the type boolean and the type Boolean.

  • boolean is a primitive type that can accept the values true or false
  • Boolean is an Object that wraps the value of a boolean primitive. It exposes more actions that can be performed on the type.

I suggest you read more about it in the documentation.

The usage depends on your use case.

It depends on your use case. If you're sure that it's acceptable to have the false value as a default one (judging by your code, I think that this is your case) then go for the primitive boolean type. It consumes a lot less memory in comparison with objects and provides the default false value, so there would be no need for setting required = false for your request parameter.

However, it may lead to unpredicted behavior for your clients. Just imagine the case with parameters like opt in or opt out for a messaging system, which identifies if a client wants to stop communication with some service. There would be a significant difference between the null and the false value for these parameters, which may lead to legal consequences for your company. So it's better to be careful with a such choice.

Related