0

Say I have some complicated function that, through subsequent nested function calls, can potentially call itself, is there an accepted method to prevent this recursive call in the case where it is undesirable?

e.g.:

function h()
{
  if(someOtherState)
    f(); // uh-oh
}

function g()
{
  if(someState)
    h();
}

function f()
{
  g();
}
2
  • 2
    No chance refactoring out the circular dependency is an option, right? Commented Jul 11, 2022 at 13:56
  • Yeah, assume that's more complicated/impossible/time consuming than it's worth, versus just dealing with it post-hoc. Commented Jul 11, 2022 at 14:00

1 Answer 1

1

Invoking Cunningham's Law here (I am not really a JS developer), a way I've found that works is:

function f()
{
  if(f.inFunction)
    return;

  f.inFunction = true;
  // Some complicated/non-deterministic code that may call f() again
  f.inFunction = false;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Probably a good idea to wrap that in try/catch/finally so that the switch isn't inadvertently left true.
Also, if the code is written to expect that a recursive call will actually do something, I'm not sure how this helps. It might be better to throw an exception and move the test that realizes the code is in an invalid state closer to the origin.
Ah good point with the exception catching...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.