Skip to content

Files

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Latest commit

0f36668 · Apr 18, 2022

History

History
68 lines (54 loc) · 2.92 KB

building-objects.asciidoc

File metadata and controls

68 lines (54 loc) · 2.92 KB

Building API objects

Builder objects

All data types in the {java-client} are immutable. Object creation uses the builder pattern that was popularized in Effective Java in 2008.

ElasticsearchClient client = ...
include-tagged::{doc-tests-src}/api_conventions/ApiConventionsTest.java[builders]

Note that a builder should not be reused after its build() method has been called.

Builder lambda expressions

Although this works nicely, having to instantiate builder classes and call the build() method is a bit verbose. So every property setter in the {java-client} also accepts a lambda expression that takes a newly created builder as a parameter and returns a populated builder. The snippet above can also be written as:

ElasticsearchClient client = ...
include-tagged::{doc-tests-src}/api_conventions/ApiConventionsTest.java[builder-lambdas]

This approach allows for much more concise code, and also avoids importing classes (and even remembering their names) since types are inferred from the method parameter signature.

Note in the above example that builder variables are only used to start a chain of property setters. The names of these variables are therefore unimportant and can be shortened to improve readability:

ElasticsearchClient client = ...
include-tagged::{doc-tests-src}/api_conventions/ApiConventionsTest.java[builder-lambdas-short]

Builder lambdas become particularly useful with complex nested queries like the one below, taken from the {ref}/query-dsl-intervals-query.html[intervals query API documentation].

This example also highlights a useful naming convention for builder parameters in deeply nested structures. For lambda expressions with a single argument, Kotlin provides the implicit it parameter and Scala allows use of _. This can be approximated in Java by using an underscore or a single letter prefix followed by a number representing the depth level (i.e. _0, _1, or b0, b1 and so on). Not only does this remove the need to create throw-away variable names, but it also improves code readability. Correct indentation also allows the structure of the query to stand out.

ElasticsearchClient client = ...
include-tagged::{doc-tests-src}/api_conventions/ApiConventionsTest.java[builder-intervals]
  1. Search results will be mapped to SomeApplicationData instances to be readily available to the application.

{doc-tests-blurb}