May sound a stupid question but towards the end of a method I need the method to run again so I have just called it again (within the same method) followed by “Return”.
It works but I’m wondering whether this is the best/safest way of handling this scenario or if I need to do it another way?
This can lead to stack overflow conditions. I would use the Calllater method of the timer http://developer.xojo.com/xojo-core-timer$CallLater which will place the call into the event loop. A delay of 0 ms is fine.
controlled method recursion is an acceptable and common programming practice… you just need to insure that the recursion can and does properly unwind itself.
One common use is in traversing a directory tree
function searchtree(dir as string)
for i=0 to dir.items.count
if dir.items(i).isDirectory then
searchTree(dir.items(i))
else
// item is a normal file
end if
next i
end function
note : this code is for illustration only, and doesn’t work as-is
I’m actually looping through an array item by item and processing data where I need to but theoretically the stack overflow or app freeze could still happen even with a timer or CallLater because I sometimes need to iterate over the same array index more than once to parse delimited data within it.
This could mean it gets stuck if I have programmed badly. So to avoid this perhaps I should log the array index value just parsed before the delayed timer call to a global property so the next time the method is about to be called it can make sure it doesn’t process the exact same timer call again if the array index is the same as the last time.
as Kem said, without know more its hard to give a good answer…
but here is another template to consider
DO
<loop thru your stuff>
if done then break
LOOP
this won’t cause a stack overflow, it MIGHT become an endless loop
and “done” depends on what you are doing… basically if you detect “need to iterate over the same array index more than once to parse delimited data within it.” then DONE=FALSE … the question becomes are you sure at some point DONE=TRUE???
When I use recursion (and I do it a lot lately) I try to find a solution which is called tail-recursion. It avoids the possible stack overflow issue (Tail call). I don’t know if the Xojo compiler implements this. I assume that the 64-bit one does “by nature”, but of course I don’t know the inner workings of Xojo’s LLVM usage.
Personally as a general rule I’d recommend to use recursion instead of loops.