Test-Driven Development
Learning about the practice of test-driven development (TDD) and its benefits.
We'll cover the following
Consider thinking about how we will test the code we’re about to write. Rather than just slapping out some code and then figuring out how to test it, try to design a test that describes the code we want to write, then write the code. This reversed approach might seem bizarre or even impossible, but it’s the core element of the unit-testing practice of test-driven development (TDD).
Test-driven development (TDD) is a software development process in which a developer writes specific test cases that defines a desired improvement or new function, then writes minimalistic code to pass that test, and finally refactors the new code to make it bug-free and straightforward.
The primary benefit of TDD
The following are benefits of test-driven development:
- With TDD, we wield unit tests as a tool to help shape and control our systems.
- Unit testing isn’t a pick-and-choose afterthought that can get shoved to the side. Instead, it’s a required part of a disciplined cycle that becomes core to how we build software.
- Our software will take on a different and perhaps better design if we employ TDD.
- With plain ol’ after-the-fact unit testing, the most significant benefit we gain is increased confidence that the code we write works as expected. With TDD, we gain that same benefit and more!
Systems degrade largely because we don’t often strive hard enough to keep the code clean. We’re good at quickly adding code into our systems, but it’s often low quality code on the first pass. We don’t spend a lot of effort cleaning up that initially bad code for many reasons. A few of the reasons listed by Pat (a developer) are listed below:
- “We have to move on to the next task. We don’t have time to polish the code.”
- “I think the code reads just fine the way it is. I wrote it and I understand it. I can add some comments to the code if it’s not clear.”
- “We can refactor the code when we need to make further changes in that area.”
- “It works. Why mess with a good thing? If it is not broken, don’t fix it. It’s too easy to break something else when refactoring code.”
Get hands-on with 1400+ tech skills courses.