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 preceding code satisfies the tests, but is not necessarily the final version. It served its purpose of getting code coverage as quickly as possible. Now, since we have tests that guarantee the integrity of the expected behavior, we can refactor the code:

private static final int SIZE = 3;public String play(int x, int y) {
  checkAxis(x);
  checkAxis(y);
  lastPlayer = nextPlayer();
  setBox(x, y, lastPlayer);
  if (isWin()) {
    return lastPlayer + " is the winner";
  }
  return "No winner";
}

private boolean isWin() {
  for (int i = 0; i < SIZE; i++) {
    if (board[0][i] + board[1][i] + board[2][i] == (lastPlayer * SIZE)) {
      return true;
    }
  }
  return false;
}

This refactored solution looks better. The play method keeps being short and easy to understand. ...

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