Skip to content
\n

Then, this is definitely a problem, as you don't use the result.
\nWhether the rule name fits for this case, is maybe debatable.

\n

But it's similar like

\n
Instant someMethod(String instantString) {\n    Instant instant = Instant.parse(instantString);\n    instant.plusSeconds(1); // uh oh, result is ignored\n    return instant;\n}
\n

On the other hand, if your complete code sample looks like this:

\n
boolean isValidInstant(String instantString) {\n    try {\n        Instant.parse(instantString);\n        return true;\n    } catch (DateTimeParseException e) {\n        return false;\n    }\n}
\n

Then we might consider this a false-positive. However, this code style is not optimal - as exceptions should only be used for exceptional circumstances - since exceptions are still expensive. That this code already explicitly takes into account, that an invalid instantString can be passed tells me, that this is not an exceptional circumstance, but one that the code almost expects to happen. Unfortunately there seems to be no method, that can tell you - without trying to parse - whether a given string is a valid instant. You'd need to implement it yourself, e.g.

\n
boolean isValidInstant(String instantString) {\n    return instantString.matches(\"\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}(?:\\\\.\\\\d{3,9})?Z\");\n}
","upvoteCount":1,"url":"https://github.com/pmd/pmd/discussions/5502#discussioncomment-12079667"}}}
Discussion options

You must be logged in to vote

Not sure. The idea of the rule UselessOperationOnImmutable is, that it finds method calls that don't use the result. This is mostly a problem for immutable types, like java.time.Instant.

So, if your complete code sample looks like this:

void someMethod(String instantString) {
    Instant.parse(instantString);
}

Then, this is definitely a problem, as you don't use the result.
Whether the rule name fits for this case, is maybe debatable.

But it's similar like

Instant someMethod(String instantString) {
    Instant instant = Instant.parse(instantString);
    instant.plusSeconds(1); // uh oh, result is ignored
    return instant;
}

On the other hand, if your complete code sample looks like this:

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@jochenberger
Comment options

Answer selected by jochenberger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants