Java Reference
In-Depth Information
Figure 13.3. A function with no side effects
The distinction between this sort of function and the methods you see in programming
languages like Java is central. (The idea of the mathematical functions like log or sin having
such side effects in unthinkable.) In particular, mathematical functions when repeatedly called
with the same arguments always return the same results. This rules out methods such as
Random.nextInt, and we further discuss this idea later under the concept of referential
transparency.
When we say functional we mean “like mathematics—no side effects.” Now a programming
subtlety appears. Do we mean that every function is built only using functions and of course
mathematical ideas such as if-then-else? Or might we allow a function to do nonfunctional
things internally, as long as it doesn't expose any of these side effects to the rest of the system?
In other words, if we as programmers perform a side effect that can't be observed by callers,
does that side effect actually exist? The caller doesn't need to know or care, because it can't
affect them.
When we wish to emphasize the difference, we refer to the first as pure functional programming
(we return to this later in the chapter) and the latter as functional-style programming.
13.2.1. Functional-style Java
In practice, you can't completely program in pure functional style in Java. For example, Java's
I/O model consists of side-effecting methods (calling Scanner.nextLine has the side effect of
consuming a line from a file, so calling it twice typically gives different results). Nonetheless, it's
possible to write core components of your system as if they were purely functional. In Java
you're going to write functional-style programs . First, there's a further subtlety about no one
seeing your side effects and hence the meaning of functional . Suppose a function or method has
no side effects, except for it incrementing a field just after entry and decrementing it just before
exit. From the point of view of a program consisting of a single thread, this method has no
visible side effects and can be regarded as functional style. On the other hand, if another thread
could inspect the field—or worse could call the method concurrently—it wouldn't be functional.
You could hide this issue by wrapping the body of this method with a lock, and this would again
enable you to argue that the method is functional. But in doing so you would have lost the ability
to execute two calls to the method in parallel using two cores on your multicore processor. Your
 
Search WWH ::




Custom Search