- Test-Driven Java Development(Second Edition)
- Alex Garcia Viktor Farcic
- 211字
- 2021-06-24 18:31:53
Refactoring
While the code that we have done so far fulfills the requirements set by the tests, it looks a bit confusing. If someone read it, it would not be clear as to what the play method does. We should refactor it by moving the code into separate methods. The refactored code will look like the following:
public void play(int x, int y) { checkAxis(x); checkAxis(y); setBox(x, y); } private void checkAxis(int axis) { if (axis < 1 || axis > 3) { throw new RuntimeException("X is outside board"); } } private void setBox(int x, int y) { if (board[x - 1][y - 1] != '\0') { throw new RuntimeException("Box is occupied"); } else { board[x - 1][y - 1] = 'X'; } }
With this refactoring, we did not change the functionality of the play method. It behaves exactly the same as it behaved before, but the new code is a bit more readable. Since we had tests that covered all the existing functionality, there was no fear that we might do something wrong. As long as all tests are passing all the time and refactoring did not introduce any new behavior, it is safe to make changes to the code.
The source code can be found in the 01-exceptions branch of the tdd-java-ch03-tic-tac-toe Git repository at https://bitbucket.org/vfarcic/tdd-java-ch03-tic-tac-toe/branch/01-exceptions.
- 在最好的年紀(jì)學(xué)Python:小學(xué)生趣味編程
- 圖解Java數(shù)據(jù)結(jié)構(gòu)與算法(微課視頻版)
- Mastering Selenium WebDriver
- PyTorch Artificial Intelligence Fundamentals
- Django:Web Development with Python
- 匯編語(yǔ)言程序設(shè)計(jì)(第2版)
- Linux命令行與shell腳本編程大全(第4版)
- Visual Basic程序設(shè)計(jì)教程
- SQL Server 入門很輕松(微課超值版)
- Visual Basic語(yǔ)言程序設(shè)計(jì)基礎(chǔ)(第3版)
- C語(yǔ)言程序設(shè)計(jì)與應(yīng)用實(shí)驗(yàn)指導(dǎo)書(第2版)
- PHP動(dòng)態(tài)網(wǎng)站開發(fā)實(shí)踐教程
- 編程的原則:改善代碼質(zhì)量的101個(gè)方法
- Node.js Web Development
- Mastering Magento Theme Design