BuilderWithConditionalException

From APIDesign

(Difference between revisions)
Jump to: navigation, search
(Throw on I/O Error)
Line 16: Line 16:
=== Throw on I/O Error ===
=== Throw on I/O Error ===
-
The builder pattern delays reading of the actual file up until the ''build()'' method is called. As reading of a file means an I/O operation and as each I/O operation in Java may yield [[checked exception]] {{JDK|java/io|IOException}}, it is desirable for the ''build()'' method to propagate it to the caller.
+
The builder pattern delays reading of the actual file up until the ''build()'' method is called. As reading of a file means an I/O operation and as each I/O operation in Java may yield [[checked exception|checked]] {{JDK|java/io|IOException}}, it is desirable for the ''build()'' method to propagate it to the caller.

Revision as of 13:23, 10 June 2016

The builder pattern is gaining more and more popularity in the APIs that I design: In Truffle API we are trying to use it a lot. For example an instance of the PolyglotEngine is constructed via a builder obtained from its newBuilder() method.

Builder for Source

These days I am trying to use the builder pattern also for construction of Source. Rather than having various (and overloaded) methods with fromFileName, etc. we'd like to have:

Source source = Source.newFromFile(file).
   mimetype("text/javascript").
   name("FancyName.js").
   build();

It works fine and allows the users to specify only those properties that are needed - for example one can omit the name - then it would be derived from the name of the file. The same applies to mimetype.

Throw on I/O Error

The builder pattern delays reading of the actual file up until the build() method is called. As reading of a file means an I/O operation and as each I/O operation in Java may yield checked IOException, it is desirable for the build() method to propagate it to the caller.

Personal tools
buy