-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Builder pattern guidelines
Thomas Segismont edited this page Dec 6, 2023
·
3 revisions
Vert.x 5 starts to introduce the builder pattern when an object created by the API needs to interact with code.
- set a user handler like
HttpClient
connection handler - set programmatically an SPI like cluster manager, address resolver, ...
- ...
For the sake of API consistency, builders should follow guidelines:
Use the with(Options)
for the builder related options, there can be multiple with
methods when the object needs.
vertx.httpClientBuilder().with(new HttpClientOptions()).with(new PoolOptions())
The default way to create an object should be its create method overloaded with reasonable set of arguments: the empty create method and the method that takes the options as argument.
HttpClient client = vertx.createHttpClient(new HttpClientOptions());
Only when non data state needs to be set, the builder shall be used.
HttpClient client = vertx.httpClientBuilder().with(new HttpClientOptions()).withConnectHandler(conn -> ...).build();
- most of the time
withXXX
is fine, e.g.withConnectHandler(...)
- avoid
setXXX
which is usually avoided in Vert.x API (besides data objects) - but it does not always have to be
withXXX
, e.g.PgClient.builder().connectingTo(connectOptionsSupplier).build()
Sometimes, an object depends on other objects, and cannot be instantiated without them. In this case, it is fine for the builder creation method to take parameters:
GraphiQLHandler handler = GraphiQLHandler.builder(vertx) // cannot be created without a Vert.x instance
.with(options)
.build();