Codementor Events

How Test Driven Development helps you write better code

Published Jan 12, 2024
How Test Driven Development helps you write better code

Writing tests is not just a way to verify code is working as intented. It can also guide and improve the process through which you create code itself. Test driven development is vital in any developer's toolbox.

But first, what is TDD?

Test Driven Development, is a methodology, and dare I say philosophy, that you can apply when writing new code. You can use TDD whenver you are writing new code, it doesn't matter which language or environment. Since the only requirements are to be able to write and run tests.

It boils down to following these steps when you want to write a new feature:

  1. Write a failing test: Instead of writing the code first, start with the test. This will be something like "Make sure hello world shows up on the screen".
  2. Make the test pass: This is when you write the code, but you write it with ONLY the failing test in mind, you tunnel vission and get only that working, whatever the simplest solution is. This will be the printing of "Hello World"
  3. Refactor: Now that everything is working, you can improve the code to make it more readable, more performant, or whatever you want to do, but resting assured that the original requirements are complete. This might be moving the printing of hello world to it's own function, change the names, or whatever improvements you cna think of.

What are the benefits of TDD?

  1. Faster feedback: When working on a new feature, it is extremely useful to quickly run your code, to get an idea on how it behaves. Instead of having to compile the code in your head.
  2. You focus on what is important: By focusing on each requirement one by one, you make sure you're not writing code for "what ifs" that never happen.
  3. You can confidently refactor code: Improving code without tests, is like walking with the lights off. You never know how what you'll hit. Any change you make can impact the rest of the codebase. Having a suite of tests that is written beforehand allows you to rest assured, knowing you did not break anything.
  4. It is actually faster than not writing tests: Every minute spent writing tests before code is worth many minutes less of debugging, failed refactorings, and more. It is also inherently less stressing, which lowers mental load and increases productivity.
  5. You tests work as documentation: Since each test represents a new requirement, the end result is a very clear and readable interface of your code.

How can I start using TDD?

You can start by learning the ropes with some excercise (kata). I personally recommend the FizzBuzz kata, but any excercise will do. Or you can schedule a few sessions with a mentor here on CodeMentor, to help you walk through the basics.

Discover and read more posts from DamianPereira
get started
post commentsBe the first to share your opinion
Show more replies