Test Driven Development: By Example

Paperback (Print)
Rent
Rent from BN.com
$12.44
(Save 75%)
Est. Return Date: 12/20/2014
Used and New from Other Sellers
Used and New from Other Sellers
from $18.37
Usually ships in 1-2 business days
(Save 63%)
Other sellers (Paperback)
  • All (18) from $18.37   
  • New (9) from $31.32   
  • Used (9) from $18.37   

Overview

Clean code that works--now. This is the seeming contradiction that lies behind much of the pain of programming. Test-driven development replies to this contradiction with a paradox--test the program before you write it.

A new idea? Not at all. Since the dawn of computing, programmers have been specifying the inputs and outputs before programming precisely. Test-driven development takes this age-old idea, mixes it with modern languages and programming environments, and cooks up a tasty stew guaranteed to satisfy your appetite for clean code that works--now.

Developers face complex programming challenges every day, yet they are not always readily prepared to determine the best solution. More often than not, such difficult projects generate a great deal of stress and bad code. To garner the strength and courage needed to surmount seemingly Herculean tasks, programmers should look to test-driven development (TDD), a proven set of techniques that encourage simple designs and test suites that inspire confidence.

By driving development with automated tests and then eliminating duplication, any developer can write reliable, bug-free code no matter what its level of complexity. Moreover, TDD encourages programmers to learn quickly, communicate more clearly, and seek out constructive feedback.

Readers will learn to:

  • Solve complicated tasks, beginning with the simple and proceeding to the more complex.
  • Write automated tests before coding.
  • Grow a design organically by refactoring to add design decisions one at a time.
  • Create tests for more complicated logic, including reflection and exceptions.
  • Use patterns to decide what tests to write.
  • Create tests using xUnit, the architecture at the heart of many programmer-oriented testing tools.

This book follows two TDD projects from start to finish, illustrating techniques programmers can use to easily and dramatically increase the quality of their work. The examples are followed by references to the featured TDD patterns and refactorings. With its emphasis on agile methods and fast development strategies, Test-Driven Development is sure to inspire readers to embrace these under-utilized but powerful techniques.

0321146530B10172002

Read More Show Less

Editorial Reviews

From Barnes & Noble
The Barnes & Noble Review
Every developer wants to write clean code that works -- but somehow, forces always seem to conspire to prevent that. Kent Beck has spent a career on the problem of improving software development: you probably know him best for inventing Extreme Programming (XP).

XP relies heavily on incremental testing. But this often slips up implementers, for whom constant testing represents a radical change. In Test-Driven Development, Beck brings testing to life, showing exactly how to use it to close the gap between decisions and feedback.

“TDD” has only two rules. No. 1: Write new code only if you first have a failing automated test. No. 2: Refactor constantly to eliminate duplication. But these rules have complex and subtle implications. You must “design organically,” making decisions based on whether your code passes its test. You must organize your development environment so this is possible. You must write your own tests: you can’t wait for specialists. And your designs must consist of highly cohesive, loosely coupled components: otherwise, micro-scale testing is simply impossible.

If this still sounds difficult at best, Beck demonstrates TDD through a book-length case study. Its “in-practice” workings will surprise you -- and, we think, convince you. Bill Camarda

Bill Camarda is a consultant, writer, and web/multimedia content developer. His 15 books include Special Edition Using Word 2000 and Upgrading & Fixing Networks For Dummies®, Second Edition.

Read More Show Less

Product Details

  • ISBN-13: 9780321146533
  • Publisher: Addison-Wesley
  • Publication date: 11/22/2002
  • Series: Addison-Wesley Signature Series
  • Edition description: New Edition
  • Pages: 220
  • Sales rank: 194,529
  • Product dimensions: 7.30 (w) x 9.10 (h) x 0.80 (d)

Meet the Author

Kent Beck consistently challenges software engineering dogma, promoting ideas like patterns, test-driven development, and Extreme Programming. Currently affiliated with Three Rivers Institute and Agitar Software, he is the author of many Addison-Wesley titles.

Read More Show Less

Read an Excerpt

