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

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. Winning logic is moved to a separate method. Not only have we kept the play method's purpose clear, but this separation also allows us to grow the winning condition's code in separation from the rest.

主站蜘蛛池模板: 通江县| 临城县| 修水县| 乌拉特后旗| 铜鼓县| 许昌县| 海伦市| 民丰县| 闵行区| 承德市| 株洲市| 宁陕县| 高碑店市| 齐河县| 黄冈市| 岳西县| 红河县| 和田县| 赤水市| 上思县| 南澳县| 德昌县| 县级市| 康马县| 察雅县| 出国| 正宁县| 云南省| 乐安县| 香港| 邯郸市| 江北区| 吉水县| 多伦县| 视频| 蓬安县| 寻乌县| 博乐市| 嘉峪关市| 本溪市| 秭归县|