Chapter 1: A Test-Driven Fable
第ㄧ章開頭以小故事說明測試的重要性,在故事中主角 Jamie 因為選擇以先寫測試,再寫登入網站功能程式碼,因此在軟體開發的初期花費許多的時間。相比之下,另ㄧ個主角 Sam 則是選擇直接開始開發登入功能,而更快速地完成目標。
不過,當程式碼需要重構時,Jamie 卻能更快速的完成重構而準時搭上回家的火車。故事的意義在於,以寫測試為驅動的開發模式,長期來看,其實更是節省時間成本的軟體開發模式。
Testing Fist Drives Design
Test-driven development (TDD) 是一種以寫測試為驅動的開發模式,也就是先把規格及測試寫好、再開發需要的程式撰寫。這樣的模式雖然被認為是違反直覺的,但卻有能夠提升設計及優化程式碼的好處。
優良的 TDD 會有以下過程:
- 建立測試
- 確認在預定設定下,測試會失敗
- 撰寫最簡單就能夠成功的測試
- 通過測試後,重構並優化程式碼
TDD 可以讓我們設計軟體上保有持續性的創新,並能將創新的設計融入在程式碼中。
一般來說,在測試驅動開發流程(test-driven process)中會有以下三種情形:
-
When you decide which test to write next, you’re making a claim about what functionality your code should have. This frequently involves thinking about how to add that functionality to the existng code, which is a design question.
-
As you write a test, you’re designing the interaction between the test and the code, which is also the interaction between the part of the code under test and the rest of the application. This part of the process is used to create the API you want the code to have.
-
After the test passes, you refactor, identifying duplication, missing abstractions, and other ways the code’s desgin can be improved.
To be continued…
Comments