Ever since Effective Java 2 came out, the builder pattern became a defacto standard for instantiating objects with multiple parameters.
Required parameters are usually passed in via a constructor, as in the example above, but having too many might defeat the purpose of a builder and spread confusion all around. Can you tell what the two arguments above denote?
A way to avoid this is to provide a no-params constructor:
and validate the data whenever a build() method is invoked:
The above works, but it would be nice to provide a fluid API where it is impossible to invoke build() before the required parameters are provided.
Let’s describe the builder with a simple interface:
Recall the first two methods, servingSize(int) and servings(int) are required. Could we force the user to start the builder chain with them?
Suppose we declare two additional interfaces:
Starting with a ServingSizeBuilder instance, you’re now forced to start the chain with the two required params and are unable to invoke build() before:
We should remove the two required setters methods from the Builder interface, as they are described in the two we defined above. We end up with:
This can be fully appreciated when implemented:
There it is! A builder where required params must be set before build() method can be invoked.