Java Reference
In-Depth Information
Removing the boilerplate was nice, but it's not the only improvement we get with lambda ex-
pressions in Java 8.
The concepts introduced in this chapter let us write simpler code, in the sense that they de-
scribe operations on data by saying
what
transformation is made rather than
how
the trans-
formation occurs. This gives us code that has less potential for bugs and expresses the pro-
grammer's intent directly.
Another aspect of getting to the
what
and not the
how
is the idea of a
side effect-free
func-
tion. These are important because we can understand the full implications of what the func-
tions are doing just by looking at what values they return.
Functions with no side effects don't change the state of anything else in the program or the
outside world. The first lambda expression in this topic had side effects because it printed
some output on the console—an
observable
side effect of the function. What about the fol-
lowing example?
private
private
ActionEvent lastEvent
;
private
private
void
void
registerHandler
() {
button
.
addActionListener
((
ActionEvent event
) -> {
this
this
.
lastEvent
=
event
;
});
}
Here we save away the
event
parameter into a field. This is a more subtle way of generating
a side effect: assigning to variables. You may not see it directly in the output of your pro-
gram, but it does change the program's state. There are limits to what Java lets you do in this
regard. Take a look at the assignment to
localEvent
in this code snippet:
ActionEvent localEvent
=
null
null
;
button
.
addActionListener
(
event
-> {
localEvent
=
event
;
});
This example tries to assign the same
event
parameter into a local variable. There's no need
to send me errata emails—I know this won't actually compile! That's actually a deliberate
choice on behalf of the designers: an attempt to encourage people to use lambda expressions
to capture values rather than capturing variables. Capturing values encourages people to
write code that is free from side effects by making it harder to do so. As mentioned in