gpt4 book ai didi

java - 如何检查 Builder 模式类中的无效输入?

转载 作者:行者123 更新时间:2023-11-30 11:23:40 26 4
gpt4 key购买 nike

下面是我的构建器类,其中两个字段是必需的,即 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、负的超时值或空的 attributeMap。如何在我的构建器类中处理这些情况?

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

有更好的方法吗?

最佳答案

创建具有共同逻辑的方法,例如

private void assertNonNegative(long val, String attr) {
if (val < 0) {
throw IllegalArgumentException(attr + " cannot be negative");
}
}

关于java - 如何检查 Builder 模式类中的无效输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21060424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com