Escape Debugging Hell with Test-Driven Development

Escape Debugging Hell with Test-Driven Development

Did you ever have days when you couldn't write a single line of code?

The task seems to be unbearable, so complex, and you probably need to refactor "this shitty thing you wrote last month". All your jump-on attempts end with Git Rollback on the file, and the same blank screen in the commit log as well as in your head.

How about turning it upside down - test it before you even start writing a thing? Yes, I know, TDD is overhyped and freaking complex, especially when it comes to trying to squeeze all the code you write into some sort of test (is this button becomes red if I add red color to it?).

Also, you might heard about TDD like it is something from high-end engineers who never write a function without covering it with zillion edge cases and a library of comprehensive mock factories.

But it's not only "coverage" moreover, TDD as a method for coding doesn't have anything in common with coverage metrics and SonarQube alerts.

It's about the way of thinking.

It’s an overwhelming overhead for simple pieces of code, but lifesaving is necessary for others.

Consider a task - you have a tree to walk through, and you need to apply something to its leaves. Sounds not straightforward, eh? Smells like recursion or like something scary from interviews like dynamic programming.

How do you approach it?

Will you jot some if-else and run the debugger on real data back and forth, waiting for the bundler to build and hoping that other cases will work out the same?

Wrong.

You've spent all day debugging and ended up with another "re-open" because the QA guys tried something different.

But how about this:

  1. Disconnect the function from the entire code completely, just a pure function with “in” and “out”.

  2. Write a test, just a happy and simple case

  3. Make it pass, not a big deal for the happy case, right?

  4. Write one more test, a different happy, or maybe the most common unhappy one

  5. Add "if" to the function to handle it

  6. Repeat

You can use test cases passed by your kind QA fella as a source for case ideas and, keep running "all tests" to catch the regression.

Do you have a 300-liner with if-else hell? Who cares? You have a working piece of software that passes all the tests!

Refactoring? Not a big deal since you have all cases covered and any tweak in the function will be tested and warned if something is off.

You are happily shipping the already tested task to your peer QA who's happy to close it ASAP.

Your manager is impressed by your quality rate, and your peers by the complexity of a task you could handle.

Your tech lead is happy with the coverage that grows even if there are no "explicit coverage tasks" assigned.