Java Reference
In-Depth Information
this often, you should stand back and see whether you can refactor them into a more concise
and readable form.
NOTE
If at this stage you feel uncomfortable with the amount of method chaining in the API,
that's entirely natural. With more experience and more time these concepts will begin to
feel quite natural, and it's not a reason to write Java code that splits up chains of opera-
tions as in Example 3-24 . Ensuring that you format the code line by line, as you would
when using the builder pattern, will boost your comfort level as well.
Higher-Order Functions
What we've repeatedly encountered throughout this chapter are what functional program-
mers call higher-order functions . A higher-order function is a function that either takes an-
other function as an argument or returns a function as its result. It's very easy to spot a
higher-order function: just look at its signature. If a functional interface is used as a paramet-
er or return type, you have a higher-order function.
map is a higher-order function because its mapper argument is a function. In fact, nearly all
the functions that we've encountered on the Stream interface are higher-order functions. In
our earlier sorting example, we also used the comparing function. comparing not only took
another function in order to extract an index value, but also returns a new Comparator . You
might think of a Comparator as an object, but it has only a single abstract method, so it's a
functional interface.
In fact, we can make a stronger statement than that. Comparator was invented when a func-
tion was needed, but all Java had at the time was objects, so we made a type of class—an an-
onymous class—that we could treat like a function. Being an object was always accidental.
Functional interfaces are a step in the direction that we actually want.
Good Use of Lambda Expressions
When I first introduced lambda expressions, I gave the example of a callback that printed
something out. That's a perfectly valid lambda expression, but it's not really helping us write
simpler and more abstract code because it's still telling the computer to perform an operation.
Search WWH ::




Custom Search