3

ほとんどの場合、すべてのパラメーターが必須になるビルダー パターンがあるため、以下のコードに示すように長いコンストラクターを作成しました。

public final class ResponseHolder {

    // all below six are related to response information
    private final String response;
    private final boolean isLinking;
    private final TypeHold typeOfId;
    private final long userTimeInMs;
    private final long userLmdInDays;
    private final String maskInfo;

    // below two are related to error handling
    private final ErrorCode error;
    private final StatusCode status;

    private ResponseHolder(Builder builder) {
        this.response = builder.response;
        this.isLinking = builder.isLinking;
        this.typeOfId = builder.typeOfId;
        this.userTimeInMs = builder.userTimeInMs;
        this.userLmdInDays = builder.userLmdInDays;
        this.maskInfo = builder.maskInfo;
        this.error = builder.error;
        this.status = builder.status;
    }

    public static class Builder {
        protected final String response;
        protected final TypeHold typeOfId;
        protected final String maskInfo;
        protected final ErrorCode error;
        protected final StatusCode status;
        protected final boolean isLinking;
        protected final long userTimeInMs;
        protected final long userLmdInDays;


        public Builder(String response, TypeHold typeOfId, String maskInfo, ErrorCode error,
                StatusCode status, boolean isLinking, long userTimeInMs, long userLmdInDays) {
            this.response = response;
            this.typeOfId = typeOfId;
            this.maskInfo = maskInfo;
            this.error = error;
            this.status = status;
            this.isLinking = isLinking;
            this.userTimeInMs = userTimeInMs;
            this.userLmdInDays = userLmdInDays
        }

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

    // getters here
}

すべてのパラメータが必須である場合、私は混乱していますが、どのように役立つのでしょうか? 上記の Builder パターンを表現するより良い方法はありますか? ビルダーコンストラクターに渡されるパラメーターの数を減らすために、独自のクラスに渡されるパラメーターを論理的にグループ化する可能性がありますか?

別々のオブジェクトを持つことで物事がかなり単純化されますが、コードに慣れていない場合は、物事を理解するのが少し難しくなります。私ができることの 1 つは、すべてのパラメーターを独自のaddParam(param)メソッドに移動し、実行時にメソッド内の必須パラメーターの検証をbuild()実行することですか?

ここで従うべきベストプラクティスは何ですか?ここで使用できるより良いアプローチはありますか?

4

2 に答える 2