问题
I always thought things that make your code uneasy to follow while being avoidable are considered as Bad Practice. Recursion seems to be one of these things (not to mention the problems it can cause like stack overflowing etc.), so I was a bit surprised when we had to learn working seriously with them during a programming course (for it ocassionally results in shorter code). And it seems to me there is a disagreement about it between the professors too...
People already asked this specific to languages (like Python, where a comment compared it to a goto
statement), mostly specific to a problem, but I am interested in general:
Is recursion considered as a Bad Practice or not in the modern programming? When should I avoid it, and are there any circumstances when can't?
Related questions I found:
Is recursion a feature in and of itself? (does not discuss whether it is good or bad)
Is recursion ever faster than looping? (answer describes that recursion can result in improvements in functional languages, but is expensive in others), also other questions discussing the performance
回答1:
Recursive programming is not a bad practice. It is a tool in your toolbox and like any tool, when it's the only tool used that's when bad things happen. Or when it's used out of a proper context.
When do you use recursion? It's good when you have a tree dataset that you need to perform the same logic upon. For example: You have a tree list of string elements and you wish to calculate total length of all strings, down one branch. You'd define a method to calculate the length of a list element and then see if the element has a sibling and if it does call the method, passing the sibling - and the process starts over.
The most common pitfall would be of a stack overflow. When the list is so large, it can't be handled all at once. So you would implement checks to ensure this never happens. Such as breaking the linked list down into manageable pieces and in your function, utilize a static variable to track the number of levels you traverse - bailing once that number is exceeded.
You should avoid using when your dataset is not a tree type dataset. The only time I can think of that you actually can't avoid using recursion is in programming languages that do not support looping (Haskell).
来源:https://stackoverflow.com/questions/41469031/is-recursion-a-bad-practice-in-general