I have a builder pattern in which most likely all my parameters are going to be mandatory so I have created a long constructor as shown below in the code.
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
}
Now I am confuse when all the parameters are mandatory, then how it can be useful? Is there any better way of representing my above Builder pattern? May be logically grouping the parameters being passed in to their own classes to reduce the number of parameters being passed to the builder constructor?
While having separate objects simplifies things quite a bit, it also makes things a little difficult to follow if one is not familiar with the code. One thing I can do is moving all parameters into their own addParam(param)
methods and then performing validation on required parameters in the build()
method at runtime?
What is best practice I should follow here and is there any better approach that I can use here?
Aucun commentaire:
Enregistrer un commentaire