Site icon Coding is Love

Test driven development with golang

Test driven development with golang

Testing – An activity dreaded by most human beings
Testing is an investigation done to make sure that the code we have written is reliable and meets the given requirements. The most common way to test code is to write unit tests for different units of the code base. This makes it easy to isolate the bugs in the code base. All of the software development processes include testing as an integral part. The one we are going to talk about today is called Test Driven Development or TDD in short.

Test-driven development is a process where tests are written before writing any code. And the code is written only to pass those tests. I know this sounds stupid, but believe me, this is a very effective software development practice. This practice ensures that we only write code that is absolutely required. So, our code is very minimalistic and meets all requirements.

The general idea of TDD is, get requirements, write a test case assuming that there is code fulfilling it, write code to pass the test case. And this process is repeated until all the requirements are met. As you can see, this is a very iterative process. These 3 steps are better known as the 3 laws of test-driven development coined by Robert Cecil Martin (uncle bob). Uncle Bob is one of the living legends of programming. I recommend following his work if you are into good practices in programming.

The 3 laws of test-driven development are formally stated as follows

  1. You can’t write any production code until you have first written a failing unit test
  2. You can’t write more of a unit test than is sufficient to fail, and not compiling is failing
  3. You can’t write more production code than is sufficient to pass the currently failing unit test

Enough of theory let’s take up an example and actually try it hands on. We will be using golang to implement this concept.

Hands on

Let’s build a simple function to list the multiples of 3 and 5 within a given range of numbers. This is a fairly simple problem to solve. Let’s look at the code step by step.

This process is long and pointless for a small problem like this. But when you write complicated code that affects millions of people, this process could save your life. Sure it’s a bit slow. But since you are writing good and clean code, you will never be slowed down by bad code. Also, the test coverage will be pretty high when you follow TDD. In fact, in our case, it is 100%.

So, this was Test-driven development in a nutshell. Hope this post gave you a perspective on how TDD could be useful. This may not be the most efficient way when you have a deadline, but it is definitely the most foolproof way to write clean code.

Exit mobile version