Recursive Call - Implementation Issues - Short-circuiting The Base Case

Short-circuiting The Base Case

Short-circuiting the base case, also known as arm's-length recursion, consists of checking the base case before making a recursive call – i.e., checking if the next call will be the base case, instead of calling and then checking for the base case. Short-circuiting is particularly done for efficiency reasons, to avoid the overhead of a function call that immediately returns. Note that since the base case has already been checked for (immediately before the recursive step), it does not need to be checked for separately, but one does need to use a wrapper function for the case when the overall recursion starts with the base case itself. For example, in the factorial function, properly the base case is 0! = 1, while immediately returning 1 for 1! is a short-circuit, and may miss 0; this can be mitigated by a wrapper function.

Short-circuiting is primarily a concern when many base cases are encountered, such as Null pointers in a tree, which can be linear in the number of function calls, hence significant savings for O(n) algorithms; this is illustrated below for a depth-first search. Short-circuiting on a tree corresponds to considering a leaf (non-empty node with no children) as the base case, rather than considering an empty node as the base case. If there is only a single base case, such as in computing the factorial, short-circuiting provides only O(1) savings.

Conceptually, short-circuiting can be considered to either have the same base case and recursive step, only checking the base case before the recursion, or it can be considered to have a different base case (one step removed from standard base case) and a more complex recursive step, namely "check valid then recurse", as in considering leaf nodes rather than Null nodes as base cases in a tree. Because short-circuiting has a more complicated flow, compared with the clear separation of base case and recursive step in standard recursion, it is often considered poor style, particularly in academia.

Read more about this topic:  Recursive Call, Implementation Issues

Famous quotes containing the words base and/or case:

    The base of all artistic genius is the power of conceiving humanity in a new, striking, rejoicing way, of putting a happy world of its own creation in place of the meaner world of common days, of generating around itself an atmosphere with a novel power of refraction, selecting, transforming, recombining the images it transmits, according to the choice of the imaginative intellect. In exercising this power, painting and poetry have a choice of subject almost unlimited.
    Walter Pater (1839–1894)

    Socialists make the mistake of confusing individual worth with success. They believe you cannot allow people to succeed in case those who fail feel worthless.
    Kenneth Baker (b. 1934)