rspec/rules/S1604/java/rule.adoc

72 lines
1.8 KiB
Plaintext

== Why is this an issue?
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.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
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();
}
})
...
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
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[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Make this anonymous inner class a lambda. [(sonar.java.source not set. Assuming 8 or greater.)]
'''
== Comments And Links
(visible only on this page)
=== on 24 Feb 2014, 10:54:33 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-455
endif::env-github,rspecator-view[]