Java Reference
In-Depth Information
Figure 13.6. Tail-recursive definition of factorial, which can reuse a
single stack frame
The bad news is that Java doesn't support this kind of optimization. But adopting tail recursion
may be a better practice than classic recursion because it opens the way to eventual compiler
optimization. Many modern JVM languages such as Scala and Groovy can optimize those uses of
recursion, which are equivalent to iteration (they'll execute at the same speed). This means that
pure-functional adherents can have their purity cake and eat it efficiently too.
The guidance when writing Java 8 is that you can often replace iteration with streams to avoid
mutation. In addition, iteration can be replaced with recursion when it lets you write an
algorithm in a more concise and side-effect-free way. Indeed, recursion can make examples
easier to read, write, and understand (for example, in the subsets example shown previously),
and programmer efficiency is often more important than small differences in execution time.
In this section, we discussed functional-style programming but only used the idea of a method
being functional—everything we said would have applied to the very first version of Java. In the
next chapter we look at the amazing and powerful possibilities offered by the introduction of
first-class functions in Java 8.
13.4. Summary
Following are the key concepts you should take away from this chapter:
Reducing shared mutable data structures can help you maintain and debug your programs in the long
term.
Functional-style programming promotes side-effect-free methods and declarative programming.
Function-style methods are characterized only by their input arguments and their output result.
 
Search WWH ::




Custom Search