Hi,

Gary and I did some work on CSV-68 Use the Builder Pattern to create
CSVFormats [1].
We have implemented a builder for CSVFormats in trunk. It is capable of...

...creating a CSVFormat from scratch by only passing in a delimiter:
CSVFormat format = CSVFormat.newBuilder(',').build();

...creating a CSVFormat from the commons-csv defaults (RFC4180 but ignoring
empty lines)
CSVFormat format = CSVFormat.defaults().build();

...creating a CSVFormat based on a
CSVFormat copyOfRFC4180 = CSVFormat.newBuilder(CSVFormat.RFC4180).build();

The builders provides the same fluent API like CSVFormat did before by
returning itself:
CSVFormat format =
CSVFormat.newBuilder(',').withRecordSeparator('\n').withIgnoreEmptyLines(true).build();

Using a builder has several advantages:
- the construction of CSVFormats can be separated from the CSVFormat itself
- the interface of CSVFormat is now much smaller
- if we want to add another parameter to CSVFormat we only have to change
CSVFormat's private ctor, and the build method. We had to change every
withXXX method before.
- CSVFormats can only be created into a valid state, because the builder
internally uses the validate method, which was package visible before and
therefore not accessible to users.

However there are also disadvantages:
- the builder is more verbose; it forces users to the build() method, where
every withXXX method returned a CSVFormat before.
- it has been argued that using the builder pattern only to make sure
CSVFormats are valid is overengineered. No other library has this kind of
validation.

Please share your thoughts about the builder.

Regards,
Benedikt

[1] https://issues.apache.org/jira/browse/CSV-68

Reply via email to