2

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();
    }

}
nopens
  • 721
  • 1
  • 4
  • 20
  • You could theoretically have an array of function references to "setOne", "setTwo", and so on, and then iterate over that. –  Aug 21 '20 at 18:53
  • @Taschi I don't know what you mean exactly. Could you add one or two sentences about how I can implement your approach or give me a suitable search term so I can google it by myself? – nopens Aug 21 '20 at 19:00
  • 2
    Check out https://stackoverflow.com/questions/49234884/how-to-declare-an-array-of-method-references, there are some examples of what I have in mind. –  Aug 21 '20 at 19:11

1 Answers1

3

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();
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578