官术网_书友最值得收藏!

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 exactly the same as it behaved before, but the new code is a bit more readable. Since we had tests that covered all the existing functionality, there was no fear that we might do something wrong. As long as all tests are passing all the time and refactoring did not introduce any new behavior, it is safe to make changes to the code.

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

主站蜘蛛池模板: 南涧| 台州市| 青龙| 浏阳市| 二手房| 巴林左旗| 鄂尔多斯市| 屏山县| 资源县| 衡阳县| 达拉特旗| 泰兴市| 新闻| 北票市| 平罗县| 乌恰县| 邳州市| 布尔津县| 仲巴县| 济源市| 通州区| 来凤县| 天等县| 平泉县| 黎平县| 庆安县| 岳普湖县| 绥化市| 济源市| 湛江市| 墨脱县| 湾仔区| 卓资县| 上栗县| 合山市| 宣威市| 吐鲁番市| 延吉市| 大埔县| 大渡口区| 彝良县|