Skip to content
Advertisement

what is wrapper function and how to use it?

For my homework, I am required to use a function called wrapper function to validate the parameter for a recursive function, which I don’t understand what it means. All i understand from wrapper function is it does nothing but just wraps around a function eg:

private static int recursive(int n){
    //do something
    .
    .
    .
}

public static int recursiveWrap(int n){
    return recursive(n);
}

I dont even know if the code above is the correct implementation for wrapper, but I know that it does nothing for the recursive function but just redundancy.

How am I supposed to use the wrapper function to validate the parameter? my recursive function has a base case which it will reach without the help of wrapper.

Advertisement

Answer

Well, a wrapper function would serve a purpose (otherwise there would be no reason for it to exist).

One such purpose could be to first validate the input before calling the actual recursive function (as is the case in your example), e.g. like this:

public static int recursive(int n){
   //do something
   .
   .
   .
}

public static int recursiveWrap(int n){
   if( n < 0 ) {
     throw new IllegalArgumentException("only positive arguments are allowed");
   }
   return recursive(n); 
}

Another purpose could be to provide a convenient entry point for recursion, e.g. for quicksort (I’ll just use int[] for simplicity reasons, a real world example would more likely use generic arrays or lists):

private static void recursiveQS(int[] array, int left, int right) {
  //actual implementation here
}

//that's what the user would call
public static void quickSort(int[] array) {
   recursiveQS(array, 0, array.length);
}

Why would you want to use wrapper functions? There are multiple possible reasons:

  • Keep the recursive function as simple as possible.
  • Validation checks often need to be done once so doing it in the recursive function would execute unnecessary code (and thus result in lower performance).
  • Provide a simple entry point for callers and handle any parameter mapping, setup etc. in the wrapper.
  • For more general purpose recursive functions there might be special validation or setup that only applies to certain situations and types of parameters. In those cases you might want to provide special wrapper functions for the special cases, i.e. you again keep the recursive function as simple as possible.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement