2023-05-03 11:06:20 +02:00
== Why is this an issue?
2022-12-14 08:58:21 +01:00
Method/constructor references are commonly agreed to be more readable than lambdas in most situations, and are therefore preferred.
2021-04-28 16:49:39 +02:00
2022-12-14 08:58:21 +01:00
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.
2021-04-28 16:49:39 +02:00
2022-12-14 08:58:21 +01:00
``++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++``.
2021-04-28 16:49:39 +02:00
*Note* that this rule is automatically disabled when the project's ``++sonar.java.source++`` is lower than ``++8++``.
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
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;
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
class A {
void process(List<A> list) {
list.stream()
.filter(B.class::isInstance)
2022-12-14 08:58:21 +01:00
.map(B.class::cast) // Note: keeping the lambda would also be compliant here, since it is shorter
2021-04-28 16:49:39 +02:00
.map(B::<String>getObject)
.forEach(System.out::println);
}
}
class B extends A {
<T> T getObject() {
return null;
}
}
----
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Replace this lambda with a method reference. [(sonar.java.source not set. Assuming 8 or greater.)]
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== is duplicated by: S2212
=== on 26 Feb 2014, 12:19:41 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-465
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]