How to check for invalid inputs in the Builder pattern class?

Below is my builder class in which two fields are mandatory which are userId and 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
}

Now I will be calling this builder class like this –

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

But it might be possible that somebody can pass wrong inputs values such as they are passing negative userId’s and negative clientId’s, negative timeout values or empty attributeMap. How to deal in these kind of situation in my builder class?

If I am having IllegalArgumentcheck for each variables in if else if block, then my whole Builder class gets flooded up with IllegalArgumentException check?

Is there any better way of doing this?

Answer

Make methods which have common logic, eg

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

Leave a Reply

Your email address will not be published. Required fields are marked *