是使用包装器类数据类型作为构建器模式中的参数,然后在构建方法期间将其转换为原始数据还是原始数据类型?还是最好在整个构建器模式中使用原始数据类型并进行所有数据转换?控制器或调用构建器模式的方法中可以为空的数据类型?
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;
}
答案 0 :(得分:3)
这取决于null
值是否有效。
您的两个示例的语义略有不同。
public Builder recent(final Boolean recent) {
if (recent != null) {
this.recent = recent;
}
return this;
}
上面的内容实际上是说this.recent
实际上可以保存一个null
值(如果它的类型也是Boolean
),但是一旦将其设置为非null值,它就会即使呼叫者需要它并传递null
(您是否想要),它也永远不会返回?
public Builder recent(final boolean recent) {
this.recent = recent;
return this;
}
这就是说recent
可以设置为true
或false
。如果null
实际上是this.recent
类型,则呼叫者不会被误认为他可以将其设置回Boolean
。如果您有合理的默认值,则甚至可以选择直接将this.recent
设置为该默认值,从而最大程度地减少了在其他地方获得错误的机会NullPointerException
。