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

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.

主站蜘蛛池模板: 罗田县| 涡阳县| 买车| 南开区| 阜城县| 岢岚县| 霍城县| 台东县| 清新县| 甘南县| 天祝| 奉节县| 新源县| 丰城市| 望谟县| 三明市| 南溪县| 通海县| 如东县| 洞口县| 婺源县| 永城市| 阜宁县| 隆安县| 临猗县| 阿瓦提县| 望江县| 湘西| 黔江区| 确山县| 陵水| 开平市| 益阳市| 平原县| 屏南县| 府谷县| 三亚市| 监利县| 梅河口市| 碌曲县| 定兴县|