Refactoring

Even though the isWin method is not the scope of the last test, it can still be refactored even more. For once, we don't need to check all the combinations, but only those related to the position of the last piece played. The final version could look like the following:

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

Refactoring can be done on any part of the code at any time, as long as all the tests are successful. While it's often easiest and fastest to refactor the code that was just written, going back to something that was written the other day, previous month, or even years ago, is more than welcome. The best time to refactor something is when someone sees an opportunity to make it better. It doesn't matter who wrote it or when; making the code better is always a good thing to do.

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.170.63