Sunday, March 3, 2013

A simple explanation of TDD (test-driven development)

rspec

When I first started learning web development, TDD (test-driven development) was a huge buzzword. It was gaining lots of traction as a development methodology and best practice and Hacker News was constantly flooded with new perspectives on the subject. My problem was that, after reading so many opinions, I still didn't have a decent grasp of what TDD was.



From Wikipedia:
Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards.

If you're a beginner, that still doesn't help much. First, what's an "automated test?" Second, what does it mean to "refactor the new code"? Let's break it down into laymen's terms and then discuss its role in web development and whether a beginner needs to worry about it while learning web development.

TDD in layman's terms


TDD is a way of writing software in small steps:

  1. Write a test for a new feature. What is a test? A test is sort of like a definition, describing what the new feature should do.

  2. Write the code for the new feature. This step is actually writing the code that will make the feature work in your web application.

  3. Run the new code to see if it works the way your test (definition) expects it to work. If it does, success! If it doesn't, go to step 4.

  4. Refactor (tweak) the code for the feature until it matches the test (definition).


Since you're writing tests for your code, you'll naturally use a specific format or syntax. Different languages require different formats, but the general idea of test => code => refactor is standard for all languages.

The benefits of TDD


TDD plays an important role in building solid, reliable web applications. It decreases the likely of releasing bugs or breaking old code because you're always testing your code as you write the application. Developers who use TDD practices tend to be more confident in their code, which means a happier developer. And, finally, TDD forces you to think smaller about your code, which is a good thing.

Should a beginner worry about TDD?


I strongly believe that starting with TDD as a beginner is the best way to learn web development. It will instill good coding habits, help you see and plan your application's development process more clearly, and have more confidence as you learn. Also, TDD has become standard in the industry, so if you plan to get a job as a web developer you'll need this skill on your resumé.

If you want to dive deeper, Peepcode has a great Rails-specific tutorial on the topic for $12.

No comments:

Post a Comment