On Sun, Feb 18, 2024 at 9:51 AM Gary Gregory <garydgreg...@gmail.com> wrote:

> > There seem to have been a lot of needless deprecations of constructors
> > and replacement with builder patterns.
>
> The use of the builder pattern avoids constructor inflation. For
> example, we had fourteen (14) constructors for ZipFile, that's
> confusing and cluttered, a builder is simpler IMO.
>

I don't find constructor inflation to be a problem when the
constructors are obvious alternatives. Look at it from the perspective
of a client of the API rather than an implementer of the API. I just
type

ZipFile z = new ZipFile(myFileObject);

Done. This is simpler to remember, write, and read than

ZipFile z = ZipFile.builder().setFile(myFileObject).build();

If that's even the variant of the builder pattern used here. Every
builder is a little different. It might be

ZipFile z = (new ZipFile.Builder()).setFile(myFileObject).build();

or perhaps

ZipFile z = ZipFile.builder().withFile(myFileObject).build();

or even

ZipFile z = ZipFile.builder().file(myFileObject).build();

There are others. Everyone understands constructors and knows what API
to expect. Builders, not so much.

Using constructors also avoids unexpected runtime exceptions like
https://issues.apache.org/jira/projects/IO/issues/IO-830 and
https://issues.apache.org/jira/projects/IO/issues/IO-831. Example in
this case

ZipFile z = ZipFile.builder()
    .setFile(myFileObject)
    .setName("myFile.zip")
   .setPath(Paths.get("/tmp/anotherfile.zip"))
    build();

There isn't a constructor equivalent of this statement because you
can't pass a file and a path and a name to one ZipFile constructor.
With constructors, there's no bug and on runtime problems. Type
checking verifies that the object has the necessary information for a
new object at compile time. With builders you don't find out till
runtime.

Builders do have a place. In particular they are useful when:

1. There are multiple arguments of the same type that are easily confused.
OR
2. Object initialization requires a lot of work that doesn't belong in
a constructor, like reading a file.

AND

3. All arguments not passed to the builder's own constructor are optional.

AND

4. Any combination and permutation of setter methods is allowed.

None of those apply to a straightforward class like ZipFile.

-- 
Elliotte Rusty Harold
elh...@ibiblio.org

---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscr...@commons.apache.org
For additional commands, e-mail: dev-h...@commons.apache.org

Reply via email to