ScarletAmaranth
ScarletAmaranth

Reputation: 5101

Suggested flow-control structure for order-dependant operations

I've run into the following issue which is not difficult to solve by any stretch of the imagination but I would like to know what the best / most elegant solution is.

I have the following method that the prototype of looks like this:

bool Team::isEveryoneDead(int teamOnTurn);

There are two teams available and depending on what instance of the team is currently on turn, I would like to check whether every Character in the team is dead in this very particular order:

  1. Loop trough all the Characters in the team that's not on turn first. Should there be any character that's alive, stop looping (and goto step 2.). Should there be noone alive, terminate the function and return.

  2. Now that I know that the team that's not on turn contains at least one character that's alive, loop trough the team that's currently on turn and check for the same thing. Should I find someone alive, stop looping and terminate / return.

The argument int teamOnTurn allows me to resolve the instance of Team that's currently on turn. The order in which i evaluate the "alive condition" is of great importance here.

Now, there are several approaches that can be taken, say hardcoding the order (since there are only 2 possible orders) and resolving the order by checking who's on turn and then executing the branch that already has the specific order like this:

bool Team::isEveryoneDead(int teamOnTurn) {
    if (Team::Blue == teamOnTurn) {
        checkThis();
        checkThat();
    } else {
        checkThat();
        checkThis();
    }
} 

This solution however wouldn't quite work for say 5! permutations for specific call-ordering for more items. What technique should one deploy to solve this with the utmost elegance :) ?

Thanks in advance, Scarlet.

Upvotes: 0

Views: 66

Answers (1)

Brady
Brady

Reputation: 10357

Try creating another internal method that actually does the checking, and let the isEveryoneDead() method orchestrate the order in which the teams are checked, maybe something like this:

bool Team::isEveryoneDead(int teamOnTurn) {
    bool isFound = isEveryoneDeadInternal( /* params for team not on turn */ );
    if(isFound) {
        isFound = isEveryoneDeadInternal( /* params for team on turn */ );
    }
    return isFound;
} 

// This method know nothing about on turn or off turn
bool Team:isEveryoneDeadInternal() {
    // Loop through all characters in the team, checking if any are alive
    // When the first live character is found, return true
    // else return false
}

This is a concept called DRY : Dont Repeat Yourself

Upvotes: 1

Related Questions