2

以下は、 と の 2 つのフィールドが必須である私のビルダー クラスuserIdですclientId

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 を渡すなど、誰かが間違った入力値を渡す可能性があります。私のビルダークラスでこのような状況に対処するにはどうすればよいですか?

の各変数に対して IllegalArgumentcheck を使用している場合、if else if blockBuilder クラス全体が 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メソッドで「フィールドaが指定されている場合、フィールドbは必須」のような制約を実装するのが典型的なケースです。

于 2014-01-11T09:32:28.130 に答える