Java Tic Tac Toe — Don’t Repeat Yourself Part Two

Yesterday I posted about the struggles I was having getting rid of some of the repetition in my code. I was using a While loop, but since each one had a different condition to satisfy, I was struggling to combine them all into one.

First thing in the morning, I paired with one of the other apprentices who suggested that I use recursion rather than a while loop. I think this is a much cleaner way of doing it. Here’s how my loop to check for a valid integer works:

int getInteger() {
try {
return input.nextInt();
} catch (InputMismatchException e) {
return getInteger();

In my IPM I discussed my concern about this repetition with my mentor, and we discussed different options to remove this duplication. We ended up agreeing on changing it so that each time I want to validate input, I can pass in a list of valid options. Then I just have to validate that it is a legal option.

In the end I replaced all three of my loops with:

public int validateSelection(List<Integer> options){
int selection = getInteger();
if (options.contains(selection)){
return selection;
} else {
return validateSelection(options);

Each time I use this, I have a for loop that creates an Integer list of valid selections, and pass that in.

This next week I’m going to be focusing on implementing the rest of my feedback, aggressively reducing duplication, having a 3x3 or 4x4 game type, drawing a UML diagram, trying out using a factory method to create my game types, and if I have time I’ll start implementing Minimax to make an unbeatable computer player.

In housekeeping news, I’m considering back to using Medium exclusively. I’d initially started this one as a way to get more comfortable using Vim, and while that has helped, I think I prefer the way that Medium displays text while writing. I’ll post a link on this site if I do end up going back to Medium.

Originally published on Jekyll

Like what you read? Give Dan Pelensky a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.