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

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.

主站蜘蛛池模板: 凉山| 红河县| 深水埗区| 东平县| 德昌县| 三河市| 南开区| 湟源县| 铁力市| 达孜县| 丹东市| 黄浦区| 通河县| 东至县| 集贤县| 扎赉特旗| 铁力市| 自治县| 光山县| 日土县| 牙克石市| 观塘区| 益阳市| 岢岚县| 泗水县| 太白县| 武陟县| 蕉岭县| 孝感市| 棋牌| 鹰潭市| 吉林省| 资阳市| 澎湖县| 承德县| 仁布县| 武定县| 顺昌县| 东丽区| 西平县| 韶山市|