Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce order of setting parameters through Builder Pattern

Recently, I was asked in an interview to implement Builder Pattern in such a way that user cannot set a parameter B unless parameter A is set.

I suggested to pass A as a required parameter when constructing the Builder but he was not satisfied with my answer. I also suggested to throw IllegelStateException if A is not set when setting B but again he was not satisfied. Could anyone suggest how can we enforce user to set A before he sets B?

class Example{
private int A;
private int B;

public static class Builder{
}

}

like image 535
rakku Avatar asked Sep 06 '25 13:09

rakku


1 Answers

To do it in plain Java, you would need to create separate Builder classes, the first for setting the A, whereupon the returned value is an instance of the second Builder which is for setting B.

One of the limitations of this approach is that it is very verbose, and doesn't scale well to having lots of optional parameters.

Alternatively, I have done this by writing a compiler plugin (I used Error Prone, since that is easiest to do with Google's build system, but there is no reason another tool couldn't be used) which checks the method call order.

like image 186
Andy Turner Avatar answered Sep 09 '25 10:09

Andy Turner