DEV Community

Discussion on: “How do you think when writing tests?” – It’s simpler than you may think

silverhusky profile image

Seems like the idea of TDD is to implement the minimum to make the tests pass and repeat the process until the whole functionality is implemented.

kaelscion profile image

Yes, that is true. But the idea behind TDD, at least in my experience, is to get very granular with the tests. Test everything. Some developers (myself included) will write a test for every function/method in every class they create. We champion the concept of "each class should do exactly one thing, and each property/attribute/object within that class must do only one thing to support or enhance that singular function.

Want a class that handles basic math? Good. Then you need a function that handles addition, subtraction, multiplication, division and a test or series of tests that account for expected use cases of each function, and wacky use cases of each function. Write the test, see it fail. Write a function just robust enough to make it pass. No more, no less. This accomplishes a couple things:

  1. The code is readable as each function makes it pretty clear what it's meant to do to support the sole function of it's parent class.

  2. The code is predictable. Expected input is obvious, expected output is obvious, and how it goes about it is obvious.

  3. The code is efficient, simple, and most of all, is verified to accomplish exactly what it sets out to do. No muss, no fuss. No frills or window dressing.

This approach means the code works as expected. If there is a problem or bug, it's easy to trace, just look at the object who's sole job it is to handle what is not being handled. Once that bug is found, write a test for it, see it fail, implement a solution that does just what it needs to pass, merge the new test and bug fix so that all future changes can properly test for this problem.

At first, TDD seems kind of asinine and irritating. But it will help keep you focused on one solution at a time, and give you peace of mind that your code works as expected and if anything happens, tracing and fixing the bug will be stupid easy compared to the copy pasta we all tend to write when we're in a hurry (you should see some of my personal projects...ugh).

While it isn't everyone's cup of tea, if you are like myself and many others and tend to get sidetracked and follow a bug down the rabbit hole for 2 hours before realizing you forgot what you were originally doing, TDD just introduces some structure and peace to the restless, hyper-curious, multithreaded minds we developers tend to have. Especially when we are excited and/or passionate about the project.