Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^536) | Array-Based Lists
to an input operation; it accesses the current item and then increments currentPos. When
currentPosreaches numItems, we reset it to 0.
We mentioned earlier that we need to keep the client from performing deletions and in-
sertions during an iteration. Let’s review how methods within a class might interact to
change the state of the list and thus cause problems. In Chapter 5, we discussed the concept
of state and mutable and immutable objects. Clearly, a Listobject is a mutable object, because
transformer methods are defined for it.resetListchanges the state variable currentPos.in-
sertand deletechange not only the contents of the list structure, but also the state variable
numItems. Likewise,getNextItemchanges the internal state of currentPos.
We need to monitor the interactions of these transformers carefully. IfcurrentPosis reset
during successive calls togetNextItem, the iteration just begins again. Ifinsertordeleteis in-
voked during an iteration, however, several things could happen. For example,currentPoscould
now be greater thannumItems, causinggetNextItemto send back an item no longer in the list.To
solve this problem of interacting transformers, we have chosen to place a precondition on the
methodgetNextItem: No transformer methods have been called since the last call togetNextItem.
public voidresetList()
// The iteration is initialized by setting currentPos to 0
{
currentPos = 0;
}
publicString getNextItem()
// Returns the item at the currentPos position; resets
// current position to first item after the last item is returned
// Assumption: no transformers have been invoked since last call
{
String next = listItems[currentPos];
if (currentPos == numItems-1)
currentPos = 0;
else
currentPos++;
returnnext;
}
Both of the methods change currentPos. Shouldn’t we consider them to be transformers?
We could certainly argue that they are, but their intentionis to set up an iteration through the
items in the list, returning one item at a time to the client.


Test Plan


The documentation for the methods in the class Listdetermines the tests necessary for a
black-box testing strategy. The code of the methods indicates a need for a clear-box testing
strategy. Thus, to test the Listclass implementation, we use a combination of black-box and
clear-box strategies. We first test the constructor by seeing whether the list is empty (in
which case a call to lengthreturns 0).
Free download pdf