Function Wrapper

FunctionWrapper is a design pattern used when dealing with relatively complicated functions with multiple (logical) points of exit, and you want to make sure that certain cleanup actions always occur. If multiple return statements exist; it is highly likely that one of these will forget to do whatever cleanup is required. Many people dislike GoTo statements (to a "cleanup" block at the end); and the ArrowAntiPattern is ugly.

This is especially applicable in languages without ExceptionHandling and/or constructs like UnwindProtect or "always" blocks. In languages without GarbageCollection, this is especially important.

The pattern is as follows:

The function is broken up into two functions--one (the wrapper) is externally visible and is what client code calls. The other is usually only internally visible (static, private, lexically nested, etc.). The wrapper function does the following:

The wrapped function does the dirty work of the computation. Since it is freed from having to worry about resource allocation and de-allocation, it can have multiple exit points without the programmer having to worry about freeing all resources correctly.

FunctionWrapper is useful for other things besides resource management:

Plus, if you add state to your FunctionWrapper and turn it from a function to a full-fledged object, you have the HandleBodyPattern


CategoryDesignPattern?


EditText of this page (last edited September 9, 2004) or FindPage with title or text search