File: ImpossibleNullComparison.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 (54 lines) | stat: -rw-r--r-- 1,534 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
This checker looks for comparisons of protocol buffer fields with null. If a
proto field is not specified, its field accessor will return a non-null default
value. Thus, the result of calling one of these accessors can never be null, and
comparisons like these often indicate a nearby error.

If you need to distinguish between an unset optional value and a default value,
you have two options. In most cases, you can simply use the `hasField()` method.
proto3 however does not generate `hasField()` methods for primitive types
(including `string` and `bytes`). In those cases you will need to wrap your
field in `google.protobuf.StringValue` or similar.

NOTE: This check applies to normal (server) protos and Lite protos. The
deprecated nano runtime does produce objects which use `null` values to indicate
field absence.

```java
void test(MyProto proto) {
  if (proto.getField() == null) {
    ...
  }
  if (proto.getRepeatedFieldList() != null) {
    ...
  }
  if (proto.getRepeatedField(1) != null) {
    ...
  }
}
```

```java
void test(MyProto proto) {
  if (!proto.hasField()) {
    ...
  }
  if (!proto.getRepeatedFieldList().isEmpty()) {
    ...
  }
  if (proto.getRepeatedFieldCount() > 1) {
    ...
  }
}
```

If the presence of a field is required information in proto3, the field can be
wrapped. For example,

```java
message MyMessage {
  google.protobuf.StringValue my_string = 1;
}
```

Presence can then be tested using `myMessage.hasMyString()`, and the value
retrieved using `myMessage.getMyString().getValue()`.