Re: dysfunctional Builder pattern?
marlow.andrew@googlemail.com wrote:
[...] Here is an example of a Builder being used:
someWidget = SomeWidgetBuilder.withFirstAttribute(firstVal).
withSixthAttribute(sixthVal).
withTenthAttribute(tenthVal).build();
The problem I have seen, and why I do not like this 'builder', is that
I have seen Product classes where you HAVE to define valid values for
certain private members and there is no suitable default value. The
Builder hides this and allows you to construct an object that is
invalid.
No: it can throw an exception from the build() method, or
from the SomeWidget() constructor that build() invokes. Whether
to throw IllegalArgumentException or IllegalStateException or
something else is up to you.
My preference is to use the ctor to construct an object, even if the
ctor list is long. One can always comment it. Thus I would say:
someWidget = new SomeWidget(startTime, endTime, partNumber, sharpness,
0, false, "widgetName");
I would comment the literal constants 0 and false, to make it clear
that there are the metric size and homeMade flag respectively.
someWidget can now never be invalid.
Can't it, though? What if the sharpness is inconsistent with
the metric size? (As all widget craftsmen know, a widget of metric
size zero necessarily has infinite sharpness; finite sharpnesses
are possible only for positive-size widgets.) Or what if startTime
is later than endTime (or earlier than endTime, in the case of
negative-size widgets)? Your constructor will presumably make
suitable validity and consistency checks -- but such checks could
just as well be made by build() as by a constructor.
--
Eric.Sosman@sun.com