File: BuilderReturnThis.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (34 lines) | stat: -rw-r--r-- 1,140 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
This check identifies instance methods in builder classes, and requires that
they either `return this;`, or are explicitly annotated with
`@CheckReturnValue`.

Instance methods in builders typically return `this`, to allow chaining.
Ignoring this result does not indicate a https://errorprone.info/bugpattern/CheckReturnValue bug. For
example, both of the following are fine:

```java
Foo.Builder builder = Foo.builder();
builder.setBar("bar"); // return value is deliberately unused
return builder.build();
```

```java
Foo.Builder builder =
    Foo.builder().setBar("bar").build();
```

Rarely, a builder method may return a new instance, which should not be ignored.
This check requires these methods to be annotated with `@CheckReturnValue`:

```java
class Builder {
  @CheckReturnValue
  Builder setFoo(String foo) {
    return new Builder(foo); // returns a new builder instead of this!
  }
}
```

This check allows the https://errorprone.info/bugpattern/CheckReturnValue enforcement to assume the
return value of instance methods in builders can safely be ignored, unless the
method is explicitly annotated with `@CheckReturnValue`.