将包装类数据类型用于构建器模式中的参数,然后在构建方法期间转换为基元数据类型,还是在整个构建器模式中使用基元数据类型并在控制器或调用构建器模式的方法中执行可为空数据类型的所有数据转换更好?
public Builder recent(final Boolean recent) {
if (recent != null) {
this.recent = recent;
}
return this;
}
与
public Builder recent(final boolean recent) {
this.recent = recent;
return this;
}
null
值是否有效。
您的两个示例的语义略有不同。
public Builder recent(final Boolean recent) {
if (recent != null) {
this.recent = recent;
}
return this;
}
上面本质上是说this.recent
实际上可以保存一个null
值(如果它的类型也是Boolean
(,但是一旦它被设置为非空值,它永远不会返回,即使调用者需要它并传递null
(这是你想要的吗(?
public Builder recent(final boolean recent) {
this.recent = recent;
return this;
}
这是说recent
可以设置为 true
或 false
.如果调用者实际上是Boolean
类型,则不会误导以认为他可以将其设置回null
this.recent
。如果您有合理的默认值,您甚至可以选择直接将this.recent
设置为该默认值,从而最大限度地减少在其他地方出错的机会获得NullPointerException
。