0

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);
    }
}
zolv
  • 1,720
  • 2
  • 19
  • 36
  • What's the point in your `Simplifier` class? It's literally just a wrapper around a `Function`. It provides exactly the same behaviour. `Simplifiers` can just contain a `List>` – Michael May 18 '18 at 13:09
  • Is there a reason you don't want to use `new Simplifier(Person::new)` (using your `new Person(Integer id)` constructor? – khelwood May 18 '18 at 13:11
  • @Michael This is just a part of my implementation so the example is more clear. The main point is the question: how to deal with a builder pattern? – zolv May 18 '18 at 13:12

0 Answers0