What is it?
Builder is an internal class that is dedicated to build an instance of a type.
When to use it?
It is useful when you have type with optional parameters (that are not always mandatory to provide when creating object). The difference is significant when there is a plenty of params. Then instead of invoking constructor with not all params required:
Type obj = new Type(param1, param2, null, null, null, param6, null);
You can invoke Builder that will distinguish mandatory params from optional ones:
Type obj = new Type.Builder(param1, param2).setParam6(param6).build();
Here just param1 and param2 are mandatory, the rest is optional.
– the code is easier to read and more robust
– good way to cope with many optional construcotr parameters
Effective Java (Joshua Bloch) is a book with advanced Java programming techniques that make Java code more robust and readable. I am currently reading it and this is why these [Effective Java] posts come up here. These are summaries of chapters that are most valuable in my opinion.
Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality