包装递归函数是否总是一个好习惯? [英] Is it always a good practice to wrap a recursive function?
问题描述
我正在使用递归函数来计算从一个节点开始并以另一个给定的一组规则(例如:最小/最大/精确的停靠点数)结束的整个图形的可能遍历次数.
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?
推荐答案
不,并非总是必要的.仅在有特定原因时才需要包装它.您可能需要将其包装的几个原因如下:
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:
- 如果传递给自身的参数与它在初始调用中接收到的参数不同,则无论出于何种原因
- 也许递归参数很复杂,调用者很难为其提供适当的初始值
- 也许初始参数与递归参数明显不同
可能还有更多.
但是许多递归方法不需要包装.例如,带有谓词的经典深度优先节点遍历方法不需要在递归过程中传递任何特殊条件,而在初始调用过程中则不需要传递任何特殊条件,因此无需将其包装.
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.
这篇关于包装递归函数是否总是一个好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!