2

下面是我的构建器类,其中两个字段是必需的,它们是userIdclientId

public final class InputKeys {

    private final long userId;
    private final int clientId;
    private final long timeout;
    private final Preference preferences;
    private final boolean debugFlag;
    private final Map<String, String> attributeMap;

    private InputKeys(Builder builder) {
    this.userId = builder.userId;
    this.clientId = builder.clientId;
    this.preferences = builder.preference;
    this.attributeMap = builder.attributeMap;
    this.timeout = builder.timeout;
    this.debugFlag = builder.debugFlag;
    }

    public static class Builder {
    protected final long userId;
    protected final int clientId;
    protected long timeout = 500L;
    protected Preference preference;
    protected boolean debugFlag;
    protected Map<String, String> attributeMap;


    public Builder(long userId, int clientId) {
        this.userId = userId;
        this.clientId = clientId;
    }

    public Builder attributeMap(Map<String, String> attributeMap) {
        this.attributeMap = attributeMap;
        return this;
    }

    public Builder preference(Preference preference) {
        this.preference = preference;
        return this;
    }

    public Builder debugFlag(boolean debugFlag) {
        this.debugFlag = debugFlag;
        return this;
    }

    public Builder timeout(long timeout) {
        this.timeout = timeout;
        return this;
    }

    public InputKeys build() {
        return new InputKeys(this);
    }
    }

    //getters  here
}

现在我将像这样调用这个构建器类 -

InputKeys keys = new InputKeys.Builder(12000L, 33L).build();

但也有可能有人会传递错误的输入值,例如他们传递负的 userId 和负的 clientId、负的超时值或空的属性映射。如何在我的构建器类中处理这种情况?

如果我对 中的每个变量都有 IllegalArgumentcheck if else if block,那么我的整个 Builder 类会被 IllegalArgumentException 检查淹没吗?

有没有更好的方法来做到这一点?

4

3 回答 3

1

制作具有共同逻辑的方法,例如

private void assertNonNegative(long val, String attr) {
    if (val < 0) {
         throw IllegalArgumentException(attr + " cannot be negative");
    }
}
于 2014-01-11T08:59:57.727 回答
0

我建议将所有检查移至build方法。这种方法没有错。

此外,在build方法中实现“如果指定了字段a则字段b是强制性的”等约束是典型的情况。

于 2014-01-11T09:32:28.130 回答
0

您需要一种更具声明性的方式来验证参数输入,以避免一次又一次地重复验证代码。

我建议使用java 注释来表明一个变量应该属于一个特定的值范围。

如果您使用Java EESpring 之类的框架,则可以使用 java 注释并让框架进行值检查。有关使用 Java EE 进行验证的信息,请参阅thisthis 。

举一个例子来验证一个Name类的属性:

public class Name {
    @NotNull
    @Size(min=1, max=16)
    private String firstname;

    @NotNull 
    @Size(min=1, max=16)
    private String lastname;
}

Java EE 将处理所有验证。

希望我有所帮助!

于 2014-01-11T09:40:55.043 回答