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

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.

主站蜘蛛池模板: 彩票| 盐边县| 陈巴尔虎旗| 泰宁县| 京山县| 河北省| 莫力| 江油市| 沅陵县| 西丰县| 昂仁县| 贵州省| 庆安县| 巧家县| 古田县| 武功县| 长泰县| 密云县| 昌邑市| 红原县| 尉犁县| 会泽县| 霍城县| 大同市| 贵德县| 高邑县| 凤山市| 大田县| 英德市| 县级市| 达孜县| 富蕴县| 峨边| 比如县| 新龙县| 临清市| 莒南县| 依安县| 丹阳市| 色达县| 新乡市|