rspec/rules/S1612/java/rule.adoc
Sylvain Kuchen e6f8cb33bd
Modify rule S1612 (Java): Short lambdas are considered compliant (#1471)
When a lambda function is shorter than its equivalent method reference, the code is considered compliant and no issue is raised
2022-12-14 08:58:21 +01:00

67 lines
1.8 KiB
Plaintext

Method/constructor references are commonly agreed to be more readable than lambdas in most situations, and are therefore preferred.
However, method references are sometimes less concise than lambdas. In such cases, it might be fine to keep the lambda if it is better for readability. This choice is ultimately up to the programmer. Therefore, this rule only raises issues on lambda functions that could be replaced by shorter method references.
``++null++`` checks can be replaced with references to the ``++Objects::isNull++`` and ``++Objects::nonNull++`` methods, ``++casts++`` can be replaced with ``++SomeClass.class::cast++`` and ``++instanceof++`` can be replaced with ``++SomeClass.class::isInstance++``.
*Note* that this rule is automatically disabled when the project's ``++sonar.java.source++`` is lower than ``++8++``.
== Noncompliant Code Example
[source,java]
----
class A {
void process(List<A> list) {
list.stream()
.filter(a -> a instanceof B)
.map(a -> (B) a)
.map(b -> b.<String>getObject())
.forEach(b -> { System.out.println(b); });
}
}
class B extends A {
<T> T getObject() {
return null;
}
}
----
== Compliant Solution
[source,java]
----
class A {
void process(List<A> list) {
list.stream()
.filter(B.class::isInstance)
.map(B.class::cast) // Note: keeping the lambda would also be compliant here, since it is shorter
.map(B::<String>getObject)
.forEach(System.out::println);
}
}
class B extends A {
<T> T getObject() {
return null;
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]