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

While the code that we have done so far fulfills the requirements set by the tests, it looks a bit confusing. If someone read it, it would not be clear as to what the play method does. We should refactor it by moving the code into separate methods. The refactored code will look like the following:

public void play(int x, int y) {
  checkAxis(x);
  checkAxis(y);
  setBox(x, y);
}

private void checkAxis(int axis) {
  if (axis < 1 || axis > 3) {
    throw new RuntimeException("X is outside board");
  }
}

private void setBox(int x, int y) {
  if (board[x - 1][y - 1] != '\0') {
    throw new RuntimeException("Box is occupied");
  } else {
    board[x - 1][y - 1] = 'X';
  }
}

With this refactoring, we did not change the functionality of the play method. It behaves ...

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