Clean code that works, in Ron Jeffries' pithy phrase, is the goal of Test-Driven Development (TDD). Clean code that works is a worthwhile goal for a whole bunch of reasons.

  • It is a predictable way to develop. You know when you are finished, without having to worry about a long bug trail.
  • It gives you a chance to learn all of the lessons that the code has to teach you. If you only slap together the first thing you think of, then you never have time to think of a second, better thing.
  • It improves the lives of the users of your software.
  • It lets your teammates count on you, and you on them.
  • It feels good to write it.

But how do we get to clean code that works? Many forces drive us away from clean code, and even from code that works. Without taking too much counsel of our fears, here's what we do: we drive development with automated tests, a style of development called Test-Driven Development (TDD). In Test-Driven Development, we

  • Write new code only if an automated test has failed
  • Eliminate duplication

These are two simple rules, but they generate complex individual and group behavior with technical implications such as the following.

  • We must design organically, with running code providing feedback between decisions.
  • We must write our own tests, because we can't wait 20 times per day for someone else to write a test.
  • Our development environment must provide rapid response to small changes.
  • Our designs must consist of many highly cohesive, loosely coupled components, just to make testing easy.

The two rules imply an order to the tasks of programming.

  • Red—Write a little test that doesn't work, and perhaps doesn't even compile at first.
  • Green—Make the test work quickly, committing whatever sins necessary in the process.
  • Refactor—Eliminate all of the duplication created in merely getting the test to work.

Red/green/refactor—the TDD mantra.

Assuming for the moment that such a programming style is possible, it further might be possible to dramatically reduce the defect density of code and make the subject of work crystal clear to all involved. If so, then writing only that code which is demanded by failing tests also has social implications.

  • If the defect density can be reduced enough, then quality assurance (QA) can shift from reactive work to proactive work.
  • If the number of nasty surprises can be reduced enough, then project managers can estimate accurately enough to involve real customers in daily development.
  • If the topics of technical conversations can be made clear enough, then software engineers can work in minute-by-minute collaboration instead of daily or weekly collaboration.
  • Again, if the defect density can be reduced enough, then we can have shippable software with new functionality every day, leading to new business relationships with customers.

So the concept is simple, but what's my motivation? Why would a software engineer take on the additional work of writing automated tests? Why would a software engineer work in tiny little steps when his or her mind is capable of great soaring swoops of design? Courage.

Courage

Test-driven development is a way of managing fear during programming. I don't mean fear in a bad way—pow widdle prwogwammew needs a pacifiew-but fear in the legitimate, this-is-a-hard-problem-and-I-can't-see-the-end-from-the-beginning sense. If pain is nature's way of saying "Stop!" then fear is nature's way of saying "Be careful." Being careful is good, but fear has a host of other effects.

  • Fear makes you tentative.
  • Fear makes you want to communicate less.
  • Fear makes you shy away from feedback.
  • Fear makes you grumpy.

