Is it always a good practice to wrap a recursive function?

拈花ヽ惹草 提交于 2021-02-10 11:51:37

问题


I am using a recursive function to calculate the number of possible traversals through a graph starting from a node and ends with another given a set of rules (eg: minimum/maximum/exact number of stops).

I am wondering if it is a good practice to call a wrapper function that calls the recursive function instead of calling it directly. Most of the time I see people use a wrapper function.

Just wondering why and what are the pros and cons and in what situations must we wrap it?


回答1:


No, it's not always necessary. You only need to wrap it when you have a specific reason to. Here are a couple of reasons you might need to wrap it:

  • If the arguments it passes to itself are different from the arguments it receives in the initial call, for whatever reason
    • Perhaps the recursion arguments are complex and it would be difficult for the caller to supply appropriate initial values for them
    • Perhaps the initial arguments are markedly different from the recursive ones
  • If you need the starting position (e.g., the wrapper) to have a different access level than the recursive method itself.

There are probably several more.

But lots of recursive methods don't need wrapping. For instance, the classic depth-first node traversal method with a predicate doesn't need anything special passed during recursion vs. during the initial call, so there's no need to wrap it.




回答2:


a recursive function usually require an argument that represents cumulative result from previous call. a hypothetical example from the problem domain would be

public int numberOfPossibleTraversals(Node node, List<Rule> rules) { ...

so the first arg is modified in each recursive call. You start the chain of calls with a starter value like this

int c = numberOfPossibleTraversals(root, rules);

sometimes (depending on the specific implementation) establishing starter values for the cumulative args may require some logic/processing. that is where "wrapper" methods may come into play. for example, the graph itself may have such a wrapper function that builds the args for the recursive function



来源:https://stackoverflow.com/questions/57690062/is-it-always-a-good-practice-to-wrap-a-recursive-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!