I have a problem to make SonarQube happy for rule:
Lambdas should be replaced with method references (squid:S1612)
An example code:
One of my entity classes with a builder pattern inside:
public class Person {
Integer id;
String name;
public Person id(Integer id) {
setId(id);
return this;
}
public Person name(String name) {
setName(name);
return this;
}
/*
* Constructors, getters, setters etc...
*/
}
My Simplifier class which creates a simplified version of the entity with only id filled:
public class Simplifier<E> {
private final Function<Integer, E> creator;
public Simplifier(Function<Integer, E> entityCreator) {
this.creator = entityCreator;
}
public E simplify(Integer id) {
return creator.apply(id);
}
}
And my Simplifiers class with all available simplifiers for my entites. Here are 2 examples, one with one-line lambda and multiline lambda:
public class Simplifiers {
public static final Simplifier<Person> PERSON_1 =
new Simplifier<>(id -> new Person().id(id));
public static final Simplifier<Person> PERSON_2 =
new Simplifier<>(
id -> {
final Person action2 = new Person();
return action2.id(id);
});
}
My problem is that SonarQube complains about PERSON_1 lambda. How can I write it so it is a method reference?
Plase note that such a syntax is not logically the same:
public static final Simplifier<Person> PERSON_3 =
new Simplifier<>(new Person()::id);
It will be only 1 instance of Person created for all calls to PERSON_3 simplifier so such a test case will fail:
public class SimplifierTest {
@Test
public void test() {
Person simpleP1 = Simplifiers.PERSON_3.simplify(1);
Person simpleP2 = Simplifiers.PERSON_3.simplify(2);
Assert.assertNotSame(simpleP1, simpleP2);
}
}