Functional programming has started (re)gaining prominence in recent years, and with good reason too. Functional programs lend an elegant solution to the concurrency problem, result in more modular systems, are more concise and are easier to test. While modern languages like Scala and Clojure have embraced the functional style whole-heartedly, Java has lagged a bit behind in its treatment of functions as first-class citizens. With the advent of Java 8 and its support for lambdas, however, Java programmers can finally start reaping the power of functional programs as well. Even without Java 8, it is possible to adopt a functional style with the aid of excellent libraries such as Guava.
34. Java 8 Gyaan
•
Functional Interface
•
Interface with a single method
without an implementation
•
Can be enforced using the
@FunctionalInterface
annotation
•
There are several standard
functional interfaces defined in
the java.lang.function
package
59. Why Functional?
•
A newer different way of thinking
•
More modular
•
Side-effect free programs
•
Immutable programs
•
•
Easier to write concurrent code
Easier to test
60. What to do in Java 6?
•
Look in the Guava or Apache Commons Lang3 library
•
But…
“As of Java 7, functional programming in Java can only be approximated
through awkward and verbose use of anonymous classes. This is expected to
change in Java 8, but Guava is currently aimed at users of Java 5 and above.!
Excessive use of Guava's functional programming idioms can lead to verbose,
confusing, unreadable, and inefficient code. These are by far the most easily
(and most commonly) abused parts of Guava, and when you go to
preposterous lengths to make your code "a one-liner," the Guava team weeps.”
— Guava Documentation
61. What to do in Java 6
•
First — Stop Whining
•
Prefer final variables
•
Minimize the use of void methods
•
Avoid use of mutable globals (statics)
•
Avoid returning nulls
•
Read Effective Java - And apply learnings!