File: ModifiedButNotUsed.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 (38 lines) | stat: -rw-r--r-- 961 bytes parent folder | download | duplicates (2)
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
35
36
37
38
Collections and proto builders which are created and mutated but never used may
be a sign of a bug, for example:

```java
  MyProto.Builder builder = MyProto.newBuilder();
  if (field != null) {
    MyProto.NestedField.Builder nestedBuilder = MyProto.NestedField.newBuilder();
    nestedBuilder.setValue(field);
    // Oops--forgot to do anything with nestedBuilder.
  }
  return builder.build();
```

Likewise, converting a proto to a builder and modifying it is a no-op unless
something is done with the return value:

```java
  void setFoo(MyProto proto, String foo) {
    proto.toBuilder().setFoo(foo).build();
  }
```

As protos are immutable, either the return value must be used:

```java
  @CheckReturnValue
  MyProto withFoo(MyProto proto, String foo) {
    return proto.toBuilder().setFoo(foo).build();
  }
```

or the Builder modified in place:

```java
  void setFoo(MyProto.Builder protoBuilder, String foo) {
    protoBuilder.setFoo(foo);
  }
```