1

I was comparing the use of compose() default method with its equivalent lambda expression and couldn't find any reason why prefering the former.

Maybe the reason is related to code expressiveness or functional style programming, as pointed here

However, comparing the two approaches to solve the question How to do function composition? I see only disadvantages in using compose() instead of lambda expressions.

1st approach with compose() according to the accepted answer:

Function<Person, Address> personToAddress = Person::getAddress;
Function<Address, String> addressToCountry = Address::getCountry;
Function<Person, String> toCountry = addressToCountry.compose(personToAddress);

2nd approach with a lambda expression:

Function<Person, String> toCountry = p -> p.getAddress().getCountry();

Why do I prefer the second one? First, it is less verbose . Second, it does not require the explicit auxiliary variables personToAddress and addressToCountry.

So, is there any reason for using compose() instead of using a lambda explicitly?

Community
  • 1
  • 1
Miguel Gamboa
  • 8,855
  • 7
  • 47
  • 94
  • 4
    The second one is appropriate when the two functions have been passed to you. i.e. they already exist. – Peter Lawrey Mar 29 '17 at 11:49
  • 2
    In your simple example you know both how to get address from a person and how to get country from address. But what if you don't know how to get an address? What if `Person` has `List
    ` and you don't know which one you are requested? Then you can request a mapper from client callsite and compose the answer.
    – M. Prokhorov Mar 29 '17 at 12:06
  • 1
    Just to nit-pick, the local variables are not strictly required. You could use a cast to link the method reference to the `Function` type – Hank D Mar 29 '17 at 15:28

1 Answers1

2

One reason is if you do not create one or even both of the functions in the same piece of code, but get them passed in from somewhere else. Then you can either write a lambda that calls apply() on the given function(s), or use compose(), which would probably be cleaner.

Philipp Wendler
  • 11,184
  • 7
  • 52
  • 87