Is it better to use wrapper classes data type for the parameters in the builder pattern and then transform to primitive during build method to its primitive data type or is it better to use primitive data types throughout the builder pattern and do all data transformation of nullable data types in the controllers or the methods that calls the builder pattern?
public Builder recent(final Boolean recent) {
if (recent != null) {
this.recent = recent;
}
return this;
}
vs
public Builder recent(final boolean recent) {
this.recent = recent;
return this;
}
It depends on whether a null
value is valid.
Your two examples have slightly different semantics.
public Builder recent(final Boolean recent) {
if (recent != null) {
this.recent = recent;
}
return this;
}
The above is essentially saying that this.recent
could actually hold a null
value (if its type is Boolean
too), but once it gets set to a non-null value, it never goes back, even if the caller requires it and passes null
(is it something you want)?
public Builder recent(final boolean recent) {
this.recent = recent;
return this;
}
This is saying that recent
can either be set to true
or false
. The caller will not be misguided into thinking he can set it back to null
if this.recent
is actually of type Boolean
. If you have a sensible default, you would even opt to set this.recent
to that default directly, minimising the chance of doing a mistake somewhere else getting a NullPointerException
.