mercredi 8 novembre 2023

Which pattern would you use to implement an "early-termination" logic?

In my project, I have several occurrences that needs verification on value using multiple conditions. Since satisfying at least one of these "conditions" is enough, and each conditions require heavy computation power, I usually try from the most lightweight one to the heaviest one, until any of them succeeds. To implement this, I usually use a pattern like below.

bool success

do {
    if (success = condition_1()) break
    if (success = condition_2()) break
    ...
} while (false)

if (!success) {
    cleanup()
} else {
    proceed()
}

The point is that I want to use the "break" statement, but to do this, I have to add a dummy do-while loop, which actually does nothing but provides context for the break statement. I doubt if doing so is okay. Would anybody have a recommendation for a better pattern on this situation?

These are the patterns I've tried as workarounds.

  • Separate the condition checks as a function, and using return statements instead of break => This is good, but sometimes I don't want to make too many functions.
  • Declare a common flag that indicates success, and run each condition if the flag is set false => This requires evaluation of if statements on each step, although their impacts on performance are minuscule.

Aucun commentaire:

Enregistrer un commentaire