Suppose you write a simple program to play a number guessing game: “I’m thinking of a whole number between X and Y…” where the user attempts to guess the number in order to win. Failures that require feedback to the user come in three main flavors:
- The user guessed incorrectly
- The user’s guess was out of range
- The user did something silly, like enter a non-integer value
The do..while form
You can do this with a loop, of course. A do..while loop seems like a natural choice here. What I don’t like is the validation and user feedback in the while clause. You’d call out to a method that hides all of the validation logic, and returns true or false. This is OK, but that boolean method will have a side effect, i.e. feedback to the user.
do {
//increment guess count
//ask for input
//read in input
} while (
//input is wrong
);
The recursive form
An alternative implementation might use recursion:
static void elicitGuess() {
//increment guess count
//ask for input
//read in the input
//validate input inline
//Failure:
//display relevant feedback
//elicitGuess()
//else return
}
I find this second way to be more natural and readable. But it also feels like the wrong thing to do, though I can’t articulate why. Maybe it’s because any time I’ve seen code that followed this kind of pattern, I’ve seen it written using loops.
Thoughts?