Description
Pattern matching in instanceof
expressions are a nice Java feature, and the automated refactoring by PatternMatchingInstanceof
is highly appreciated and something that we would like to use for the common case of if (foo instanceof Foo) { ... ((Foo)foo) ... }
. However, in some other cases it is not so obvious whether the code becomes better readable with the refactoring, in particular in cases where the cast is outside of the block that starts with the instanceof
.
Examples would be test1
and test2
in the following:
public class Test {
void test1() {
Object o = 1;
// This is rewritten into pattern matching by Error Prone
if (!(o instanceof Integer)) {
return;
}
System.out.println(((Integer) o) + 0);
}
void test2() {
Object o = 1;
// This is rewritten into pattern matching by Error Prone
if (!(o instanceof Integer)) {
} else {
System.out.println(((Integer) o) + 0);
}
}
void test3() {
Object o = 1;
// This is *not* rewritten into pattern matching by Error Prone but one could do so in Java.
if (o instanceof Integer) {
} else {
return;
}
System.out.println(((Integer) o) + 0);
}
}
Consider that there could be much more code between the instanceof
and the cast. I added test3
as an example where the code is currently not rewritten by Error Prone (in version 2.37.0) although it would be legal to do so, to show that the current check is also not fully consistent and does not fulfill the property "produces a rewrite suggestion whenever it is legal in Java".
We discussed in our team that while we like to use PatternMatchingInstanceof in general, we would prefer to not have an automated refactoring that enforces rewritings such as the ones from the above examples.
Thus I would like to ask whether it would be possible to either make PatternMatchingInstanceof apply only in cases where the casts are either inside the same expression as the instanceof
or in the block that starts with the instanceof
, or, if this is undesired in general, to introduce a configuration option that would allow us to configure it in that way. This would be appreciated.