Search code examples
javabuilder-pattern

How to use a Builder for different length of input?


I am using a Builder(pattern) to build and return an object. There is a defined order depending on the number of available arguments on how the methods should be called. Currently I use if-else blocks. Is there a java 8 or higher alternative to use the builder dynamically?

public Task createTask(String[] params){
    if(params.length < 1){
       throw new IllegalArgumentException();
    }
    else if(params.length == 1){
        return new TaskBuilder().setOne(params[0]).build();
    }
    else if(params.length == 2){
        return new TaskBuilder().setOne(params[0])
                                .setTwo(params[1]).build();
    }
    else if(params.length == 3){
        return new TaskBuilder().setOne(params[0])
                                .setTwo(params[1])
                                .setThree(params[2]).build();
    }
    else if(params.length == 4){
        return new TaskBuilder().setOne(params[0])
                                .setTwo(params[1])
                                .setThree(params[2])
                                .setFour(params[3]).build();

    }
    else if(params.length == 5){
        return new TaskBuilder().setOne(params[0])
                                .setTwo(params[1])
                                .setThree(params[2])
                                .setFour(params[3])
                                .setFive(params[4]).build();

    }
    else{
        throw new IllegalArgumentException();
    }

}

Solution

  • You don't really need anything fancy like function references. All you have to do is break the builder calls up:

    public Task createTask(String[] params){
        if (params.length < 1 || params.length > 5) {
            throw new IllegalArgumentException();
        }
    
        TaskBuilder builder = new TaskBuilder();
    
        if (params.length >= 1) { builder = builder.setOne(params[0]); }
        if (params.length >= 2) { builder = builder.setTwo(params[1]); }
        if (params.length >= 3) { builder = builder.setThree(params[2]); }
        if (params.length >= 4) { builder = builder.setFour(params[3]); }
        if (params.length >= 5) { builder = builder.setFive(params[4]); }
        
        return builder.build();
    }