Java – Benefits of Using Static Inner Builder Class

java

During the course of writing the code guidelines for a company I found myself recommending using the Builder pattern from Effective Java, instead of telescopic constructors.

However, after thinking about it a bit more, surely a more elegant solution is to just remove the builder class and the also remove the extra constructors with optional arguments.

So just have the one constructor with required parameters, normal getters/setters, and comment the code. When implementing just create a new instance of yr object then set values.

My original thinking was the benefit came from removing the confusion as to what paramters were optional and what were required; however the true benefit comes from using method chaining/fluent interface.

The builder pattern has benefits when you make lots of new instances as the ide can do the leg work and also if there are many (15+) optional parameters. However, is it worth the extra time coding the static inner class, would you recommend using the builder, or is it a waste of time ?

Best Answer

I tend to follow a pattern that constructors should provide all of the mandatory values required to create a valid and consistent object. For optional values, I try to think about what the most common default should be, so that setters are used as little as possible.

If I find that there are lots of optional values or that a larger proportion of optional values tend to be altered from their defaults, then I'll use the builder pattern (static inner builder or other similar design).

Josh generally gives pretty darn good advice - the best thing I like about him is that the advice comes from the trenches - he admits himself that he made mistakes in designing parts of Java, and Effective Java is partly kind of his 'cure' so to speak :-)

Related Topic