- 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.
推薦閱讀
- Learning PostgreSQL
- Kubernetes實戰
- Pandas Cookbook
- Azure IoT Development Cookbook
- Practical DevOps
- Java EE 7 Development with NetBeans 8
- 大學計算機基礎(第2版)(微課版)
- Python Web數據分析可視化:基于Django框架的開發實戰
- Learning Concurrency in Kotlin
- 微信小程序開發與實戰(微課版)
- 用戶體驗可視化指南
- OpenStack Networking Essentials
- Mastering Unreal Engine 4.X
- 信息學奧林匹克競賽初賽精講精練
- Docker on Windows