Why should we use method Resferences instead of both?

Asked

Viewed 42 times

2

When passing functions as argument to high-order functions, we can usually use two different Java 8 mechanisms+:

1. Lambas:

var averageLength = stringList.stream()
    .filter(s -> s != null)
    .mapToInt(s -> s.length())
    .average();

2. Method of reference:

var averageLength = stringList.stream()
    .filter(Objects::nonNull)
    .mapToInt(String::length)
    .average();

By default Intellij IDEA recommends replacing Amble for method References (even when the code becomes slightly more extensive as in the example above).

My question is, why is it recommended to use method References instead of Amble? Is it a purely legibility issue? Reuse? Performance?

  • 1

    If you do not know, I want to see who will know :D but if you are asking something like this it is because you must be triggering an answer to the question itself. Allow me to go ahead and link a response from a guy who definitely knows why (Brian Goetz): https://stackoverflow.com/a/24493905/2241463

  • 1

    Just today I gave preference to an anonymous class Runnable for reasons of legibility, by a method run() and all. He wanted to isolate a feature of it in a method he called himself, and if he used a lambda (which is usually more readable) this would not be allowed. I don’t remember the case now, so I won’t rule out a possible bad design on my part. :)

  • But just to see how this thing that has the most legibility can not take to iron and fire, depends on each person.

  • Can fit anonymous classes, ETA Expansion (or whatever the name given to it in the Java world), LambdaMetafactory, etc on the question. I just did not mention not to complicate further :).

  • "this thing of which has the highest readability can not take the iron and fire". I saw now that I expressed myself badly here, readability naturally is very important, what I meant is that the question of which is the most readable form is relative and depends on personal perception.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.