Sunday, May 20, 2012

Unit Testing: Writing better code faster


Summary

  • Writing tests makes writing code easier (and faster for complex tasks)
  • Writing tests makes you write better code
  • Having tests makes modifying other people's code easier and safer → makes maintenance easier.

Easier writing

  • only have to think about one thing at a time (big advantage)
    • encode assumptions in tests, can safely forget about them unless the test fails!
    • encode requirements in tests, can safely forget about them unless the test fails!
  • easy profiling (just run a test many times)

Better writing

  • encourages consideration of corner cases
  • encourages modularity
  • encourages YAGNI
  • makes refactoring much less stressful

Better maintenance

  • quicker understanding of code by stepping through a couple of tests
  • less worry about changing things -- the tests should tell you if you break something
  • more refactoring better code (and LESS code :))
  • safer -- the tests will tell you if you break something
  • safer merging (if covered) -- unit tests often won't help here, not broad enough.

Caveats

Unit testing is a tool, not a goal. Don't get religious about it. For example, it won't catch SQL injection problems or XSS attacks. Don't write tests that will never fail. Don't test the same thing more than once.

The more often a test fails, the more useful it is.

Sources and Quotes

Have Fun Testing!
Probably the most important tip is to have fun. When I first encountered unit testing, I was sceptical and thought it was just extra work. But I gave it a chance, because smart people who I trusted told me that it's very useful.

Unit testing puts your brain into a state which is very different from coding state. It is challenging to
think about what is a simple and correct set of tests for this given component.

Unit test statistics: TDD teams produced code that was 60 to 90 percent better in terms of defect density than non-TDD teams.
They also discovered that TDD teams took longer to complete their projects—15 to 35 percent longer.

c2.com: The original took 3 people a year, and this took just me 9 months. The rate of bug reports has dropped off by more than 90%.

Personal experiences

NUI Iceberg
IosAttributeFilter
Multileg cancels

No comments: