P Derlyuk wrote:Does anyone have any good tips when writing recursive methods?
Yes: DON'T.
Actually, that's a bit over the top, but it's not a bad base to work from:
Unless you have a good mathematics background, most of us find recursive logic quite difficult to follow; so if there's a simple way of solving the problem without recursion, it's probably better to use it.Any recursive method can be "unrolled" - and one test of how good a recursive solution is is how bad it looks when it is unrolled
.
My general rule of thumb is that if recursion provides a
logarithmic solution (ie, the maximum "depth" of calls required is
logₓ(n)), then it's probably the best way to go. It's also quite good for things like path or tree traversals since it isolates the logic to "what do I do now?", allowing you to forget about the rest of the structure (to some extent).
HIH
Winston