Nicole Carpenter
Web Developer

Wrappers


10 Jun 2016

I started to hear the term “wrapper” during my apprenticeship, and I generally used context clues to decide on its meaning, but I thought I would take a closer look.

Using a wrapper, or wrapping a specific function, came up first when I was working with my hangman application’s input/output methods. My mentor encouraged me to wrap the system actions like print and readline in application functions so their behavior could be tested. More recently, I read and heard the term while working on my minimax variants. In that case the wrapper was a driver function that would call the minimax/negamax function, separating the return from the recursive functionality to improve performance and hide some of the algorithm’s complexity.

Wrapping functions is also useful when working with third party APIs. This would work similar to when I wrapped my system function in the hangman application because I own neither the system functions nor the API functions. While system functions are more stable, we would wrap APIs because they are potentially unstable.

Say you are working with a third party API and call a number of its functions in your application, in multiple places. What happens if the API is updated and the method names or arguments change? If your application calls directly to the API functions, you would have to change every occurrence of the function within the application.

Wrapping API functions would mean that you make functions within your own application to call to the API’s functions, and your application would call to these functions rather than directly to the API. Now, if the application changes something with the functions, the only thing that would have to change would be the wrapper functions, as these would be the only connection point between the application and the API. If this sounds familiar, it’s because this is exactly what I was talking about when discussing the Adapter Pattern in a previous post. The Facade Pattern also creates a wrapper interface in its implementation.

Beyond wrapping at a method level, classes can also wrap the functionality of other classes. This would typically come in the form of one class that contains an instance of another class so as not to directly expose the instance. The class in which the wrapped class is contained is encapsulating the other class instance, deepening its level of abstraction.