None of these effects are helpful when programming, especially when programming something hard. So the question becomes how we face a difficult situation and,

  • Instead of being tentative, begin learning concretely as quickly as possible.
  • Instead of clamming up, communicate more clearly.
  • Instead of avoiding feedback, search out helpful, concrete feedback.
  • (You'll have to work on grumpiness on your own.)

Imagine programming as turning a crank to pull a bucket of water from a well. When the bucket is small, a free-spinning crank is fine. When the bucket is big and full of water, you're going to get tired before the bucket is all the way up. You need a ratchet mechanism to enable you to rest between bouts of cranking. The heavier the bucket, the closer the teeth need to be on the ratchet.

The tests in test-driven development are the teeth of the ratchet. Once we get one test working, we know it is working, now and forever. We are one step closer to having everything working than we were when the test was broken. Now we get the next one working, and the next, and the next. By analogy, the tougher the programming problem, the less ground that each test should cover.

Readers of my book Extreme Programming Explained will notice a difference in tone between Extreme Programming (XP) and TDD. TDD isn't an absolute the way that XP is. XP says, "Here are things you must be able to do to be prepared to evolve further." TDD is a little fuzzier. TDD is an awareness of the gap between decision and feedback during programming, and techniques to control that gap. "What if I do a paper design for a week, then test-drive the code? Is that TDD?" Sure, it's TDD. You were aware of the gap between decision and feedback, and you controlled the gap deliberately.

That said, most people who learn TDD find that their programming practice changed for good. Test Infected is the phrase Erich Gamma coined to describe this shift. You might find yourself writing more tests earlier, and working in smaller steps than you ever dreamed would be sensible. On the other hand, some software engineers learn TDD and then revert to their earlier practices, reserving TDD for special occasions when ordinary programming isn't making progress.

There certainly are programming tasks that can't be driven solely by tests (or at least, not yet). Security software and concurrency, for example, are two topics where TDD is insufficient to mechanically demonstrate that the goals of the software have been met. Although it's true that security relies on essentially defect-free code, it also relies on human judgment about the methods used to secure the software. Subtle concurrency problems can't be reliably duplicated by running the code.

Once you are finished reading this book, you should be ready to

  • Start simply
  • Write automated tests
  • Refactor to add design decisions one at a time

This book is organized in three parts.

  • Part I, The Money Example—An example of typical model code written using TDD. The example is one I got from Ward Cunningham years ago and have used many times since: multi-currency arithmetic. This example will enable you to learn to write tests before code and grow a design organically.
  • Part II, The xUnit Example—An example of testing more complicated logic, including reflection and exceptions, by developing a framework for automated testing. This example also will introduce you to the xUnit architecture that is at the heart of many programmer-oriented testing tools. In the second example, you will learn to work in even smaller steps than in the first example, including the kind of self-referential hoo-ha beloved of computer scientists.
  • Part III, Patterns for Test-Driven Development—Included are patterns for deciding what tests to write, how to write tests using xUnit, and a greatest-hits selection of the design patterns and refactorings used in the examples.

I wrote the examples imagining a pair programming session. If you like looking at the map before wandering around, then you may want to go straight to the patterns in Part III and use the examples as illustrations. If you prefer just wandering around and then looking at the map to see where you've been, then try reading through the examples, referring to the patterns when you want more detail about a technique, and using the patterns as a reference. Several reviewers of this book commented they got the most out of the examples when they started up a programming environment, entered the code, and ran the tests as they read.

A note about the examples. Both of the examples, multi-currency calculation and a testing framework, appear simple. There are (and I have seen) complicated, ugly, messy ways of solving the same problems. I could have chosen one of those complicated, ugly, messy solutions, to give the book an air of "reality." However, my goal, and I hope your goal, is to write clean code that works. Before teeing off on the examples as being too simple, spend 15 seconds imagining a programming world in which all code was this clear and direct, where there were no complicated solutions, only apparently complicated problems begging for careful thought. TDD can help you to lead yourself to exactly that careful thought.

0321146530P10172002

Read More Show Less

Table of Contents

Preface.

Acknowledgments.

Introduction.

I. THE MONEY EXAMPLE.

1. Multi-Currency Money.

2. Degenerate Objects.

3. Equality for All.

4. Privacy.

5. Franc-ly Speaking.

6. Equality for All, Redux.

7. Apples and Oranges.

8. Makin' Objects.

9. Times We're Livin' In.

10. Interesting Times.

11. The Root of All Evil.

12. Addition, Finally.

13. Make It.

14. Change.

15. Mixed Currencies.

16. Abstraction, Finally.

17. Money Retrospective.

II. The xUnit Example.

18. First Steps to xUnit.

19. Set the Table.

20. Cleaning Up After.

21. Counting.

22. Dealing with Failure.

23. How Suite It Is.

24. xUnit Retrospective.

III. Patterns for Test-Driven Development.

25. Test-Driven Development Patterns.

26. Red Bar Patterns.

27. Testing Patterns.

28. Green Bar Patterns.

29. xUnit Patterns.

30. Design Patterns.

31. Refactoring.

32. Mastering TDD.

Appendix I: Influence Diagrams.

Appendix II: Fibonacci.

Afterword.

Index. 0321146530T10172002

Read More Show Less

Preface

Clean code that works, in Ron Jeffries' pithy phrase, is the goal of Test-Driven Development (TDD). Clean code that works is a worthwhile goal for a whole bunch of reasons.

  • It is a predictable way to develop. You know when you are finished, without having to worry about a long bug trail.
  • It gives you a chance to learn all of the lessons that the code has to teach you. If you only slap together the first thing you think of, then you never have time to think of a second, better thing.
  • It improves the lives of the users of your software.
  • It lets your teammates count on you, and you on them.
  • It feels good to write it.

But how do we get to clean code that works? Many forces drive us away from clean code, and even from code that works. Without taking too much counsel of our fears, here's what we do: we drive development with automated tests, a style of development called Test-Driven Development (TDD). In Test-Driven Development, we

  • Write new code only if an automated test has failed
  • Eliminate duplication

These are two simple rules, but they generate complex individual and group behavior with technical implications such as the following.

  • We must design organically, with running code providing feedback between decisions.
  • We must write our own tests, because we can't wait 20 times per day for someone else to write a test.
  • Our development environment must provide rapid response to small changes.
  • Our designs must consist of many highly cohesive, loosely coupled components, just to make testing easy.

The two rules imply an order to the tasks of programming.

  • Red--Write a little test that doesn't work, and perhaps doesn't even compile at first.
  • Green--Make the test work quickly, committing whatever sins necessary in the process.
  • Refactor--Eliminate all of the duplication created in merely getting the test to work.

Red/green/refactor--the TDD mantra.

Assuming for the moment that such a programming style is possible, it further might be possible to dramatically reduce the defect density of code and make the subject of work crystal clear to all involved. If so, then writing only that code which is demanded by failing tests also has social implications.

  • If the defect density can be reduced enough, then quality assurance (QA) can shift from reactive work to proactive work.
  • If the number of nasty surprises can be reduced enough, then project managers can estimate accurately enough to involve real customers in daily development.
  • If the topics of technical conversations can be made clear enough, then software engineers can work in minute-by-minute collaboration instead of daily or weekly collaboration.
  • Again, if the defect density can be reduced enough, then we can have shippable software with new functionality every day, leading to new business relationships with customers.

So the concept is simple, but what's my motivation? Why would a software engineer take on the additional work of writing automated tests? Why would a software engineer work in tiny little steps when his or her mind is capable of great soaring swoops of design? Courage.

Courage

Test-driven development is a way of managing fear during programming. I don't mean fear in a bad way--pow widdle prwogwammew needs a pacifiew-but fear in the legitimate, this-is-a-hard-problem-and-I-can't-see-the-end-from-the-beginning sense. If pain is nature's way of saying "Stop!" then fear is nature's way of saying "Be careful." Being careful is good, but fear has a host of other effects.

  • Fear makes you tentative.
  • Fear makes you want to communicate less.
  • Fear makes you shy away from feedback.
  • Fear makes you grumpy.

None of these effects are helpful when programming, especially when programming something hard. So the question becomes how we face a difficult situation and,

  • Instead of being tentative, begin learning concretely as quickly as possible.
  • Instead of clamming up, communicate more clearly.
  • Instead of avoiding feedback, search out helpful, concrete feedback.
  • (You'll have to work on grumpiness on your own.)

Imagine programming as turning a crank to pull a bucket of water from a well. When the bucket is small, a free-spinning crank is fine. When the bucket is big and full of water, you're going to get tired before the bucket is all the way up. You need a ratchet mechanism to enable you to rest between bouts of cranking. The heavier the bucket, the closer the teeth need to be on the ratchet.

The tests in test-driven development are the teeth of the ratchet. Once we get one test working, we know it is working, now and forever. We are one step closer to having everything working than we were when the test was broken. Now we get the next one working, and the next, and the next. By analogy, the tougher the programming problem, the less ground that each test should cover.

Readers of my book Extreme Programming Explained will notice a difference in tone between Extreme Programming (XP) and TDD. TDD isn't an absolute the way that XP is. XP says, "Here are things you must be able to do to be prepared to evolve further." TDD is a little fuzzier. TDD is an awareness of the gap between decision and feedback during programming, and techniques to control that gap. "What if I do a paper design for a week, then test-drive the code? Is that TDD?" Sure, it's TDD. You were aware of the gap between decision and feedback, and you controlled the gap deliberately.

That said, most people who learn TDD find that their programming practice changed for good. Test Infected is the phrase Erich Gamma coined to describe this shift. You might find yourself writing more tests earlier, and working in smaller steps than you ever dreamed would be sensible. On the other hand, some software engineers learn TDD and then revert to their earlier practices, reserving TDD for special occasions when ordinary programming isn't making progress.

There certainly are programming tasks that can't be driven solely by tests (or at least, not yet). Security software and concurrency, for example, are two topics where TDD is insufficient to mechanically demonstrate that the goals of the software have been met. Although it's true that security relies on essentially defect-free code, it also relies on human judgment about the methods used to secure the software. Subtle concurrency problems can't be reliably duplicated by running the code.

Once you are finished reading this book, you should be ready to

  • Start simply
  • Write automated tests
  • Refactor to add design decisions one at a time

This book is organized in three parts.

  • Part I, The Money Example--An example of typical model code written using TDD. The example is one I got from Ward Cunningham years ago and have used many times since: multi-currency arithmetic. This example will enable you to learn to write tests before code and grow a design organically.
  • Part II, The xUnit Example--An example of testing more complicated logic, including reflection and exceptions, by developing a framework for automated testing. This example also will introduce you to the xUnit architecture that is at the heart of many programmer-oriented testing tools. In the second example, you will learn to work in even smaller steps than in the first example, including the kind of self-referential hoo-ha beloved of computer scientists.
  • Part III, Patterns for Test-Driven Development--Included are patterns for deciding what tests to write, how to write tests using xUnit, and a greatest-hits selection of the design patterns and refactorings used in the examples.

I wrote the examples imagining a pair programming session. If you like looking at the map before wandering around, then you may want to go straight to the patterns in Part III and use the examples as illustrations. If you prefer just wandering around and then looking at the map to see where you've been, then try reading through the examples, referring to the patterns when you want more detail about a technique, and using the patterns as a reference. Several reviewers of this book commented they got the most out of the examples when they started up a programming environment, entered the code, and ran the tests as they read.

A note about the examples. Both of the examples, multi-currency calculation and a testing framework, appear simple. There are (and I have seen) complicated, ugly, messy ways of solving the same problems. I could have chosen one of those complicated, ugly, messy solutions, to give the book an air of "reality." However, my goal, and I hope your goal, is to write clean code that works. Before teeing off on the examples as being too simple, spend 15 seconds imagining a programming world in which all code was this clear and direct, where there were no complicated solutions, only apparently complicated problems begging for careful thought. TDD can help you to lead yourself to exactly that careful thought.

0321146530P10172002

Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star

(0)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(0)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing all of 5 Customer Reviews
  • Posted November 23, 2009

    more from this reviewer

    Helpful and straight forward

    I found this book a valuable introduction to TDD

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted October 11, 2009

    I Also Recommend:

    Gentle introduction to TDD

    Test driven development (TDD) is a landmark development in the craft of software development, and Kent Beck is one of its inventors. This is a great book for software professionals wanting an introduction to techniques, with clean and straightforward examples of the fundamental concepts and the basic approach. This book is thinner than most of the other books in this field, which may be what you want if you are short on time or haven't yet decided on whether you want to start writing code this way. On the other hand, if you already have experience with xUnit and you are in the midst of testing a complex application, you may find this book somewhat short on the details involved in knowing the difference between good tests and merely adequate tests.

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted April 6, 2004

    Great Step-by-Step Example of Test-Driven Development

    I enjoyed reading this book, however I must advise that non-coders will probably have difficulty in staying with it. I don¿t mean that as a put-down of any kind. It¿s obvious that the intended audience is the developer who is trying to understand the concept of test-driven development. A tester, however, would learn in this book that test-driven development uses tests that are different in nature and rigor than those commonly thought of as ¿unit tests.¿ I think Beck does a good job in explaining test-driven development in a way that is easy to understand. I still have some concerns about the nature of test-driven development, such as the emphasis on function over design. But I think Beck achieved a reasonable goal of presenting by example what test-driven development is all about. The goal of test-driven development is a reasonable way to achieve ¿clean code that works ¿ now.¿ As a tester, I think the awareness of test-driven development is a good thing. I also think that this technique must be combined with other methods, such as getting quality requirements, verification and validation, to achieve a final result that meets the users¿ needs. Readability - 4 Coverage of topics - 5 Depth of coverage - 5 Credibility - 5 Accuracy - 5 Relevance to software quality - 5 Overall - 5

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted January 23, 2003

    Beck nails it again

    What an excellent book on an excellent subject. Beck makes learning Test Driven Development (TDD) easy as he walks you through a few examples explaining the pros and cons along the way. Whether you are a newcomer to the software industry or an old dog looking to learn a few new tricks this book is definetly for you.

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted October 31, 2008

    No text was provided for this review.

Sort by: Showing all of 5 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)