1

Hi I have a doubt on builder design pattern.From the pluralsight videos I understood that this pattern is used to avoid the complexity of telescopic constructors in mutable classes. Some other sites explain it as a way to develop or construct complex object by keeping builder as a composition.I am totally confused.Please clarify the same?

Anoop M Nair
  • 1,057
  • 1
  • 13
  • 31
  • 1
    See this answer: http://stackoverflow.com/a/1953567/1155984 – uraimo Jun 16 '15 at 05:21
  • [Item 2. Page 11 and on](http://uet.vnu.edu.vn/~chauttm/e-books/java/Effective.Java.2nd.Edition.May.2008.3000th.Release.pdf) – PM 77-1 Jun 16 '15 at 05:23
  • Said quickly, the interest of Builder design pattern is to have several classes builder (one per type of initialization) and one class director for managing the desired builder. The interest of Factory pattern is the caller have not to know the implementation, just the interface of the object build. Theses 2 goals are not incompatibles. – Max Jun 16 '15 at 09:00

1 Answers1

2

Complex constructors can be bad for immutable or mutable classes.

One problem with big constructors (or a hierarchy of constructors) is that you can end up with a large constructor used for multiple purposes. For example some parameters might be null if you are creating a brand new object but they must not be null when you call it from somewhere else.

It's painful to figure out how to use these constructors. Even if they have built in validation you still have to check that you are creating it the right way. The builder could have methods that provide hints or force people to create it the right way. For example builder.copy(obj).setName("newObj").build(). This gives a hint about how to copy an object, it might be better than looking through the constructors for the correct one to use.

Another problem is that you must supply all the required constructor args. Even if there are sane defaults, you might be forced to supply something. The builder could contain default values so you only set the parameters you are interested in.

Another problem is that a big constructor might have multiple parameters of the same type in a row. It's asking for someone to bung in the wrong value accidentally. A builder forces you to call a method with a meaningful name.

A builder also has the same advantage as a static factory. It could return an interface instead of the concrete type. This is good because you encourage clients classes to work against the interface.

The linked answer in the comments has more good reasons.

roby
  • 3,103
  • 1
  • 16
  • 14