Java Reference
In-Depth Information
operation. And yes, this does mean that the caller needs to check whether each method call may
result in an empty Optional. This may sound like a huge deal, but pragmatically, given our
guidance on functional-style programming versus pure functional programming, you may
choose to use exceptions locally but not expose them via large-scale interfaces, thereby gaining
the advantages of functional style without the risk of code bloat.
Finally, to be regarded as functional, your function or method should call only those
side-effecting library functions for which you can hide their nonfunctional behavior (that is,
ensuring that any mutation they make on data structures is hidden from your caller, perhaps by
copying first and by catching any exceptions they might raise). In section 13.2.4 , “Functional
style in practice,” you'll see an example where we hide the use of side-effecting library function
List.add inside our method insertAll by copying the list.
These prescriptions can often be marked using comments or by declaring a method with a
marker annotation—and match the restrictions we placed on functions we passed to parallel
stream-processing operations such as Stream.map in chapters 4 - 7 .
Finally, for pragmatic reasons, you may find it convenient for functional-style code still to be
able to output debugging information to some form of log file. Yes, this means the code can't be
strictly described as functional, but in practice you retain most of the benefits of functional-style
programming.
13.2.2. Referential transparency
The restrictions on “no visible side-effects” (no mutating structure visible to callers, no I/O, no
exceptions) encode the concept of referential transparency . A function is referentially
transparent if it always returns the same result value when called with the same argument value.
The method String.replace is referentially transparent because "raoul".replace('r', 'R') will
always produce the same result (the method replace returns a new String with all lowercase 'r'
replaced with uppercase 'R') rather than updating its this object so it can be considered a
function.
Put another way, a function consistently produces the same result given the same input, no
matter where and when it's invoked. It also explains why we don't regard Random.nextInt as
functional. In Java using a Scanner object to get the input from a user's keyboard violates
referential transparency because calling the method nextLine may produce a different result at
each call. But adding together two final int variables always produces the same result, because
the content of the variables can never change.
 
Search WWH ::




Custom Search