Java Reference
In-Depth Information
Consider a system that doesn't mutate any data structures. It would be a dream to maintain
because you wouldn't have any bad surprises about some object somewhere that unexpectedly
modifies a data structure! A method, which modifies neither the state of its enclosing class nor
the state of any other objects and returns its entire results using return, is called pure or
side-effect free .
What constitutes a side effect more concretely? In a nutshell, a side effect is an action that's not
totally enclosed within the function itself. Here are some examples:
Modifying a data structure in place, including assigning to any field, apart from initialization inside a
constructor (for example, setter methods)
Throwing an exception
Doing I/O operations such as writing to a file
Another way to look at this idea of no side effects is to consider immutable objects. An
immutable object is an object that can't change its state after it's instantiated so it can't be
affected by the actions of a function. This means that once immutable objects are instantiated,
they can never go into an unexpected state. You can share them without having to copy them,
and they're thread-safe because they can't be modified.
The idea of no side effects might appear as a pretty severe restriction, and you may doubt
whether real systems can be built in this way. We hope to convince you of this by the end of the
chapter. The good news is that components of systems that embrace this idea can use multicore
parallelism without using locking, because the methods can no longer interfere with each other.
In addition, this is great for immediately understanding which parts of the program are
independent.
These ideas come from functional programming, which we turn to in the next section. But first,
let's explore the idea of declarative programming , upon which functional programming is
based.
13.1.2. Declarative programming
There are two ways of thinking about implementing a system by writing a program. One way
centers on how things are done: “first do this, then update that, then ....” For example, if you
want to calculate the most expensive transaction in a list, you'll typically execute a sequence of
commands: take a transaction from the list and compare it with the provisional most expensive
transaction; if it's more expensive, then it becomes the provisional most expensive; repeat with
the next transaction in the list and so on.
 
Search WWH ::




Custom Search