Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Functions - Two Functions or Last Optional Parameter

When writing recursive functions, it sometimes happens that something should happen only on the first pass of the recursive algorithm. When this is true, I have two options,

  1. Have an optional parameter called "first run" which is set to true by default but when called recursively, the argument is false
  2. Have two functions

Which option is preferable? If it is the latter, what should I name these functions? (e.g. if its a flood fill algorithm would I choose FloodFill and FloodFillRecursive?)

Thanks in advance, ell.

like image 921
Ell Avatar asked Jan 27 '26 12:01

Ell


1 Answers

I might use two functions, and I would say that the function that will be called should be named FloodFill : the user doesn't need to know how that function is implemented, so it should not be named FloodFillRecursive.


Actually, FloodFillRecursive could be the name of the inner function : the one that contains the implementation, the on that is called by the one called by the user -- as it is that second function that is recursive.
Ideally, that function should not be visible from the users : it should be kind of hidden in your library (be it trully hidden, or using some naming-convention that informs users they should not call it directly).

And, this way, if you change implementation, you will not have your users call a FloodFillRecursive function that might no be recursive anymore.

like image 136
Pascal MARTIN Avatar answered Jan 29 '26 13:01

Pascal MARTIN