Java Reference
In-Depth Information
14.2.1. Destructive updates vs. functional
Let's consider the problems that can otherwise arise. Suppose you represent train journeys from
A to B as a mutable TrainJourney class (a simple implementation of a singly linked list), with an
int field modeling some detail of the journey such as the price of the current leg of the journey.
Journeys requiring you to change trains will have several linked TrainJourney objects using the
onward field; a direct train or final leg of a journey will have onward being null:
class TrainJourney {
public int price;
public TrainJourney onward;
public TrainJourney(int p, TrainJourney t) {
price = p;
onward = t;
}
}
Now suppose you have separate TrainJourney objects representing a journey from X to Y and
from Y to Z. You may wish to create one journey that links the two TrainJourney objects (that is,
X to Y to Z).
A simple traditional imperative method to link these train journeys is as follows:
static TrainJourney link(TrainJourney a, TrainJourney b){
if (a==null) return b;
TrainJourney t = a;
while(t.onward != null){
t = t.onward;
}
t.onward = b;
return a;
}
This works by finding the last leg in the TrainJourney for a and replacing the null marking the
end of a's list with list b (you need a special case if a has no elements).
Here's the problem: suppose a variable firstJourney contains the route from X to Y and a
variable secondJourney contains the route from Y to Z. If you call link(firstJourney,
secondJourney), this code destructively updates firstJourney to also contain secondJourney, so
in addition to the single user who requests a trip from X to Z seeing the combined journey as
 
Search WWH ::




Custom Search