Red-Green-Refactor

来源:互联网 发布:淘宝秒刷钻 编辑:程序博客网 时间:2024/05/24 06:24

Notice:

   The original article's link as "http://jamesshore.com/Blog/Red-Green-Refactor.html";


A lot of people liked my description of test-driven development during the Microsoft TDD flap. Here it is again so you can more easily bookmark it:

  1. Think: Figure out what test will best moveyour code towards completion. (Take as much time as you need. This isthe hardest step for beginners.)

  2. Red:Write a very small amount of test code. Only a few lines... usually nomore than five. Run the tests and watch the new test fail: the test barshould turn red. (This should only take about 30 seconds.)

  3. Green:Write a very small amount of production code. Again, usually no morethan five lines of code. Don't worry about design purity or conceptualelegance. Sometimes you can just hardcode the answer. This is okaybecause you'll be refactoring in a moment. Run the tests and watch thempass: the test bar will turn green. (This should only take about 30seconds, too.)

  4. Refactor: Now thatyour tests are passing, you can make changes without worrying aboutbreaking anything. Pause for a moment. Take a deep breath if you needto. Then look at the code you've written, and ask yourself if you canimprove it. Look for duplication and other "code smells." If you seesomething that doesn't look right, but you're not sure how to fix it,that's okay. Take a look at it again after you've gone through thecycle a few more times. (Take as much time as you need on this step.)After each little refactoring, run the tests and make sure they stillpass.

  5. Repeat: Do it again. You'llrepeat this cycle dozens of times in an hour. Typically, you'll runthrough several cycles (three to five) very quickly, then find yourselfslowing down and spending more time on refactoring. Than you'll speedup again. 20-40 cycles in an hour is not unreasonable.

This process works well for two reasons. First, you're working inbaby steps, constantly forming hypotheses and checking them. ("The barshould turn red now... now it should turn green... now it should stillbe green... now it should be red...") Whenever you make a mistake, youcatch it right away. It's only been a few lines of code since you madethe mistake, which makes the mistake very easy to find and fix. We allknow that finding mistakes, not fixing them, is the most expensive partof programming.

The other reason this process works well is that you're alwaysthinking about design. Either you're deciding which test you're goingto write next, which is an interface design process, or you're decidinghow to refactor, which is a code design process. All of this thought ondesign is immediately tested by turning it into code, which veryquickly shows you if the design is good or bad.


PS: When you're writing unit tests, be sure to follow Michael Feathers' guidelines.

原创粉丝点击