rspec/rules/S6201/java/rule.adoc
2021-04-28 18:08:03 +02:00

37 lines
988 B
Plaintext
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

In Java 16, the feature "Pattern matching for instanceof" is finalized and can be used in production. Previously developers needed to do 3 operations in order to do this: check the variable type, cast it and assign the casted value to the new variable. This approach is quite verbose and can be replaced with pattern matching for ``++instanceof++``, doing these 3 actions (check, cast and assign) in one expression.
This rule raises an issue when an ``++instanceof++`` check followed by a cast and an assignment could be replaced by pattern matching.
== Noncompliant Code Example
----
int f(Object o) {
if (o instanceof String) {  // Noncompliant
String string = (String) o;
return string.length();
}
return 0;
}
----
== Compliant Solution
----
int f(Object o) {
  if (o instanceof String string) {  // Compliant
    return string.length();
  }
  return 0;
}
----
== See
* https://openjdk.java.net/jeps/394[JEP 394: Pattern Matching for instanceof]