Skip to content

Replace use of String.format(…) with formatted Strings #2751

Closed
@jxblum

Description

@jxblum

This task replaces all uses of String.format("..", args) with "..".formatted(args) (formatted Strings).

From my perspective, the code has:

  1. Much improved focus and visibility on the "message" being crafted for Exceptions or LOG messages FIRST rather than boilerplate code used to format the String message, and...

  2. Reduced, unnatural line breaks in the source code, such as, but not limited to:

    public void someMethod() {

        throw new IllegalArgumentException(String
                .format("some arbitrarily long message containing placeholders", argOne, argTwo, 
                        ..., argN);
    }

From my perspective, the above is not as readable as:

    public void someMethod() {

        throw new IllegalArgumentException("some arbitrarily long message containing placeholders"
                .formatted(argOne, argTwo, ..., argN);
    }

This refactoring also reduced the use of the following technique to avoid weird, unusual and unnatural source code formatting by the code formatter:

String message = String.format("...", args);
throw new IllegalArgumentException(message, ex);

Thereby keeping the "message" with the Exception.

Although, I must WARN that, in certain cases, the Exception "messages" was unusually long with placeholders spread throughout, such as:

    public void someMethod() {

        throw new IllegalArgumentException(("some really, really loooooooooooooooooooooooooong"
                + " message containing multiple formatting placeholders"
                + " across multiple lines")
                .formatted(argOne, argTwo, ..., argN);
    }

In which case, when using "..".formatted(args) you need to wrap the concatenated message with parentheses, like so:

("multiline, concatenated message, with placeholders").formatted(args)

This is a minor trade-off, and I do not think it impairs the readability in any way.

Additionally, and fortunately, the IDE is smart enough to pick up on this and wrap the formatted String appropriately.

I considered the use of text block (or multi-line Strings) in Java, but you must be careful since the text block will preserve tabs and other (potentially) hidden characters (e.g. newlines) contained in the String.

All in all, even despite the necessary use of () in only a few places, I think the use of "..".formatted(args) is much cleaner, clearer to read, and more succinct than String.format(..).

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions