Java Reference
In-Depth Information
How can we benefit from the FP paradigm? One way would be to switch to using an FP lan-
guage; some of the leading ones are Haskell, Ocaml, Erlang, and the LISP family. But most
of those would require walking away from the Java ecosystem. You could consider using
Scala or Clojure , JVM-based languages that provide functional programming support in the
context of an OO language.
But this is the Java Cookbook , so you can imagine we're going to try to get some of the be-
nefits of functional programming while remaining in the Java language. Some features of FP
include:
▪ Pure functions; having no side-effects and whose results depend only on their inputs and
not on mutable state elsewhere in the program
▪ First-class functions (e.g., functions as data)
▪ Immutable data
▪ Extensive use of recursion and lazy evaluation
Pure functions are completely self-contained; their operation depends only on the input para-
meters and internal logic, not on any variable “state” in other parts of the program—indeed,
there are no “global variables,” only global constants . Although this can be hard to accept for
those schooled in imperative languages like Java, it does make it much easier to test and en-
sure program correctness! It means that, no matter what else is going on in the program (even
with multiple threads), a method call like computeValue(27) will always, unconditionally,
return the same value every time (with exceptions, of course, for things like the current time,
random seeds, etc., which are global state).
We'll use the terms function and method interchangeably in this chapter, although it's not
strictly correct. FP people use the term “function” in the mathematical function sense, where-
as “methods” in Java just mean “some code you can call” (a Java “method call” is also re-
ferred to as a message being sent to an object, in the OO view of things).
“Functions as data” means that you can create an object that is a function, pass it into another
function, write a function that returns another function, and so on—with no special syntax,
because, well, functions are data.
One of Java 8's approach to FP is the definition of “functional interfaces.” A functional in-
terface in Java is one that has only one method, such as the widely used Runnable , whose
only method is run() , or the common Swing “action handler” ActionListener , whose only
method is actionPerformed(ActionEvent) . Actually, also new in Java 8, interfaces can
Search WWH ::




Custom Search