File: InlineFormatString.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 (30 lines) | stat: -rw-r--r-- 964 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
Prefer to use literal format strings directly in the call to a formatting method
over extracting them to a constant. That is, prefer this:

```java
throw new IllegalArgumentException(
    String.format("Uh oh, can't use %s with %s", badArgA, badArgB));
```

to this:

```java
private static final String ERROR_MESSAGE = "Uh oh, can't use %s with %s";
...
throw new IllegalArgumentException(String.format(ERROR_MESSAGE, badArgA, badArgB));
```

Extracting the format string to a constant makes it harder to read the
`String.format` call, and to see that the correct format arguments are being
passed.

If a single format string is used by multiple calls to `String.format`, consider
extracting a helper method instead of making the string a constant:

```java
String errorMessage(String badArgA, String badArgB) {
  return String.format("Uh oh, can't use %s with %s", badArgA, badArgB);
}
...
throw new IllegalArgumentException(errorMessage(badArgA, badArgB));
```