Recursion implementation techniques
There are a few implementation issues that should be addressed. These include the use of wrapper methods and short-circuiting the base case. These techniques can assist in the use of recursion.
Using a wrapper method
A wrapper method is used to support recursion. This method will not actually perform recursion but will call one that does. The wrapper method may:
Validate parameters
Perform initialization
Handle exceptions as errors are generated
The following is an example of a wrapper method for the arrayTotal
method, which is duplicated here for your convenience:
public int arrayTotal(int numbers[], int index) { if (index == 0) { return numbers[0]; } else { return numbers[index] + arrayTotal(numbers, index - 1); } }
In the arrayTotalHelper
method, the index
variable is checked to see if it is within the bounds of the array. If it is not, then the exception needs to be handled:
public int arrayTotalHelper...