TDD: What & How?

Programming is like exploring a dark house. You go from room to room to room. Writing the test is like turning on the light. Then you can avoid the table, furniture and save your shins i.e resulting clean design from refactoring. Then you are ready to explore the next room.

There is famous saying in software development that

If it isn’t tested, it’s already broken.

We are going to talk about Test Driven Development(TDD). In this practice, we drive the development using test cases. Basically, it is a programming practice that emphasizes writing test cases before the actual development. Don’t write a line of new code unless you first have a failing automated test.

The idea behind test-driven development is

Image result for tdd

Let’s see how to apply TDD with an example of creating a Calculator Assuming we have an empty class Calculator right now.

So we will start first writing test for adding two numbers.

This is the failing test as there is no add method. It won’t even compile. So corresponding to test case, we will create method add in Calculator to pass the test.

Next, we will write a failing test for subtraction of two numbers,

Again, corresponding to the test case, we will add another method sub to pass the test.

Notice, we have instantiated calculator twice in both tests. We could refactor it to initialize it once to eliminate duplication of code.

Now let’s formalize the rules applying to programming while following TDD:

Red:  write a failing test that doesn’t even compile at first.

Green: write minimal code to pass the test.

Refactor:  eliminate all duplicated code created to pass the test

This is the TDD mantra: red/green/refactor

Benefits of TDD are as follows:

1) TDD is also known as Feedback Driven Development. It gives instant feedback if anything goes wrong.  So, it provides regression benefit.

2) It provides design benefits. As we end up writing the only minimal amount of code. So, resulting in code is highly cohesive, loosely coupled and less error prone.

Conclusion:

TDD is one of the ways to develop software with a better design.  It revolves around the red/green/refactor cycle.  We write a test so that we can write production code. We don’t write the test to test the code. It gives more control to developers over feedback. It fills the gap between decision and feedback during programming and control over that gap.

Hope, this blog will help you.

Please feel free to suggest and comment.

References

  1. Test Driven Development: By Example
  2. https://www.guru99.com/test-driven-development.html


knoldus-advt-sticker

Written by 

I am a Software Consultant with experience of more than 1.5 years. I am a Functional Programing i.e Scala and Big Data technology enthusiast.I am a active blogger, love to travel, explore and a foodie.

Leave a Reply

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!

%d bloggers like this: