Implementation

This specification poses a couple of challenges. First, where should we place the invocation of the saveMove method? The setBox private method looks like a good place. That's where we are doing validations of if the turn is valid, and if it is, we can call the saveMove method. However, that method expects a bean instead of the variables x, y, and lastPlayer that are being used right now, so we might want to change the signature of the setBox method.

This is how the method looks now:

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

This is how it looks after the necessary changes are applied:

private void setBox(TicTacToeBean bean) {
  if (board[bean.getX() - 1][bean.getY() - 1] != '') {
    throw new RuntimeException("Box is occupied");
  } else {
    board[bean.getX() - 1][bean.getY() - 1] = lastPlayer;
    getTicTacToeCollection().saveMove(bean);
  }
}

The change of the setBox signature triggers a few other changes. Since it is invoked from the play method, we'll need to instantiate the bean there:

public String play(int x, int y) {
  checkAxis(x);
  checkAxis(y);
  lastPlayer = nextPlayer();
// setBox(x, y, lastPlayer);
  setBox(new TicTacToeBean(1, x, y, lastPlayer));
  if (isWin(x, y)) {
    return lastPlayer + " is the winner";
  } else if (isDraw()) {
    return RESULT_DRAW;
  } else {
    return NO_WINNER;
  }
}

You might have noticed that we used a constant value 1 as a turn. There is still no specification that says otherwise, so we took a shortcut. We'll deal with it later.

All those changes were still very simple, and it took a reasonably short period of time to implement them. If the changes were bigger, we might have chosen a different path; and made a simpler change to get to the final solution through refactoring. Remember that speed is the key. You don't want to get stuck with an implementation that does not pass tests for a long time.

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

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