我应该在生成器模式中使用基元数据类型还是包装器数据类型



将包装类数据类型用于构建器模式中的参数,然后在构建方法期间转换为基元数据类型,还是在整个构建器模式中使用基元数据类型并在控制器或调用构建器模式的方法中执行可为空数据类型的所有数据转换更好?

   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可以设置为 truefalse .如果调用者实际上是Boolean类型,则不会误导以认为他可以将其设置回null this.recent。如果您有合理的默认值,您甚至可以选择直接将this.recent设置为该默认值,从而最大限度地减少在其他地方出错的机会获得NullPointerException

最新更新