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

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.

主站蜘蛛池模板: 沐川县| 吉安县| 武清区| 吕梁市| 彭水| 韩城市| 鄱阳县| 五大连池市| 丹江口市| 玉环县| 瓮安县| 湘潭市| 白沙| 东海县| 定西市| 南召县| 阿拉尔市| 金门县| 静宁县| 沈丘县| 定结县| 双流县| 扎赉特旗| 秭归县| 嵩明县| 黑山县| 邛崃市| 南宁市| 英吉沙县| 玉屏| 壤塘县| 马公市| 积石山| 峨边| 息烽县| 贵南县| 茶陵县| 章丘市| 金寨县| 静安区| 合水县|