O'Reilly logo

Test-Driven Java Development - Second Edition by Viktor Farcic, Alex Garcia

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Refactoring

The way we're handling possible diagonal wins, the calculation doesn't look right. Maybe the reutilization of the existing loop would make more sense:

private boolean isWin() {
  int playerTotal = lastPlayer * 3;
  char diagonal1 = '\0';
  char diagonal2 = '\0';
  for (int i = 0; i < SIZE; i++) {
    diagonal1 += board[i][i];
    diagonal2 += board[i][SIZE - i - 1];
    if (board[0][i] + board[1][i] + board[2][i]) == playerTotal) {
      return true;
    } else if (board[i][0] + board[i][1] + board[i][2] == playerTotal) {
      return true;
    }
  }
  if (diagonal1 == playerTotal || diagonal2 == playerTotal) {
    return true;
  }
  return false;
}

The source code can be found in the 03-wins branch of the tdd-java-ch03-tic-tac-toe Git repository at https://bitbucket.org/vfarcic/tdd-java-ch03-tic-tac-toe/branch/03-wins ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required