As we write code, we want to test it to make sure that it works as designed. A 10 line function will generally be easier to test than an entire 1000 line program simply because there is less behavior to check. And, if we realize that a 10 line function has a bug, it is much easier to find and fix the issue than if all we know is that the full 1000 line program is not working correctly.
This testing can be done in multiple ways. We can write code in a main function that uses the code we are testing or we can develop automatic unit tests to verify the functionβs behavior. Automatic unit tests that use a framework like Doctest are generally easier to write and run than hand-written test logic. So whenever possible, it makes sense to try to leverage automatic testing.
Test driven development (TDD) is a programming methodology that focuses on the importance of not just writing code, but verifying that the code is actually correct. Instead of writing code and then (maybe) figuring out how to test it, in TDD we write tests first and then write the code to pass those tests. The TDD process looks like:
Identify the next function to implement (or fix or improve).
Run the test and see it fail. If the function is new, we donβt need to run the test to know that it will fail... there is no code yet! But if we are fixing a bug, it is important to know that the new test identifies the issue by failing given the current code.
At a basic level, test driven development boils down to common sense: When working on something, it is important to have a goal in mind and it is important to be able to tell if work you have done meets that goal or not.