Best way to conditionally execute a function?

Yes, I know the wording is difficult to understand, but this is what really hurts me. In a recent project I have a function that recurses and there are a number of conditions that would cause it to stop recursing (three at the moment). Which situation would be optional? (IE best performance or ease of maintenance).

1) Conditional refund:

void myRecursingFunction (int i, int j){
    if (conditionThatWouldStopRecursing) return;
    if (anotherConditionThatWouldStopRecursing) return;
    if (thirdConditionThatWouldStopRecursing) return;

    doSomeCodeHere();
    myRecursingFunction(i + 1, j);
    myRecursingFunction(i, j + 1);
}

      

2) Wrap the whole thing in an if statement

void myRecursingFunction (int i, int j){
    if (
        !conditionThatWouldStopRecursing &&
        !anotherConditionThatWouldStopRecursing &&
        !thirdConditionThatWouldStopRecursing
    ){
        doSomeCodeHere();
        myRecursingFunction(i + 1, j);
        myRecursingFunction(i, j + 1);
    }
}

      

3) You are doing it wrong noob, no sane algorithm will ever use recursion.

+2


source to share


5 answers


Both of these approaches should result in the same IL code behind the scenes since they are equivalent to boolean expressions. Note that each termination condition will be evaluated in the order in which you write it (since the compiler cannot figure out which is most likely), so you will want to set the most common termination condition first.



Although structured programming dictates the second approach is better, I personally prefer the code to return conditions as a separate block at the top of the recursive method. I find it easier to read and read (although I'm not a fan of returns in random areas of the method body).

+6


source


I would go with the first solution as it is quite clear what conditions should stop the recursion. It's more readable and more maintainable imho.



+3


source


If this is what should be fast, I would recommend using the most common case as quickly as possible (i.e. putting the base case at the end, because you will only hit it once). Also consider putting base register-1 in front of the recursive clause (i.e., do the test before you call the function again, rather than checking it when writing to a subsequent call) if that would make a difference.

And, with all this stuff, don't optimize unless it's a problem. I went for clarity first.

+3


source


I like option 1 better ...

Option 2 is much easier to read. Here you must understand the 3 negatives and combine them all together with. I know this is not "hard" but it takes a lot longer and then look at option 1

+1


source


My vote for option # 1. This looks clearer to me.

0


source







All Articles