- Test-Driven Java Development(Second Edition)
- Alex Garcia Viktor Farcic
- 163字
- 2021-06-24 18:31:55
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.
推薦閱讀
- 復雜軟件設計之道:領域驅動設計全面解析與實戰
- Python科學計算(第2版)
- Git Version Control Cookbook
- Getting Started with React
- 小程序,巧運營:微信小程序運營招式大全
- 大數據分析與應用實戰:統計機器學習之數據導向編程
- NGINX Cookbook
- SpringBoot從零開始學(視頻教學版)
- 高效使用Greenplum:入門、進階與數據中臺
- Java程序設計實用教程(第2版)
- 每個人的Python:數學、算法和游戲編程訓練營
- Implementing Domain:Specific Languages with Xtext and Xtend
- Python繪圖指南:分形與數據可視化(全彩)
- Serverless工程實踐:從入門到進階
- INSTANT EaselJS Starter