error-prone-support icon indicating copy to clipboard operation
error-prone-support copied to clipboard

Rewrite `ImmutableMap.Builder#build` to `buildOrThrow`

Open EnricSala opened this issue 8 months ago • 0 comments

Problem

An ImmutableMap.Builder has two terminal methods which accomplish the same thing: build or buildOrThrow.

The buildOrThrow method should be preferred, because the documentation of build specifies:

Prefer the equivalent method {@link #buildOrThrow()} to make it explicit that the method will throw an exception if there are duplicate keys. The {@code build()} method will soon be deprecated.

Description of the proposed new feature

  • [ ] Support a stylistic preference.
  • [x] Avoid a common gotcha, or potential problem.
    • Make the behavior evident: an exception may be thrown (in case of duplicate keys).
  • [ ] Improve performance.

I would like to rewrite the following code:

ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
builder.build();

to:

ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
builder.buildOrThrow();

EnricSala avatar Jun 18 '24 07:06 EnricSala