[SONARJAVA-4485] Modify rule S1604: Update rule in line with LayC (#1978)

This commit is contained in:
Johann Beleites 2023-06-07 17:13:11 +02:00 committed by GitHub
parent 32b4450609
commit 6f958bf170
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 23 deletions

8
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,8 @@
{
"grammarly.selectors": [
{
"language": "markdown",
"scheme": "file"
}
]
}

View File

@ -1,41 +1,54 @@
== Why is this an issue?
Before Java 8, the only way to partially support closures in Java was by using anonymous inner classes. But the syntax of anonymous classes may seem unwieldy and unclear.
Before Java 8, the only way to partially support closures in Java was by using anonymous inner classes.
Java 8 introduced lambdas, which are significantly more readable and should be used instead.
This rule is automatically disabled when the project's `sonar.java.source` is lower than `8`, as lambda expressions were introduced in Java 8.
With Java 8, most uses of anonymous inner classes should be replaced by lambdas to highly increase the readability of the source code.
=== Code examples
==== Noncompliant code example
*Note* that this rule is automatically disabled when the project's ``++sonar.java.source++`` is lower than ``++8++``.
=== Noncompliant code example
[source,java]
[source,java,diff-id=1,diff-type=noncompliant]
----
myCollection.stream().map(new Mapper<String,String>() {
public String map(String input) {
myCollection.stream().map(new Function<String,String>() { // Noncompliant, use a lambda expression instead
@Override
public String apply(String input) {
return new StringBuilder(input).reverse().toString();
}
});
Predicate<String> isEmpty = new Predicate<String> {
boolean test(String myString) {
return myString.isEmpty();
}
}
})
...
----
==== Compliant solution
=== Compliant solution
[source,java]
[source,java,diff-id=1,diff-type=compliant]
----
myCollection.stream().map(input -> new StringBuilder(input).reverse().toString());
Predicate<String> isEmpty = myString -> myString.isEmpty();
myCollection.stream()
.map(input -> new StringBuilder(input).reverse().toString()) // Compliant
...
----
==== Noncompliant code example
[source,java,diff-id=2,diff-type=noncompliant]
----
Predicate<String> isEmpty = new Predicate<String>() { // Noncompliant, use a lambda expression instead
@Override
public boolean test(String myString) {
return myString.isEmpty();
}
};
----
==== Compliant solution
[source,java,diff-id=2,diff-type=compliant]
----
Predicate<String> isEmpty = myString -> myString.isEmpty(); // Compliant
----
== Resources
* https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html[Lambda Expressions - The Java™ Tutorials]
ifdef::env-github,rspecator-view[]