Skip to content

Builder pattern guidelines

Julien Viet edited this page Dec 5, 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:

Main options configuration

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())

Builders shall not be the default way to get the resource

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();

Use meaningful names for configuring the builder

  • 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()
Clone this wiki locally